#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Inspection {
pub format: &'static str,
pub size: Option<(u32, u32)>,
pub bytes_per_pixel: Option<u64>,
pub frames: Option<u32>,
pub orientation: Option<u16>,
pub truncated: Option<bool>,
pub icc_profile: bool,
}
pub(crate) const DECODED_FORMATS: [&str; 2] = ["jpeg", "png"];
pub(crate) fn inspect(bytes: &[u8]) -> Inspection {
let mut inspection = Inspection {
format: sniff(bytes),
size: None,
bytes_per_pixel: None,
frames: None,
orientation: None,
truncated: None,
icc_profile: false,
};
match inspection.format {
"jpeg" => walk_jpeg(bytes, &mut inspection),
"png" => walk_png(bytes, &mut inspection),
_ => {}
}
inspection
}
pub(crate) fn sniff(bytes: &[u8]) -> &'static str {
const SIGNATURES: [(&[u8], &str); 12] = [
(b"\xFF\xD8\xFF", "jpeg"),
(b"\x89PNG\r\n\x1A\n", "png"),
(b"GIF87a", "gif"),
(b"GIF89a", "gif"),
(b"\xFF\x0A", "jxl"),
(b"\0\0\0\x0CJXL \r\n\x87\n", "jxl"),
(b"BM", "bmp"),
(b"II*\0", "tiff"),
(b"MM\0*", "tiff"),
(b"\0\0\x01\0", "ico"),
(b"%PDF", "pdf"),
(b"8BPS", "psd"),
];
if bytes.is_empty() {
return "empty";
}
if let Some((_, format)) = SIGNATURES.iter().find(|(signature, _)| bytes.starts_with(signature)) {
return format;
}
if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
return "webp";
}
if bytes.len() >= 12 && &bytes[4..8] == b"ftyp" {
return match &bytes[8..12] {
b"avif" | b"avis" => "avif",
b"heic" | b"heix" | b"heim" | b"heis" | b"hevc" | b"hevx" => "heic",
b"mif1" | b"msf1" => "heif",
_ => "isobmff",
};
}
sniff_text(bytes)
}
fn sniff_text(bytes: &[u8]) -> &'static str {
let start = bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes);
let start = &start[start.iter().take_while(|byte| byte.is_ascii_whitespace()).count()..];
let head: Vec<u8> = start.iter().take(1024).map(u8::to_ascii_lowercase).collect();
let contains = |needle: &[u8]| head.windows(needle.len()).any(|window| window == needle);
if ["<!doctype html", "<html", "<head", "<body"]
.iter()
.any(|tag| head.starts_with(tag.as_bytes()))
{
"html"
} else if contains(b"<svg") {
"svg"
} else if head.starts_with(b"<?xml") {
"xml"
} else if head.starts_with(b"{") || head.starts_with(b"[") {
"json"
} else {
"unknown"
}
}
fn u16_be(bytes: &[u8], at: usize) -> Option<u16> {
Some(u16::from_be_bytes(bytes.get(at..at.checked_add(2)?)?.try_into().ok()?))
}
fn u32_be(bytes: &[u8], at: usize) -> Option<u32> {
Some(u32::from_be_bytes(bytes.get(at..at.checked_add(4)?)?.try_into().ok()?))
}
fn walk_jpeg(bytes: &[u8], inspection: &mut Inspection) {
inspection.frames = Some(1);
inspection.truncated = jpeg_segments(bytes, inspection);
}
fn jpeg_segments(bytes: &[u8], inspection: &mut Inspection) -> Option<bool> {
let mut at = 2;
loop {
if at >= bytes.len() {
return Some(true);
}
if bytes[at] != 0xFF {
return None;
}
while at < bytes.len() && bytes[at] == 0xFF {
at += 1;
}
let Some(&marker) = bytes.get(at) else {
return Some(true);
};
at += 1;
match marker {
0xD9 => return Some(false),
0x01 | 0xD0..=0xD7 => continue,
0x00 => return None,
_ => {}
}
let Some(length) = u16_be(bytes, at) else {
return Some(true);
};
let length = usize::from(length);
if length < 2 {
return None;
}
let end = at + length;
let payload = &bytes[(at + 2).min(bytes.len())..end.min(bytes.len())];
match marker {
0xC0..=0xCF if !matches!(marker, 0xC4 | 0xC8 | 0xCC) => {
if let (Some(&precision), Some(height), Some(width), Some(&components)) =
(payload.first(), u16_be(payload, 1), u16_be(payload, 3), payload.get(5))
{
inspection.size = Some((u32::from(width), u32::from(height)));
let sample = if precision > 8 { 2 } else { 1 };
inspection.bytes_per_pixel = Some(u64::from(components.min(3)) * sample);
}
}
0xE1 if inspection.orientation.is_none() => {
if let Some(tiff) = payload.strip_prefix(b"Exif\0\0") {
inspection.orientation = exif_orientation(tiff);
}
}
_ => {}
}
if end > bytes.len() {
return Some(true);
}
at = end;
if marker == 0xDA {
let Some(next) = skip_entropy_coded(bytes, at) else {
return Some(true);
};
at = next;
}
}
}
fn skip_entropy_coded(bytes: &[u8], mut at: usize) -> Option<usize> {
loop {
let found = at + bytes.get(at..)?.iter().position(|&byte| byte == 0xFF)?;
match bytes.get(found + 1) {
None => return None,
Some(0x00 | 0xD0..=0xD7) => at = found + 2,
Some(_) => return Some(found),
}
}
}
fn walk_png(bytes: &[u8], inspection: &mut Inspection) {
inspection.frames = Some(1);
let mut at = 8;
let mut seen_pixels = false;
inspection.truncated = loop {
let (Some(length), Some(kind)) = (u32_be(bytes, at), bytes.get(at + 4..at + 8)) else {
break Some(true);
};
let start = at + 8;
let Some(end) = usize::try_from(length)
.ok()
.and_then(|length| start.checked_add(length))
else {
break None;
};
if end.saturating_add(4) > bytes.len() {
break Some(true);
}
let data = &bytes[start..end];
match kind {
b"IHDR" if data.len() >= 13 => {
if let (Some(width), Some(height)) = (u32_be(data, 0), u32_be(data, 4)) {
inspection.size = Some((width, height));
}
let channels: u64 = match data[9] {
0 => 1,
4 => 2,
2 | 3 => 3,
_ => 4,
};
inspection.bytes_per_pixel = Some(channels * if data[8] == 16 { 2 } else { 1 });
}
b"acTL" => inspection.frames = u32_be(data, 0).or(inspection.frames),
b"eXIf" => inspection.orientation = exif_orientation(data),
b"iCCP" if !seen_pixels => inspection.icc_profile = true,
b"IDAT" => seen_pixels = true,
b"IEND" => break Some(false),
_ => {}
}
at = end + 4;
};
}
fn exif_orientation(tiff: &[u8]) -> Option<u16> {
let little = match tiff.get(..4)? {
b"II*\0" => true,
b"MM\0*" => false,
_ => return None,
};
let read16 = |at: usize| -> Option<u16> {
let pair: [u8; 2] = tiff.get(at..at.checked_add(2)?)?.try_into().ok()?;
Some(if little {
u16::from_le_bytes(pair)
} else {
u16::from_be_bytes(pair)
})
};
let read32 = |at: usize| -> Option<u32> {
let quad: [u8; 4] = tiff.get(at..at.checked_add(4)?)?.try_into().ok()?;
Some(if little {
u32::from_le_bytes(quad)
} else {
u32::from_be_bytes(quad)
})
};
let directory = usize::try_from(read32(4)?).ok()?;
let entries = usize::from(read16(directory)?);
(0..entries).find_map(|index| {
let entry = directory.checked_add(2 + 12 * index)?;
(read16(entry)? == 0x0112 && read16(entry + 2)? == 3).then(|| read16(entry + 8))?
})
}
#[cfg(test)]
mod tests {
use super::*;
fn exif(little: bool, orientation: u16) -> Vec<u8> {
let mut tiff = Vec::new();
if little {
tiff.extend_from_slice(b"II*\0");
tiff.extend_from_slice(&8u32.to_le_bytes());
tiff.extend_from_slice(&1u16.to_le_bytes());
tiff.extend_from_slice(&0x0112u16.to_le_bytes());
tiff.extend_from_slice(&3u16.to_le_bytes());
tiff.extend_from_slice(&1u32.to_le_bytes());
tiff.extend_from_slice(&orientation.to_le_bytes());
} else {
tiff.extend_from_slice(b"MM\0*");
tiff.extend_from_slice(&8u32.to_be_bytes());
tiff.extend_from_slice(&1u16.to_be_bytes());
tiff.extend_from_slice(&0x0112u16.to_be_bytes());
tiff.extend_from_slice(&3u16.to_be_bytes());
tiff.extend_from_slice(&1u32.to_be_bytes());
tiff.extend_from_slice(&orientation.to_be_bytes());
}
tiff.extend_from_slice(&[0, 0, 0, 0, 0, 0]);
tiff
}
#[test]
fn the_orientation_tag_reads_in_either_byte_order() {
assert_eq!(exif_orientation(&exif(true, 6)), Some(6));
assert_eq!(exif_orientation(&exif(false, 8)), Some(8));
assert_eq!(exif_orientation(b"II*\0\xFF\xFF\xFF\xFF"), None);
assert_eq!(exif_orientation(b"nonsense"), None);
assert_eq!(exif_orientation(&exif(true, 6)[..12]), None);
}
#[test]
fn formats_are_named_from_their_first_bytes() {
assert_eq!(sniff(b""), "empty");
assert_eq!(sniff(b"GIF89a\x01\x00"), "gif");
assert_eq!(sniff(b"RIFF\0\0\0\0WEBPVP8 "), "webp");
assert_eq!(sniff(b"\0\0\0\x1Cftypavif"), "avif");
assert_eq!(sniff(b"\0\0\0\x18ftypheic"), "heic");
assert_eq!(sniff(b"\xEF\xBB\xBF <!DOCTYPE html><title>404</title>"), "html");
assert_eq!(sniff(b"<?xml version=\"1.0\"?><svg xmlns=\"\">"), "svg");
assert_eq!(sniff(b"\x01\x02\x03"), "unknown");
}
#[test]
fn a_jpeg_walk_stops_at_its_end_marker_or_runs_out() {
let mut jpeg = vec![0xFF, 0xD8];
jpeg.extend_from_slice(&[0xFF, 0xC0, 0, 17, 8, 0, 2, 0, 3, 3]);
jpeg.extend_from_slice(&[0; 9]);
jpeg.extend_from_slice(&[0xFF, 0xDA, 0, 2, 1, 0xFF, 0x00, 2, 0xFF, 0xD3, 4]);
jpeg.extend_from_slice(&[0xFF, 0xD9]);
let whole = inspect(&jpeg);
assert_eq!(whole.size, Some((3, 2)));
assert_eq!(whole.bytes_per_pixel, Some(3));
assert_eq!(whole.truncated, Some(false));
for cut in 3..jpeg.len() {
assert_eq!(inspect(&jpeg[..cut]).truncated, Some(true), "cut at {cut}");
}
let mut garbage = jpeg.clone();
garbage[2] = 0x12;
assert_eq!(inspect(&garbage).truncated, None);
}
}