use alloc::vec::Vec;
use crate::error::{Error, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ChromaFormat {
Monochrome,
#[default]
Yuv420,
Yuv422,
Yuv444,
}
impl ChromaFormat {
pub const fn from_idc(idc: u8) -> Option<ChromaFormat> {
Some(match idc {
0 => ChromaFormat::Monochrome,
1 => ChromaFormat::Yuv420,
2 => ChromaFormat::Yuv422,
3 => ChromaFormat::Yuv444,
_ => return None,
})
}
pub const fn x_shift(self) -> u32 {
match self {
ChromaFormat::Yuv420 | ChromaFormat::Yuv422 => 1,
_ => 0,
}
}
pub const fn y_shift(self) -> u32 {
match self {
ChromaFormat::Yuv420 => 1,
_ => 0,
}
}
pub const fn chroma_size(self, width: u32, height: u32) -> (u32, u32) {
if matches!(self, ChromaFormat::Monochrome) {
return (0, 0);
}
(
width.div_ceil(1 << self.x_shift()),
height.div_ceil(1 << self.y_shift()),
)
}
}
#[derive(Debug, Clone, Default)]
pub struct Frame {
pub width: u32,
pub height: u32,
pub bit_depth: u8,
pub chroma: ChromaFormat,
pub y: Vec<u16>,
pub cb: Vec<u16>,
pub cr: Vec<u16>,
pub y_stride: u32,
pub c_stride: u32,
}
impl Frame {
pub fn validate(&self) -> Result<()> {
if self.width == 0 || self.height == 0 {
return Err(Error::Malformed("decoded frame has a zero dimension"));
}
if self.y_stride < self.width {
return Err(Error::Malformed("luma stride is narrower than the frame"));
}
let need = (self.y_stride as usize).saturating_mul(self.height as usize);
if self.y.len() < need {
return Err(Error::Malformed("luma plane is shorter than its geometry"));
}
if self.chroma == ChromaFormat::Monochrome {
return Ok(());
}
let (cw, ch) = self.chroma.chroma_size(self.width, self.height);
if self.c_stride < cw {
return Err(Error::Malformed("chroma stride is narrower than the frame"));
}
let need = (self.c_stride as usize).saturating_mul(ch as usize);
if self.cb.len() < need || self.cr.len() < need {
return Err(Error::Malformed(
"chroma plane is shorter than its geometry",
));
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VideoSignal {
pub full_range: bool,
pub description: Option<[u8; 3]>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Info {
pub width: u32,
pub height: u32,
pub bit_depth: u8,
pub chroma: ChromaFormat,
}