Skip to main content

moq_video/
frame.rs

1//! [`Frame`]: one raw picture, and [`Surface`]: its pixels and where they live.
2//!
3//! Representations chosen so the common path stays zero-copy:
4//! - `Surface::PixelBuffer` is an Apple `CVPixelBuffer` (IOSurface-backed NV12).
5//!   Capture and the VideoToolbox decoder both produce it, and the VideoToolbox
6//!   encoder consumes it directly, no copy and no color conversion.
7//! - `Surface::Texture` is a Windows Direct3D11 NV12 texture, produced by Media
8//!   Foundation capture/decode and Windows.Graphics.Capture, one GPU blit removed from their pools
9//!   (which they recycle, so a frame has to be lifted out of them), and consumed
10//!   by the hardware encoder MFT on the same device with no copy at all, so a
11//!   camera or a decoder reaches an encoder without touching the CPU. Drawing one
12//!   still goes through `into_i420`, since the render module imports a
13//!   `PixelBuffer` but has no Direct3D11 path yet.
14// `render` is deliberately not a doc link: the module sits behind a non-default
15// feature, so linking it fails the `-D warnings` rustdoc build of a plain build.
16//! - `Surface::DmaBuf` is a Linux DRM allocation, produced by PipeWire capture.
17//!   The Vulkan renderer imports supported packed formats directly, while CPU
18//!   consumers map linear allocations only.
19//! - `Surface::Vulkan` is an external Linux Vulkan image with an explicit
20//!   timeline semaphore. Encoders import and convert it on its device, with
21//!   no CPU download fallback, then return its producer slot after GPU completion.
22//! - `Surface::HardwareBuffer` is an Android `AHardwareBuffer`, produced by the
23//!   MediaCodec decoder rendering into an `ImageReader`. A GPU consumer imports
24//!   it as a GL or Vulkan image; `into_i420` reads the planes back instead.
25//! - `Surface::I420` is CPU-resident planar I420, for the CPU encode path and
26//!   platforms without a zero-copy capture.
27//!
28//! A backend that consumes a GPU surface takes the frame as-is; a CPU encoder
29//! asks for I420 via [`Surface::into_i420`], which downloads GPU frames that
30//! permit readback. External Vulkan surfaces intentionally refuse that fallback.
31
32use 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/// One raw (uncompressed) video frame: the pixels plus when they are shown.
49///
50/// The currency of the crate's raw side: capture sources and
51/// [`decode`](crate::decode) produce these, and
52/// [`encode::Encoder::encode`](crate::encode::Encoder::encode) consumes them,
53/// handing back the compressed [`encode::Encoded`](crate::encode::Encoded).
54#[non_exhaustive]
55pub struct Frame {
56	/// Presentation timestamp. It rides through the encoder with the picture, so a
57	/// backend that buffers or reorders still stamps each packet with the time of
58	/// the frame it actually encoded. Capture streams use a monotonic timeline
59	/// private to that stream; turnkey publishing maps it to the broadcast clock.
60	pub timestamp: Timestamp,
61	/// The pixels, and where they currently live.
62	pub surface: Surface,
63}
64
65impl Frame {
66	/// A frame shown at `timestamp`.
67	pub fn new(timestamp: Timestamp, surface: Surface) -> Self {
68		Self { timestamp, surface }
69	}
70
71	/// The frame resolution, from the surface itself.
72	pub fn size(&self) -> Size {
73		Size::new(self.surface.width(), self.surface.height())
74	}
75
76	/// A copy of this frame scaled to exactly `size` (both dimensions even and
77	/// non-zero), preserving the timestamp. GPU-backed surfaces scale on the GPU
78	/// and stay there unless `config` says otherwise. The exact-size operation;
79	/// [`decode::Config::scale_hint`](crate::decode::Config::scale_hint) is the
80	/// best-effort request that lets a decoder with a hardware scaler skip it.
81	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/// A DRM pixel format code carried by a Linux DMA-BUF.
90///
91/// The four bytes are the kernel DRM fourcc, kept as a newtype so a stride,
92/// PipeWire format id, or another bare integer cannot be passed accidentally.
93#[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	/// Semi-planar 8-bit 4:2:0 YUV: one luma plane, one interleaved Cb/Cr plane.
100	pub const NV12: Self = Self::from_bytes(*b"NV12");
101	/// Fully planar 8-bit 4:2:0 YUV as named by DRM (`YU12`): luma, then Cb, then Cr.
102	pub const YUV420: Self = Self::from_bytes(*b"YU12");
103	/// Packed BGRx8888 as named by DRM (`XR24`).
104	pub const XRGB8888: Self = Self::from_bytes(*b"XR24");
105	/// Packed BGRA8888 as named by DRM (`AR24`).
106	pub const ARGB8888: Self = Self::from_bytes(*b"AR24");
107	/// Packed RGBx8888 as named by DRM (`XB24`).
108	pub const XBGR8888: Self = Self::from_bytes(*b"XB24");
109	/// Packed RGBA8888 as named by DRM (`AB24`).
110	pub const ABGR8888: Self = Self::from_bytes(*b"AB24");
111
112	/// Build a DRM fourcc from its four ASCII bytes.
113	pub const fn from_bytes(bytes: [u8; 4]) -> Self {
114		Self(u32::from_le_bytes(bytes))
115	}
116
117	/// The integer value used by DRM, Vulkan, EGL, and VAAPI descriptors.
118	pub const fn as_raw(self) -> u32 {
119		self.0
120	}
121}
122
123/// One plane within a Linux DMA-BUF allocation.
124#[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	/// Describe a plane's byte offset and row stride.
134	pub const fn new(offset: u32, stride: u32) -> Self {
135		Self { offset, stride }
136	}
137
138	/// Byte offset of this plane from the start of the exported allocation.
139	pub const fn offset(&self) -> u32 {
140		self.offset
141	}
142
143	/// Bytes between adjacent rows in this plane.
144	pub const fn stride(&self) -> u32 {
145		self.stride
146	}
147}
148
149/// An exported Linux DMA-BUF descriptor and its producer lease.
150///
151/// Keep this value alive for as long as an external device may read from the
152/// descriptor returned by [`as_fd`](Self::as_fd). Dropping it releases the
153/// producer's buffer when no other frame or export still owns that lease.
154#[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/// How long to wait on a producer's write fence before giving up.
168///
169/// Vulkan does not adopt a DMA-BUF's implicit fence, so a reader has to wait for
170/// it here. A screen frame's fence signals within a frame time; anything past
171/// this is a wedged compositor, and the caller's CPU fallback beats blocking a
172/// render thread forever.
173#[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		// A signal restarts the wait against the same deadline rather than
186		// granting a fresh budget, so the total stall stays bounded.
187		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		// SAFETY: `event` is valid for this call and `fd` remains borrowed until
192		// the producer's current write fence has completed.
193		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	/// Borrow the exported descriptor without separating it from its producer lease.
223	pub fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {
224		std::os::fd::AsFd::as_fd(&self.fd)
225	}
226
227	/// Split the descriptor from the lease that keeps the producer's buffer alive,
228	/// for a consumer that has to own the two separately. Only the renderer does.
229	#[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/// A Linux DMA-BUF surface with an on-demand exported descriptor.
250///
251/// Cloning this value retains the producer's surface but opens no file
252/// descriptor. [`export`](Self::export) duplicates the descriptor only when a
253/// consumer is ready to import it, avoiding one open fd for every buffered
254/// frame. Dropping the last clone or [`DmaBufExport`] releases the producer's
255/// buffer.
256#[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	/// Retain an external DMA-BUF and its producer's release guard.
284	///
285	/// Clones share the descriptor and guard; exports duplicate the FD as needed.
286	/// External buffers refuse CPU download, including linear allocations.
287	#[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	/// Wait for producer writes, then export the descriptor with its producer lease.
321	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	/// DRM fourcc describing the plane layout.
331	pub const fn format(&self) -> DrmFormat {
332		self.format
333	}
334
335	/// DRM format modifier describing the allocation's tiling.
336	pub const fn modifier(&self) -> u64 {
337		self.modifier
338	}
339
340	/// Visible width in pixels.
341	///
342	/// Not the extent the producer allocated, which is padded: the padding is in
343	/// each plane's [`stride`](DmaBufPlane::stride) and in where the next plane
344	/// [`starts`](DmaBufPlane::offset), and neither follows from this.
345	pub const fn width(&self) -> u32 {
346		self.width
347	}
348
349	/// Visible height in pixels. As [`width`](Self::width), this is not the
350	/// allocated extent.
351	pub const fn height(&self) -> u32 {
352		self.height
353	}
354
355	/// Plane offsets and row strides, in format order.
356	pub fn planes(&self) -> &[DmaBufPlane] {
357		&self.planes
358	}
359
360	/// The color space of these samples where the producer named one.
361	///
362	/// `None` for the usual case of a producer that says nothing, which for YUV
363	/// pixels means the consumer falls back to [`Color::infer`]. Packed RGB
364	/// needs no answer at all.
365	pub const fn color(&self) -> Option<Color> {
366		self.color
367	}
368}
369
370/// The format, tiling, and plane layout of an external DMA-BUF.
371#[cfg(target_os = "linux")]
372#[derive(Clone, Debug)]
373pub(crate) struct DmaBufLayout {
374	/// DRM fourcc describing the pixel format.
375	pub(crate) format: DrmFormat,
376	/// DRM modifier describing memory tiling; defaults to linear.
377	pub(crate) modifier: u64,
378	/// Visible image dimensions.
379	pub(crate) size: Size,
380	/// Plane offsets and row strides, in format order.
381	pub(crate) planes: Vec<DmaBufPlane>,
382	/// Color space of YUV samples, when the producer knows it.
383	pub(crate) color: Option<Color>,
384}
385
386#[cfg(target_os = "linux")]
387impl DmaBufLayout {
388	/// Describe linear planes and set optional tiling and color fields afterward.
389	#[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/// The producer-owned half of a DMA-BUF surface.
420///
421/// Kept private to the crate so backend lifetimes and download mechanisms do
422/// not become public implementable API. [`DmaBuf`] is the stable consumer seam.
423#[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/// Where a frame's pixels currently live.
430///
431/// Decoders and capture sources hand these out; encoders and renderers consume
432/// them. Match to take a zero-copy fast path for the representation you can use,
433/// and fall back to [`into_i420`](Self::into_i420) for representations that
434/// permit CPU readback. `Surface::Vulkan` intentionally refuses that fallback:
435///
436/// ```ignore
437/// match surface {
438///     #[cfg(any(target_os = "macos", target_os = "ios"))]
439///     Surface::PixelBuffer(buffer) => draw_metal(buffer),
440///     other => upload(other.into_i420()?),
441/// }
442/// ```
443///
444/// Variants are platform-gated, and the enum is `#[non_exhaustive]` so new
445/// representations stay additive: write that `other` arm and your code keeps
446/// building everywhere.
447#[non_exhaustive]
448pub enum Surface {
449	/// Zero-copy GPU surface (Apple `CVPixelBuffer`), from capture or a
450	/// VideoToolbox decode.
451	#[cfg(apple)]
452	PixelBuffer(apple::PixelBuffer),
453	/// Zero-copy GPU texture (Windows Direct3D11 NV12).
454	#[cfg(target_os = "windows")]
455	Texture(d3d11::Texture),
456	/// GPU buffer (Linux CUDA NV12). Produced by the NVDEC decoder or the GPU
457	/// color converter, and scaled on the GPU into the NVENC encoder's input.
458	#[cfg(all(target_os = "linux", feature = "nvidia"))]
459	Cuda(cuda::Frame),
460	/// External Vulkan RGBA8 / BGRA8 image with explicit GPU synchronization.
461	#[cfg(target_os = "linux")]
462	Vulkan(vulkan::Frame),
463	/// Linux DMA-BUF, exported on access and retained until the last clone drops.
464	#[cfg(target_os = "linux")]
465	DmaBuf(DmaBuf),
466	/// Zero-copy GPU buffer (Android `AHardwareBuffer`, 4:2:0 8-bit). Produced
467	/// only by the MediaCodec decoder.
468	#[cfg(all(target_os = "android", feature = "mediacodec"))]
469	HardwareBuffer(android::HardwareBuffer),
470	/// CPU-resident planar I420.
471	I420(I420),
472}
473
474impl Surface {
475	/// The frame width in pixels.
476	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	/// The frame height in pixels.
495	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	/// A second handle on this picture, which capture keeps to repeat a still
514	/// screen. A GPU surface is retained rather than copied. `None` for an Android
515	/// buffer, which holds a decoder's queue slot and never comes from capture.
516	#[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	/// Convert tightly-packed RGBA (`width * height * 4` bytes, no row padding) to
547	/// a CPU I420 surface in [`Color::infer`]'s color space for `size`, limited
548	/// range. The result reports it via [`I420::color`], and an encoder writes it
549	/// into the bitstream, so the pixels and their label cannot disagree.
550	///
551	/// The bring-your-own-pixels entry point: wrap the result in a [`Frame`] to
552	/// encode it. A capture source or decoder hands you a surface directly, often a
553	/// GPU one, so don't route those through here.
554	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	/// A copy scaled to `size`. GPU-backed surfaces stay on the GPU. The pixel
575	/// half of [`Frame::resize`],
576	/// which is what you usually want since it carries the timestamp across too.
577	///
578	/// A GPU scaler that a driver refuses falls back to downloading and scaling
579	/// on the CPU where the surface permits readback. External Vulkan surfaces fail
580	/// instead because their contract forbids CPU pixel access.
581	///
582	/// The result keeps the source's [`color`](Self::color). An unlabelled source
583	/// means what [`Color::infer`] guesses for its own size, so the result is
584	/// labelled with that: scaling across 576 lines would otherwise change the
585	/// guess without changing the samples.
586	pub fn resize(&self, size: Size, config: &crate::resize::Config) -> Result<Surface, Error> {
587		let output = config.output.resolve(self);
588		// Counts as a use on builds where every GPU arm is compiled out.
589		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				// A transfer session or pool can fail on older hardware. Keep the
603				// stream alive with the universal CPU path.
604				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				// E.g. the driver rejected the vendored PTX: degrade to a CPU
616				// resize (download once) instead of killing the stream.
617				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				// A driver that won't render to NV12 has no video-processor path
635				// at all: degrade to a CPU resize (download once) instead of
636				// killing the stream.
637				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			// Scaled by the VA-API video processor, which also converts packed
644			// RGB to NV12 on the way, so the result is ready for the VAAPI
645			// encoder to import. If VA-API is missing or refuses the buffer,
646			// download and resize on the CPU.
647			#[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	/// The pixels as tightly-packed I420 (YUV 4:2:0): Y (`width * height` bytes),
669	/// then U, then V (`width/2 * height/2` each), no row padding.
670	///
671	/// Free for `Surface::I420`; downloads native GPU surfaces that permit
672	/// readback, so it is the universal arm of a `match` on every other
673	/// platform. A external Vulkan surface returns [`Error::Unsupported`] because
674	/// its contract deliberately exposes no CPU pixel path.
675	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	/// Convert to owned, tightly packed RGBA8 pixels on the CPU.
687	///
688	/// Native GPU surfaces that permit readback are downloaded first; CPU I420 is
689	/// converted directly. External Vulkan surfaces return [`Error::Unsupported`].
690	/// The conversion honors [`color`](Self::color) and otherwise falls back to
691	/// [`Color::infer`].
692	pub fn to_rgba(&self, config: &crate::convert::Config) -> Result<crate::convert::Rgba, Error> {
693		crate::convert::rgba(self, config)
694	}
695
696	/// The pixels as a CoreVideo pixel buffer, the mirror of
697	/// [`into_i420`](Self::into_i420) pointing the other way.
698	///
699	/// Free for `Surface::PixelBuffer` (a retain, staying on the GPU);
700	/// a CPU frame is uploaded into a fresh buffer, so this always yields something
701	/// drawable rather than making you write the upload. Wrap it in a
702	/// `CVMetalTextureCache` to render it.
703	///
704	/// Check `CVPixelBufferGetPixelFormatType` before sampling: a hardware decode
705	/// gives NV12 (bi-planar), an uploaded CPU frame planar I420.
706	///
707	/// A decoded buffer comes from the decoder's pool, so holding many frames holds
708	/// pool slots and eventually stalls decoding. Draw and drop.
709	#[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	/// The color space these samples are in, when it is known rather than
720	/// guessed. A decoded frame carries its stream's; `None` for pixels that
721	/// merely passed through without anything naming their space, a camera's raw
722	/// YUYV among them.
723	///
724	/// Worth reading before encoding pixels you resized or decoded: they keep
725	/// their source's space, which need not match what an encoder sized for them
726	/// would infer. Pass this to
727	/// [`encode::Config::color`](crate::encode::Config::color) to keep the label
728	/// honest; the encoder refuses a frame that disagrees with it.
729	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	/// Name the space of a surface that names none, leaving one that does alone.
748	///
749	/// For what the crate knows and the surface cannot carry on its own: the
750	/// stream a decoder read, or the size a frame had before a resize. A CoreVideo
751	/// buffer's attachment names only the matrix, so a label overrides it; an
752	/// external Vulkan image is RGB and takes none.
753	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	/// A CPU I420 view, downloading a GPU frame only if necessary.
773	///
774	/// Borrowed for `Surface::I420`, owned for a GPU surface that permits
775	/// readback, and unsupported for external Vulkan. The borrowing counterpart to
776	/// [`into_i420`](Self::into_i420), for a
777	/// caller that cannot give up the surface: a publisher's preview frame is
778	/// shared with every rendition's encoder, so its `Arc` never has a refcount
779	/// of one and no consuming exit is reachable from it.
780	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/// A raw video frame in planar I420 (YUV 4:2:0), tightly packed (no padding),
802/// at the encoder resolution. Width and height are even (chroma is 2x2).
803#[derive(Clone)]
804pub struct I420 {
805	pub(crate) width: u32,
806	pub(crate) height: u32,
807	/// Y plane (`width * height`) then U then V (`width/2 * height/2` each).
808	pub(crate) data: Vec<u8>,
809	/// The color space these samples are in, when it is known rather than
810	/// guessed. Set by the conversions that pick a matrix themselves; `None`
811	/// where the pixels only passed through (a decode, a camera) and the
812	/// bitstream's answer did not come with them.
813	pub(crate) color: Option<Color>,
814}
815
816impl I420 {
817	/// Wrap tightly-packed I420 planes: Y (`width * height`), then U, then V
818	/// (`width/2 * height/2` each), no row padding.
819	///
820	/// Both dimensions must be even and non-zero (4:2:0 chroma is 2x2), and `data`
821	/// must be exactly [`I420::len`] bytes. Checked here so a short buffer can't
822	/// reach a plane split and panic downstream.
823	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	/// The frame resolution.
841	pub fn size(&self) -> Size {
842		Size::new(self.width, self.height)
843	}
844
845	/// The frame width in pixels.
846	pub fn width(&self) -> u32 {
847		self.width
848	}
849
850	/// The frame height in pixels.
851	pub fn height(&self) -> u32 {
852		self.height
853	}
854
855	/// The packed planes, Y then U then V.
856	pub fn data(&self) -> &[u8] {
857		&self.data
858	}
859
860	/// Consume the image and return its packed planes.
861	pub fn into_data(self) -> Vec<u8> {
862		self.data
863	}
864
865	/// The color space these samples are in, or `None` when the crate does not
866	/// know: the pixels came out of a decoder or a camera, and the bitstream's
867	/// color description did not travel with them.
868	///
869	/// Anything converting these samples to RGB needs an answer either way, so
870	/// treat `None` as "fall back to [`Color::infer`]" rather than "does not
871	/// matter". Use [`with_color`](Self::with_color) if you know better.
872	pub fn color(&self) -> Option<Color> {
873		self.color
874	}
875
876	/// Declare the color space of these samples, for a caller who knows it (the
877	/// stream's VUI, a camera's documented output) where the crate cannot.
878	pub fn with_color(mut self, color: Color) -> Self {
879		self.color = Some(color);
880		self
881	}
882
883	/// Tightly-packed I420 byte length for the given even dimensions.
884	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	/// Convert RGBA (`stride` bytes per row, >= `width * 4`) to I420 in
892	/// [`Color::infer`]'s color space for this size, limited range. Used by
893	/// [`Surface::rgba`] (tightly packed) and the screen-capture paths, whose
894	/// surfaces carry a driver-chosen row pitch.
895	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	/// Convert BGRA to I420 in [`Color::infer`]'s color space for this size.
907	/// `stride` is the source row pitch in bytes (>= `width * 4`), so a padded
908	/// surface maps directly. Used by PipeWire capture's BGRx/BGRA shared-memory
909	/// buffers.
910	#[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	/// Pack strided Y/U/V planes (4:2:0, full-size luma, half-size chroma) into a
925	/// tightly-packed I420 buffer. `y_stride` / `uv_stride` are the source row
926	/// strides, which a decoder may pad wider than the visible width. Used by the
927	/// software H.264 decode backend, whose `DecodedYUV` exposes strided planes.
928	/// Width and height must be even (4:2:0 chroma).
929	#[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	/// Convert tightly-packed RGB (`width * height * 3` bytes) to I420 in
983	/// [`Color::infer`]'s color space for this size. Used by [`Self::from_mjpeg`].
984	#[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	/// Decode one Motion-JPEG frame to I420 in [`Color::infer`]'s color space.
1004	/// Used by the Linux V4L2 and PipeWire camera paths.
1005	///
1006	/// The stream reports the negotiated size and the encoder is built from it,
1007	/// so a frame that decodes to another size is an error rather than a frame
1008	/// published as this stream's.
1009	#[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		// zune-jpeg 0.5 reads through a seekable cursor, not a bare slice.
1014		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	/// Convert packed YUYV (YUV 4:2:2, `stride` bytes per row) to I420. A chroma
1030	/// resample (4:2:2 -> 4:2:0), no color-space conversion. Used for the raw
1031	/// V4L2 and PipeWire camera capture paths (Linux).
1032	#[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		// A chroma resample, not a color conversion: these samples are in
1048		// whatever space the camera produced, which the caller names if it can.
1049		Self::pack(&planar, size, None)
1050	}
1051
1052	/// Split tightly-packed NV12 (Y plane `width * height`, then interleaved UV
1053	/// `width/2 * height/2` pairs) into planar I420. A chroma deinterleave, no
1054	/// color-space conversion. Used by the Windows Media Foundation and Linux
1055	/// PipeWire capture paths, and by the VAAPI decoder.
1056	#[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	/// Resize to `width` x `height` (both even) with a per-plane SIMD bilinear
1086	/// convolution: Y at full size, U/V at quarter size. The CPU half of
1087	/// [`Frame::resize`].
1088	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		// The resizer caches its convolution state; recreating it per frame on a
1095		// live path would throw that away, so keep one per thread (decode/encode
1096		// loops are single-threaded).
1097		thread_local! {
1098			static RESIZER: RefCell<Resizer> = RefCell::new(Resizer::new());
1099		}
1100
1101		// Bilinear convolution: proper filter support at any downscale factor,
1102		// the cheapest option that doesn't alias.
1103		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		// Resampling moves samples around, it does not reinterpret them.
1137		Ok(Self {
1138			width,
1139			height,
1140			data,
1141			color: self.color,
1142		})
1143	}
1144
1145	/// Flatten the three planes of a freshly-converted image into one tightly
1146	/// packed I420 buffer (Y, then U, then V).
1147	/// `color` is what the caller's conversion produced: the RGB conversions pick
1148	/// a matrix, so they know it outright, while a caller that only resamples
1149	/// chroma passes `None` and leaves the samples' space open.
1150	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	/// The Y (luma) plane, `width * height` bytes.
1169	pub fn y(&self) -> &[u8] {
1170		&self.data[..self.luma_len()]
1171	}
1172
1173	/// The U (chroma) plane, `width/2 * height/2` bytes.
1174	pub fn u(&self) -> &[u8] {
1175		let start = self.luma_len();
1176		&self.data[start..start + self.chroma_len()]
1177	}
1178
1179	/// The V (chroma) plane, `width/2 * height/2` bytes.
1180	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/// Interleave separate U and V planes into a packed NV12 chroma plane
1187/// (`u[i], v[i]` -> `uv[2i], uv[2i+1]`). `uv` must be twice the length of `u`.
1188#[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/// Split a packed NV12 chroma plane into separate U and V planes, the inverse of
1197/// [`interleave_uv`].
1198#[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/// A bounded least-recently-used cache that never evicts a value in use.
1210///
1211/// Both GPU scalers want the same thing: the object that does the scaling is
1212/// expensive to build, cheap to reuse, and not safe to drive from two threads at
1213/// once, while a rendition ladder resizes on a thread per rung. So each key owns
1214/// a serialized value, rungs share rather than contend, and a long-lived process
1215/// does not retain every size it has ever seen.
1216#[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	//! Android graphics surfaces: the [`HardwareBuffer`] behind
1340	//! `Surface::HardwareBuffer`, plus the read-back to CPU I420.
1341
1342	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	// Plane indices of an `AIMAGE_FORMAT_YUV_420_888` image. The format always
1351	// reports three planes in this order, whether the device laid the picture out
1352	// planar (I420) or semi-planar (NV12/NV21); only the pixel strides differ, and
1353	// `HardwareBuffer::plane` reads those rather than assuming a layout.
1354	const Y: i32 = 0;
1355	const U: i32 = 1;
1356	const V: i32 = 2;
1357
1358	/// The `ImageReader` a decoded picture came out of.
1359	///
1360	/// A newtype rather than the `ndk` type directly so the thread-safety
1361	/// assertion lives in one place that the decoder and the frames outliving it
1362	/// both share.
1363	pub(crate) struct Reader(ImageReader);
1364
1365	// No `unsafe impl` here on purpose. Both holders of a `Reader` carry their
1366	// own (`HardwareBuffer` below, and the decoder backend), so auto-trait
1367	// derivation over this type is never consulted, and asserting `Sync` for it
1368	// would claim concurrent acquires are sound when nothing performs them.
1369
1370	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	/// A decoded picture still in GPU memory, as an Android `AHardwareBuffer`.
1385	///
1386	/// The MediaCodec decoder renders into an `ImageReader` and hands out the
1387	/// images it acquires, so the picture reaches a GL or Vulkan consumer without
1388	/// a CPU round trip. [`buffer`](Self::buffer) is that handle; everything else
1389	/// goes through [`Surface::into_i420`](crate::Surface::into_i420), which reads
1390	/// the planes back.
1391	///
1392	/// A frame occupies a slot in the decoder's fixed-size buffer queue for as long
1393	/// as it lives, and the decoder stalls once the queue is empty. Draw and drop
1394	/// rather than holding a backlog.
1395	pub struct HardwareBuffer {
1396		/// The reader owns the queue each image is a slot in, and deleting it
1397		/// invalidates images already acquired from it, so a frame outliving its
1398		/// decoder has to keep the reader alive too.
1399		_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		/// The space the samples are in, from the stream the decoder read.
1406		pub(crate) color: Option<Color>,
1407	}
1408
1409	// SAFETY: an `AImage` is an owned handle to one buffer-queue slot, so it is not
1410	// tied to the thread that acquired it. Every method here is a read
1411	// (`AImage_getPlane*`, `AImage_getHardwareBuffer`) of an image nothing else can
1412	// reach: the decoder acquires it and hands ownership straight out, and it is
1413	// never re-acquired. The reader alongside it carries its own assertion. `Sync`
1414	// is load-bearing the same way it is for the CoreVideo pixel buffer, since
1415	// moq-transcode fans decoded frames out as `Arc<Frame>`.
1416	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		/// The visible picture's horizontal offset within the hardware buffer.
1433		pub fn left(&self) -> u32 {
1434			self.left
1435		}
1436
1437		/// The visible picture's vertical offset within the hardware buffer.
1438		pub fn top(&self) -> u32 {
1439			self.top
1440		}
1441
1442		/// The picture width in pixels.
1443		pub fn width(&self) -> u32 {
1444			self.width
1445		}
1446
1447		/// The picture height in pixels.
1448		pub fn height(&self) -> u32 {
1449			self.height
1450		}
1451
1452		/// The `AHardwareBuffer` holding the pixels, with a reference acquired for
1453		/// the caller, to import as a GL image (`EGL_ANDROID_image_native_buffer`) or
1454		/// a Vulkan one (`VK_ANDROID_external_memory_android_hardware_buffer`).
1455		///
1456		/// The reference keeps the allocation alive, but only this surface keeps the
1457		/// *picture* in it: dropping the surface returns the slot to the decoder,
1458		/// which writes the next picture over the same memory. Sample the visible
1459		/// rectangle reported by [`left`](Self::left), [`top`](Self::top),
1460		/// [`width`](Self::width), and [`height`](Self::height) while you still hold
1461		/// the surface.
1462		///
1463		/// # Errors
1464		///
1465		/// Fails when the image has no hardware buffer behind it, which is what a
1466		/// software `ImageReader` allocation reports.
1467		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			// The getter borrows: it hands back the image's own handle without
1473			// touching the refcount, so the caller needs a reference of its own.
1474			Ok(buffer.acquire())
1475		}
1476
1477		/// Read the picture back to packed I420 (the CPU path).
1478		///
1479		/// A layout change, not a color conversion, so the samples keep whatever
1480		/// space they arrived in. The device chooses the layout and the strides, and
1481		/// both are read off the image rather than assumed, so a planar device and a
1482		/// semi-planar one produce the same bytes here.
1483		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		/// One plane's bytes and the two strides needed to walk them.
1507		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	/// A borrowed image plane: its bytes, its row pitch, and the gap between
1523	/// horizontally adjacent samples (2 where the device interleaved U and V).
1524	struct Plane<'a> {
1525		data: &'a [u8],
1526		row: usize,
1527		pixel: usize,
1528	}
1529
1530	impl Plane<'_> {
1531		/// Copy a `width` x `height` sample window into `dst`, tightly packed.
1532		///
1533		/// # Errors
1534		///
1535		/// Fails when the plane is shorter than its own strides say it should be,
1536		/// rather than reading past the mapping.
1537		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	//! CoreVideo surfaces on macOS and iOS: the [`PixelBuffer`] behind
1597	//! `Surface::PixelBuffer`, GPU resize, and download/upload between it and CPU
1598	//! I420.
1599
1600	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	/// Read-only lock flag (`kCVPixelBufferLock_ReadOnly`).
1621	const LOCK_READ_ONLY: CVPixelBufferLockFlags = CVPixelBufferLockFlags(1);
1622
1623	/// Enough reusable scalers for a large rendition ladder without retaining
1624	/// every resolution a long-lived process has ever seen.
1625	const SCALER_CACHE_CAPACITY: usize = 16;
1626
1627	/// Transfer sessions and destination pools are reusable, but VideoToolbox does
1628	/// not promise concurrent access to a session. Each cached output size gets
1629	/// its own serialized scaler so independent ladder rungs do not contend.
1630	type ScalerCache = Mutex<Cache<(u32, u32), Scaler>>;
1631	static SCALERS: LazyLock<ScalerCache> = LazyLock::new(|| Mutex::new(Cache::new(SCALER_CACHE_CAPACITY)));
1632
1633	/// A captured GPU surface. Cloning is a cheap retain (no pixel copy), which
1634	/// is what keeps the capture -> encode path zero-copy.
1635	pub struct PixelBuffer {
1636		pub(crate) buffer: CFRetained<CVPixelBuffer>,
1637		pub(crate) width: u32,
1638		pub(crate) height: u32,
1639		/// The space the decoder read from the stream's VUI, which names the
1640		/// primaries and transfer the matrix attachment leaves out.
1641		pub(crate) color: Option<Color>,
1642	}
1643
1644	// SAFETY: CVPixelBuffer is a reference-counted CoreFoundation wrapper around
1645	// an IOSurface. Retain/release are thread-safe, every &self access is a
1646	// plain field read or a read-only CVPixelBufferLockBaseAddress, and no code
1647	// path write-locks a shared surface, so the handle can move between threads
1648	// (capture delegate -> encode loop, decode callback -> consumer) and be
1649	// shared by reference. objc2 leaves CoreVideo types !Send/!Sync out of
1650	// conservatism. Sync is load-bearing: the VideoToolbox decoder hands these
1651	// out as decoded frames, and moq-transcode shares them as Arc<Frame>
1652	// across its rung fanout.
1653	unsafe impl Send for PixelBuffer {}
1654	unsafe impl Sync for PixelBuffer {}
1655
1656	impl PixelBuffer {
1657		/// The underlying CoreVideo buffer, to hand to Metal or another CoreVideo
1658		/// consumer. Borrowing keeps it on the GPU.
1659		pub fn buffer(&self) -> &CVPixelBuffer {
1660			&self.buffer
1661		}
1662
1663		/// The buffer width in pixels.
1664		pub fn width(&self) -> u32 {
1665			self.width
1666		}
1667
1668		/// The buffer height in pixels.
1669		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		/// Scale into an NV12 buffer owned by the destination-size pool.
1683		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		/// The color space this buffer's matrix attachment names, falling back to
1703		/// [`Color::infer`] when it carries none.
1704		///
1705		/// VideoToolbox copies the matrix out of the stream's VUI onto every decoded
1706		/// buffer, so this is the source's own answer wherever the source gave one.
1707		/// The range is not in this attachment; the caller pairs it with the one the
1708		/// pixel format names.
1709		fn matrix(&self) -> Color {
1710			let inferred = Color::infer(Size::new(self.width, self.height));
1711			// SAFETY: a null attachment mode is documented as "don't report it".
1712			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			// Compare against the constants rather than the string literals: these
1720			// are CFString identities Apple owns, not values we should spell out.
1721			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				// BT.2020 and the P3 matrices land here. A decoded buffer carries the
1727				// decoder's label instead, so only an unlabelled one guesses.
1728				inferred
1729			}
1730		}
1731
1732		/// The color space these samples are in: the decoder's label, or else the
1733		/// matrix from the buffer's attachment, paired with the range its pixel
1734		/// format names (VideoToolbox converts to the format it was asked for).
1735		/// `None` for a format that names no range.
1736		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		/// Download an NV12 surface to packed I420 (the CPU encode path).
1749		///
1750		/// A deinterleave, not a color conversion, so the samples keep whatever
1751		/// space they arrived in. The pixel format names the range and the buffer's
1752		/// matrix attachment names the matrix, so a decoded frame reports the space
1753		/// its own bitstream declared rather than one guessed from its size.
1754		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			// Plane 0: Y, copied row by row honoring stride.
1776			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			// Plane 1: interleaved UV -> split into U and V.
1784			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	/// One VideoToolbox transfer session and destination pool for an output size.
1805	struct Scaler {
1806		session: CFRetained<VTPixelTransferSession>,
1807		pool: CFRetained<CVPixelBufferPool>,
1808		width: u32,
1809		height: u32,
1810	}
1811
1812	// SAFETY: the cache only exposes a Scaler behind its per-size Mutex, so the
1813	// transfer session and pool are used and released serially even when resize
1814	// calls arrive on different executor threads.
1815	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	/// Build a reusable NV12 IOSurface pool for one output size.
1877	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	/// A pixel buffer with its base address locked, unlocked on drop so no early
1934	/// return leaks the lock.
1935	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		/// Plane `index`'s base address and row stride, checked to hold `rows`
1952		/// rows of `row_bytes` each, so copying that much stays inside it.
1953		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	/// Upload a packed I420 test picture as NV12, including CoreVideo row
1984	/// padding, so a test starts from the decoder's surface format rather than
1985	/// the planar layout [`upload_i420`] produces.
1986	#[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	/// Allocate a planar I420 `CVPixelBuffer` and copy the frame into it: the
2041	/// upload half of [`Surface::into_i420`], for when the pixels are on the
2042	/// CPU but a CoreVideo consumer (the VideoToolbox encoder, a renderer) needs a
2043	/// buffer. Note the format is planar I420, not the NV12 a hardware decode
2044	/// hands back, so callers query `CVPixelBufferGetPixelFormatType`.
2045	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	/// Copy a tightly-packed source plane into a pixel-buffer plane, honoring its
2075	/// (possibly padded) row stride.
2076	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			// SAFETY: `plane` checked the plane holds `rows` rows of `row_bytes`.
2081			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// Compiled for every test build so its policy tests run without a GPU.
2104#[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	//! Windows Direct3D11 surfaces: the NV12 [`Texture`] behind
2111	//! `Surface::Texture`, shared by Media Foundation capture, decode, and encode.
2112
2113	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	/// Create a hardware Direct3D11 device on `adapter`, or the default one,
2150	/// multithread-protected (Media Foundation's internal threads or WGC and our
2151	/// capture thread both touch it). The shared low-level constructor behind the
2152	/// Media Foundation device manager, Windows.Graphics.Capture, and the render
2153	/// export.
2154	pub(crate) fn create_device(adapter: Option<&IDXGIAdapter>) -> Result<ID3D11Device, Error> {
2155		// A named adapter picks the driver itself.
2156		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	/// A GPU texture (NV12) on its producer's Direct3D11 device: a Media Foundation
2187	/// source reader, DXVA decoder, or Windows.Graphics.Capture session. Holds
2188	/// that device so the download fallback and the hardware encoder run on the
2189	/// device that owns the texture. Cloning the COM handles is a cheap `AddRef`,
2190	/// which is what keeps capture -> encode and decode -> encode zero-copy.
2191	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		/// Blit the `width` x `height` picture out of a Media Foundation sample into
2201		/// a texture we own, staying on `device` and on the GPU.
2202		///
2203		/// The exit from a Media Foundation pool, which a frame cannot simply be
2204		/// handed out of. Both producers here allocate their output from a pool and
2205		/// recycle a slot the moment its sample is released, so a texture handle
2206		/// alone is not ownership: the next picture is written over a frame a
2207		/// consumer is still holding. Keeping the sample instead is worse, because a
2208		/// decoder's pool is short (8 slices on the hardware this was written
2209		/// against) and it has no error to report when it runs dry: the MFT blocks
2210		/// inside `ProcessInput` waiting for a picture buffer a consumer is holding.
2211		/// A decoder's slices are bound `D3D11_BIND_DECODER` and nothing else, on
2212		/// top of that, so no shader can sample one and no encoder can read it.
2213		///
2214		/// One GPU-to-GPU copy buys a frame that outlives its producer, holds
2215		/// nothing back, and can be bound. It also crops the coded size (a decoder
2216		/// allocates in whole macroblocks) to the display size, so the result is
2217		/// exactly the picture. `width` and `height` are that display size, which
2218		/// the texture itself does not know.
2219		///
2220		/// Errors if the sample is system-memory backed, which is the caller's cue
2221		/// to take its CPU path.
2222		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			// One plain slice in the producer's own format.
2231			let mut desc = D3D11_TEXTURE2D_DESC::default();
2232			unsafe { source.GetDesc(&mut desc) };
2233			let texture = alloc(device, width, height, desc.Format)?;
2234
2235			// Every edge has to be even for 4:2:0 chroma; the decoder's frame size is
2236			// validated even before it reaches here.
2237			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(&region));
2248			}
2249
2250			Ok(Self {
2251				device: device.clone(),
2252				texture,
2253				width,
2254				height,
2255				color: None,
2256			})
2257		}
2258
2259		/// Convert a BGRA surface someone else recycles (a WGC frame, an exported
2260		/// render target) to an owned, even-sized NV12 texture.
2261		#[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		/// The Direct3D11 texture holding the pixels. Borrowing keeps them on the
2281		/// GPU.
2282		///
2283		/// NV12, one slice, exactly [`width`](Self::width) x
2284		/// [`height`](Self::height), and bound for everything the driver supports
2285		/// for the format: sampling in a shader, drawing into, and the hardware
2286		/// encoder. This crate allocated it, so none of that is the producer's
2287		/// choice leaking through.
2288		pub fn texture(&self) -> &ID3D11Texture2D {
2289			&self.texture
2290		}
2291
2292		/// The Direct3D11 device the texture belongs to. Anything reading the
2293		/// texture has to run on this device.
2294		pub fn device(&self) -> &ID3D11Device {
2295			&self.device
2296		}
2297
2298		/// The frame width in pixels.
2299		pub fn width(&self) -> u32 {
2300			self.width
2301		}
2302
2303		/// The frame height in pixels.
2304		pub fn height(&self) -> u32 {
2305			self.height
2306		}
2307
2308		/// Copy the NV12 texture to a CPU-readable staging texture and
2309		/// deinterleave it into packed I420 (the CPU encode path, when the encoder
2310		/// can't consume the GPU texture directly).
2311		pub(crate) fn download_i420(&self) -> Result<I420, Error> {
2312			let context = unsafe { self.device.GetImmediateContext() }.map_err(|e| err("GetImmediateContext", e))?;
2313
2314			// A CPU-readable copy of the source texture's single slice.
2315			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			// The UV plane begins after the *texture's* Y plane, which spans the
2352			// allocated height, not the display height. A DXVA decode pool allocates
2353			// textures at the coded size (e.g. 1088 rows for a 1080p display), so
2354			// keying the offset off `self.height` would read chroma from inside the
2355			// still-luma padding rows and produce garbage color.
2356			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			// Y plane: h rows of `pitch` bytes, only the first w used.
2363			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			// Interleaved UV plane sits right after the full Y plane, h/2 rows.
2369			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		/// Scale to `width` x `height` on the GPU, staying on this texture's device.
2389		/// The Windows GPU path used by
2390		/// [`Frame::resize`](crate::Frame::resize).
2391		///
2392		/// Errors rather than falling back, so the caller decides. Two things a
2393		/// driver can refuse: rendering to NV12 at all (no output view, so no
2394		/// scale), and an input view over a texture bound only for shader
2395		/// sampling. [`bind_flags`] asks for render-target and video-encoder
2396		/// support up front, so both come down to what the driver granted.
2397		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	/// Enough reusable video processors for a large rendition ladder without
2455	/// retaining every device and scale a long-lived process has ever seen.
2456	const SCALER_CACHE_CAPACITY: usize = 16;
2457
2458	/// Building a video processor costs orders of magnitude more than using one,
2459	/// and `ID3D11VideoContext` is not safe to drive from two threads at once, so
2460	/// each device and scale gets one serialized processor that its ladder rungs
2461	/// share.
2462	static SCALERS: LazyLock<Mutex<Cache<ScalerKey, ScalerState>>> =
2463		LazyLock::new(|| Mutex::new(Cache::new(SCALER_CACHE_CAPACITY)));
2464
2465	/// A usable scaler, or a remembered capability failure for this exact key.
2466	enum ScalerState {
2467		Ready(Scaler),
2468		Unsupported {
2469			/// Keeps the pointer in the cache key unique while this marker exists.
2470			_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	/// Which device and which scale a cached processor is for.
2488	///
2489	/// The device is keyed by pointer because `ID3D11Device` is not hashable. That
2490	/// is sound only because every cached [`ScalerState`] holds a reference to the
2491	/// same device: the address cannot be freed and handed to a different device
2492	/// while an entry keyed on it is alive.
2493	#[derive(Clone, PartialEq, Eq, Hash)]
2494	struct ScalerKey {
2495		device: usize,
2496		plan: Plan,
2497	}
2498
2499	/// One Direct3D11 video processor, configured for a single source and target
2500	/// size, crop, format and color conversion. Shared by resize and WGC capture.
2501	struct Scaler {
2502		/// Keeps the device keying this entry alive, so its address stays unique.
2503		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	/// Whether a failed scale proves this key unsupported or can succeed later.
2513	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			// The frame rates are what a processor uses to decide it should
2530			// deinterlace or interpolate; matching them says neither.
2531			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				// Capture crops odd edges; resize maps the entire input picture.
2583				context.VideoProcessorSetStreamSourceRect(&processor, 0, true, Some(&full));
2584				context.VideoProcessorSetStreamDestRect(&processor, 0, true, Some(&scaled));
2585				// Drivers ship denoise and edge enhancement on by default here.
2586				// This is a resize, not a filter chain, so a rung must not come out
2587				// looking different from the frame it was scaled from.
2588				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		/// Blit `source` into a new texture at the target size.
2610		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			// The stream struct holds the view in a `ManuallyDrop`, so releasing it
2670			// is ours to do whether or not the blit succeeded.
2671			// SAFETY: the field is live and read exactly once.
2672			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	/// A plain single-slice texture on `device`, bound for whatever the driver
2682	/// supports. Where every frame this module hands out is allocated.
2683	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	/// Upload packed I420 as an NV12 texture on `device`, the inverse of
2707	/// [`Texture::download_i420`]. Only the tests need it: every texture in a live
2708	/// pipeline comes from a producer that already put it on the GPU.
2709	#[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		// Tightly packed, so the row pitch is the width and the depth pitch is
2722		// the whole buffer.
2723		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	/// A synthetic pool surface for the opt-in WGC conversion/encoding tests.
2744	#[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	/// The Direct3D11 texture behind a Media Foundation sample, and which slice of
2763	/// it this sample is. Errors if the sample is system-memory backed.
2764	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		// GetResource returns a fresh ref (`AddRef`) we take ownership of.
2771		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	/// What a texture of `format` can be bound as on this device: everything a
2782	/// consumer might want (sampling it in a shader, drawing into it, feeding it to
2783	/// the hardware encoder) that the driver actually supports for the format.
2784	///
2785	/// Asked rather than assumed, because NV12 is exactly the format a driver is
2786	/// allowed to be picky about, and `CreateTexture2D` fails outright on a flag it
2787	/// does not support. Whatever comes back, the texture is still copyable and
2788	/// downloadable, so a bare-bones driver costs a consumer a copy rather than the
2789	/// frame.
2790	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	/// Whether explicit GPU-resize tests can render to an NV12 destination.
2808	#[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						// A green odd edge must be cropped, not scaled into the red picture.
2838						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				// Simulate immediate reuse of a WGC pool frame after conversion.
2855				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				// HD -> SD scaling must keep 709, not infer 601 from the new height.
2869				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				// Mapping the final result fences the preceding ordered GPU blits.
2909				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	/// A conversion that picks a matrix says so; one that only moves samples
2922	/// around must not.
2923	///
2924	/// The distinction decides whether a renderer trusts the frame or guesses
2925	/// from the resolution, and guessing wrong tints saturated colors (see the
2926	/// render module's HD test). Labeling everything with the RGB matrix would be
2927	/// worse than labeling nothing: a 720p camera's BT.709 samples would be
2928	/// pinned to BT.601 rather than inferring BT.709 correctly.
2929	#[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		// Resampling moves samples around; it does not reinterpret them.
2944		let resized = converted.resize(Size::new(32, 32)).expect("resize");
2945		assert_eq!(resized.color(), Some(Color::BT601), "resize preserves the space");
2946
2947		// A passthrough leaves it open for the consumer to infer.
2948		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	/// An unlabelled 720p frame means BT.709 to every player. Scaled to 480p it
2959	/// would read as BT.601, so the resize names the space it came from.
2960	#[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		// A labelled source keeps its own label, not the size guess.
2975		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	/// V4L2 hands back YUYV already in the camera's color space, so the 4:2:2 ->
2987	/// 4:2:0 chroma resample must not claim it is BT.601: a 720p camera is
2988	/// usually BT.709, and mislabeling pins it to the wrong matrix instead of
2989	/// letting the resolution heuristic get it right.
2990	#[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		// YUYV packs two pixels into four bytes.
2995		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	/// The MJPEG half of camera capture, which the nightly `vivid` lane cannot
3001	/// reach: the driver offers raw formats only. The fixture is one solid red
3002	/// 32x16 baseline JPEG, as a UVC camera would send it.
3003	#[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	/// A real frame from a Sony ZV-E10 (MJPEG-only UVC, 4:2:2, sent without an
3028	/// end-of-image marker), byte for byte as the V4L2 and PipeWire paths
3029	/// receive it. Each 80x80 block of the luma, and the mean of each chroma
3030	/// plane, must match ffmpeg's decode of the same file, so a squashed,
3031	/// shifted, or torn picture fails. ffmpeg's full-to-limited range scaling
3032	/// rounds a little higher than the RGB round trip does, up to 4 on a block.
3033	#[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	/// A short buffer is rejected at construction rather than panicking later: the
3078	/// plane splits in `y`/`u`/`v` and the CoreVideo upload both index blindly, so
3079	/// a public `I420` has to be impossible to build malformed.
3080	#[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		// Odd and zero dimensions have no valid 4:2:0 chroma.
3090		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	/// Derived byte counts must fail before allocation when the declared image is
3095	/// too large for the host address space.
3096	#[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	/// The counterpart for the RGBA entry point: a buffer that isn't exactly one
3110	/// frame of the declared size is a caller mistake, not slack to truncate.
3111	#[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	/// Consuming a CPU surface moves its allocation without dropping the size or
3121	/// color. A transposed image has the same byte count, so bytes alone could not
3122	/// preserve which geometry the caller declared.
3123	#[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	/// CPU I420 is borrowed in place, while a native allocation is downloaded
3145	/// into owned pixels. Callers can delay either result without confusing the
3146	/// ownership model.
3147	#[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	/// Software decoders may align each plane beyond its visible width. Padding
3192	/// must not leak into the packed fallback or shift a later row.
3193	#[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	/// The conversion picks its matrix by resolution, matching what a player
3209	/// assumes for an untagged stream, and reports the one it used.
3210	///
3211	/// The regression: every RGB conversion hardcoded BT.601. A 1080p screen
3212	/// capture was converted with BT.601, encoded untagged, and decoded with the
3213	/// BT.709 inverse, which turns pure red into roughly (255, 24, 0). Grays are
3214	/// unaffected, which is why it survived casual inspection.
3215	#[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		// Decode with the matrix a player picks for an untagged stream of this
3227		// size, and sample the middle of the frame.
3228		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			// Red survives the round trip at every size. Before the fix the 720p and
3257			// 1080p cases came back around (255, 24, 0).
3258			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	/// The frame's size comes from the surface rather than a field alongside it,
3267	/// so the two cannot drift apart, and a resize carries the timing across.
3268	#[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	/// `into_pixel_buffer` is total: a CPU frame uploads rather than failing, so a
3284	/// renderer never has to write the upload itself. Software-decoded frames take
3285	/// this path.
3286	#[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	/// A gradient I420 frame with structure in every plane, so resize bugs
3301	/// (plane swaps, stride mistakes) shift the averages measurably.
3302	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	/// Mean absolute error between two equal-length planes.
3328	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	/// The CPU resize follows the source gradients at any downscale factor: a
3334	/// horizontal luma ramp stays a ramp, and the chroma ramps follow too.
3335	#[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		// Reference: the same gradients sampled at the destination geometry.
3342		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	/// VideoToolbox and the CPU convolution agree on a smooth NV12 gradient.
3349	/// The result remains a pixel buffer, pinning the residency regression.
3350	#[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	/// CPU output downloads a CoreVideo pixel buffer before scaling.
3372	#[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	/// The packed-pixel exit is total for a hardware surface and produces the
3386	/// same image as its CPU representation, including padded CoreVideo rows.
3387	#[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	/// A pixel buffer that claims a larger picture than CoreVideo allocated is
3405	/// refused rather than read past its planes, and leaves it unlocked.
3406	#[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		// The failed download released its lock, so the buffer still reads.
3414		assert_eq!(surface.download_i420().unwrap().height, 48);
3415	}
3416
3417	#[cfg(apple)]
3418	use super::apple::nv12_surface;
3419
3420	/// A Direct3D11 texture stays on the GPU by default.
3421	#[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	/// Direct3D11 resize can be forced onto the CPU.
3449	#[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	/// GPU (video processor) and CPU (bilinear convolution) resizes agree on a
3472	/// smooth gradient, so the scaler is scaling rather than merely not failing.
3473	/// Runs on real hardware; skips without a Direct3D11 device.
3474	#[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	/// GPU (box filter) and CPU (bilinear convolution) resizes agree on a
3502	/// smooth gradient. Runs on real hardware; skips without the NVIDIA driver.
3503	#[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		// Same probe as the codec backends: no driver, no test.
3513		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); // odd-ish sizes: exercise pitch != width
3521		let src_i420 = gradient_i420(w, h);
3522
3523		// Upload as pitched NV12: Y rows, then interleaved UV rows.
3524		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		// SAFETY: the frame's buffer is exactly host.len() bytes.
3540		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}