use super::{be, len};
pub(crate) struct Header {
pub(crate) process: u8,
pub(crate) precision: u8,
pub(crate) width: u64,
pub(crate) height: u64,
pub(crate) sampling: Vec<(u64, u64)>,
pub(crate) ids: Vec<u8>,
pub(crate) first_scan_components: u64,
pub(crate) first_scan_selectors: Vec<u8>,
pub(crate) first_scan_ss: u8,
}
pub(super) fn working_bytes(data: &[u8]) -> Option<u64> {
let h = header(data)?;
let nc = len(&h.sampling);
if !matches!(h.process, 0..=2) || h.precision != 8 || !matches!(nc, 1 | 3 | 4) {
return None;
}
if h.width == 0 || h.height == 0 {
return None;
}
let geometry = Geometry::new(&h);
let output = h.width.saturating_mul(h.height).saturating_mul(nc);
let rows = geometry.row_buffers(&h);
let multi_scan = h.process == 2 || h.first_scan_components < nc;
let planes = if multi_scan { geometry.planes(&h) } else { 0 };
let Some(blocks) = geometry.remux_blocks(&h) else {
return Some(output.saturating_add(rows).saturating_add(planes));
};
let remuxed = len(data).saturating_mul(5) / 4 + 1024;
let remux = blocks
.saturating_mul(128)
.saturating_add(remuxed.saturating_mul(3));
let zune = output
.saturating_add(rows)
.saturating_add(remuxed.saturating_mul(2).max(geometry.planes(&h)));
Some(remux.max(zune))
}
struct Geometry {
hmax: u64,
vmax: u64,
mcu_x: u64,
mcu_y: u64,
interleaved: bool,
}
impl Geometry {
fn new(h: &Header) -> Self {
let hmax = h.sampling.iter().map(|s| s.0).max().unwrap_or(1).max(1);
let vmax = h.sampling.iter().map(|s| s.1).max().unwrap_or(1).max(1);
Self {
hmax,
vmax,
mcu_x: h.width.div_ceil(8 * hmax),
mcu_y: h.height.div_ceil(8 * vmax),
interleaved: h.sampling.len() > 1 && (hmax != 1 || vmax != 1),
}
}
fn remux_blocks(&self, h: &Header) -> Option<u64> {
let nc = len(&h.sampling);
let uniform = h.sampling.windows(2).all(|w| w.first() == w.last());
let mcu_blocks: u64 = h.sampling.iter().map(|&(a, b)| a * b).sum();
let blocks = self
.mcu_x
.saturating_mul(self.mcu_y)
.saturating_mul(mcu_blocks);
let accepted = matches!(h.process, 0 | 1)
&& (2..=4).contains(&nc)
&& !uniform
&& mcu_blocks <= 10
&& h.first_scan_components < nc
&& blocks <= u64::try_from(crate::dct::MAX_REMUX_BLOCKS).unwrap_or(u64::MAX);
accepted.then_some(blocks)
}
fn row_buffers(&self, h: &Header) -> u64 {
if !self.interleaved {
let stride = h.width.div_ceil(8) * 8;
return 2 * len(&h.sampling) * stride * 8 + 2 * stride * 8;
}
let luma = h.sampling.first().copied().unwrap_or((1, 1));
let chroma_sub = h.sampling.iter().skip(1).any(|&s| s != (1, 1));
let doubled = if (luma.0 == 2 || luma.1 == 2) && chroma_sub {
2
} else {
1
};
let mut total = 0u64;
let mut widest = 0u64;
for &(hc, vc) in &h.sampling {
let (hc, vc) = (hc.max(1), vc.max(1));
let stride = hc * self.mcu_x * 8;
let ratio = (self.hmax / hc).max(1) * (self.vmax / vc).max(1);
let raw = stride * vc * 8;
let upsample = (stride * ratio * doubled * 8).max(raw * 2);
total = total
.saturating_add(raw + 2 * stride * vc + vc * stride * ratio)
.saturating_add(upsample);
widest = widest.max(stride * 8);
}
total.saturating_add(widest).saturating_mul(2)
}
fn planes(&self, h: &Header) -> u64 {
let elements: u64 = if self.interleaved {
h.sampling
.iter()
.map(|&(hc, vc)| (self.mcu_x * 64 * hc).saturating_mul(self.mcu_y * vc))
.sum()
} else {
len(&h.sampling)
.saturating_mul(h.width.div_ceil(8) * 64)
.saturating_mul(h.height.div_ceil(8))
};
elements.saturating_mul(2)
}
}
pub(crate) fn header(data: &[u8]) -> Option<Header> {
if data.get(..2)? != [0xFF, 0xD8] {
return None;
}
let mut frame: Option<Header> = None;
let mut at = 2usize;
loop {
while data.get(at) == Some(&0xFF) && data.get(at + 1) == Some(&0xFF) {
at += 1;
}
if *data.get(at)? != 0xFF {
return None;
}
let marker = *data.get(at + 1)?;
at += 2;
if matches!(marker, 0x01 | 0xD0..=0xD7) {
continue;
}
let length = usize::try_from(be::<2>(data, at)?).ok()?;
let payload = data.get(at + 2..at.checked_add(length)?)?;
match marker {
0xC0..=0xCF if !matches!(marker, 0xC4 | 0xC8 | 0xCC) => {
frame.get_or_insert(sof(marker, payload)?);
}
0xDA => {
let mut f = frame?;
let ns = usize::from(*payload.first()?);
f.first_scan_components = u64::from(*payload.first()?);
if let Some(ss) = payload.get(1 + 2 * ns) {
f.first_scan_ss = *ss;
f.first_scan_selectors = payload
.get(1..1 + 2 * ns)
.unwrap_or_default()
.as_chunks::<2>()
.0
.iter()
.map(|&[cs, _]| cs)
.collect();
}
return Some(f);
}
0xD9 => return None,
_ => {}
}
at = at.checked_add(length)?;
}
}
fn sof(marker: u8, p: &[u8]) -> Option<Header> {
let nf = usize::from(*p.get(5)?);
let specs = p.get(6..6 + 3 * nf)?;
Some(Header {
process: marker & 0x0F,
precision: *p.first()?,
height: be::<2>(p, 1)?,
width: be::<2>(p, 3)?,
sampling: specs
.as_chunks::<3>()
.0
.iter()
.map(|&[_, hv, _]| (u64::from(hv >> 4), u64::from(hv & 0x0F)))
.collect(),
ids: specs
.as_chunks::<3>()
.0
.iter()
.map(|&[c, _, _]| c)
.collect(),
first_scan_components: 0,
first_scan_selectors: Vec::new(),
first_scan_ss: 0,
})
}