use super::super::kernels::{
PlaneSample, Rgb24Geometry, float_to_rgb24_kernel, rgb_to_yuv_kernel, rgb24_to_float_kernel,
yuv_to_rgb_kernel,
};
use super::super::{CpuClient, CpuRuntime};
use crate::dtype::{DType, Element};
use crate::error::{Error, Result};
use crate::ops::ConvLayout;
use crate::ops::common::{YuvFrame, rgb_strides, rgb24_strides};
use crate::tensor::Tensor;
pub fn color_float_ok(dtype: DType) -> bool {
matches!(dtype, DType::F32 | DType::F64)
|| (cfg!(feature = "f16") && matches!(dtype, DType::F16 | DType::BF16))
}
macro_rules! with_float {
($dtype:expr, $op:expr, $t:ident => $body:expr) => {
match $dtype {
DType::F32 => {
type $t = f32;
$body
}
DType::F64 => {
type $t = f64;
$body
}
#[cfg(feature = "f16")]
DType::F16 => {
type $t = half::f16;
$body
}
#[cfg(feature = "f16")]
DType::BF16 => {
type $t = half::bf16;
$body
}
dtype => return Err(Error::UnsupportedDType { dtype, op: $op }),
}
};
}
pub(crate) use with_float;
unsafe fn decode_samples<P: PlaneSample, O: Element>(
client: &CpuClient,
frame: &YuvFrame,
out: &Tensor<CpuRuntime>,
layout: ConvLayout,
) {
let strides = rgb_strides(out.strides(), layout);
unsafe { yuv_to_rgb_kernel::<P, O>(client, frame, out.ptr() as *mut O, strides) }
}
pub fn yuv_to_rgb_run(
client: &CpuClient,
frame: &YuvFrame,
out: &Tensor<CpuRuntime>,
layout: ConvLayout,
) -> Result<()> {
with_float!(out.dtype(), "yuv_to_rgb", T => {
unsafe {
if frame.wide {
decode_samples::<u16, T>(client, frame, out, layout);
} else {
decode_samples::<u8, T>(client, frame, out, layout);
}
}
});
Ok(())
}
pub fn rgb_to_yuv_run(
client: &CpuClient,
frame: &YuvFrame,
rgb: &Tensor<CpuRuntime>,
layout: ConvLayout,
) -> Result<()> {
let strides = rgb_strides(rgb.strides(), layout);
with_float!(rgb.dtype(), "rgb_to_yuv", T => {
let src = rgb.ptr() as *const T;
unsafe {
if frame.wide {
rgb_to_yuv_kernel::<T, u16>(client, frame, src, strides);
} else {
rgb_to_yuv_kernel::<T, u8>(client, frame, src, strides);
}
}
});
Ok(())
}
pub fn rgb24_to_float_run(
client: &CpuClient,
rgb24: &Tensor<CpuRuntime>,
out: &Tensor<CpuRuntime>,
layout: ConvLayout,
size: [usize; 2],
) -> Result<()> {
let g = Rgb24Geometry {
size,
src_strides: rgb24_strides(rgb24.strides()),
dst_strides: rgb_strides(out.strides(), layout),
};
with_float!(out.dtype(), "rgb24_to_float", T => {
unsafe {
rgb24_to_float_kernel::<T>(client, rgb24.ptr() as *const u8, out.ptr() as *mut T, g)
}
});
Ok(())
}
pub fn float_to_rgb24_run(
client: &CpuClient,
rgb: &Tensor<CpuRuntime>,
out: &Tensor<CpuRuntime>,
layout: ConvLayout,
size: [usize; 2],
) -> Result<()> {
let g = Rgb24Geometry {
size,
src_strides: rgb_strides(rgb.strides(), layout),
dst_strides: rgb24_strides(out.strides()),
};
with_float!(rgb.dtype(), "float_to_rgb24", T => {
unsafe {
float_to_rgb24_kernel::<T>(client, rgb.ptr() as *const T, out.ptr() as *mut u8, g)
}
});
Ok(())
}