use super::color_packed::{packed_interleaved_views, packed_view};
use super::color_validation::validate_planes;
use crate::dtype::DType;
use crate::error::{Error, Result};
use crate::ops::traits::{ChromaSiting, ColorRange, ConvLayout, YuvPlanes, YuvSpec};
use crate::runtime::Runtime;
use crate::tensor::Tensor;
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ColorCoeffs {
pub y_off: i32,
pub c_off: i32,
pub c_div16: f32,
pub cr_r: f32,
pub cb_b: f32,
pub g_cb: f32,
pub g_cr: f32,
pub kr: f32,
pub kg: f32,
pub kb: f32,
pub y_mul: f32,
pub c_mul: f32,
pub y_lo: f32,
pub y_hi: f32,
pub c_lo: f32,
pub c_hi: f32,
}
impl ColorCoeffs {
pub fn new(spec: &YuvSpec, bits: u32) -> Self {
let (kr, kb) = spec.matrix.kr_kb();
let kg = 1.0 - kr - kb;
let s = f64::from(1u32 << bits.saturating_sub(8));
let max = f64::from((1u32 << bits) - 1);
let (y_off, c_off, y_mul, c_mul, y_lo, y_hi, c_lo, c_hi) = match spec.range {
ColorRange::Limited => (
16.0 * s,
128.0 * s,
219.0 * s,
224.0 * s,
16.0 * s,
235.0 * s,
16.0 * s,
240.0 * s,
),
ColorRange::Full => (0.0, (max + 1.0) / 2.0, max, max, 0.0, max, 0.0, max),
};
Self {
y_off: y_off as i32,
c_off: c_off as i32,
c_div16: (16.0 * c_mul) as f32,
cr_r: (2.0 * (1.0 - kr)) as f32,
cb_b: (2.0 * (1.0 - kb)) as f32,
g_cb: (-2.0 * kb * (1.0 - kb) / kg) as f32,
g_cr: (-2.0 * kr * (1.0 - kr) / kg) as f32,
kr: kr as f32,
kg: kg as f32,
kb: kb as f32,
y_mul: y_mul as f32,
c_mul: c_mul as f32,
y_lo: y_lo as f32,
y_hi: y_hi as f32,
c_lo: c_lo as f32,
c_hi: c_hi as f32,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PlaneView {
pub addr: u64,
pub row_stride: isize,
pub col_stride: isize,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct YuvFrame {
pub height: usize,
pub width: usize,
pub wide: bool,
pub shift: u32,
pub center: bool,
pub y: PlaneView,
pub u: PlaneView,
pub v: PlaneView,
pub coeffs: ColorCoeffs,
}
impl YuvFrame {
pub fn pixels(&self) -> usize {
self.height * self.width
}
}
fn plane_view<R: Runtime<DType = DType>>(t: &Tensor<R>) -> PlaneView {
PlaneView {
addr: t.ptr(),
row_stride: t.strides()[0],
col_stride: t.strides()[1],
}
}
fn split_interleaved<R: Runtime<DType = DType>>(
uv: &Tensor<R>,
op: &'static str,
) -> Result<(PlaneView, PlaneView)> {
let base = plane_view(uv);
let elem = uv.dtype().size_in_bytes() as i64;
let pair = base.col_stride.checked_mul(2);
let v_shift = (base.col_stride as i64).checked_mul(elem);
let (Some(pair), Some(v_shift)) = (pair, v_shift) else {
return Err(Error::InvalidArgument {
arg: "planes",
reason: format!(
"{op}: plane uv column stride {} overflows when doubled; pass a view with a \
smaller column stride",
base.col_stride
),
});
};
let u = PlaneView {
col_stride: pair,
..base
};
let v = PlaneView {
addr: base.addr.wrapping_add_signed(v_shift),
..u
};
Ok((u, v))
}
pub fn plan_yuv_frame<R: Runtime<DType = DType>>(
planes: &YuvPlanes<'_, R>,
spec: &YuvSpec,
op: &'static str,
) -> Result<YuvFrame> {
let [height, width] = validate_planes(planes, op)?;
let bytes = planes.sample_bytes();
let (y, (u, v)) = match *planes {
YuvPlanes::Nv12 { y, uv } | YuvPlanes::P010 { y, uv } => {
(plane_view(y), split_interleaved(uv, op)?)
}
YuvPlanes::I420 { y, u, v } => (plane_view(y), (plane_view(u), plane_view(v))),
YuvPlanes::Nv12Packed { y, uv } | YuvPlanes::P010Packed { y, uv } => (
packed_view(&y, bytes, op)?,
packed_interleaved_views(&uv, bytes, op)?,
),
YuvPlanes::I420Packed { y, u, v } => (
packed_view(&y, bytes, op)?,
(packed_view(&u, bytes, op)?, packed_view(&v, bytes, op)?),
),
};
let wide = bytes == 2;
Ok(YuvFrame {
height,
width,
wide,
shift: if wide { 6 } else { 0 },
center: spec.siting == ChromaSiting::Center,
y,
u,
v,
coeffs: ColorCoeffs::new(spec, planes.bits()),
})
}
pub fn rgb_strides(strides: &[isize], layout: ConvLayout) -> [isize; 3] {
match layout {
ConvLayout::Nchw => [strides[1], strides[2], strides[3]],
ConvLayout::Nhwc => [strides[3], strides[1], strides[2]],
}
}
pub fn rgb24_strides(strides: &[isize]) -> [isize; 3] {
[strides[2], strides[0], strides[1]]
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ops::traits::ColorMatrix;
use crate::runtime::cpu::{CpuDevice, CpuRuntime};
#[test]
fn limited_8bit_constants() {
let spec = YuvSpec::new(ColorMatrix::Bt709, ColorRange::Limited, ChromaSiting::Left);
let k = ColorCoeffs::new(&spec, 8);
assert_eq!((k.y_off, k.c_off), (16, 128));
assert_eq!((k.y_mul, k.c_mul), (219.0, 224.0));
assert_eq!((k.y_lo, k.y_hi, k.c_lo, k.c_hi), (16.0, 235.0, 16.0, 240.0));
assert_eq!(k.cr_r, 1.5748);
assert_eq!(k.cb_b, 1.8556);
}
#[test]
fn full_10bit_constants() {
let spec = YuvSpec::new(ColorMatrix::Bt601, ColorRange::Full, ChromaSiting::Center);
let k = ColorCoeffs::new(&spec, 10);
assert_eq!((k.y_off, k.c_off), (0, 512));
assert_eq!((k.y_mul, k.y_hi, k.c_hi), (1023.0, 1023.0, 1023.0));
assert_eq!(k.c_div16, 16.0 * 1023.0);
}
#[test]
fn interleaved_chroma_splits_into_u_and_v() {
let uv = Tensor::<CpuRuntime>::zeros(&[2, 8], DType::U16, &CpuDevice::new()).unwrap();
let (u, v) = split_interleaved(&uv, "t").unwrap();
assert_eq!((u.row_stride, u.col_stride), (8, 2));
assert_eq!(v.addr, u.addr + 2);
assert_eq!(v.col_stride, 2);
}
}