use crate::codestream::MainHeader;
use crate::codestream::markers::Rect;
use crate::{Error, Result};
use super::BandKind;
pub(crate) const MAX_PRECINCTS: usize = 1 << 18;
pub(crate) const MAX_CODE_BLOCKS: usize = 1 << 20;
pub(crate) struct BandGeom {
pub(crate) kind: BandKind,
pub(crate) origin: (u32, u32),
pub(crate) width: usize,
pub(crate) height: usize,
pub(crate) block_cols: usize,
pub(crate) block_rows: usize,
pub(crate) bounds: (i64, i64, i64, i64),
pub(crate) first_block: (i64, i64),
pub(crate) block_exp: (u32, u32),
pub(crate) precincts: Vec<PrecinctGeom>,
}
pub(crate) struct PrecinctGeom {
pub(crate) cols: usize,
pub(crate) rows: usize,
pub(crate) first: usize,
pub(crate) stride: usize,
}
impl PrecinctGeom {
pub(crate) fn block(&self, x: usize, y: usize) -> usize {
self.first + y * self.stride + x
}
}
impl BandGeom {
pub(crate) fn block_count(&self) -> usize {
self.block_cols * self.block_rows
}
pub(crate) fn block_rects(&self) -> impl Iterator<Item = (usize, usize, usize, usize)> + use<> {
let (bx0, bx1, by0, by1) = self.bounds;
let (first_col, first_row) = self.first_block;
let cbw = 1i64 << self.block_exp.0;
let cbh = 1i64 << self.block_exp.1;
let cols = self.block_cols;
(0..self.block_rows).flat_map(move |j| {
let gy0 = (first_row + j as i64) * cbh;
let cy0 = gy0.max(by0);
let cy1 = (gy0 + cbh).min(by1);
(0..cols).map(move |i| {
let gx0 = (first_col + i as i64) * cbw;
let cx0 = gx0.max(bx0);
let cx1 = (gx0 + cbw).min(bx1);
(
(cx0 - bx0) as usize,
(cy0 - by0) as usize,
(cx1 - cx0) as usize,
(cy1 - cy0) as usize,
)
})
})
}
}
pub(crate) struct ResolutionGeom {
pub(crate) ppx: u32,
pub(crate) ppy: u32,
pub(crate) precincts_wide: usize,
pub(crate) precincts_high: usize,
pub(crate) bands: Vec<BandGeom>,
}
impl ResolutionGeom {
pub(crate) fn heap_bytes(&self) -> usize {
self.bands.capacity() * std::mem::size_of::<BandGeom>()
+ self
.bands
.iter()
.map(|b| b.precincts.capacity() * std::mem::size_of::<PrecinctGeom>())
.sum::<usize>()
}
pub(crate) fn precinct_count(&self) -> usize {
self.precincts_wide * self.precincts_high
}
}
fn ceil_shr(a: i64, exp: u32) -> i64 {
debug_assert!(exp < 63, "ceil_shr needs a shift below 63");
-((-a) >> exp)
}
pub(crate) fn band_rects(
rect: Rect,
nl: u32,
r: u32,
) -> impl Iterator<Item = (BandKind, i64, i64, i64, i64)> {
debug_assert!(r <= nl && nl <= 32, "resolution {r} of {nl} levels");
let (tcx0, tcx1) = (i64::from(rect.x0), i64::from(rect.x1));
let (tcy0, tcy1) = (i64::from(rect.y0), i64::from(rect.y1));
let level = nl - r;
let bands = if r == 0 {
let ll = (
BandKind::Ll,
ceil_shr(tcx0, level),
ceil_shr(tcx1, level),
ceil_shr(tcy0, level),
ceil_shr(tcy1, level),
);
[ll; 3]
} else {
let nb = level + 1;
let half = 1i64 << (nb - 1);
[
(BandKind::Hl, 1, 0),
(BandKind::Lh, 0, 1),
(BandKind::Hh, 1, 1),
]
.map(|(kind, xob, yob)| {
(
kind,
ceil_shr(tcx0 - xob * half, nb),
ceil_shr(tcx1 - xob * half, nb),
ceil_shr(tcy0 - yob * half, nb),
ceil_shr(tcy1 - yob * half, nb),
)
})
};
bands.into_iter().take(if r == 0 { 1 } else { 3 })
}
pub(crate) fn resolution_geoms(
header: &MainHeader,
tile: u32,
comp: usize,
precinct_budget: &mut usize,
block_budget: &mut usize,
) -> Result<Vec<ResolutionGeom>> {
let siz = &header.siz;
let cod = &header
.components
.get(comp)
.ok_or_else(|| Error::inconsistent(format!("no coding parameters for component {comp}")))?
.coding;
let nl = cod.decomposition_levels as i64;
if nl > 32 {
return Err(Error::inconsistent(format!(
"{nl} decomposition levels exceed the 32-level maximum"
)));
}
let rect = siz.tile_component_rect(tile, comp).ok_or_else(|| {
Error::inconsistent(format!("no tile {tile} or no component {comp} in `SIZ`"))
})?;
if rect.is_empty() {
return Err(Error::codestream(format!(
"tile {tile} has an empty area on component {comp}"
)));
}
let (tcx0, tcx1) = (i64::from(rect.x0), i64::from(rect.x1));
let (tcy0, tcy1) = (i64::from(rect.y0), i64::from(rect.y1));
let xcb = cod.code_block_width as u32 + 2;
let ycb = cod.code_block_height as u32 + 2;
if xcb > 10 || ycb > 10 || xcb + ycb > 12 {
return Err(Error::marker(format!(
"code-block size 2^{xcb} x 2^{ycb} is over the 4096-sample limit"
)));
}
let mut levels = Vec::with_capacity((nl + 1) as usize);
for r in 0..=nl {
let level = nl - r;
let shift = level as u32;
let (trx0, trx1) = (ceil_shr(tcx0, shift), ceil_shr(tcx1, shift));
let (try0, try1) = (ceil_shr(tcy0, shift), ceil_shr(tcy1, shift));
let (ppx, ppy) = cod.precinct(r as usize);
debug_assert!(r == 0 || (ppx >= 1 && ppy >= 1));
let (precincts_wide, tl_prc_x) = prc_span(trx0, trx1, ppx);
let (precincts_high, tl_prc_y) = prc_span(try0, try1, ppy);
let here = precincts_wide.checked_mul(precincts_high);
match here.filter(|&n| n <= *precinct_budget) {
Some(n) => *precinct_budget -= n,
None => {
return Err(Error::limit_fixed(
crate::LimitKind::TilePrecincts,
format!(
"tile {tile} holds more than {MAX_PRECINCTS} precincts, the limit for a tile"
),
));
}
}
let cbg = if r == 0 {
Cbg {
x0: tl_prc_x,
y0: tl_prc_y,
x_exp: ppx,
y_exp: ppy,
wide: precincts_wide,
high: precincts_high,
}
} else {
Cbg {
x0: ceil_shr(tl_prc_x, 1),
y0: ceil_shr(tl_prc_y, 1),
x_exp: ppx - 1,
y_exp: ppy - 1,
wide: precincts_wide,
high: precincts_high,
}
};
let (xcb, ycb) = (xcb.min(cbg.x_exp), ycb.min(cbg.y_exp));
let mut bands = Vec::new();
if precincts_wide * precincts_high > 0 {
bands.reserve_exact(if r == 0 { 1 } else { 3 });
for (kind, bx0, bx1, by0, by1) in band_rects(rect, nl as u32, r as u32) {
bands.push(band_geom(
kind,
bx0,
bx1,
by0,
by1,
xcb,
ycb,
&cbg,
tile,
block_budget,
)?);
}
}
levels.push(ResolutionGeom {
ppx,
ppy,
precincts_wide,
precincts_high,
bands,
});
}
Ok(levels)
}
struct Cbg {
x0: i64,
y0: i64,
x_exp: u32,
y_exp: u32,
wide: usize,
high: usize,
}
fn prc_span(lo: i64, hi: i64, exp: u32) -> (usize, i64) {
if hi <= lo {
return (0, 0);
}
let first = lo >> exp;
((ceil_shr(hi, exp) - first) as usize, first << exp)
}
#[allow(clippy::too_many_arguments)]
fn band_geom(
kind: BandKind,
bx0: i64,
bx1: i64,
by0: i64,
by1: i64,
xcb: u32,
ycb: u32,
cbg: &Cbg,
tile: u32,
block_budget: &mut usize,
) -> Result<BandGeom> {
let width = (bx1 - bx0).max(0) as usize;
let height = (by1 - by0).max(0) as usize;
let (block_cols, first_col) = grid_span(bx0, bx1, xcb);
let (block_rows, first_row) = grid_span(by0, by1, ycb);
match block_cols
.checked_mul(block_rows)
.filter(|&n| n <= *block_budget)
{
Some(n) => *block_budget -= n,
None => {
return Err(Error::limit_fixed(
crate::LimitKind::TileCodeBlocks,
format!(
"tile {tile} holds more than {MAX_CODE_BLOCKS} code-blocks, the limit for a tile"
),
));
}
}
let group_w = 1i64 << cbg.x_exp;
let group_h = 1i64 << cbg.y_exp;
let mut precincts = Vec::with_capacity(cbg.wide * cbg.high);
for j in 0..cbg.high {
let gy0 = cbg.y0 + j as i64 * group_h;
let (py0, py1) = (gy0.max(by0), (gy0 + group_h).min(by1));
for i in 0..cbg.wide {
let gx0 = cbg.x0 + i as i64 * group_w;
let (px0, px1) = (gx0.max(bx0), (gx0 + group_w).min(bx1));
let (cols, col0) = grid_span(px0, px1, xcb);
let (rows, row0) = grid_span(py0, py1, ycb);
let first = if cols * rows == 0 {
0
} else {
(row0 - first_row) as usize * block_cols + (col0 - first_col) as usize
};
precincts.push(PrecinctGeom {
cols,
rows,
first,
stride: block_cols,
});
}
}
debug_assert_eq!(
precincts.iter().map(|p| p.cols * p.rows).sum::<usize>(),
block_cols * block_rows,
"the precincts must partition the band's code-block grid"
);
Ok(BandGeom {
kind,
origin: (bx0.max(0) as u32, by0.max(0) as u32),
width,
height,
block_cols,
block_rows,
bounds: (bx0, bx1, by0, by1),
first_block: (first_col, first_row),
block_exp: (xcb, ycb),
precincts,
})
}
fn grid_span(lo: i64, hi: i64, exp: u32) -> (usize, i64) {
if hi <= lo {
return (0, 0);
}
let first = lo >> exp;
((ceil_shr(hi, exp) - first) as usize, first)
}