use std::mem::size_of;
use anyhow::{bail, Result};
use image::{DynamicImage, Rgb32FImage};
use crate::{pixel::CastFromPrimitive, Pixel, Rgb16Image};
pub struct YUVImage<'a, T: Pixel> {
width: u32,
height: u32,
chroma_sampling: ChromaSampling,
bit_depth: u8,
y: &'a [T],
u: Option<&'a [T]>,
v: Option<&'a [T]>,
}
impl<'a, T> YUVImage<'a, T>
where
T: Pixel,
{
#[allow(clippy::missing_panics_doc)]
pub fn new(
width: u32,
height: u32,
chroma_sampling: ChromaSampling,
bit_depth: u8,
y: &'a [T],
u: Option<&'a [T]>,
v: Option<&'a [T]>,
) -> Result<Self> {
let pixels = (width * height) as usize;
if pixels == 0 {
bail!("Width and height must be greater than 0");
}
if y.len() != pixels {
bail!("Size of Y plane did not match passed width and height");
}
if (chroma_sampling == ChromaSampling::YUV420 || chroma_sampling == ChromaSampling::YUV422)
&& (width % 2 != 0 || height % 2 != 0)
{
bail!("Width and height must be multiples of 2 for subsampled chroma");
}
match chroma_sampling {
ChromaSampling::YUV400 => {
if u.is_some() || v.is_some() {
bail!("Found unexpected chroma data with grayscale YUV image");
}
}
ChromaSampling::YUV420 => {
if u.is_none() || v.is_none() {
bail!("Expected 3 planes of YUV data");
}
if u.as_ref().unwrap().len() != pixels / 4
|| v.as_ref().unwrap().len() != pixels / 4
{
bail!("Expected chroma planes to be 1/4 resolution for 4:2:0 subsampled image");
}
}
ChromaSampling::YUV422 => {
if u.is_none() || v.is_none() {
bail!("Expected 3 planes of YUV data");
}
if u.as_ref().unwrap().len() != pixels / 2
|| v.as_ref().unwrap().len() != pixels / 2
{
bail!("Expected chroma planes to be 1/2 resolution for 4:2:2 subsampled image");
}
}
ChromaSampling::YUV444 => {
if u.is_none() || v.is_none() {
bail!("Expected 3 planes of YUV data");
}
if u.as_ref().unwrap().len() != pixels || v.as_ref().unwrap().len() != pixels {
bail!("Expected chroma planes to match luma resolution for 4:4:4 YUV image");
}
}
}
if size_of::<T>() == 1 && bit_depth > 8 {
bail!("Expected >8-bit image but received 1 byte per pixel");
}
if size_of::<T>() == 2 && bit_depth <= 8 {
bail!("Expected 8-bit image but received 2 bytes per pixel");
}
Ok(YUVImage {
width,
height,
chroma_sampling,
bit_depth,
y,
u,
v,
})
}
#[must_use]
pub fn to_rgb32f(&self) -> Rgb32FImage {
let scale = f32::from(1u16 << (self.bit_depth - 8));
let yuv_to_rgb = |yuv: (u16, u16, u16)| {
let y = (f32::from(yuv.0) - 16. * scale) * (1. / (219. * scale));
let u = (f32::from(yuv.1) - 128. * scale) * (1. / (224. * scale));
let v = (f32::from(yuv.2) - 128. * scale) * (1. / (224. * scale));
let r = 1.28033f32.mul_add(v, y);
let g = y - 0.21482 * u - 0.38059 * v;
let b = 2.12798f32.mul_add(u, y);
(r, g, b)
};
let y = &self.y;
let u = &self.u.unwrap_or(self.y);
let v = &self.v.unwrap_or(self.y);
let subsampling = match self.chroma_sampling {
ChromaSampling::YUV400 | ChromaSampling::YUV444 => 1,
ChromaSampling::YUV422 => 2,
ChromaSampling::YUV420 => 4,
};
Rgb32FImage::from_vec(
self.width,
self.height,
y.iter()
.enumerate()
.flat_map(|(i, y)| {
let rgbf = unsafe {
yuv_to_rgb((
u16::cast_from(*y),
u16::cast_from(*u.get_unchecked(i / subsampling)),
u16::cast_from(*v.get_unchecked(i / subsampling)),
))
};
[rgbf.0, rgbf.1, rgbf.2].into_iter()
})
.collect(),
)
.expect("conversion produced invalid values for RGBF")
}
#[must_use]
pub fn to_rgb16(&self) -> Rgb16Image {
DynamicImage::ImageRgb32F(self.to_rgb32f()).into_rgb16()
}
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum ChromaSampling {
YUV420,
YUV422,
YUV444,
YUV400,
}