use crate::Window;
use crate::codestream::markers::Siz;
use crate::jp2::Jp2Metadata;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Header {
pub width: u32,
pub height: u32,
pub components: Vec<ComponentInfo>,
pub max_reduction: u8,
pub quality_layers: u16,
pub image_area: Window,
pub tiles: TileGrid,
pub jp2: Option<Jp2Metadata>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct TileGrid {
pub columns: u32,
pub rows: u32,
pub tile_width: u32,
pub tile_height: u32,
pub x_offset: u32,
pub y_offset: u32,
image: Window,
}
impl TileGrid {
#[must_use]
pub const fn count(&self) -> u32 {
self.columns.saturating_mul(self.rows)
}
#[must_use]
pub fn tile(&self, index: u32) -> Option<Window> {
if index >= self.count() {
return None;
}
let (p, q) = (
u64::from(index % self.columns),
u64::from(index / self.columns),
);
let (w, h) = (u64::from(self.tile_width), u64::from(self.tile_height));
let (xo, yo) = (u64::from(self.x_offset), u64::from(self.y_offset));
let image = self.image;
let clamp = |v: u64, lo: u32, hi: u32| v.clamp(u64::from(lo), u64::from(hi)) as u32;
Some(Window::new(
clamp(xo + p * w, image.x0, image.x1),
clamp(yo + q * h, image.y0, image.y1),
clamp(xo + (p + 1) * w, image.x0, image.x1),
clamp(yo + (q + 1) * h, image.y0, image.y1),
))
}
pub(crate) fn of_siz(siz: &Siz) -> Self {
let (columns, rows) = siz.tile_grid();
TileGrid {
columns,
rows,
tile_width: siz.tile_width,
tile_height: siz.tile_height,
x_offset: siz.tile_x_offset,
y_offset: siz.tile_y_offset,
image: image_area(siz),
}
}
}
pub(crate) fn image_area(siz: &Siz) -> Window {
Window::new(siz.x_offset, siz.y_offset, siz.x_size, siz.y_size)
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ComponentInfo {
pub bit_depth: u8,
pub signed: bool,
pub x_sampling: u8,
pub y_sampling: u8,
pub width: u32,
pub height: u32,
}
impl ComponentInfo {
pub(crate) fn on_grid(
siz: &Siz,
bit_depth: u8,
signed: bool,
x_sampling: u8,
y_sampling: u8,
reduction: u8,
) -> Self {
let (width, height) = siz
.sampled_extent_at(x_sampling, y_sampling, reduction)
.unwrap_or((0, 0));
ComponentInfo {
bit_depth,
signed,
x_sampling,
y_sampling,
width,
height,
}
}
pub(crate) fn of_siz(siz: &Siz, reduction: u8) -> Vec<Self> {
siz.components
.iter()
.map(|c| {
Self::on_grid(
siz,
c.bit_depth,
c.signed,
c.x_sampling,
c.y_sampling,
reduction,
)
})
.collect()
}
}