use crate::peak::dct::header;
use crate::{Codec, ImageCodecError};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DeclaredGeometry {
Pixels {
width: u32,
height: u32,
},
Tiles {
count: u64,
},
Rows {
rows: u32,
},
}
impl std::fmt::Display for DeclaredGeometry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Pixels { width, height } => write!(f, "{width} x {height} pixels"),
Self::Tiles { count } => write!(f, "{count} tiles"),
Self::Rows { rows } => write!(f, "{rows} rows"),
}
}
}
impl ImageCodecError {
#[must_use]
pub fn refusal_key(&self) -> Option<&'static str> {
match self {
Self::DeclaredGeometryExceedsData { codec, .. } => Some(match codec {
Codec::Dct => "image/evidence/dct",
Codec::Jpx => "image/evidence/jpx",
Codec::Ccitt => "image/evidence/ccitt",
Codec::Jbig2 => "image/evidence/jbig2",
Codec::Jxl => "image/evidence/jxl",
}),
_ => None,
}
}
}
fn refuse(
codec: Codec,
declared: DeclaredGeometry,
min_bytes: u64,
have: usize,
) -> ImageCodecError {
ImageCodecError::DeclaredGeometryExceedsData {
codec,
declared,
min_bytes,
have_bytes: u64::try_from(have).unwrap_or(u64::MAX),
}
}
fn dct_min_bits(data: &[u8]) -> Result<Option<(u64, DeclaredGeometry)>, ImageCodecError> {
let Some(h) = header(data) else {
return Ok(None);
};
if h.process == 2 && h.first_scan_ss != 0 {
return Err(ImageCodecError::Corrupt {
codec: Codec::Dct,
detail: format!(
"progressive frame's first scan starts at coefficient {}; the DC scan \
must come first (T.81 G.1.1.1.1)",
h.first_scan_ss
),
});
}
if !matches!(h.process, 0..=2) || h.height == 0 || h.first_scan_selectors.is_empty() {
return Ok(None);
}
let hmax = h.sampling.iter().map(|s| s.0).max().unwrap_or(0);
let vmax = h.sampling.iter().map(|s| s.1).max().unwrap_or(0);
if hmax == 0 || vmax == 0 {
return Ok(None);
}
let mut fewest: Option<u64> = None;
for cs in &h.first_scan_selectors {
let Some(at) = h.ids.iter().position(|id| id == cs) else {
return Ok(None);
};
let Some(&(hc, vc)) = h.sampling.get(at) else {
return Ok(None);
};
let x = (h.width * hc).div_ceil(hmax).div_ceil(8);
let y = (h.height * vc).div_ceil(vmax).div_ceil(8);
let blocks = x.saturating_mul(y);
fewest = Some(fewest.map_or(blocks, |f| f.min(blocks)));
}
let per_block = if h.process == 2 { 1 } else { 2 };
let declared = DeclaredGeometry::Pixels {
width: u32::try_from(h.width).unwrap_or(u32::MAX),
height: u32::try_from(h.height).unwrap_or(u32::MAX),
};
Ok(fewest.map(|b| (b.saturating_mul(per_block), declared)))
}
pub(crate) fn dct(data: &[u8]) -> Result<(), ImageCodecError> {
let Some((bits, declared)) = dct_min_bits(data)? else {
return Ok(());
};
let have_bits = u64::try_from(data.len())
.unwrap_or(u64::MAX)
.saturating_mul(8);
if have_bits >= bits {
return Ok(());
}
Err(refuse(Codec::Dct, declared, bits.div_ceil(8), data.len()))
}
#[cfg(feature = "jpx")]
const JPX_TILE_PART_BYTES: u64 = 14;
#[cfg(feature = "jpx")]
pub(crate) fn jpx_tiles(tiles: u64, floor: u64, len: usize) -> Result<(), ImageCodecError> {
let min_bytes = tiles.saturating_mul(JPX_TILE_PART_BYTES);
if tiles <= floor || u64::try_from(len).unwrap_or(u64::MAX) >= min_bytes {
return Ok(());
}
Err(refuse(
Codec::Jpx,
DeclaredGeometry::Tiles { count: tiles },
min_bytes,
len,
))
}
pub(crate) fn ccitt_max_rows(len: usize) -> u64 {
u64::try_from(len)
.unwrap_or(u64::MAX)
.saturating_mul(8)
.saturating_add(1)
}
pub(crate) fn ccitt_rows(rows: u32, len: usize) -> Result<(), ImageCodecError> {
if u64::from(rows) <= ccitt_max_rows(len) {
return Ok(());
}
let min_bytes = u64::from(rows - 1).div_ceil(8);
Err(refuse(
Codec::Ccitt,
DeclaredGeometry::Rows { rows },
min_bytes,
len,
))
}