yuv2rgb 0.0.2

Functions for converting images between colorspaces
Documentation
use std::mem::size_of;

use anyhow::{bail, Result};
use image::{DynamicImage, Rgb32FImage};

use crate::{pixel::CastFromPrimitive, Pixel, Rgb16Image};

/// A representation of a YUV image as raw planar data.
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,
{
    /// Creates a representation of a YUV image as raw planar data.
    ///
    /// # Errors
    ///
    /// - If the resolution information provided does not match the resolution of the planes.
    /// - If chroma planes are missing when they should exist.
    /// - If chroma planes are provided for a grayscale (YUV400) image.
    /// - If the bit depth provided does not match the size of `T`.
    #[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,
        })
    }

    /// Converts this YUV image to RGB32F
    #[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)| {
            // Assumes BT.709
            // TODO: Actually implement different colorspaces
            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));

            // [-0.804677, 1.81723]
            let r = 1.28033f32.mul_add(v, y);
            // [−0.316650, 1.09589]
            let g = y - 0.21482 * u - 0.38059 * v;
            // [-1.28905, 2.29781]
            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)| {
                    // SAFETY: YUVImage can only be instantiated with valid data,
                    // so the bounds of these planes will always be correct.
                    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")
    }

    /// Converts this YUV image to RGB16
    #[must_use]
    pub fn to_rgb16(&self) -> Rgb16Image {
        DynamicImage::ImageRgb32F(self.to_rgb32f()).into_rgb16()
    }
}

/// Chroma subsampling format
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum ChromaSampling {
    /// Both vertically and horizontally subsampled.
    YUV420,
    /// Horizontally subsampled.
    YUV422,
    /// Not subsampled.
    YUV444,
    /// Monochrome.
    YUV400,
}