Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Linked smart objects: read embedded WebP/GIF/BMP/EXR sizes from their headers (#5216)

Valentin Klein88b2a21b335f
diff --git a/crates/codecs/src/codecs/exr.rs b/crates/codecs/src/codecs/exr.rs
index 2506dd062..a55810b4b 100644
--- a/crates/codecs/src/codecs/exr.rs
+++ b/crates/codecs/src/codecs/exr.rs
@@ -187,6 +187,21 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError>
Ok(img)
}
+/// The size of the part [`decode`] opens, from the headers alone. Deep files are refused (their
+/// flattened size comes from the deep decoder), as is a part [`decode`] cannot show.
+pub(crate) fn probe(bytes: &[u8], limits: &Limits) -> Result<(u32, u32), CodecError> {
+ let meta = read_meta(bytes, limits)?;
+ if meta.requirements.has_deep_data {
+ return Err(CodecError::unsupported(F, "no header-only size probe for deep data"));
+ }
+ let pick = pick_part(&meta);
+ let info = meta.headers.get(pick).map(|h| part_info(pick, h)).ok_or_else(|| err("no parts"))?;
+ if info.color_rank() == 0 {
+ return Err(CodecError::unsupported(F, "no R/G/B or Y channels"));
+ }
+ Ok((info.width, info.height))
+}
+
/// Decode one part of a multi-part file by its index into [`info`]'s list. A file with
/// deep parts is not mixed: the deep decoder composites those instead.
pub(crate) fn decode_part(bytes: &[u8], index: usize, limits: &Limits) -> Result<Image, CodecError> {
diff --git a/crates/codecs/src/codecs/via_image.rs b/crates/codecs/src/codecs/via_image.rs
index c91be5baf..7e7eb76b2 100644
--- a/crates/codecs/src/codecs/via_image.rs
+++ b/crates/codecs/src/codecs/via_image.rs
@@ -37,7 +37,8 @@ pub(crate) fn bmp_palette(bytes: &[u8]) -> Result<Option<Vec<[u8; 3]>>, CodecErr
Ok(decoder.get_palette().map(|palette| palette.to_vec()))
}
-pub(crate) fn decode(f: Format, bytes: &[u8], limits: &Limits) -> Result<Image, CodecError> {
+/// The `image` decoder for `f` with our limits, its header read and its size checked.
+fn open<'a>(f: Format, bytes: &'a [u8], limits: &Limits) -> Result<impl ImageDecoder + 'a, CodecError> {
let fmt = image_format(f).ok_or_else(|| CodecError::unsupported(f, "not handled by image backend"))?;
let mut reader = image::ImageReader::with_format(Cursor::new(bytes), fmt);
let mut il = image::Limits::default();
@@ -45,9 +46,14 @@ pub(crate) fn decode(f: Format, bytes: &[u8], limits: &Limits) -> Result<Image,
il.max_image_height = Some(limits.max_height);
il.max_alloc = Some(limits.max_alloc);
reader.limits(il);
- let mut dec = reader.into_decoder().map_err(|e| map_err(f, e))?;
+ let dec = reader.into_decoder().map_err(|e| map_err(f, e))?;
let (w, h) = dec.dimensions();
limits.check_bytes(w, h, dec.color_type().bytes_per_pixel() as u64)?;
+ Ok(dec)
+}
+
+pub(crate) fn decode(f: Format, bytes: &[u8], limits: &Limits) -> Result<Image, CodecError> {
+ let mut dec = open(f, bytes, limits)?;
let icc = dec.icc_profile().ok().flatten();
let exif = dec.exif_metadata().ok().flatten();
let dynimg = DynamicImage::from_decoder(dec).map_err(|e| map_err(f, e))?;
@@ -60,6 +66,18 @@ pub(crate) fn decode(f: Format, bytes: &[u8], limits: &Limits) -> Result<Image,
Ok(img)
}
+/// The stored size and EXIF block [`decode`] would find, from the decoder's header alone: the
+/// same reader, limits and size check, without decoding pixels. AVIF is refused: its decoder
+/// decodes the image as it opens.
+pub(crate) fn probe(f: Format, bytes: &[u8], limits: &Limits) -> Result<(u32, u32, Option<Vec<u8>>), CodecError> {
+ if f == Format::Avif {
+ return Err(CodecError::unsupported(f, "no header-only size probe"));
+ }
+ let mut dec = open(f, bytes, limits)?;
+ let (w, h) = dec.dimensions();
+ Ok((w, h, dec.exif_metadata().ok().flatten()))
+}
+
/// Counts a GIF's frames (image descriptors) by walking its blocks, without decompressing any.
/// The total is unknown when the blocks end before the trailer or break off.
fn gif_more_frames(b: &[u8]) -> Option<DecodeWarning> {
diff --git a/crates/codecs/src/codecs/webp.rs b/crates/codecs/src/codecs/webp.rs
index 36473041d..b7b6e2a66 100644
--- a/crates/codecs/src/codecs/webp.rs
+++ b/crates/codecs/src/codecs/webp.rs
@@ -17,7 +17,10 @@ fn err(e: impl std::fmt::Display) -> CodecError {
CodecError::malformed(F, e)
}
-pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError> {
+type Decoder<'a> = image_webp::WebPDecoder<Cursor<&'a [u8]>>;
+
+/// The decoder with its chunks read, the stored size and the output layout, the size checked.
+fn open<'a>(bytes: &'a [u8], limits: &Limits) -> Result<(Decoder<'a>, u32, u32, ChannelLayout), CodecError> {
let mut dec = image_webp::WebPDecoder::new(Cursor::new(bytes)).map_err(err)?;
dec.set_memory_limit(limits.alloc_usize());
let (w, h) = dec.dimensions();
@@ -26,6 +29,11 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError>
// VP8L back-references and VP8 skipped macroblocks compress flat areas extremely well, so the
// ratio is generous; it still stops a header-only file from asking for a gigabyte.
Limits::check_plausible(u64::from(w) * u64::from(h) * layout.channels() as u64, bytes.len(), 1 << 16)?;
+ Ok((dec, w, h, layout))
+}
+
+pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError> {
+ let (mut dec, w, h, layout) = open(bytes, limits)?;
let size = dec.output_buffer_size().ok_or_else(|| err("image too large"))?;
let mut buf = alloc_zeroed::<u8>(size)?;
dec.read_image(&mut buf).map_err(err)?;
@@ -41,6 +49,13 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError>
Ok(img)
}
+/// The stored size and EXIF block [`decode`] would find, from the container's chunks alone: the
+/// same header reads and size checks, without decoding the bitstream.
+pub(crate) fn probe(bytes: &[u8], limits: &Limits) -> Result<(u32, u32, Option<Vec<u8>>), CodecError> {
+ let (mut dec, w, h, _) = open(bytes, limits)?;
+ Ok((w, h, dec.exif_metadata().ok().flatten()))
+}
+
pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result<Vec<u8>, CodecError> {
let img = src.converted(plan.layout, plan.sample);
if !opts.webp_lossless {
diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs
index 438e1857e..3831cf654 100644
--- a/crates/codecs/src/lib.rs
+++ b/crates/codecs/src/lib.rs
@@ -102,6 +102,27 @@ pub fn decode_as_with(format: Format, bytes: &[u8], opts: &DecodeOptions) -> Res
finish_decode(img, o, opts)
}
+/// The upright pixel size [`decode`] would return, read from the file's header without decoding
+/// pixels, for WebP, OpenEXR (flat) and the GIF/BMP/TGA/ICO/QOI/HDR family. It runs the same
+/// header reads and size checks as the decoder (default [`Limits`]) and swaps the size for an
+/// EXIF orientation of 5–8, so wherever [`decode`] succeeds the two agree. Other formats (and
+/// deep EXR or AVIF) return [`CodecError::Unsupported`]: decode those to learn their size.
+pub fn probe_size(bytes: &[u8]) -> Result<(u32, u32), CodecError> {
+ let format = detect(bytes).ok_or(CodecError::UnknownFormat)?;
+ if !caps(format).read {
+ return Err(CodecError::unsupported(format, "decoding is not available for this format"));
+ }
+ let l = &Limits::default();
+ let (w, h, exif) = match format {
+ Format::WebP => webp::probe(bytes, l)?,
+ Format::OpenExr => exr::probe(bytes, l).map(|(w, h)| (w, h, None))?,
+ Format::Gif | Format::Bmp | Format::Tga | Format::Ico | Format::Qoi | Format::Hdr | Format::Avif => via_image::probe(format, bytes, l)?,
+ _ => return Err(CodecError::unsupported(format, "no header-only size probe")),
+ };
+ let o = exif.as_deref().map_or(1, exif_orientation);
+ Ok(if (5..=8).contains(&o) { (h, w) } else { (w, h) })
+}
+
/// Returns the embedded colour table for an indexed BMP, if it has one.
pub fn bmp_palette(bytes: &[u8]) -> Result<Option<Vec<[u8; 3]>>, CodecError> {
via_image::bmp_palette(bytes)
diff --git a/crates/codecs/tests/orientation.rs b/crates/codecs/tests/orientation.rs
index 980833079..c1f176b87 100644
--- a/crates/codecs/tests/orientation.rs
+++ b/crates/codecs/tests/orientation.rs
@@ -236,6 +236,7 @@ fn webp_opens_upright() {
// WebP has no gray mode: it comes back as RGB.
let img = decode(&out).unwrap().convert(ChannelLayout::Gray, SampleType::U8);
assert_eq!((img.dimensions(), img.data()), ((w as u32, h as u32), &up[..]), "o={o}");
+ assert_eq!(probe_size(&out).unwrap(), (w as u32, h as u32), "the header probe turns upright too, o={o}");
}
}
@@ -554,3 +555,24 @@ fn long_orientation_reads_and_rewrites_in_both_byte_orders() {
assert_eq!(kept.strip_prefix(b"Exif\0\0").unwrap_or(kept), &ifd(big, &[long(1)], &[])[..]);
}
}
+
+/// `probe_size` reads the size `decode` returns from the header alone, for every format it
+/// covers, and a file cut short inside its header is refused rather than given a size.
+#[test]
+fn probe_size_matches_decode() {
+ let img = synth(7, 5, ChannelLayout::Rgb, SampleType::U8, 3, 0.0);
+ let probed = [Format::WebP, Format::Gif, Format::Bmp, Format::Tga, Format::Qoi, Format::Hdr, Format::Ico, Format::OpenExr];
+ assert!(probed.iter().all(|f| rw_formats().contains(f)));
+ for format in rw_formats() {
+ let bytes = encode(&img, format, &EncodeOptions::default()).unwrap();
+ let decoded = decode(&bytes).unwrap().dimensions();
+ match probe_size(&bytes) {
+ Ok(size) => assert_eq!(size, decoded, "{format:?}"),
+ Err(_) => assert!(!probed.contains(&format), "{format:?} should be probed"),
+ }
+ if probed.contains(&format) {
+ assert!(probe_size(&bytes[..10]).is_err(), "{format:?} cut inside its header");
+ }
+ }
+ assert!(probe_size(&[]).is_err());
+}
diff --git a/crates/io/src/linked.rs b/crates/io/src/linked.rs
index 6634735ef..e200b875e 100644
--- a/crates/io/src/linked.rs
+++ b/crates/io/src/linked.rs
@@ -136,9 +136,11 @@ pub(crate) fn source_size_in_blocks<'a>(
}
/// Pixel size of an embedded source file from its header: PSD/PSB, TIFF (the default page's
-/// directory), PNG (`IHDR`) and JPEG (the frame header); any other image is decoded flat by
-/// `photocraft-codecs`. It never imports a document: a layered TIFF can carry PSD layer data
-/// whose `lnkD` holds another file, so a full import here would nest without bound (#2465).
+/// directory), PNG (`IHDR`) and JPEG (the frame header); WebP, GIF, BMP, EXR and the rest of
+/// `photocraft_codecs::probe_size`'s formats from their decoder's header; anything else (or a
+/// header that probe cannot read) is decoded flat by `photocraft-codecs`. It never imports a
+/// document: a layered TIFF can carry PSD layer data whose `lnkD` holds another file, so a full
+/// import here would nest without bound (#2465).
pub(crate) fn source_size_probe(bytes: &[u8]) -> Option<(f64, f64)> {
let be32 = |at: usize| bytes.get(at..at + 4).map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]));
let size = |w: u32, h: u32| (f64::from(w), f64::from(h));
@@ -151,10 +153,7 @@ pub(crate) fn source_size_probe(bytes: &[u8]) -> Option<(f64, f64)> {
}
[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A, ..] => be32(16).zip(be32(20)).map(|(w, h)| size(w, h)),
[0xFF, 0xD8, ..] => jpeg_size(bytes),
- _ => photocraft_codecs::decode(bytes).ok().map(|img| {
- let (w, h) = img.dimensions();
- size(w, h)
- }),
+ _ => photocraft_codecs::probe_size(bytes).or_else(|_| photocraft_codecs::decode(bytes).map(|img| img.dimensions())).ok().map(|(w, h)| size(w, h)),
}
}
@@ -408,9 +407,11 @@ mod tests {
fn source_size_probe_reads_headers() {
use photocraft_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType};
let img = Image::new(7, 5, ChannelLayout::Rgb, SampleType::U8).unwrap();
- for format in [Format::Png, Format::Jpeg, Format::Tiff, Format::Bmp] {
+ for format in [Format::Png, Format::Jpeg, Format::Tiff, Format::Bmp, Format::WebP, Format::Gif, Format::OpenExr, Format::Tga] {
let bytes = photocraft_codecs::encode(&img, format, &EncodeOptions::default()).unwrap();
assert_eq!(source_size_probe(&bytes), Some((7.0, 5.0)), "{format:?}");
+ // A header cut short neither panics nor invents a size (the decode fallback fails too).
+ assert_eq!(source_size_probe(&bytes[..10]), None, "{format:?} truncated");
}
let mut psd = b"8BPS\0\x01".to_vec();
psd.extend([0; 6]);