mod mosaic;
use alloc::vec::Vec;
use crate::error::{Error, Result};
use crate::hevc::Frame;
use crate::image::check_pixels;
use crate::reader::Reader;
pub use mosaic::Mosaic;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Grid {
pub rows: u32,
pub columns: u32,
pub output_width: u32,
pub output_height: u32,
}
impl Grid {
pub const fn tile_count(&self) -> u64 {
self.rows as u64 * self.columns as u64
}
}
pub fn parse(data: &[u8]) -> Result<Grid> {
let mut r = Reader::new(data);
let version = r.u8("grid version")?;
if version != 0 {
return Err(Error::Unsupported("grid version above 0"));
}
let flags = r.u8("grid flags")?;
let rows = u32::from(r.u8("grid rows")?) + 1;
let columns = u32::from(r.u8("grid columns")?) + 1;
let (output_width, output_height) = if flags & 1 != 0 {
(r.u32("grid output width")?, r.u32("grid output height")?)
} else {
(
u32::from(r.u16("grid output width")?),
u32::from(r.u16("grid output height")?),
)
};
if output_width == 0 || output_height == 0 {
return Err(Error::Malformed("grid declares a zero output dimension"));
}
Ok(Grid {
rows,
columns,
output_width,
output_height,
})
}
pub fn check_tiles(grid: &Grid, tiles: &[u32]) -> Result<()> {
if tiles.len() as u64 != grid.tile_count() {
return Err(Error::Malformed(
"the grid's tile count disagrees with the length of its dimg reference",
));
}
Ok(())
}
pub fn compose(grid: &Grid, tiles: &[Frame], max_pixels: u64) -> Result<Frame> {
let mosaic = Mosaic::new(grid, tiles)?;
check_pixels(mosaic.width(), mosaic.height(), max_pixels)?;
let (w, h) = (mosaic.width() as usize, mosaic.height() as usize);
let (cw, ch) = mosaic.chroma_size();
let (cw, ch) = (cw as usize, ch as usize);
fn short() -> Error {
Error::Malformed("grid tile is shorter than the row it must supply")
}
let mut y = alloc::vec![0u16; w * h];
for (r, row) in y.chunks_exact_mut(w).enumerate() {
mosaic.luma_row(r, row).ok_or_else(short)?;
}
let mut cb = alloc::vec![0u16; cw * ch];
let mut cr = alloc::vec![0u16; cw * ch];
if cw > 0 {
for (r, row) in cb.chunks_exact_mut(cw).enumerate() {
mosaic.chroma_row(false, r, row).ok_or_else(short)?;
}
for (r, row) in cr.chunks_exact_mut(cw).enumerate() {
mosaic.chroma_row(true, r, row).ok_or_else(short)?;
}
}
Ok(Frame {
width: mosaic.width(),
height: mosaic.height(),
bit_depth: mosaic.bit_depth(),
chroma: mosaic.chroma(),
y,
cb,
cr,
y_stride: mosaic.width(),
c_stride: cw as u32,
})
}
pub fn tile_ids(refs: &[crate::meta::iref::ItemReference], grid_item: u32) -> Vec<u32> {
crate::meta::iref::targets(refs, grid_item, crate::meta::iref::RefKind::Dimg).to_vec()
}