From a2541707240580153c8ea9ef3043ec0257468d0a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 15:48:40 +0000 Subject: [PATCH 01/10] Share WebP header inspection --- crates/image-codecs/src/lib.rs | 1 + crates/image-codecs/src/webp_probe.rs | 47 +++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 crates/image-codecs/src/webp_probe.rs diff --git a/crates/image-codecs/src/lib.rs b/crates/image-codecs/src/lib.rs index 6516b9ff2..961a04327 100644 --- a/crates/image-codecs/src/lib.rs +++ b/crates/image-codecs/src/lib.rs @@ -31,6 +31,7 @@ pub mod orientation; pub mod resolution; pub mod source_settings; pub mod web; +pub mod webp_probe; pub use crate::allocation::probe_allocation_size; pub use crate::cicp::Cicp; pub use crate::cicp::ContentLightLevel; diff --git a/crates/image-codecs/src/webp_probe.rs b/crates/image-codecs/src/webp_probe.rs new file mode 100644 index 000000000..8376274df --- /dev/null +++ b/crates/image-codecs/src/webp_probe.rs @@ -0,0 +1,47 @@ +//! Header-only WebP inspection with image-chunk completeness checks. + +use crate::{CodecError, Format}; + +/// Stored width, height and EXIF orientation without decoding pixels. The image payload must +/// fit in the input, but its compressed contents are not validated. Uses the default decode limits. +pub fn header(bytes: &[u8]) -> Result<(u32, u32, u16), CodecError> { + let err = |s: &str| CodecError::malformed(Format::WebP, s); + let mut p = 12usize; + let mut has_image = false; + let mut exif = None; + while let Some(h) = bytes.get(p..p.saturating_add(8)) { + let size = u32::from_le_bytes([h[4], h[5], h[6], h[7]]) as usize; + let end = p.saturating_add(8).saturating_add(size); + if matches!(&h[..4], b"VP8 " | b"VP8L" | b"ANMF") { + if end > bytes.len() { + return Err(err("truncated image data")); + } + has_image = true; + } else if &h[..4] == b"EXIF" && end <= bytes.len() && exif.is_none() { + exif = bytes.get(p + 8..end); + } + p = end.saturating_add(size & 1); + } + if !has_image { + return Err(err("no image data")); + } + let (w, h) = crate::probe_size(bytes)?; + let orientation = exif.map_or(1, crate::exif_orientation); + let (w, h) = if (5..=8).contains(&orientation) { (h, w) } else { (w, h) }; + Ok((w, h, orientation)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rejects_missing_and_truncated_image_chunks() { + let mut bytes = b"RIFF\x00\x00\x00\x00WEBP".to_vec(); + assert!(header(&bytes).is_err()); + bytes.extend_from_slice(b"VP8 "); + bytes.extend_from_slice(&10u32.to_le_bytes()); + bytes.push(0); + assert!(header(&bytes).is_err()); + } +} From 8a1bad8c2cc47f71c2a75fb19b67b54762fe8389 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 15:48:56 +0000 Subject: [PATCH 02/10] Cover WebP stored orientation --- crates/image-codecs/src/webp_probe.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/image-codecs/src/webp_probe.rs b/crates/image-codecs/src/webp_probe.rs index 8376274df..d70fac38d 100644 --- a/crates/image-codecs/src/webp_probe.rs +++ b/crates/image-codecs/src/webp_probe.rs @@ -35,6 +35,14 @@ pub fn header(bytes: &[u8]) -> Result<(u32, u32, u16), CodecError> { mod tests { use super::*; + #[test] + fn preserves_stored_dimensions_with_exif_orientation() { + let mut image = crate::Image::from_u8(2, 3, crate::ChannelLayout::Rgb, vec![42; 18]).unwrap(); + image.meta.exif = Some(b"II\x2a\x00\x08\x00\x00\x00\x01\x00\x12\x01\x03\x00\x01\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00\x00".to_vec()); + let bytes = crate::encode(&image, Format::WebP, &crate::EncodeOptions::default()).unwrap(); + assert_eq!(header(&bytes).unwrap(), (2, 3, 6)); + } + #[test] fn rejects_missing_and_truncated_image_chunks() { let mut bytes = b"RIFF\x00\x00\x00\x00WEBP".to_vec(); From 82e258ab6eae4f4d6cd9dfe463a8640fd20c96d9 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 15:50:14 +0000 Subject: [PATCH 03/10] Exercise camera orientation in WebP fixture --- crates/image-codecs/src/webp_probe.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/image-codecs/src/webp_probe.rs b/crates/image-codecs/src/webp_probe.rs index d70fac38d..8e33a71cf 100644 --- a/crates/image-codecs/src/webp_probe.rs +++ b/crates/image-codecs/src/webp_probe.rs @@ -39,7 +39,11 @@ mod tests { fn preserves_stored_dimensions_with_exif_orientation() { let mut image = crate::Image::from_u8(2, 3, crate::ChannelLayout::Rgb, vec![42; 18]).unwrap(); image.meta.exif = Some(b"II\x2a\x00\x08\x00\x00\x00\x01\x00\x12\x01\x03\x00\x01\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00\x00".to_vec()); - let bytes = crate::encode(&image, Format::WebP, &crate::EncodeOptions::default()).unwrap(); + let mut bytes = crate::encode(&image, Format::WebP, &crate::EncodeOptions::default()).unwrap(); + // The writer correctly makes exported pixels upright; simulate a camera file carrying orientation 6. + let exif = bytes.windows(4).position(|v| v == b"EXIF").unwrap(); + let tiff = exif + 8; + bytes[tiff + 18] = 6; assert_eq!(header(&bytes).unwrap(), (2, 3, 6)); } From c6f4f5115e6d7e5a53180f297c7cda8c5c4cb3c9 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 17:12:58 +0000 Subject: [PATCH 04/10] Preserve legacy EXIF orientation in PNG inspection --- crates/image-codecs/src/png_probe.rs | 2 +- crates/metadata/src/compat_orientation.rs | 52 +++++++++++++++++++++++ crates/metadata/src/lib.rs | 1 + 3 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 crates/metadata/src/compat_orientation.rs diff --git a/crates/image-codecs/src/png_probe.rs b/crates/image-codecs/src/png_probe.rs index 7edda454d..73f1199eb 100644 --- a/crates/image-codecs/src/png_probe.rs +++ b/crates/image-codecs/src/png_probe.rs @@ -88,7 +88,7 @@ pub fn header_with_max_pixels(b: &[u8], max_pixels: u64) -> Result<(u32, u32, u1 if !after_idat { return Err(err("truncated image data")); } - Ok((w, h, exif.map_or(1, crate::exif_orientation))) + Ok((w, h, exif.map_or(1, craft_metadata::compat_orientation::orientation))) } /// Container color declarations preceding image data. Raw values leave color policy to callers. diff --git a/crates/metadata/src/compat_orientation.rs b/crates/metadata/src/compat_orientation.rs new file mode 100644 index 000000000..3590b7c48 --- /dev/null +++ b/crates/metadata/src/compat_orientation.rs @@ -0,0 +1,52 @@ +//! 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. + +/// 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. +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; + } + 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)); + } + } + orientation.unwrap_or(1) +} + +#[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); + } +} diff --git a/crates/metadata/src/lib.rs b/crates/metadata/src/lib.rs index ff2c530fa..05f9b81b4 100644 --- a/crates/metadata/src/lib.rs +++ b/crates/metadata/src/lib.rs @@ -20,6 +20,7 @@ //! [`Embedded`] and call [`from_embedded`]. pub mod camera_fields; +pub mod compat_orientation; mod container; pub mod cr3; mod datetime; From e3712dd643591f1a36ab04e5be6329e8fd4d8a76 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 17:14:48 +0000 Subject: [PATCH 05/10] Preserve legacy WebP EXIF orientation --- crates/image-codecs/src/webp_probe.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/image-codecs/src/webp_probe.rs b/crates/image-codecs/src/webp_probe.rs index 8e33a71cf..07d6e0269 100644 --- a/crates/image-codecs/src/webp_probe.rs +++ b/crates/image-codecs/src/webp_probe.rs @@ -26,7 +26,7 @@ pub fn header(bytes: &[u8]) -> Result<(u32, u32, u16), CodecError> { return Err(err("no image data")); } let (w, h) = crate::probe_size(bytes)?; - let orientation = exif.map_or(1, crate::exif_orientation); + let orientation = exif.map_or(1, craft_metadata::compat_orientation::orientation); let (w, h) = if (5..=8).contains(&orientation) { (h, w) } else { (w, h) }; Ok((w, h, orientation)) } From f04d6381c76a4ff68b255a59c17ee3b32d73949b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 17:18:18 +0000 Subject: [PATCH 06/10] Share legacy EXIF summary and thumbnail inspection --- crates/metadata/src/compat_orientation.rs | 206 ++++++++++++++++++---- 1 file changed, 168 insertions(+), 38 deletions(-) diff --git a/crates/metadata/src/compat_orientation.rs b/crates/metadata/src/compat_orientation.rs index 3590b7c48..69f6c9517 100644 --- a/crates/metadata/src/compat_orientation.rs +++ b/crates/metadata/src/compat_orientation.rs @@ -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> { + 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 { + 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 { + 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 { + 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, 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 { + 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, + /// (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 { + 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()); } } From 42abc84c82cd573e2fb0277298caffecb7bee905 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 17:19:33 +0000 Subject: [PATCH 07/10] Match legacy partial-value boundary --- crates/metadata/src/compat_orientation.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/metadata/src/compat_orientation.rs b/crates/metadata/src/compat_orientation.rs index 69f6c9517..22db7b414 100644 --- a/crates/metadata/src/compat_orientation.rs +++ b/crates/metadata/src/compat_orientation.rs @@ -163,7 +163,7 @@ mod tests { let mut bytes = minimal_exif(6); bytes[14..18].fill(0); assert_eq!(orientation(&bytes), 6); - bytes.truncate(21); + bytes.truncate(19); assert_eq!(orientation(&bytes), 1); } From 1fb21f048785bba73b5ba604ec61cf5fb69367b0 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 17:25:28 +0000 Subject: [PATCH 08/10] Share legacy TIFF RAW classification policy --- crates/image-codecs/src/codecs/tiff.rs | 93 +++++++++++++++++++- crates/image-codecs/src/lib.rs | 6 ++ crates/image-codecs/tests/legacy_tiff_raw.rs | 21 +++++ 3 files changed, 119 insertions(+), 1 deletion(-) create mode 100644 crates/image-codecs/tests/legacy_tiff_raw.rs diff --git a/crates/image-codecs/src/codecs/tiff.rs b/crates/image-codecs/src/codecs/tiff.rs index c74ab4436..376d3dcf6 100644 --- a/crates/image-codecs/src/codecs/tiff.rs +++ b/crates/image-codecs/src/codecs/tiff.rs @@ -71,6 +71,18 @@ const TAG_DNG_VERSION: u16 = 50706; /// first IFD is often a reduced preview, so this runs before decoding. /// Reads only bounds-checked header bytes; anything malformed is "not raw". fn camera_raw(b: &[u8]) -> bool { + camera_raw_mode(b, false) +} + +/// The older LightCraft RAW/TIFF classification policy, sharing this bounded directory walk. +pub(crate) fn legacy_camera_raw(b: &[u8]) -> bool { + camera_raw_mode(b, true) +} + +fn camera_raw_mode(b: &[u8], legacy: bool) -> bool { + if legacy && b.get(8..10) == Some(b"CR") { + return true; + } let le = match b.get(0..4) { Some(b"II*\0") => true, Some(b"MM\0*") => false, @@ -92,8 +104,48 @@ fn camera_raw(b: &[u8]) -> bool { let value = |e: usize| match u16_at(e.saturating_add(2))? { 3 => u16_at(e.saturating_add(8)).map(u32::from), 4 | 13 => u32_at(e.saturating_add(8)), + 1 | 7 if legacy => b.get(e.saturating_add(8)).copied().map(u32::from), _ => None, }; + // The compatibility policy recognizes Sony lossless YCbCr only when IFD0 names Sony. + let is_sony = if legacy { + u32_at(4) + .and_then(|v| usize::try_from(v).ok()) + .and_then(|ifd| { + let n = usize::from(u16_at(ifd)?); + if n > 4096 { + return None; + } + for i in 0..n { + let e = ifd.checked_add(2)?.checked_add(i.checked_mul(12)?)?; + let tag = u16_at(e)?; + let ty = u16_at(e + 2)?; + let count = u32_at(e + 4)? as usize; + if tag == 0x010f { + let matches = (|| { + let size = match ty { + 1 | 2 | 6 | 7 => 1usize, + 3 | 8 => 2, + 4 | 9 | 11 | 13 => 4, + 5 | 10 | 12 => 8, + _ => return None, + }; + let len = size.checked_mul(count)?; + let start = if len <= 4 { e + 8 } else { u32_at(e + 8)? as usize }; + Some(b.get(start..start.checked_add(len)?)?.get(..4)?.eq_ignore_ascii_case(b"SONY")) + })() + .unwrap_or(false); + if matches { + return Some(true); + } + } + } + Some(false) + }) + .unwrap_or(false) + } else { + false + }; let mut queue: Vec = u32_at(4).into_iter().collect(); let mut visited = 0; while let Some(ifd) = queue.pop() { @@ -104,6 +156,44 @@ fn camera_raw(b: &[u8]) -> bool { } let ifd = ifd as usize; let Some(n) = u16_at(ifd) else { continue }; + if legacy + && (n > 4096 + || (n > 0 + && ifd + .checked_add(2) + .and_then(|p| usize::from(n - 1).checked_mul(12).and_then(|v| p.checked_add(v))) + .and_then(|p| p.checked_add(8)) + .is_none_or(|end| end > b.len()))) + { + continue; + } + if is_sony { + let mut cfa = false; + let (mut compression, mut photo, mut samples) = (None, None, None); + let (mut saw_compression, mut saw_photo, mut saw_samples) = (false, false, false); + for i in 0..usize::from(n) { + let e = ifd.saturating_add(2 + 12 * i); + match u16_at(e) { + Some(0x828e) => cfa = true, + Some(0x0103) if !saw_compression => { + saw_compression = true; + compression = value(e); + } + Some(0x0106) if !saw_photo => { + saw_photo = true; + photo = value(e); + } + Some(0x0115) if !saw_samples => { + saw_samples = true; + samples = value(e); + } + _ => {} + } + } + if cfa && compression == Some(7) && photo == Some(6) && samples == Some(3) { + return true; + } + } for i in 0..usize::from(n) { let e = ifd.saturating_add(2 + 12 * i); let (Some(tag), Some(count)) = (u16_at(e), u32_at(e.saturating_add(4))) else { @@ -111,6 +201,7 @@ fn camera_raw(b: &[u8]) -> bool { }; match tag { TAG_DNG_VERSION => return true, + 0x0103 if legacy && matches!(value(e), Some(32767 | 32769 | 32770 | 34316 | 34713 | 65000 | 65535)) => return true, TAG_PHOTOMETRIC if matches!(value(e), Some(PHOTOMETRIC_CFA | PHOTOMETRIC_LINEAR_RAW)) => { return true; } @@ -125,7 +216,7 @@ fn camera_raw(b: &[u8]) -> bool { _ => {} } } - if let Some(next) = u32_at(ifd.saturating_add(2 + 12 * usize::from(n))).filter(|&o| o != 0) { + if !legacy && let Some(next) = u32_at(ifd.saturating_add(2 + 12 * usize::from(n))).filter(|&o| o != 0) { queue.push(next); } } diff --git a/crates/image-codecs/src/lib.rs b/crates/image-codecs/src/lib.rs index d8659bf54..96a6d78a2 100644 --- a/crates/image-codecs/src/lib.rs +++ b/crates/image-codecs/src/lib.rs @@ -216,6 +216,12 @@ pub fn probe_size(bytes: &[u8]) -> Result<(u32, u32), CodecError> { Ok(if (5..=8).contains(&o) { (h, w) } else { (w, h) }) } +/// Classify classic TIFF camera RAWs using LightCraft's historical bounded heuristic. +/// This compatibility policy differs from the decoder's own RAW rejection policy. +pub fn legacy_tiff_raw_hint(bytes: &[u8]) -> bool { + tiff::legacy_camera_raw(bytes) +} + /// A JPEG's frame as its header declares it, read without decoding pixels: the stored size, the /// layout [`decode`] returns, whether [`decode`] hands the file to its whole-coefficient /// decoder (arithmetic-coded, lossless or 12-bit frames), whose working set is several times the diff --git a/crates/image-codecs/tests/legacy_tiff_raw.rs b/crates/image-codecs/tests/legacy_tiff_raw.rs new file mode 100644 index 000000000..87d99bad7 --- /dev/null +++ b/crates/image-codecs/tests/legacy_tiff_raw.rs @@ -0,0 +1,21 @@ +use craft_image_codecs::legacy_tiff_raw_hint; + +fn tiff(tag: u16, ty: u16, value: u32) -> Vec { + let mut b = b"II\x2a\0\x08\0\0\0\x01\0".to_vec(); + b.extend_from_slice(&tag.to_le_bytes()); + b.extend_from_slice(&ty.to_le_bytes()); + b.extend_from_slice(&1u32.to_le_bytes()); + b.extend_from_slice(&value.to_le_bytes()); + b.extend_from_slice(&0u32.to_le_bytes()); + b +} + +#[test] +fn recognizes_legacy_raw_compression_and_broad_cr_marker() { + assert!(legacy_tiff_raw_hint(&tiff(0x0103, 3, 34713))); + assert!(!legacy_tiff_raw_hint(&tiff(0x0103, 3, 1))); + assert!(legacy_tiff_raw_hint(b"II*\0\x08\0\0\0CR")); + let mut cut = tiff(0xc612, 1, 1); + cut.truncate(17); + assert!(!legacy_tiff_raw_hint(&cut)); +} From 72f4465d027fff411850407b25c81fc71a37f6cd Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 00:26:49 +0100 Subject: [PATCH 09/10] metadata: cover big-endian, thumbnail and interop paths in the legacy EXIF summary --- crates/metadata/src/compat_orientation.rs | 55 +++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/crates/metadata/src/compat_orientation.rs b/crates/metadata/src/compat_orientation.rs index 22db7b414..9a4b90a99 100644 --- a/crates/metadata/src/compat_orientation.rs +++ b/crates/metadata/src/compat_orientation.rs @@ -179,4 +179,59 @@ mod tests { assert_eq!(summarize(b"II*\0\xff\xff\xff\xff"), ExifSummary::default()); assert_eq!(summarize(&[]), ExifSummary::default()); } + + /// Big-endian IFD: `entries` are (tag, type, count, value-or-offset), value left-justified. + fn be_ifd(out: &mut Vec, entries: &[(u16, u16, u32, [u8; 4])], next: u32) { + out.extend_from_slice(&(entries.len() as u16).to_be_bytes()); + for (tag, typ, count, value) in entries { + out.extend_from_slice(&tag.to_be_bytes()); + out.extend_from_slice(&typ.to_be_bytes()); + out.extend_from_slice(&count.to_be_bytes()); + out.extend_from_slice(value); + } + out.extend_from_slice(&next.to_be_bytes()); + } + + #[test] + fn big_endian_thumbnail_and_adobe_rgb_interop_hint() { + let (ifd1, exif, interop, rational, thumb) = (38u32, 68u32, 98u32, 164u32, 172u32); + let mut b = b"MM\0\x2a\0\0\0\x08".to_vec(); + be_ifd(&mut b, &[(0x0112, 3, 1, [0, 6, 0, 0]), (0x8769, 4, 1, exif.to_be_bytes())], ifd1); + be_ifd(&mut b, &[(0x0201, 4, 1, thumb.to_be_bytes()), (0x0202, 1, 1, [6, 0, 0, 0])], 0); + be_ifd(&mut b, &[(0xA001, 3, 1, [0xFF, 0xFF, 0, 0]), (0xA005, 13, 1, interop.to_be_bytes())], 0); + // Every tag-1 candidate is read; only the ASCII "R03" one matches. + be_ifd( + &mut b, + &[(1, 99, 1, [0; 4]), (1, 5, 1, rational.to_be_bytes()), (1, 4, 1, *b"R98\0"), (1, 3, 1, *b"R9\0\0"), (1, 2, 4, *b"R03\0")], + 0, + ); + assert_eq!(b.len(), rational as usize); + b.extend_from_slice(&[0, 0, 0, 1, 0, 0, 0, 2]); + b.extend_from_slice(&[0xFF, 0xD8, 0xFF, 0xD9, 0, 0]); + let s = summarize(&b); + assert_eq!(s, ExifSummary { orientation: Some(6), thumbnail: Some((thumb as usize, 6)), adobe_rgb_hint: true }); + // A thumbnail that is not a JPEG, or runs past the blob, is ignored. + let mut not_jpeg = b.clone(); + not_jpeg[thumb as usize] = 0; + assert_eq!(summarize(¬_jpeg).thumbnail, None); + assert_eq!(summarize(&b[..b.len() - 1]).thumbnail, None); + // Without ColorSpace 0xFFFF the interop index is not consulted. + let mut srgb = b.clone(); + srgb[(exif + 10) as usize] = 0; + assert!(!summarize(&srgb).adobe_rgb_hint); + } + + #[test] + fn rejects_bad_headers_types_and_oversized_tables() { + assert_eq!(summarize(b"XX\0\x2a\0\0\0\x08"), ExifSummary::default()); + assert_eq!(summarize(b"MM\0\x2b\0\0\0\x08"), ExifSummary::default()); + let mut huge = b"MM\0\x2a\0\0\0\x08".to_vec(); + huge.extend_from_slice(&5000u16.to_be_bytes()); + assert_eq!(summarize(&huge), ExifSummary::default()); + // Orientation stored with an unsupported type (SRATIONAL) is ignored. + let mut bytes = minimal_exif(6); + bytes[12..14].copy_from_slice(&10u16.to_le_bytes()); + assert_eq!(orientation(&bytes), 1); + assert_eq!(orientation(&[b"Exif\0\0".as_slice(), &minimal_exif(3)].concat()), 3); + } } From 2c2fcd1a28e27f6931e102068228a945dc89623e Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 00:50:39 +0100 Subject: [PATCH 10/10] image-codecs: cover the legacy Sony lossless YCbCr rule and skipped directories --- crates/image-codecs/tests/legacy_tiff_raw.rs | 44 ++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/crates/image-codecs/tests/legacy_tiff_raw.rs b/crates/image-codecs/tests/legacy_tiff_raw.rs index 87d99bad7..770801734 100644 --- a/crates/image-codecs/tests/legacy_tiff_raw.rs +++ b/crates/image-codecs/tests/legacy_tiff_raw.rs @@ -19,3 +19,47 @@ fn recognizes_legacy_raw_compression_and_broad_cr_marker() { cut.truncate(17); assert!(!legacy_tiff_raw_hint(&cut)); } + +/// A little-endian TIFF with one IFD of (tag, type, count, value) entries and `tail` after it. +fn ifd(entries: &[(u16, u16, u32, [u8; 4])], tail: &[u8]) -> Vec { + let mut b = b"II\x2a\0\x08\0\0\0".to_vec(); + b.extend_from_slice(&(entries.len() as u16).to_le_bytes()); + for (tag, ty, count, value) in entries { + b.extend_from_slice(&tag.to_le_bytes()); + b.extend_from_slice(&ty.to_le_bytes()); + b.extend_from_slice(&count.to_le_bytes()); + b.extend_from_slice(value); + } + b.extend_from_slice(&0u32.to_le_bytes()); + b.extend_from_slice(tail); + b +} + +#[test] +fn sony_lossless_ycbcr_needs_a_sony_make_and_every_layout_tag() { + let short = |v: u16| [v.to_le_bytes()[0], v.to_le_bytes()[1], 0, 0]; + let layout = [(0x828e, 1, 4, [0, 1, 1, 2]), (0x0103, 3, 1, short(7)), (0x0106, 3, 1, short(6)), (0x0115, 3, 1, short(3))]; + // Make stored after the IFD (ASCII, 5 bytes): 8 + 2 + 5 * 12 + 4 = 74. + let with_make = |make: (u16, u16, u32, [u8; 4]), tail: &[u8]| ifd(&[&[make], &layout[..]].concat(), tail); + assert!(legacy_tiff_raw_hint(&with_make((0x010f, 2, 5, 74u32.to_le_bytes()), b"SONY\0"))); + assert!(legacy_tiff_raw_hint(&with_make((0x010f, 7, 4, *b"sony"), b""))); + assert!(!legacy_tiff_raw_hint(&with_make((0x010f, 2, 6, 74u32.to_le_bytes()), b"Nikon\0"))); + assert!(!legacy_tiff_raw_hint(&with_make((0x010f, 99, 4, *b"SONY"), b""))); + assert!(!legacy_tiff_raw_hint(&with_make((0x010f, 2, 5, 9999u32.to_le_bytes()), b""))); + // A Sony file without the full lossless layout is not a RAW by this rule. + let partial = ifd(&[(0x010f, 7, 4, *b"SONY"), layout[0], layout[1], layout[2]], b""); + assert!(!legacy_tiff_raw_hint(&partial)); + // Repeated tags: the first value wins. + let repeated = ifd(&[&[(0x010f, 7, 4, *b"SONY")], &layout[..], &[(0x0103, 3, 1, short(1))]].concat(), b""); + assert!(legacy_tiff_raw_hint(&repeated)); +} + +#[test] +fn oversized_or_cut_directories_are_skipped() { + let mut huge = b"II\x2a\0\x08\0\0\0".to_vec(); + huge.extend_from_slice(&5000u16.to_le_bytes()); + assert!(!legacy_tiff_raw_hint(&huge)); + let mut cut = ifd(&[(0x010f, 7, 4, *b"SONY"), (0x0103, 3, 1, [7, 0, 0, 0])], b""); + cut.truncate(20); + assert!(!legacy_tiff_raw_hint(&cut)); +}