Skip to main content

moq_video/frame/
cuda.rs

1//! Linux CUDA device memory: the NV12 [`Frame`] behind `Surface::Cuda`, which
2//! NVDEC or a `Converter` produces and NVENC scales into its own input on the
3//! GPU.
4//!
5//! # The GPU-only path
6//!
7//! External producers publish `Surface::Vulkan` with `encode::Config::input`
8//! naming their device. NVENC imports and converts those images here, caching
9//! one full-size conversion per capture and color space, then scaling each
10//! rendition on the GPU. Those images are never downloaded.
11//!
12//! Native `Surface::Cuda` frames from NVDEC also stay on the GPU. Their portable
13//! `Surface` methods permit CPU readback for software transcoding, while an
14//! external Vulkan image refuses that fallback.
15//!
16//! NVENC reads a registered `cuMemAlloc` NV12 buffer
17//! (`NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR`): each session's own `Target`,
18//! which every frame is copied into, or scaled into when its size differs. The
19//! one copy is what lets a session register once rather than per frame, and
20//! costs microseconds of GPU time. The SDK 12.1 bindings could also register
21//! the imported Vulkan image itself as a CUDA array in an RGB session, but NVENC
22//! would then own the color matrix, and the smaller rendition would still need
23//! its own conversion, so a kernel that writes NV12 straight from the image is
24//! the one pass this path needs: no staging copy in either direction.
25//!
26//! What the hardware says (RTX 3070 Ti, driver 595.91.07, `just rs gpu`):
27//! the kernels match a CPU reference exactly, and an `nsys --trace=cuda` capture
28//! of `tests::vulkan_cuda_three_view_workload` records no `cuMemcpy` in either
29//! direction.
30//!
31//! # Nothing per frame takes the driver's device lock
32//!
33//! Allocating, freeing, and registering device memory go through the
34//! driver's per-GPU lock, which every process on the device shares, and
35//! `cuMemFree` also waits for the whole device. Paid per frame, those calls
36//! serialize every transcode on the GPU while its engines sit idle. So every
37//! frame's buffer comes from a `Pool` and goes back to it, and each NVENC
38//! session copies or scales its input into one `Target` it registered once. Scaling
39//! and copies run on their owner's own stream, never the legacy default
40//! stream, which would wait for every other thread's work in the process.
41
42use std::collections::HashMap;
43use std::num::NonZeroUsize;
44use std::sync::{Arc, Mutex, OnceLock};
45
46use cudarc::driver::{CudaContext, CudaFunction, CudaStream, LaunchConfig, PushKernelArg, result};
47
48use super::pool::{self, Pool};
49use super::{I420, cuda_vulkan, vulkan};
50use crate::{Color, Error, Size};
51
52/// The NV12 box-filter resize kernels, vendored as PTX (see nv12_resize.cu)
53/// and JIT-compiled by the driver, so building needs no CUDA toolkit.
54const RESIZE_PTX: &str = include_str!("nv12_resize.ptx");
55
56/// The loaded resize kernels, one set per device: a module belongs to the
57/// context that loaded it, and every frame on a device shares that device's
58/// primary context.
59struct Kernels {
60	luma: CudaFunction,
61	chroma: CudaFunction,
62}
63
64/// Resize kernels by device ordinal, or why loading them failed there.
65type Loaded = HashMap<usize, Result<Arc<Kernels>, String>>;
66
67fn kernels(ctx: &Arc<CudaContext>) -> Result<Arc<Kernels>, Error> {
68	static KERNELS: OnceLock<Mutex<Loaded>> = OnceLock::new();
69	let mut loaded = KERNELS
70		.get_or_init(Default::default)
71		.lock()
72		.expect("CUDA resize kernels poisoned");
73	loaded
74		.entry(ctx.ordinal())
75		.or_insert_with(|| {
76			let module = ctx
77				.load_module(cudarc::nvrtc::Ptx::from_src(RESIZE_PTX))
78				.map_err(|e| format!("load nv12_resize PTX: {e:?}"))?;
79			Ok(Arc::new(Kernels {
80				luma: module
81					.load_function("resize_luma")
82					.map_err(|e| format!("load resize_luma: {e:?}"))?,
83				chroma: module
84					.load_function("resize_chroma")
85					.map_err(|e| format!("load resize_chroma: {e:?}"))?,
86			}))
87		})
88		.clone()
89		.map_err(|e| Error::codec(anyhow::anyhow!("CUDA resize unavailable: {e}")))
90}
91
92/// Whether the driver loads the resize kernels on `ctx`'s device. A driver can
93/// refuse the vendored PTX, so a consumer that would scale on the GPU checks
94/// once and otherwise leaves scaling to [`Surface::resize`](crate::Surface::resize),
95/// which falls back to the CPU.
96pub(crate) fn scales(ctx: &Arc<CudaContext>) -> bool {
97	kernels(ctx).is_ok()
98}
99
100/// The CUDA ordinal of the device behind `device`'s render node, matched by PCI
101/// address, or `None` when it names no render node.
102///
103/// Fails when no CUDA device sits at the node's address, which a node another
104/// driver runs, or one `CUDA_VISIBLE_DEVICES` hides, cannot satisfy.
105pub(crate) fn ordinal(device: &crate::Device) -> Result<Option<usize>, Error> {
106	let Some(node) = device.render() else {
107		return Ok(None);
108	};
109	let pci = crate::device::Pci::of(node)?;
110	let cuda = |e: result::DriverError| Error::codec(anyhow::anyhow!("CUDA enumerate: {e:?}"));
111	let count = CudaContext::device_count().map_err(cuda)?;
112	let mut devices = Vec::new();
113	for ordinal in 0..count {
114		let physical = result::device::get(ordinal).map_err(cuda)?;
115		let attribute = |attribute| {
116			// SAFETY: `physical` came from `device::get` just above.
117			let value = unsafe { result::device::get_attribute(physical, attribute) }.map_err(cuda)?;
118			u32::try_from(value).map_err(|_| Error::codec(anyhow::anyhow!("CUDA device {ordinal}: negative PCI field")))
119		};
120		use cudarc::driver::sys::CUdevice_attribute as A;
121		let address = crate::device::Pci {
122			domain: attribute(A::CU_DEVICE_ATTRIBUTE_PCI_DOMAIN_ID)?,
123			bus: attribute(A::CU_DEVICE_ATTRIBUTE_PCI_BUS_ID)?,
124			device: attribute(A::CU_DEVICE_ATTRIBUTE_PCI_DEVICE_ID)?,
125		};
126		devices.push((ordinal as usize, address));
127	}
128	pci.find(devices)
129		.map(Some)
130		.ok_or_else(|| Error::Unsupported(format!("no CUDA device is {device}")))
131}
132
133/// An owned device allocation. Plain `cuMemAlloc` on purpose: NVENC's
134/// resource registration rejects stream-ordered pool memory
135/// (`cuMemAllocAsync`), which is what cudarc's `CudaSlice` uses on any GPU
136/// with memory-pool support.
137struct Raw {
138	ctx: Arc<CudaContext>,
139	ptr: cudarc::driver::sys::CUdeviceptr,
140	len: usize,
141}
142
143impl Raw {
144	fn alloc(ctx: &Arc<CudaContext>, len: usize) -> Result<Self, Error> {
145		ctx.bind_to_thread()
146			.map_err(|e| Error::codec(anyhow::anyhow!("CUDA bind: {e:?}")))?;
147		// SAFETY: a plain device allocation, freed exactly once by Drop.
148		let ptr = unsafe { result::malloc_sync(len) }
149			.map_err(|e| Error::codec(anyhow::anyhow!("CUDA alloc of {len} bytes: {e:?}")))?;
150		Ok(Self {
151			ctx: ctx.clone(),
152			ptr,
153			len,
154		})
155	}
156}
157
158impl Drop for Raw {
159	fn drop(&mut self) {
160		// Drop may run on any thread; freeing needs the context current.
161		if self.ctx.bind_to_thread().is_ok() {
162			// SAFETY: the pointer came from `malloc_sync` and is freed once.
163			let _ = unsafe { result::free_sync(self.ptr) };
164		}
165	}
166}
167
168/// The pool's allocator: one context, plain device memory.
169struct Device(Arc<CudaContext>);
170
171impl pool::Alloc for Device {
172	type Buffer = Raw;
173
174	fn alloc(&self, len: usize) -> Result<Raw, Error> {
175		Raw::alloc(&self.0, len)
176	}
177}
178
179/// Recycled NV12 buffers on one device for a producer that cannot refuse a
180/// frame, such as a decoder: never exhausted, and holding at most as many
181/// buffers as its frames ever had alive at once. Frames scaled from these draw
182/// from the same buffers.
183#[derive(Clone)]
184pub(crate) struct Frames(Arc<Pool<Device>>);
185
186impl Frames {
187	/// Buffers on `ctx`'s device.
188	pub(crate) fn new(ctx: &Arc<CudaContext>) -> Self {
189		Self(Arc::new(Pool::new(Device(ctx.clone()), None)))
190	}
191
192	/// An uninitialized frame of `size` (both dimensions even) at row pitch
193	/// `pitch`: the caller writes the full extent.
194	pub(crate) fn alloc(&self, size: Size, pitch: u32) -> Result<Frame, Error> {
195		let reservation = self.0.reserve().expect("an unbounded pool always has room");
196		Frame::pooled(reservation, size, pitch, None)
197	}
198}
199
200/// A GPU NV12 frame in CUDA device memory: NVDEC's or a `Converter`'s
201/// output and NVENC's zero-copy input. One buffer holds both planes at a
202/// shared row `pitch`: `height` luma rows, then `height / 2` interleaved-UV
203/// rows. Cloning bumps refcounts (no pixel copy), which keeps decode -> encode
204/// on the GPU; an encoder holds a clone until it has read the frame.
205///
206/// Both codecs use the device's primary CUDA context (`CudaContext::new`
207/// retains it), so a frame decoded by NVDEC is directly addressable by NVENC.
208#[derive(Clone)]
209pub struct Frame {
210	buf: Arc<pool::Lease<Device>>,
211	pub(crate) width: u32,
212	pub(crate) height: u32,
213	/// Row pitch in bytes of both planes (>= `width`).
214	pub(crate) pitch: u32,
215	/// The space the samples are in: the one a `Converter` wrote, or the stream's
216	/// when a decoder produced them.
217	pub(crate) color: Option<Color>,
218}
219
220impl std::fmt::Debug for Frame {
221	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
222		f.debug_struct("Frame")
223			.field("size", &self.size())
224			.field("pitch", &self.pitch)
225			.field("color", &self.color)
226			.finish()
227	}
228}
229
230/// NV12 bytes for `height` rows at `pitch`: the luma rows plus half as many
231/// chroma rows. Refused rather than wrapped when the product does not fit, so
232/// an absurd size cannot become a short allocation the kernels overrun.
233fn nv12_len(height: u32, pitch: u32) -> Result<usize, Error> {
234	(pitch as usize)
235		.checked_mul(height as usize)
236		.and_then(|luma| luma.checked_mul(3))
237		.map(|bytes| bytes / 2)
238		.ok_or_else(|| {
239			Error::codec(anyhow::anyhow!(
240				"NV12 frame of {height} rows at pitch {pitch} is too large"
241			))
242		})
243}
244
245/// The row pitch for frames this module allocates: 256-byte aligned for
246/// comfortable coalescing, and a multiple of 4 as NVENC registration requires.
247/// A width whose pitch does not fit `u32` is refused rather than wrapped into
248/// an allocation the kernels would overrun.
249fn aligned_pitch(width: u32) -> Result<u32, Error> {
250	width
251		.checked_next_multiple_of(256)
252		.ok_or_else(|| Error::codec(anyhow::anyhow!("frame width {width} is too wide for a CUDA NV12 pitch")))
253}
254
255impl Frame {
256	/// An uninitialized frame of `size` filling `reservation` at row pitch `pitch`.
257	fn pooled(
258		reservation: pool::Reservation<Device>,
259		size: Size,
260		pitch: u32,
261		color: Option<Color>,
262	) -> Result<Self, Error> {
263		debug_assert!(pitch >= size.width && size.width.is_multiple_of(2) && size.height.is_multiple_of(2));
264		Ok(Self {
265			buf: Arc::new(reservation.fill(nv12_len(size.height, pitch)?)?),
266			width: size.width,
267			height: size.height,
268			pitch,
269			color,
270		})
271	}
272
273	/// The frame size in pixels.
274	pub fn size(&self) -> Size {
275		Size::new(self.width, self.height)
276	}
277
278	/// The color space of the samples: the one a `Converter` wrote, or `None`
279	/// for a decoded frame that merely passed through.
280	pub fn color(&self) -> Option<Color> {
281		self.color
282	}
283
284	/// The raw device pointer, for FFI (the NVDEC copy destination, the
285	/// NVENC resource registration). Valid while `self` is alive.
286	pub(crate) fn device_ptr(&self) -> u64 {
287		self.buf.ptr
288	}
289
290	/// Download and de-pitch to packed I420 (the CPU fallback: a software
291	/// encoder, or a caller that wants bytes).
292	pub(crate) fn download_i420(&self) -> Result<I420, Error> {
293		self.buf
294			.ctx
295			.bind_to_thread()
296			.map_err(|e| Error::codec(anyhow::anyhow!("CUDA bind: {e:?}")))?;
297		let mut host = vec![0u8; self.buf.len];
298		// SAFETY: the buffer is `len` bytes of device memory and stays alive
299		// for the synchronous copy.
300		unsafe { result::memcpy_dtoh_sync(&mut host, self.buf.ptr) }
301			.map_err(|e| Error::codec(anyhow::anyhow!("CUDA download: {e:?}")))?;
302
303		let (w, h) = (self.width as usize, self.height as usize);
304		let (cw, ch) = (w / 2, h / 2);
305		let pitch = self.pitch as usize;
306
307		let mut data = vec![0u8; I420::len(self.size())?];
308		let (luma, chroma) = data.split_at_mut(w * h);
309		let (u_dst, v_dst) = chroma.split_at_mut(cw * ch);
310
311		for row in 0..h {
312			luma[row * w..row * w + w].copy_from_slice(&host[row * pitch..row * pitch + w]);
313		}
314		let uv_base = pitch * h;
315		for row in 0..ch {
316			let src = &host[uv_base + row * pitch..uv_base + row * pitch + w];
317			for col in 0..cw {
318				u_dst[row * cw + col] = src[col * 2];
319				v_dst[row * cw + col] = src[col * 2 + 1];
320			}
321		}
322
323		Ok(I420 {
324			width: self.width,
325			height: self.height,
326			data,
327			// A deinterleave, not a color conversion: the space is whatever the
328			// samples were in, known only when the crate converted them.
329			color: self.color,
330		})
331	}
332
333	/// A copy scaled to `size` (both dimensions even) on the GPU, for
334	/// [`Surface::resize`](crate::Surface::resize), which falls back to the CPU
335	/// when this fails. The copy comes from this frame's own pool, so a full
336	/// bounded pool is one such failure; an NVENC session scales into its own
337	/// [`Target`] instead.
338	pub(crate) fn resize(&self, size: Size) -> Result<Self, Error> {
339		size.validate("resize to")?;
340		let pool = self.buf.pool();
341		let reservation = pool.reserve().ok_or_else(|| {
342			Error::Unsupported(format!(
343				"GPU frame pool of {} buffers exhausted",
344				pool.capacity().map_or(0, NonZeroUsize::get)
345			))
346		})?;
347		let dst = Self::pooled(reservation, size, aligned_pitch(size.width)?, self.color)?;
348		self.scale_into(&dst, &self.buf.ctx.default_stream())?;
349		Ok(dst)
350	}
351
352	/// Copy into `dst`, the same size, on `stream` and wait for it. The copy
353	/// engine needs no PTX, unlike [`scale_into`](Self::scale_into).
354	fn copy_into(&self, dst: &Self, stream: &Arc<CudaStream>) -> Result<(), Error> {
355		stream
356			.context()
357			.bind_to_thread()
358			.map_err(|e| Error::codec(anyhow::anyhow!("CUDA bind: {e:?}")))?;
359		// NV12 keeps its chroma rows right after the luma rows at the same pitch,
360		// so one copy of 3/2 the height moves both planes.
361		let copy = cudarc::driver::sys::CUDA_MEMCPY2D {
362			srcXInBytes: 0,
363			srcY: 0,
364			srcMemoryType: cudarc::driver::sys::CUmemorytype::CU_MEMORYTYPE_DEVICE,
365			srcHost: std::ptr::null(),
366			srcDevice: self.buf.ptr,
367			srcArray: std::ptr::null_mut(),
368			srcPitch: self.pitch as usize,
369			dstXInBytes: 0,
370			dstY: 0,
371			dstMemoryType: cudarc::driver::sys::CUmemorytype::CU_MEMORYTYPE_DEVICE,
372			dstHost: std::ptr::null_mut(),
373			dstDevice: dst.buf.ptr,
374			dstArray: std::ptr::null_mut(),
375			dstPitch: dst.pitch as usize,
376			WidthInBytes: self.width as usize,
377			Height: self.height as usize * 3 / 2,
378		};
379		// SAFETY: both buffers are live NV12 allocations of `width` x `height` at
380		// their own pitch, which is at least `width`, so every row stays inside.
381		unsafe { cudarc::driver::sys::cuMemcpy2DAsync_v2(&copy, stream.cu_stream()) }
382			.result()
383			.map_err(|e| Error::codec(anyhow::anyhow!("CUDA copy: {e:?}")))?;
384		// As for `scale_into`: NVENC orders only against the default stream.
385		stream
386			.synchronize()
387			.map_err(|e| Error::codec(anyhow::anyhow!("CUDA copy sync: {e:?}")))
388	}
389
390	/// Scale this frame into `dst` with the box-filter kernels on `stream`, a
391	/// stream of this frame's device, and wait for them.
392	fn scale_into(&self, dst: &Self, stream: &Arc<CudaStream>) -> Result<(), Error> {
393		let kernels = kernels(&self.buf.ctx)?;
394		let (width, height) = (dst.width, dst.height);
395		let pitch = dst.pitch;
396
397		let block = (16u32, 16, 1);
398		let grid = |w: u32, h: u32| (w.div_ceil(16), h.div_ceil(16), 1);
399		let launch_err = |plane: &str, e| Error::codec(anyhow::anyhow!("CUDA resize {plane}: {e:?}"));
400
401		// Luma plane: one thread per destination pixel.
402		//
403		// SAFETY: both buffers are live NV12 allocations of pitch * height *
404		// 3 / 2 bytes, and the kernels bound every access by the dimensions
405		// passed alongside the pointers.
406		unsafe {
407			stream
408				.launch_builder(&kernels.luma)
409				.arg(&self.buf.ptr)
410				.arg(&self.pitch)
411				.arg(&self.width)
412				.arg(&self.height)
413				.arg(&dst.buf.ptr)
414				.arg(&pitch)
415				.arg(&width)
416				.arg(&height)
417				.launch(LaunchConfig {
418					grid_dim: grid(width, height),
419					block_dim: block,
420					shared_mem_bytes: 0,
421				})
422		}
423		.map_err(|e| launch_err("luma", e))?;
424
425		// Chroma plane: one thread per destination UV pair, offset past the
426		// luma rows in both buffers.
427		let src_uv = self.buf.ptr + u64::from(self.pitch) * u64::from(self.height);
428		let dst_uv = dst.buf.ptr + u64::from(pitch) * u64::from(height);
429		let (src_pw, src_ph) = (self.width / 2, self.height / 2);
430		let (dst_pw, dst_ph) = (width / 2, height / 2);
431		// SAFETY: as above; the UV offsets stay inside the same allocations.
432		unsafe {
433			stream
434				.launch_builder(&kernels.chroma)
435				.arg(&src_uv)
436				.arg(&self.pitch)
437				.arg(&src_pw)
438				.arg(&src_ph)
439				.arg(&dst_uv)
440				.arg(&pitch)
441				.arg(&dst_pw)
442				.arg(&dst_ph)
443				.launch(LaunchConfig {
444					grid_dim: grid(dst_pw, dst_ph),
445					block_dim: block,
446					shared_mem_bytes: 0,
447				})
448		}
449		.map_err(|e| launch_err("chroma", e))?;
450
451		// The frame may head straight to NVENC, which orders only against the
452		// default stream, so wait for the kernels rather than queueing.
453		stream
454			.synchronize()
455			.map_err(|e| Error::codec(anyhow::anyhow!("CUDA resize sync: {e:?}")))
456	}
457}
458
459/// The RGBA / BGRA to NV12 kernel, vendored as PTX (see rgba_to_nv12.cu) and
460/// JIT-compiled by the driver like the resize kernels.
461const CONVERT_PTX: &str = include_str!("rgba_to_nv12.ptx");
462
463/// Converts imported Vulkan images to NV12 [`Frame`]s on the GPU, from a
464/// bounded pool of device buffers.
465///
466/// One converter serves one device and one color space: the matrix and range
467/// it writes are what the encoder opened for the same
468/// [`encode::Config::color`](crate::encode::Config::color) declares in the
469/// bitstream, and the frames it returns report that space through
470/// [`Frame::color`] so the two cannot silently disagree. Convert once at the
471/// captured size, into a `Slot` from `reserve`, and let each rendition's
472/// encoder scale the result into its own [`Target`]. Every converted buffer
473/// comes from the pool sized by `capacity`, so a producer that outruns its
474/// encoder gets `None` from `reserve` instead of unbounded device memory. Drop
475/// the frames the encoders have finished with and the buffers come back.
476///
477/// The pixels are taken as the producer's final display-referred output: no
478/// transfer function is applied on the way to Y'CbCr, so an sRGB-encoded 8-bit
479/// render target is not gamma-encoded twice. Chroma is 4:2:0, each sample the
480/// average of its 2x2 block.
481pub(crate) struct Converter {
482	ctx: Arc<CudaContext>,
483	color: Color,
484	kernel: CudaFunction,
485	pool: Arc<Pool<Device>>,
486	importer: cuda_vulkan::Importer,
487}
488
489impl std::fmt::Debug for Converter {
490	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
491		f.debug_struct("Converter")
492			.field("device", &self.ctx.ordinal())
493			.field("color", &self.color)
494			.field("capacity", &self.pool.capacity())
495			.finish_non_exhaustive()
496	}
497}
498
499impl Converter {
500	/// Open CUDA device `ordinal`, load the conversion kernel, and size the
501	/// buffer pool. One live frame per captured frame in flight, plus slack, is
502	/// a reasonable `capacity`.
503	pub(crate) fn new(ordinal: usize, color: Color, capacity: NonZeroUsize) -> Result<Self, Error> {
504		let ctx = CudaContext::new(ordinal)
505			.map_err(|e| Error::Unsupported(format!("CUDA device {ordinal} is unavailable: {e:?}")))?;
506		let kernel = ctx
507			.load_module(cudarc::nvrtc::Ptx::from_src(CONVERT_PTX))
508			.and_then(|module| module.load_function("rgba_to_nv12"))
509			.map_err(|e| Error::Unsupported(format!("CUDA color conversion unavailable: {e:?}")))?;
510		Ok(Self {
511			importer: cuda_vulkan::Importer::new(ordinal)?,
512			pool: Arc::new(Pool::new(Device(ctx.clone()), Some(capacity))),
513			ctx,
514			color,
515			kernel,
516		})
517	}
518
519	/// The color space every converted frame is in.
520	pub fn color(&self) -> Color {
521		self.color
522	}
523
524	/// Import `frame` as its reader, so dropping it returns the producer slot
525	/// even when no pool buffer is free to convert it.
526	pub(crate) fn import(&self, frame: &vulkan::Frame) -> Result<(), Error> {
527		self.importer.import(frame).map(drop)
528	}
529
530	/// Hold one pool buffer for the next frame, or `None` while every buffer is
531	/// live: back-pressure, so drop the frame and try again after the encoder
532	/// releases one.
533	pub(crate) fn reserve(&self) -> Option<Slot> {
534		Some(Slot {
535			reservation: self.pool.reserve()?,
536			ctx: self.ctx.clone(),
537			color: self.color,
538			kernel: self.kernel.clone(),
539			importer: self.importer.clone(),
540		})
541	}
542}
543
544/// One buffer held from a `Converter`'s pool, filled by converting or
545/// scaling a frame into it. Dropped unfilled, or on a failed fill, it goes
546/// back to the pool.
547pub(crate) struct Slot {
548	reservation: pool::Reservation<Device>,
549	ctx: Arc<CudaContext>,
550	color: Color,
551	kernel: CudaFunction,
552	importer: cuda_vulkan::Importer,
553}
554
555impl std::fmt::Debug for Slot {
556	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
557		f.debug_struct("Slot")
558			.field("device", &self.ctx.ordinal())
559			.field("color", &self.color)
560			.finish_non_exhaustive()
561	}
562}
563
564impl Slot {
565	/// Convert a published Vulkan image to an NV12 frame at the same size.
566	///
567	/// Reads the image in place on its own stream, behind the producer's
568	/// ready signal, and returns once the kernel has finished: the image may
569	/// be dropped afterwards, and the frame can go straight to an encoder that
570	/// does not order against CUDA streams. Fails without touching the CPU when
571	/// the image lives on another device or has an odd dimension (4:2:0 chroma
572	/// needs even ones).
573	pub(crate) fn convert(self, frame: &vulkan::Frame) -> Result<Frame, Error> {
574		let frame = self.importer.import(frame)?;
575		if frame.cuda_context().ordinal() != self.ctx.ordinal() {
576			return Err(Error::Unsupported(format!(
577				"Vulkan image on CUDA device {} cannot be converted on device {}",
578				frame.cuda_context().ordinal(),
579				self.ctx.ordinal()
580			)));
581		}
582		let size = frame.size();
583		size.validate("Vulkan/CUDA conversion of")?;
584
585		let dst = Frame::pooled(self.reservation, size, aligned_pitch(size.width)?, Some(self.color))?;
586		let weights = self.color.coefficients();
587		let bgra = u32::from(frame.format() == vulkan::Format::Bgra8);
588		let stream = frame.cuda_stream();
589
590		// One thread per 2x2 block: the kernel writes four luma samples and one
591		// UV pair.
592		let (blocks_w, blocks_h) = (size.width / 2, size.height / 2);
593		// SAFETY: the surface object is live for as long as `frame` is, the
594		// destination is a live NV12 allocation of pitch * height * 3 / 2
595		// bytes, and the kernel bounds every access by the dimensions passed
596		// alongside.
597		unsafe {
598			stream
599				.launch_builder(&self.kernel)
600				.arg(&frame.cuda_surface())
601				.arg(&size.width)
602				.arg(&size.height)
603				.arg(&bgra)
604				.arg(&weights.y)
605				.arg(&weights.u)
606				.arg(&weights.v)
607				.arg(&dst.buf.ptr)
608				.arg(&dst.pitch)
609				.launch(LaunchConfig {
610					grid_dim: (blocks_w.div_ceil(16), blocks_h.div_ceil(16), 1),
611					block_dim: (16, 16, 1),
612					shared_mem_bytes: 0,
613				})
614		}
615		.map_err(|e| Error::codec(anyhow::anyhow!("CUDA color conversion: {e:?}")))?;
616
617		// The frame may head straight to NVENC, which does not order against
618		// our stream, and the caller may drop the image next; wait here.
619		stream
620			.synchronize()
621			.map_err(|e| Error::codec(anyhow::anyhow!("CUDA color conversion sync: {e:?}")))?;
622		Ok(dst)
623	}
624}
625
626/// One NV12 buffer that frames are copied or scaled into, for a consumer that reads it
627/// in place: an NVENC session registers it once and encodes every frame from
628/// it. Scaling runs on the target's own stream, so it never waits on other
629/// work in the process.
630pub(crate) struct Target {
631	frame: Frame,
632	stream: Arc<CudaStream>,
633}
634
635impl std::fmt::Debug for Target {
636	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
637		f.debug_struct("Target")
638			.field("frame", &self.frame)
639			.finish_non_exhaustive()
640	}
641}
642
643impl Target {
644	/// Allocate a `size` (both dimensions even) buffer on `ctx`'s device.
645	pub(crate) fn new(ctx: &Arc<CudaContext>, size: Size) -> Result<Self, Error> {
646		size.validate("CUDA target")?;
647		let frame = Frames::new(ctx).alloc(size, aligned_pitch(size.width)?)?;
648		let stream = ctx
649			.new_stream()
650			.map_err(|e| Error::codec(anyhow::anyhow!("CUDA stream: {e:?}")))?;
651		Ok(Self { frame, stream })
652	}
653
654	/// The buffer, uninitialized until the first [`fill`](Self::fill).
655	pub(crate) fn frame(&self) -> &Frame {
656		&self.frame
657	}
658
659	/// Copy or scale `src` into the buffer and wait for it, so the consumer may
660	/// read the buffer next. A copy needs no kernel; scaling fails without
661	/// touching the CPU when the driver refuses the kernels (see [`scales`]).
662	/// Either fails when `src` lives on another device.
663	pub(crate) fn fill(&mut self, src: &Frame) -> Result<(), Error> {
664		if src.buf.ctx.ordinal() != self.frame.buf.ctx.ordinal() {
665			return Err(Error::Unsupported(format!(
666				"CUDA frame on device {} cannot be scaled on device {}",
667				src.buf.ctx.ordinal(),
668				self.frame.buf.ctx.ordinal()
669			)));
670		}
671		if src.size() == self.frame.size() {
672			src.copy_into(&self.frame, &self.stream)?;
673		} else {
674			src.scale_into(&self.frame, &self.stream)?;
675		}
676		self.frame.color = src.color;
677		Ok(())
678	}
679}
680
681#[cfg(test)]
682#[path = "cuda_test.rs"]
683mod tests;