use crate::PaletteClass;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DensityUnit {
Inch,
Centimeter,
Meter,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ImageHeader {
pub pixels: (usize, usize),
pub density: Option<(u32, u32, DensityUnit)>,
}
const IHDR: &[u8] = b"IHDR";
const PHYS: &[u8] = b"pHYs";
const PLTE: &[u8] = b"PLTE";
const TRNS: &[u8] = b"tRNS";
const PNG_PALETTE: u8 = 3;
const PNG_ALPHA_TYPES: [u8; 2] = [4, 6];
const PNG_DATA: [&[u8]; 2] = [b"IDAT", b"IEND"];
const PNG_METER: u8 = 1;
const APP0: u8 = 0xe0;
const JFIF: &[u8] = b"JFIF\0";
#[must_use]
pub fn gif_pixels(data: &[u8]) -> Option<(usize, usize)> {
let head = data.get(6..10)?;
let w = u16::from_le_bytes([*head.first()?, *head.get(1)?]);
let h = u16::from_le_bytes([*head.get(2)?, *head.get(3)?]);
(w > 0 && h > 0).then_some((usize::from(w), usize::from(h)))
}
#[must_use]
pub fn bmp_pixels(data: &[u8]) -> Option<(usize, usize)> {
let w_bytes: [u8; 4] = data.get(18..22)?.try_into().ok()?;
let h_bytes: [u8; 4] = data.get(22..26)?.try_into().ok()?;
let w = usize::try_from(i32::from_le_bytes(w_bytes)).ok()?;
let h = usize::try_from(i32::from_le_bytes(h_bytes).unsigned_abs()).ok()?;
(w > 0 && h > 0).then_some((w, h))
}
#[must_use]
pub fn png_header(data: &[u8]) -> Option<ImageHeader> {
(data.get(12..16) == Some(IHDR)).then_some(())?;
let pixels = (
usize::try_from(be32(data, 16)?).ok()?,
usize::try_from(be32(data, 20)?).ok()?,
);
Some(ImageHeader {
pixels,
density: png_density(data),
})
}
fn png_density(data: &[u8]) -> Option<(u32, u32, DensityUnit)> {
let (_, body) = png_chunks(data).find(|(kind, _)| *kind == PHYS)?;
let (x, y) = (be32(body, 0)?, be32(body, 4)?);
(body.get(8) == Some(&PNG_METER) && x > 0 && y > 0).then_some((x, y, DensityUnit::Meter))
}
#[must_use]
pub fn png_palette_class(data: &[u8]) -> Option<PaletteClass> {
(png_color_type(data) == Some(PNG_PALETTE)).then_some(())?;
let mut palette = None;
for (kind, body) in png_chunks(data) {
if kind == TRNS {
return None;
}
if kind == PLTE {
palette = Some(body);
}
}
let gray = palette?
.chunks(3)
.all(|entry| matches!(entry, [red, green, blue] if red == green && green == blue));
match (data.get(24)?, gray) {
(1, _) => Some(PaletteClass::OneBit),
(4, false) => Some(PaletteClass::FourBitColor),
(8, false) => Some(PaletteClass::EightBitColor),
_ => None,
}
}
#[must_use]
pub fn png_color_type(data: &[u8]) -> Option<u8> {
(data.get(12..16) == Some(IHDR)).then_some(())?;
data.get(25).copied()
}
#[must_use]
pub fn png_can_be_clear(data: &[u8]) -> Option<bool> {
let color_type = png_color_type(data)?;
Some(PNG_ALPHA_TYPES.contains(&color_type) || png_chunks(data).any(|(kind, _)| kind == TRNS))
}
#[must_use]
pub fn png_header_complete(data: &[u8]) -> bool {
let mut at = 8_usize;
loop {
let Some(length) = be32(data, at).and_then(|v| usize::try_from(v).ok()) else {
return false;
};
let Some(kind_end) = at.checked_add(8) else {
return false;
};
let Some(kind) = data.get(at + 4..kind_end) else {
return false;
};
if PNG_DATA.contains(&kind) {
return true;
}
let Some(next) = kind_end.checked_add(length).and_then(|e| e.checked_add(4)) else {
return false;
};
if next > data.len() {
return false;
}
at = next;
}
}
fn png_chunks(data: &[u8]) -> impl Iterator<Item = (&[u8], &[u8])> {
let mut at = Some(8_usize);
std::iter::from_fn(move || {
let start = at.take()?;
let length = usize::try_from(be32(data, start)?).ok()?;
let kind = data.get(start.checked_add(4)?..start.checked_add(8)?)?;
if PNG_DATA.contains(&kind) {
return None;
}
let first = start.checked_add(8)?;
let end = first.checked_add(length)?;
let body = data.get(first..end)?;
at = end.checked_add(4);
Some((kind, body))
})
}
#[must_use]
pub fn jpeg_header(data: &[u8]) -> Option<ImageHeader> {
let mut density = None;
let mut at = 2;
loop {
let (&mark, &kind) = (data.get(at)?, data.get(at + 1)?);
if mark != 0xff {
return None;
}
let frame = matches!(kind, 0xc0..=0xcf) && !matches!(kind, 0xc4 | 0xc8 | 0xcc);
if frame {
let pixels = (
usize::from(be16(data, at + 7)?),
usize::from(be16(data, at + 5)?),
);
return Some(ImageHeader { pixels, density });
}
let length = usize::from(be16(data, at + 2)?);
if kind == APP0
&& let Some(segment) = data.get(at + 4..at + 2 + length)
{
density = jfif_density(segment).or(density);
}
at += 2 + length;
}
}
fn jfif_density(segment: &[u8]) -> Option<(u32, u32, DensityUnit)> {
if !segment.starts_with(JFIF) {
return None;
}
let unit = match segment.get(7)? {
1 => DensityUnit::Inch,
2 => DensityUnit::Centimeter,
_ => return None,
};
let (x, y) = (u32::from(be16(segment, 8)?), u32::from(be16(segment, 10)?));
(x > 0 && y > 0).then_some((x, y, unit))
}
fn be32(data: &[u8], at: usize) -> Option<u32> {
let bytes: [u8; 4] = data.get(at..at.checked_add(4)?)?.try_into().ok()?;
Some(u32::from_be_bytes(bytes))
}
fn be16(data: &[u8], at: usize) -> Option<u16> {
Some(u16::from_be_bytes([
*data.get(at)?,
*data.get(at.checked_add(1)?)?,
]))
}
#[cfg(test)]
mod tests {
use crate::PaletteClass;
use super::{DensityUnit, jpeg_header, png_can_be_clear, png_header, png_palette_class};
fn png(chunks: &[(&[u8], Vec<u8>)]) -> Vec<u8> {
let mut file = b"\x89PNG\r\n\x1a\n".to_vec();
for (kind, body) in chunks {
let length = u32::try_from(body.len()).unwrap();
file.extend_from_slice(&length.to_be_bytes());
file.extend_from_slice(kind);
file.extend_from_slice(body);
file.extend_from_slice(&[0; 4]);
}
file
}
fn ihdr(width: u32, height: u32) -> Vec<u8> {
let mut body = width.to_be_bytes().to_vec();
body.extend_from_slice(&height.to_be_bytes());
body.extend_from_slice(&[8, 2, 0, 0, 0]);
body
}
fn palette_ihdr(depth: u8) -> Vec<u8> {
let mut body = ihdr(4, 4);
body[8..10].copy_from_slice(&[depth, 3]);
body
}
fn class(depth: u8, entries: &[u8], clear: bool) -> Option<PaletteClass> {
let mut chunks = vec![
(&b"IHDR"[..], palette_ihdr(depth)),
(b"PLTE", entries.to_vec()),
];
if clear {
chunks.push((b"tRNS", vec![255]));
}
chunks.push((b"IDAT", vec![0]));
png_palette_class(&png(&chunks))
}
#[test]
fn png_palette_class_from_its_depth_its_entries_and_its_transparency() {
let (gray, color) = (&[0, 0, 0, 255, 255, 255][..], &[0, 0, 0, 40, 90, 170][..]);
let (one, four, eight) = (
Some(PaletteClass::OneBit),
Some(PaletteClass::FourBitColor),
Some(PaletteClass::EightBitColor),
);
let cases = [
(1, gray, false, one),
(1, color, false, one),
(2, color, false, None),
(4, color, false, four),
(4, gray, false, None),
(8, color, false, eight),
(8, gray, false, None),
(1, gray, true, None),
(8, color, true, None),
];
for (depth, entries, clear, expected) in cases {
assert_eq!(class(depth, entries, clear), expected);
}
}
#[test]
fn png_palette_class_needs_a_palette_before_the_data() {
let rgb = png(&[(b"IHDR", ihdr(4, 4)), (b"IDAT", vec![0])]);
assert_eq!(png_palette_class(&rgb), None);
let color = vec![0, 0, 0, 40, 90, 170];
let late = png(&[
(b"IHDR", palette_ihdr(8)),
(b"IDAT", vec![0]),
(b"PLTE", color.clone()),
]);
assert_eq!(png_palette_class(&late), None);
let after = png(&[
(b"IHDR", palette_ihdr(8)),
(b"PLTE", color),
(b"IDAT", vec![0]),
(b"tRNS", vec![0]),
]);
assert_eq!(png_palette_class(&after), Some(PaletteClass::EightBitColor));
}
fn typed_can_be_clear(color_type: u8, transparency: Option<bool>) -> Option<bool> {
let mut header = ihdr(4, 4);
header[9] = color_type;
let mut chunks = vec![(&b"IHDR"[..], header)];
if transparency == Some(true) {
chunks.push((b"tRNS", vec![0, 0]));
}
chunks.push((b"IDAT", vec![0]));
if transparency == Some(false) {
chunks.push((b"tRNS", vec![0, 0]));
}
png_can_be_clear(&png(&chunks))
}
#[test]
fn png_can_be_clear_by_its_alpha_sample_or_a_transparency_chunk_before_the_data() {
let cases = [
(2, None, true),
(0, None, true),
(3, None, true),
(6, None, false),
(4, None, false),
(2, Some(true), false),
(3, Some(true), false),
(2, Some(false), true),
];
for (color_type, transparency, opaque) in cases {
assert_eq!(
typed_can_be_clear(color_type, transparency),
Some(!opaque),
"{color_type} {transparency:?}"
);
}
assert_eq!(png_can_be_clear(b"not a png"), None);
}
fn phys(x: u32, y: u32, unit: u8) -> Vec<u8> {
let mut body = x.to_be_bytes().to_vec();
body.extend_from_slice(&y.to_be_bytes());
body.push(unit);
body
}
#[test]
fn png_gives_its_pixels_and_its_density_before_the_data() {
let file = png(&[
(b"IHDR", ihdr(300, 200)),
(b"tEXt", b"a".to_vec()),
(b"pHYs", phys(3_780, 2_835, 1)),
(b"IDAT", Vec::new()),
]);
let header = png_header(&file).unwrap();
assert_eq!(header.pixels, (300, 200));
assert_eq!(header.density, Some((3_780, 2_835, DensityUnit::Meter)));
}
#[test]
fn png_density_after_the_data_or_without_a_unit_counts_as_none() {
let late = png(&[
(b"IHDR", ihdr(3, 2)),
(b"IDAT", Vec::new()),
(b"pHYs", phys(3_780, 3_780, 1)),
]);
assert_eq!(png_header(&late).unwrap().density, None);
let aspect = png(&[(b"IHDR", ihdr(3, 2)), (b"pHYs", phys(1, 2, 0))]);
assert_eq!(png_header(&aspect).unwrap().density, None);
let zero = png(&[(b"IHDR", ihdr(3, 2)), (b"pHYs", phys(0, 3_780, 1))]);
assert_eq!(png_header(&zero).unwrap().density, None);
let mut cut = png(&[(b"IHDR", ihdr(3, 2)), (b"pHYs", phys(3_780, 3_780, 1))]);
cut.truncate(cut.len() - 8);
assert_eq!(png_header(&cut).unwrap().pixels, (3, 2));
assert_eq!(png_header(&cut).unwrap().density, None);
}
#[test]
fn png_without_its_header_chunk_first_has_no_header() {
let file = png(&[(b"pHYs", phys(1, 1, 1)), (b"IHDR", ihdr(3, 2))]);
assert_eq!(png_header(&file), None);
}
fn jpeg(app0: &[u8], width: u16, height: u16) -> Vec<u8> {
let mut file = vec![0xff, 0xd8, 0xff, 0xe0];
file.extend_from_slice(&u16::try_from(app0.len() + 2).unwrap().to_be_bytes());
file.extend_from_slice(app0);
file.extend_from_slice(&[0xff, 0xc0, 0, 11, 8]);
file.extend_from_slice(&height.to_be_bytes());
file.extend_from_slice(&width.to_be_bytes());
file.extend_from_slice(&[1, 1, 0x11, 0]);
file
}
#[test]
fn jpeg_gives_its_pixels_and_its_jfif_density() {
let per_inch = jpeg(b"JFIF\0\x01\x02\x01\x00\x48\x00\x90\0\0", 640, 480);
let header = jpeg_header(&per_inch).unwrap();
assert_eq!(header.pixels, (640, 480));
assert_eq!(header.density, Some((72, 144, DensityUnit::Inch)));
let per_cm = jpeg(b"JFIF\0\x01\x02\x02\x00\x76\x00\x76\0\0", 4, 3);
assert_eq!(
jpeg_header(&per_cm).unwrap().density,
Some((118, 118, DensityUnit::Centimeter))
);
let aspect = jpeg(b"JFIF\0\x01\x02\x00\x00\x01\x00\x01\0\0", 4, 3);
assert_eq!(jpeg_header(&aspect).unwrap().density, None);
let other = jpeg(b"JFXX\0\x01\x02\x01\x00\x48\x00\x48\0\0", 4, 3);
assert_eq!(jpeg_header(&other).unwrap().density, None);
}
#[test]
fn jpeg_cut_short_has_no_header() {
assert_eq!(jpeg_header(b"\xff\xd8\xff\xe0 cut short"), None);
}
}