Share legacy EXIF summary and thumbnail inspection

This commit is contained in:
Dylan M. Taylor committed 2026-11-15 17:18:18 +00:00
1 parent c6f4f5115e
commit f04d6381c7
1 file changed
+168 -38
+168 -38
View File
@@ -1,52 +1,182 @@
//! Compatibility orientation reading for legacy clients that accepted loosely formed classic EXIF.
//! The ordinary `exif_orientation` API remains strict; use this only to retain older behavior.
//! Compatibility EXIF summary and helpers for legacy clients that accepted loosely formed classic TIFF.
//! The ordinary strict EXIF orientation API remains unchanged.
/// Read the last IFD0 orientation entry as older lightweight readers did. Entry count is bounded;
/// a complete entry table is required, but an absent next-IFD pointer is accepted. BYTE, UNDEFINED,
/// SHORT, LONG and IFD values are read inline regardless of count. Invalid/missing values give 1.
/// Read a legacy orientation, with an optional `Exif\0\0` prefix.
pub fn orientation(bytes: &[u8]) -> u16 {
let b = bytes.strip_prefix(b"Exif\0\0").unwrap_or(bytes);
let little = match b.get(..2) {
Some(b"II") => true,
Some(b"MM") => false,
_ => return 1,
};
let u16_at =
|at: usize| b.get(at..at.checked_add(2)?).map(|v| if little { u16::from_le_bytes([v[0], v[1]]) } else { u16::from_be_bytes([v[0], v[1]]) });
let u32_at = |at: usize| {
b.get(at..at.checked_add(4)?)
.map(|v| if little { u32::from_le_bytes([v[0], v[1], v[2], v[3]]) } else { u32::from_be_bytes([v[0], v[1], v[2], v[3]]) })
};
if u16_at(2) != Some(42) {
return 1;
summarize(bytes.strip_prefix(b"Exif\0\0").unwrap_or(bytes)).orientation.unwrap_or(1)
}
/// Byte-order aware reader over a TIFF-structured blob.
#[derive(Clone, Copy)]
struct Tiff<'a> {
pub data: &'a [u8],
le: bool,
}
#[derive(Clone, Copy, Debug)]
struct Entry {
pub tag: u16,
pub typ: u16,
pub count: u32,
/// Offset of the 4-byte value/offset field within `data`.
pub value_pos: usize,
}
impl<'a> Tiff<'a> {
pub fn new(data: &'a [u8]) -> Option<Tiff<'a>> {
let le = match data.get(0..2)? {
b"II" => true,
b"MM" => false,
_ => return None,
};
Some(Tiff { data, le })
}
let Some(ifd) = u32_at(4).and_then(|v| usize::try_from(v).ok()) else { return 1 };
let Some(count) = u16_at(ifd).map(usize::from).filter(|n| *n <= 4096) else { return 1 };
let Some(start) = ifd.checked_add(2) else { return 1 };
let Some(end) = count.checked_mul(12).and_then(|n| start.checked_add(n)).filter(|end| *end <= b.len()) else { return 1 };
let mut orientation = None;
for at in (start..end).step_by(12) {
if u16_at(at) == Some(0x0112) {
let value = match u16_at(at + 2) {
Some(3) => u16_at(at + 8).map(u32::from),
Some(4 | 13) => u32_at(at + 8),
Some(1 | 7) => b.get(at + 8).copied().map(u32::from),
_ => None,
};
orientation = value.map(|v| v as u16).filter(|v| (1..=8).contains(v));
pub fn u16_at(&self, pos: usize) -> Option<u16> {
let b = self.data.get(pos..pos.checked_add(2)?)?;
Some(if self.le { u16::from_le_bytes([b[0], b[1]]) } else { u16::from_be_bytes([b[0], b[1]]) })
}
pub fn u32_at(&self, pos: usize) -> Option<u32> {
let b = self.data.get(pos..pos.checked_add(4)?)?;
let a = [b[0], b[1], b[2], b[3]];
Some(if self.le { u32::from_le_bytes(a) } else { u32::from_be_bytes(a) })
}
pub fn first_ifd(&self) -> Option<usize> {
let magic = self.u16_at(2)?;
if magic != 42 {
return None;
}
Some(self.u32_at(4)? as usize)
}
/// Entries of the IFD at `pos` and the offset of the next IFD (0 = none).
pub fn ifd(&self, pos: usize) -> Option<(Vec<Entry>, usize)> {
let n = self.u16_at(pos)? as usize;
if n > 4096 {
return None;
}
let mut v = Vec::with_capacity(n);
for i in 0..n {
let e = pos.checked_add(2)?.checked_add(i.checked_mul(12)?)?;
v.push(Entry { tag: self.u16_at(e)?, typ: self.u16_at(e + 2)?, count: self.u32_at(e + 4)?, value_pos: e + 8 });
}
let next =
pos.checked_add(2).and_then(|p| n.checked_mul(12).and_then(|v| p.checked_add(v))).and_then(|p| self.u32_at(p)).unwrap_or(0) as usize;
Some((v, next))
}
/// First value of a SHORT/LONG entry.
pub fn uint(&self, e: &Entry) -> Option<u32> {
match e.typ {
3 => self.u16_at(e.value_pos).map(u32::from),
4 | 13 => self.u32_at(e.value_pos),
1 | 7 => self.data.get(e.value_pos).map(|b| *b as u32),
_ => None,
}
}
orientation.unwrap_or(1)
/// Raw bytes of an entry's value (for ASCII/UNDEFINED/BYTE types).
pub fn bytes(&self, e: &Entry) -> Option<&'a [u8]> {
let size = match e.typ {
1 | 2 | 6 | 7 => 1usize,
3 | 8 => 2,
4 | 9 | 11 | 13 => 4,
5 | 10 | 12 => 8,
_ => return None,
};
let len = size.checked_mul(e.count as usize)?;
let start = if len <= 4 { e.value_pos } else { self.u32_at(e.value_pos)? as usize };
self.data.get(start..start.checked_add(len)?)
}
}
/// What the decoder cares about from an EXIF (TIFF-structured) blob.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ExifSummary {
/// Valid orientation (1–8), if present.
pub orientation: Option<u16>,
/// (offset, length) of the IFD1 JPEG thumbnail within the blob.
pub thumbnail: Option<(usize, usize)>,
/// EXIF ColorSpace = 0xFFFF with InteropIndex "R03" (Adobe RGB (1998) "option" files).
pub adobe_rgb_hint: bool,
}
pub fn summarize(blob: &[u8]) -> ExifSummary {
let mut s = ExifSummary::default();
let Some(t) = Tiff::new(blob) else { return s };
let Some(ifd0) = t.first_ifd() else { return s };
let Some((entries, next)) = t.ifd(ifd0) else { return s };
let mut exif_ifd = None;
for e in &entries {
match e.tag {
0x0112 => s.orientation = t.uint(e).map(|v| v as u16).filter(|v| (1..=8).contains(v)),
0x8769 => exif_ifd = t.uint(e).map(|v| v as usize),
_ => {}
}
}
if next != 0
&& next != ifd0
&& let Some((e1, _)) = t.ifd(next)
{
let off = e1.iter().find(|e| e.tag == 0x0201).and_then(|e| t.uint(e));
let len = e1.iter().find(|e| e.tag == 0x0202).and_then(|e| t.uint(e));
if let (Some(o), Some(l)) = (off, len) {
let (o, l) = (o as usize, l as usize);
if l > 4 && o.checked_add(l).is_some_and(|end| end <= blob.len()) && blob[o..o + 2] == [0xFF, 0xD8] {
s.thumbnail = Some((o, l));
}
}
}
if let Some(p) = exif_ifd
&& let Some((ee, _)) = t.ifd(p)
{
let cs = ee.iter().find(|e| e.tag == 0xA001).and_then(|e| t.uint(e));
let interop = ee.iter().find(|e| e.tag == 0xA005).and_then(|e| t.uint(e));
if cs == Some(0xFFFF)
&& let Some((ie, _)) = interop.and_then(|p| t.ifd(p as usize))
{
s.adobe_rgb_hint = ie.iter().any(|e| e.tag == 1 && t.bytes(e).is_some_and(|b| b.starts_with(b"R03")));
}
}
s
}
/// Build a tiny EXIF blob (little-endian TIFF) with just an orientation tag. Used by tests and by
/// callers that need to stamp orientation on export when no source EXIF exists.
pub fn minimal_exif(orientation: u16) -> Vec<u8> {
let mut v = Vec::with_capacity(26);
v.extend_from_slice(b"II");
v.extend_from_slice(&42u16.to_le_bytes());
v.extend_from_slice(&8u32.to_le_bytes());
v.extend_from_slice(&1u16.to_le_bytes());
v.extend_from_slice(&0x0112u16.to_le_bytes());
v.extend_from_slice(&3u16.to_le_bytes());
v.extend_from_slice(&1u32.to_le_bytes());
v.extend_from_slice(&orientation.to_le_bytes());
v.extend_from_slice(&[0, 0]);
v.extend_from_slice(&0u32.to_le_bytes());
v
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_legacy_count_zero_but_bounds_the_table() {
let mut b = b"II\x2a\0\x08\0\0\0\x01\0\x12\x01\x03\0\0\0\0\0\x06\0\0\0".to_vec();
assert_eq!(orientation(&b), 6);
b.truncate(21);
assert_eq!(orientation(&b), 1);
let mut bytes = minimal_exif(6);
bytes[14..18].fill(0);
assert_eq!(orientation(&bytes), 6);
bytes.truncate(21);
assert_eq!(orientation(&bytes), 1);
}
#[test]
fn orientation_roundtrip() {
for o in 1..=8 {
assert_eq!(summarize(&minimal_exif(o)).orientation, Some(o));
}
}
#[test]
fn garbage_ok() {
assert_eq!(summarize(b"II*\0\xff\xff\xff\xff"), ExifSummary::default());
assert_eq!(summarize(&[]), ExifSummary::default());
}
}