use cudarc::driver::safe::CudaContext;
use cudarc::driver::{DeviceRepr, PushKernelArg};
use std::sync::Arc;
use super::loader::{
BLOCK_SIZE, MAX_GRID_DIM_X, dtype_suffix, get_kernel_function, get_or_load_module,
launch_config,
};
use crate::dtype::DType;
use crate::error::{Error, Result};
use crate::ops::common::{ColorCoeffs, PlaneView, YuvFrame};
use crate::runtime::cuda::GuardedStream;
pub const COLOR_MODULE: &str = "color";
#[repr(C)]
#[derive(Debug, Clone, Copy)]
#[allow(dead_code, reason = "only color.cu reads the fields")]
struct ColorPlaneArg {
addr: u64,
row_stride: i64,
col_stride: i64,
}
impl From<PlaneView> for ColorPlaneArg {
fn from(p: PlaneView) -> Self {
Self {
addr: p.addr,
row_stride: p.row_stride as i64,
col_stride: p.col_stride as i64,
}
}
}
#[repr(C)]
#[derive(Debug, Clone, Copy)]
#[allow(dead_code, reason = "only color.cu reads the fields")]
struct YuvKernelArgs {
y: ColorPlaneArg,
u: ColorPlaneArg,
v: ColorPlaneArg,
rgb: u64,
rgb_c: i64,
rgb_h: i64,
rgb_w: i64,
height: i64,
width: i64,
k: ColorCoeffs,
shift: u32,
center: u32,
}
unsafe impl DeviceRepr for YuvKernelArgs {}
#[repr(C)]
#[derive(Debug, Clone, Copy)]
#[allow(dead_code, reason = "only color.cu reads the fields")]
struct Rgb24KernelArgs {
src: u64,
dst: u64,
src_strides: [i64; 3],
dst_strides: [i64; 3],
height: i64,
width: i64,
}
unsafe impl DeviceRepr for Rgb24KernelArgs {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum YuvDirection {
ToRgb,
ToYuv,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Rgb24Direction {
Unpack,
Pack,
}
fn float_suffix(dtype: DType) -> Option<&'static str> {
matches!(dtype, DType::F32 | DType::F64 | DType::F16 | DType::BF16).then(|| dtype_suffix(dtype))
}
fn yuv_kernel_name(direction: YuvDirection, wide: bool, float: DType) -> Option<String> {
let f = float_suffix(float)?;
let p = if wide { "u16" } else { "u8" };
Some(match direction {
YuvDirection::ToRgb => format!("yuv_to_rgb_{p}_{f}"),
YuvDirection::ToYuv => format!("rgb_to_yuv_{f}_{p}"),
})
}
fn rgb24_kernel_name(direction: Rgb24Direction, float: DType) -> Option<String> {
let f = float_suffix(float)?;
Some(match direction {
Rgb24Direction::Unpack => format!("rgb24_to_float_{f}"),
Rgb24Direction::Pack => format!("float_to_rgb24_{f}"),
})
}
unsafe fn launch<A: DeviceRepr>(
context: &Arc<CudaContext>,
stream: &GuardedStream,
device_index: usize,
name: &str,
total: u64,
args: &A,
) -> Result<()> {
if total == 0 {
return Ok(());
}
let module = get_or_load_module(context, device_index, COLOR_MODULE)?;
let func = get_kernel_function(&module, name)?;
let blocks = total.div_ceil(u64::from(BLOCK_SIZE));
let grid = (blocks.min(u64::from(MAX_GRID_DIM_X)) as u32, 1, 1);
let cfg = launch_config(grid, (BLOCK_SIZE, 1, 1), 0);
unsafe {
let mut builder = stream.launch_builder(&func);
builder.arg(args);
builder
.launch(cfg)
.map_err(|e| Error::Internal(format!("CUDA kernel '{name}' launch failed: {e:?}")))?;
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub unsafe fn launch_yuv(
context: &Arc<CudaContext>,
stream: &GuardedStream,
device_index: usize,
direction: YuvDirection,
frame: &YuvFrame,
float: DType,
rgb_ptr: u64,
rgb_strides: [isize; 3],
) -> Result<()> {
let op = match direction {
YuvDirection::ToRgb => "yuv_to_rgb",
YuvDirection::ToYuv => "rgb_to_yuv",
};
let name = yuv_kernel_name(direction, frame.wide, float)
.ok_or(Error::UnsupportedDType { dtype: float, op })?;
let total = match direction {
YuvDirection::ToRgb => frame.pixels(),
YuvDirection::ToYuv => frame.pixels() / 4,
} as u64;
let [rgb_c, rgb_h, rgb_w] = rgb_strides.map(|s| s as i64);
let args = YuvKernelArgs {
y: frame.y.into(),
u: frame.u.into(),
v: frame.v.into(),
rgb: rgb_ptr,
rgb_c,
rgb_h,
rgb_w,
height: frame.height as i64,
width: frame.width as i64,
k: frame.coeffs,
shift: frame.shift,
center: u32::from(frame.center),
};
unsafe { launch(context, stream, device_index, &name, total, &args) }
}
#[derive(Debug, Clone, Copy)]
pub struct Rgb24Launch {
pub direction: Rgb24Direction,
pub float: DType,
pub size: [usize; 2],
pub src: u64,
pub dst: u64,
pub src_strides: [isize; 3],
pub dst_strides: [isize; 3],
}
pub unsafe fn launch_rgb24(
context: &Arc<CudaContext>,
stream: &GuardedStream,
device_index: usize,
l: &Rgb24Launch,
) -> Result<()> {
let op = match l.direction {
Rgb24Direction::Unpack => "rgb24_to_float",
Rgb24Direction::Pack => "float_to_rgb24",
};
let name = rgb24_kernel_name(l.direction, l.float)
.ok_or(Error::UnsupportedDType { dtype: l.float, op })?;
let [h, w] = l.size;
let args = Rgb24KernelArgs {
src: l.src,
dst: l.dst,
src_strides: l.src_strides.map(|s| s as i64),
dst_strides: l.dst_strides.map(|s| s as i64),
height: h as i64,
width: w as i64,
};
let total = (h * w * 3) as u64;
unsafe { launch(context, stream, device_index, &name, total, &args) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn kernel_names_cover_every_dtype_pair() {
assert_eq!(
yuv_kernel_name(YuvDirection::ToRgb, true, DType::BF16).as_deref(),
Some("yuv_to_rgb_u16_bf16")
);
assert_eq!(
yuv_kernel_name(YuvDirection::ToYuv, false, DType::F64).as_deref(),
Some("rgb_to_yuv_f64_u8")
);
assert_eq!(
rgb24_kernel_name(Rgb24Direction::Pack, DType::F16).as_deref(),
Some("float_to_rgb24_f16")
);
assert_eq!(
yuv_kernel_name(YuvDirection::ToRgb, false, DType::I32),
None
);
}
#[test]
fn argument_structs_match_the_cuda_layout() {
assert_eq!(std::mem::size_of::<ColorCoeffs>(), 64);
assert_eq!(std::mem::size_of::<YuvKernelArgs>(), 192);
assert_eq!(std::mem::size_of::<Rgb24KernelArgs>(), 80);
}
}