Files
texrra-engine/crates/texrra-tex-core/src/pdf_image/jpeg.rs
T

222 lines
7.6 KiB
Rust

//! JPEG frame, density and color-profile metadata.
use std::collections::BTreeMap;
pub(super) const SIGNATURE: &[u8] = b"\xff\xd8";
pub(super) struct Header {
pub size: [u16; 2],
pub precision: u8,
pub components: u8,
pub density: [u32; 2],
pub xdv_density: [f64; 2],
pub progressive: bool,
pub icc: Option<Vec<u8>>,
pub adobe: bool,
}
pub(super) fn read(bytes: &[u8]) -> Result<Header, &'static str> {
let mut rest = bytes
.strip_prefix(SIGNATURE)
.ok_or("missing JPEG signature")?;
let mut density = [0, 0];
let mut xdv_density = [0.0; 2];
let mut first = true;
let mut profile_chunks = BTreeMap::new();
let mut adobe = false;
let truncated = "premature end of JPEG header";
loop {
rest = rest.strip_prefix(&[0xff]).ok_or("expected JPEG marker")?;
while let Some(following) = rest.strip_prefix(&[0xff]) {
rest = following;
}
let (&marker, remaining) = rest.split_first().ok_or(truncated)?;
rest = remaining;
match marker {
0xd9 | 0xda => return Err("JPEG has no frame header"),
0x01 | 0xd0..=0xd8 => {
first = false;
continue;
}
_ => {}
}
let length = usize::from(u16::from_be_bytes(
rest.get(..2)
.ok_or(truncated)?
.try_into()
.expect("two-byte JPEG length"),
));
let segment = rest.get(2..length).ok_or(truncated)?;
rest = &rest[length..];
match marker {
0xc0..=0xc3 => {
let &[precision, h0, h1, w0, w1, components, ref table @ ..] = segment else {
return Err(truncated);
};
if !matches!(components, 1 | 3 | 4) {
return Err("unsupported JPEG color space");
}
if table.len() != 3 * usize::from(components) {
return Err("invalid JPEG component table");
}
let size = [u16::from_be_bytes([w0, w1]), u16::from_be_bytes([h0, h1])];
if size.contains(&0) || precision == 0 {
return Err("invalid JPEG frame dimensions or precision");
}
return Ok(Header {
size,
precision,
components,
density,
xdv_density: if xdv_density == [0.0; 2] {
[72.0; 2]
} else {
xdv_density
},
progressive: marker == 0xc2,
icc: assemble_profile(&profile_chunks),
adobe,
});
}
0xc5..=0xc7 | 0xc9..=0xcb | 0xcd..=0xcf => {
return Err("unsupported JPEG compression");
}
0xe0 => {
if let Some(&[_, _, unit, x0, x1, y0, y1, ..]) = segment.strip_prefix(b"JFIF\0") {
let x = u32::from(u16::from_be_bytes([x0, x1]));
let y = u32::from(u16::from_be_bytes([y0, y1]));
xdv_density = match unit {
1 => [f64::from(x), f64::from(y)],
2 => [f64::from(x) * 2.54, f64::from(y) * 2.54],
_ => [72.0; 2],
};
if first {
density = match unit {
1 => [x, y],
2 => [x * 254 / 100, y * 254 / 100],
_ => [0, 0],
};
if density.contains(&0) {
density = [density[0].max(density[1]); 2];
}
}
}
}
0xe1 => {
if let Some(tiff) = segment.strip_prefix(b"Exif\0") {
let start = tiff
.iter()
.position(|&byte| byte != 0)
.unwrap_or(tiff.len());
if let Some((legacy, exact)) = exif_density(&tiff[start..]) {
if first {
density = legacy;
}
if xdv_density.iter().all(|dpi| *dpi < 0.1) {
xdv_density = exact;
}
}
}
}
0xe2 => {
if let Some(&[index, count, ref bytes @ ..]) =
segment.strip_prefix(b"ICC_PROFILE\0")
{
profile_chunks.insert(index, (count, bytes));
}
}
0xee if segment.starts_with(b"Adobe") => adobe = true,
_ => {}
}
first = false;
}
}
fn assemble_profile(chunks: &BTreeMap<u8, (u8, &[u8])>) -> Option<Vec<u8>> {
let &(total, _) = chunks.get(&1)?;
if usize::from(total) != chunks.len() {
return None;
}
let mut profile = Vec::new();
for index in 1..=total {
let &(count, data) = chunks.get(&index)?;
if count != total {
return None;
}
profile.extend_from_slice(data);
}
Some(profile)
}
fn exif_density(tiff: &[u8]) -> Option<([u32; 2], [f64; 2])> {
let little = match tiff.get(..2)? {
b"II" => true,
b"MM" => false,
_ => return None,
};
let short = |at: usize| {
let bytes = tiff.get(at..at.checked_add(2)?)?.try_into().ok()?;
Some(if little {
u16::from_le_bytes(bytes)
} else {
u16::from_be_bytes(bytes)
})
};
let long = |at: usize| {
let bytes = tiff.get(at..at.checked_add(4)?)?.try_into().ok()?;
Some(if little {
u32::from_le_bytes(bytes)
} else {
u32::from_be_bytes(bytes)
})
};
if short(2)? != 42 {
return None;
}
let start = usize::try_from(long(4)?).ok()?;
let entries = usize::from(short(start)?);
let start = start.checked_add(2)?;
let end = start.checked_add(12 * entries)?;
tiff.get(start..end)?;
let mut density = [72, 72];
let mut exact = [72.0; 2];
let mut cm = false;
for at in (start..end).step_by(12) {
match (short(at)?, short(at + 2)?, long(at + 4)?) {
(tag @ (282 | 283), 5, 1) => {
let offset = usize::try_from(long(at + 8)?).ok()?;
let numerator = long(offset)?;
let denominator = long(offset.checked_add(4)?)?;
if denominator != 0 {
let axis = usize::from(tag == 283);
density[axis] = numerator / denominator;
exact[axis] = f64::from(numerator) / f64::from(denominator);
}
}
(296, 3, 1) => cm = short(at + 8)? == 3,
_ => {}
}
}
if cm {
density =
density.map(|value| u32::try_from(u64::from(value) * 254 / 100).unwrap_or(u32::MAX));
exact = exact.map(|dpi| dpi * 2.54);
}
Some((density, exact))
}
#[cfg(test)]
mod tests {
use super::read;
#[test]
fn jfif_keeps_fractional_xdv_density_and_legacy_integer_density() {
let mut jpeg = b"\xff\xd8\xff\xe0\x00\x10JFIF\0\x01\x02\x02\x00\x30\x00\x39\0\0".to_vec();
jpeg.extend_from_slice(b"\xff\xc0\x00\x0b\x08\x00\x64\x00\xb4\x01\x01\x11\x00");
let header = read(&jpeg).unwrap();
assert_eq!(header.size, [180, 100]);
assert_eq!(header.density, [121, 144]);
assert_eq!(header.xdv_density, [48.0 * 2.54, 57.0 * 2.54]);
}
}