1use 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
52const RESIZE_PTX: &str = include_str!("nv12_resize.ptx");
55
56struct Kernels {
60 luma: CudaFunction,
61 chroma: CudaFunction,
62}
63
64type 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
92pub(crate) fn scales(ctx: &Arc<CudaContext>) -> bool {
97 kernels(ctx).is_ok()
98}
99
100pub(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 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
133struct 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 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 if self.ctx.bind_to_thread().is_ok() {
162 let _ = unsafe { result::free_sync(self.ptr) };
164 }
165 }
166}
167
168struct 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#[derive(Clone)]
184pub(crate) struct Frames(Arc<Pool<Device>>);
185
186impl Frames {
187 pub(crate) fn new(ctx: &Arc<CudaContext>) -> Self {
189 Self(Arc::new(Pool::new(Device(ctx.clone()), None)))
190 }
191
192 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#[derive(Clone)]
209pub struct Frame {
210 buf: Arc<pool::Lease<Device>>,
211 pub(crate) width: u32,
212 pub(crate) height: u32,
213 pub(crate) pitch: u32,
215 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
230fn 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
245fn 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 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 pub fn size(&self) -> Size {
275 Size::new(self.width, self.height)
276 }
277
278 pub fn color(&self) -> Option<Color> {
281 self.color
282 }
283
284 pub(crate) fn device_ptr(&self) -> u64 {
287 self.buf.ptr
288 }
289
290 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 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 color: self.color,
330 })
331 }
332
333 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 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 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 unsafe { cudarc::driver::sys::cuMemcpy2DAsync_v2(©, stream.cu_stream()) }
382 .result()
383 .map_err(|e| Error::codec(anyhow::anyhow!("CUDA copy: {e:?}")))?;
384 stream
386 .synchronize()
387 .map_err(|e| Error::codec(anyhow::anyhow!("CUDA copy sync: {e:?}")))
388 }
389
390 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 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 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 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 stream
454 .synchronize()
455 .map_err(|e| Error::codec(anyhow::anyhow!("CUDA resize sync: {e:?}")))
456 }
457}
458
459const CONVERT_PTX: &str = include_str!("rgba_to_nv12.ptx");
462
463pub(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 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 pub fn color(&self) -> Color {
521 self.color
522 }
523
524 pub(crate) fn import(&self, frame: &vulkan::Frame) -> Result<(), Error> {
527 self.importer.import(frame).map(drop)
528 }
529
530 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
544pub(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 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 let (blocks_w, blocks_h) = (size.width / 2, size.height / 2);
593 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 stream
620 .synchronize()
621 .map_err(|e| Error::codec(anyhow::anyhow!("CUDA color conversion sync: {e:?}")))?;
622 Ok(dst)
623 }
624}
625
626pub(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 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 pub(crate) fn frame(&self) -> &Frame {
656 &self.frame
657 }
658
659 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;