Skip to content

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

Import warns when it keeps only the first frame or page, or a JPEG ends early (#518, #523) (#563)

BFlat8a8371395b01
diff --git a/apps/photocraft-cli/tests/cli.rs b/apps/photocraft-cli/tests/cli.rs
index 9ce1be6cb..90d596634 100644
--- a/apps/photocraft-cli/tests/cli.rs
+++ b/apps/photocraft-cli/tests/cli.rs
@@ -143,6 +143,37 @@ fn info_prints_layer_tree_json() {
std::fs::remove_dir_all(d).unwrap();
}
+/// #518, #523: a truncated JPEG and an animated GIF open, but `info` lists why the image is
+/// incomplete and `convert` prints it on stderr (and still succeeds); complete files stay quiet.
+#[test]
+fn info_and_convert_report_decode_warnings() {
+ let d = tmp("decode-warnings");
+ let noise: Vec<u8> = (0..64 * 48 * 3).map(|i: u32| (i.wrapping_mul(7919) % 251) as u8).collect();
+ let img = photocraft_codecs::Image::from_u8(64, 48, photocraft_codecs::ChannelLayout::Rgb, noise).unwrap();
+ let jpeg = photocraft_codecs::encode(&img, photocraft_codecs::Format::Jpeg, &Default::default()).unwrap();
+ // Three 1x1 frames.
+ let mut gif = b"GIF89a\x01\0\x01\0\x80\0\0\0\0\0\xFF\xFF\xFF".to_vec();
+ for _ in 0..3 {
+ gif.extend_from_slice(b"\x2C\0\0\0\0\x01\0\x01\0\0\x02\x02\x44\x01\0");
+ }
+ gif.push(0x3B);
+ let cases = [
+ ("whole.jpg", &jpeg[..], None),
+ ("half.jpg", &jpeg[..jpeg.len() / 2], Some("JPEG data ends early (the file is truncated or damaged); part of the image is missing")),
+ ("anim.gif", &gif[..], Some("only the first of 3 frames was imported")),
+ ];
+ for (name, bytes, warning) in cases {
+ let file = d.join(name);
+ std::fs::write(&file, bytes).unwrap();
+ let (out, _) = ok(bin().arg("info").arg(&file).arg("--compact"));
+ let v: Value = serde_json::from_str(&out).unwrap();
+ assert_eq!(v["warnings"], json!(warning.into_iter().collect::<Vec<_>>()), "{name}");
+ let (_, err) = ok(bin().arg("convert").arg(&file).arg(d.join(format!("{name}.png"))));
+ assert_eq!(err.trim(), warning.map(|w| format!("warning: {w}")).unwrap_or_default(), "{name}");
+ }
+ std::fs::remove_dir_all(d).unwrap();
+}
+
#[test]
fn run_commands_and_save() {
let d = tmp("run");
diff --git a/book/src/formats/raster-formats.md b/book/src/formats/raster-formats.md
index a2ee5ced0..5af721d8a 100644
--- a/book/src/formats/raster-formats.md
+++ b/book/src/formats/raster-formats.md
@@ -26,4 +26,4 @@ Format adapters pass compatible allocation limits into PNG, TIFF, WebP, and `ima
`Limits::none()` exists for callers with a deliberate reason to relax policy. It remains bounded by representable memory sizes, but it removes the default resource policy and should not be used for untrusted input.
-Animated containers are represented as a single decoded frame by the current codec API. Refer to [`crates/codecs/README.md`](https://github.com/storytold/photocraft/blob/main/crates/codecs/README.md) and source capability declarations for current behavior.
+Animated containers and multi-page TIFFs are represented as a single decoded frame or page by the current codec API; opening one adds an import warning such as "only the first of 3 frames was imported". A JPEG cut off inside its image data opens with a warning that its data ends early (an error when it holds no image data at all). Refer to [`crates/codecs/README.md`](https://github.com/storytold/photocraft/blob/main/crates/codecs/README.md) and source capability declarations for current behavior.
diff --git a/crates/automation/tests/mcp.rs b/crates/automation/tests/mcp.rs
index 313f23f7d..20eb83653 100644
--- a/crates/automation/tests/mcp.rs
+++ b/crates/automation/tests/mcp.rs
@@ -287,6 +287,28 @@ async fn open_png_and_inspect() {
cleanup(&dir);
}
+/// #518, #523: `doc_open` returns why an opened image is incomplete.
+#[tokio::test(flavor = "multi_thread")]
+async fn open_reports_decode_warnings() {
+ let dir = tmp("open-warnings");
+ let jpeg = write_image(&dir, "whole.jpg", photocraft_codecs::Format::Jpeg);
+ std::fs::write(dir.join("cut.jpg"), &jpeg[..jpeg.len() - 4]).unwrap();
+ // Two 1x1 frames.
+ let mut gif = b"GIF89a\x01\0\x01\0\x80\0\0\0\0\0\xFF\xFF\xFF".to_vec();
+ for _ in 0..2 {
+ gif.extend_from_slice(b"\x2C\0\0\0\0\x01\0\x01\0\0\x02\x02\x44\x01\0");
+ }
+ gif.push(0x3B);
+ std::fs::write(dir.join("anim.gif"), gif).unwrap();
+ let client = connect(headless_in(&dir)).await;
+ let warnings = async |path: &str| json_of(&call(&client, "doc_open", json!({"path": path})).await)["warnings"].clone();
+ assert_eq!(warnings("whole.jpg").await, json!([]));
+ assert_eq!(warnings("cut.jpg").await, json!(["JPEG data ends early (the file is truncated or damaged); part of the image is missing"]));
+ assert_eq!(warnings("anim.gif").await, json!(["only the first of 2 frames was imported"]));
+ client.cancel().await.unwrap();
+ cleanup(&dir);
+}
+
fn write_image(dir: &std::path::Path, name: &str, format: photocraft_codecs::Format) -> Vec<u8> {
let img = photocraft_codecs::Image::from_u8(16, 8, photocraft_codecs::ChannelLayout::Rgb, (0..384).map(|i| (i * 7 % 251) as u8).collect()).unwrap();
let bytes = photocraft_codecs::encode(&img, format, &Default::default()).unwrap();
diff --git a/crates/codecs/README.md b/crates/codecs/README.md
index 5657795fd..11ac365c1 100644
--- a/crates/codecs/README.md
+++ b/crates/codecs/README.md
@@ -15,7 +15,8 @@ It follows the "avoid GIMP's hole" rules in `plan/architecture.md` §1.1:
* **Honest.** `caps(format)` says what each format holds, and
`fidelity_warnings(&image, format)` lists what an export will lose before you write it. Both
functions use the same encode plan as `encode`, so a warning appears exactly when the file
- changes.
+ changes. On the way in, `Image::warnings` lists what the decoded image doesn't show: frames or
+ pages left out, or data that ended early.
```rust
use photocraft_codecs::*;
@@ -73,7 +74,10 @@ the same.
files.
* **Animation and multi-page files** (APNG, animated GIF/WebP, multi-page TIFF): only the first
frame or page is decoded, and a single frame is written. `FormatCaps::animation` marks
- containers that can hold more frames.
+ containers that can hold more frames. The decoded image then carries a
+ `DecodeWarning::MoreFrames` / `MorePages` in `Image::warnings`, with the total when the file
+ states it (frames and TIFF directories are counted without decoding them; reduced-resolution
+ TIFF directories and transparency masks are not pages).
* **EXIF in TIFF** is stored as a sub-IFD rather than a blob, so it is not preserved yet.
`caps.exif = false` for TIFF, and a warning is raised.
* **Orientation** (EXIF tag 274 in JPEG, PNG `eXIf` and WebP; the IFD0 tag in TIFF) is applied on
@@ -88,6 +92,9 @@ the same.
release).
* **JPEG**
* 8-bit only. Neither decoder backend supports 12-bit.
+ * A file cut off inside its image data decodes leniently (a baseline JPEG's missing rows come
+ out grey) but never silently: the image carries `DecodeWarning::Truncated`. A file that ends
+ before any scan data is an error.
* CMYK is always written 4:4:4 (subsampled CMYK is not portable) as Adobe-inverted CMYK with an
APP14 marker.
* Text is not written because there is no COM-segment support.
diff --git a/crates/codecs/src/codecs/jpeg.rs b/crates/codecs/src/codecs/jpeg.rs
index fbe779309..19e524a18 100644
--- a/crates/codecs/src/codecs/jpeg.rs
+++ b/crates/codecs/src/codecs/jpeg.rs
@@ -10,7 +10,7 @@ use zune_core::options::DecoderOptions;
use crate::Format;
use crate::error::CodecError;
use crate::fidelity::Plan;
-use crate::image::{ChannelLayout, Image, Metadata, SampleType};
+use crate::image::{ChannelLayout, DecodeWarning, Image, Metadata, SampleType};
use crate::options::{EncodeOptions, Limits};
use crate::orientation::{upright_exif, upright_xmp};
@@ -101,11 +101,70 @@ pub(crate) fn scan_metadata(b: &[u8]) -> JpegMeta {
m
}
+/// How a JPEG's data ends, seen from its marker structure.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum DataEnd {
+ /// An end-of-image marker follows the scans (or the structure is too odd to tell).
+ Complete,
+ /// The file ends inside the image data, before the end-of-image marker.
+ Truncated,
+ /// The file ends before the first scan holds any data: nothing can be decoded.
+ Empty,
+}
+
+/// Walks the marker segments (skipped by their length) and the entropy-coded scan data
+/// (skipped up to the next marker that isn't a stuffed `FF 00`, a restart or a fill byte),
+/// so an embedded thumbnail's end marker or data after the end of the image don't count.
+fn data_end(b: &[u8]) -> DataEnd {
+ // Where the bytes run out: inside the image data once a scan has held some.
+ let cut = |scan_data: bool| if scan_data { DataEnd::Truncated } else { DataEnd::Empty };
+ let mut i = 2; // past SOI
+ let mut scan_data = false;
+ loop {
+ let Some(&byte) = b.get(i) else { return cut(scan_data) };
+ if byte != 0xFF {
+ // Not where a marker should be: too odd to judge.
+ return DataEnd::Complete;
+ }
+ let Some(&code) = b.get(i + 1) else { return cut(scan_data) };
+ match code {
+ 0xD9 => return DataEnd::Complete,
+ 0xFF => i += 1,
+ 0x01 | 0xD0..=0xD8 => i += 2,
+ _ => {
+ let Some(len) = b.get(i + 2..i + 4).and_then(|s| <[u8; 2]>::try_from(s).ok()).map(u16::from_be_bytes) else {
+ return cut(scan_data);
+ };
+ i = i.saturating_add(2 + usize::from(len));
+ if code == 0xDA {
+ let start = i;
+ loop {
+ let Some(p) = b.get(i..).and_then(|r| r.iter().position(|&v| v == 0xFF)) else {
+ return cut(scan_data || b.len() > start);
+ };
+ i += p;
+ match b.get(i + 1) {
+ Some(0x00 | 0xD0..=0xD7) => i += 2,
+ Some(0xFF) => i += 1,
+ _ => break,
+ }
+ }
+ scan_data |= i > start;
+ }
+ }
+ }
+ }
+}
+
fn err(e: impl std::fmt::Display) -> CodecError {
CodecError::malformed(F, e)
}
pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError> {
+ let end = data_end(bytes);
+ if end == DataEnd::Empty {
+ return Err(err("the file ends before any image data"));
+ }
let meta = scan_metadata(bytes);
if let Some((w, h, nc)) = meta.frame {
limits.check_bytes(w, h, u64::from(nc.max(1)))?;
@@ -150,6 +209,9 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError>
let mut img = Image::from_raw(w, h, layout, SampleType::U8, px)?;
img.icc = meta.icc;
img.meta = Metadata { exif: meta.exif, xmp: meta.xmp, dpi: meta.dpi, text: Vec::new() };
+ if end == DataEnd::Truncated {
+ img.warnings.push(DecodeWarning::Truncated { format: F });
+ }
Ok(img)
}
diff --git a/crates/codecs/src/codecs/png.rs b/crates/codecs/src/codecs/png.rs
index c2ab4f03f..ad89f8a4c 100644
--- a/crates/codecs/src/codecs/png.rs
+++ b/crates/codecs/src/codecs/png.rs
@@ -6,7 +6,7 @@ use std::io::{Cursor, Write};
use crate::Format;
use crate::error::CodecError;
use crate::fidelity::Plan;
-use crate::image::{ChannelLayout, Image, Metadata, SampleType};
+use crate::image::{ChannelLayout, DecodeWarning, Image, Metadata, SampleType};
use crate::options::{EncodeOptions, Limits, PngCompression};
const F: Format = Format::Png;
@@ -27,6 +27,8 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError>
limits.check_bytes(w, h, 8)?;
}
let mut reader = decoder.read_info().map_err(map_png_err)?;
+ // APNG: the IDAT image is the first frame, or an extra default image when no fcTL precedes it.
+ let images = reader.info().animation_control.map_or(1, |a| u64::from(a.num_frames) + u64::from(reader.info().frame_control.is_none()));
let (color, depth) = reader.output_color_type();
let layout = match color {
png::ColorType::Grayscale => ChannelLayout::Gray,
@@ -82,6 +84,9 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError>
}
}
img.meta = meta;
+ if images > 1 {
+ img.warnings.push(DecodeWarning::MoreFrames { total: u32::try_from(images).ok() });
+ }
Ok(img)
}
diff --git a/crates/codecs/src/codecs/tiff.rs b/crates/codecs/src/codecs/tiff.rs
index fe7609f8d..ac5148f8b 100644
--- a/crates/codecs/src/codecs/tiff.rs
+++ b/crates/codecs/src/codecs/tiff.rs
@@ -1,6 +1,7 @@
//! TIFF via the `tiff` crate: 8/16-bit integer and 32-bit float, gray/RGB/
//! CMYK with optional (unassociated) alpha, ICC (34675), XMP (700), DPI and
-//! a few ASCII text tags. Only the first IFD is read.
+//! a few ASCII text tags. Only the first IFD is read; further pages are counted and reported
+//! as a [`DecodeWarning::MorePages`].
use std::borrow::Cow;
use std::io::Cursor;
@@ -13,7 +14,7 @@ use tiff::tags::{PhotometricInterpretation, ResolutionUnit, SampleFormat, Tag, T
use crate::Format;
use crate::error::CodecError;
use crate::fidelity::Plan;
-use crate::image::{ChannelLayout, Image, Metadata, SampleType};
+use crate::image::{ChannelLayout, DecodeWarning, Image, Metadata, SampleType};
use crate::options::{EncodeOptions, Limits, TiffCompression};
const F: Format = Format::Tiff;
@@ -230,9 +231,36 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError>
}
}
img.meta = meta;
+ img.warnings.extend(more_pages(&mut dec));
Ok(img)
}
+/// Counts the pages after the first IFD without decoding their pixels, skipping
+/// reduced-resolution copies (thumbnails) and transparency masks. The total is unknown when
+/// a directory can't be read or there are more than `MAX_IFDS`.
+fn more_pages(dec: &mut Decoder<Cursor<&[u8]>>) -> Option<DecodeWarning> {
+ const MAX_IFDS: u32 = 10_000;
+ let mut pages = 1u32;
+ let mut walked = 0;
+ let mut total = None;
+ loop {
+ if !dec.more_images() {
+ total = Some(pages);
+ break;
+ }
+ walked += 1;
+ if walked > MAX_IFDS || dec.next_image().is_err() {
+ break;
+ }
+ // NewSubfileType bit 0: a reduced-resolution image; bit 2: a transparency mask.
+ let kind = dec.find_tag_unsigned::<u32>(Tag::NewSubfileType).ok().flatten().unwrap_or(0);
+ if kind & 0b101 == 0 {
+ pages += 1;
+ }
+ }
+ (pages > 1).then_some(DecodeWarning::MorePages { total })
+}
+
fn rational_f64(v: tiff::decoder::ifd::Value) -> Option<f64> {
use tiff::decoder::ifd::Value;
match v {
diff --git a/crates/codecs/src/codecs/via_image.rs b/crates/codecs/src/codecs/via_image.rs
index 9ad550d5c..eca2fbb74 100644
--- a/crates/codecs/src/codecs/via_image.rs
+++ b/crates/codecs/src/codecs/via_image.rs
@@ -8,7 +8,7 @@ use image::{DynamicImage, ImageDecoder, ImageFormat};
use crate::Format;
use crate::error::CodecError;
use crate::fidelity::Plan;
-use crate::image::{ChannelLayout, Image, SampleType};
+use crate::image::{ChannelLayout, DecodeWarning, Image, SampleType};
use crate::options::{EncodeOptions, Limits};
fn image_format(f: Format) -> Option<ImageFormat> {
@@ -49,9 +49,49 @@ pub(crate) fn decode(f: Format, bytes: &[u8], limits: &Limits) -> Result<Image,
let mut img = from_dynamic(f, dynimg)?;
img.icc = icc;
img.meta.exif = exif;
+ if f == Format::Gif {
+ img.warnings.extend(gif_more_frames(bytes));
+ }
Ok(img)
}
+/// 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> {
+ // Size of the colour table a packed-fields byte announces.
+ let table = |flags: u8| if flags & 0x80 != 0 { 3usize << ((flags & 7) + 1) } else { 0 };
+ // Skips the data sub-blocks starting at `i` (each length-prefixed, ended by a zero length).
+ let skip = |mut i: usize| -> Option<usize> {
+ loop {
+ let n = usize::from(*b.get(i)?);
+ i = i.checked_add(1 + n)?;
+ if n == 0 {
+ return Some(i);
+ }
+ }
+ };
+ // Header (6 bytes), logical screen descriptor (7) and the global colour table.
+ let mut i = 13 + table(*b.get(10)?);
+ let mut frames = 0u32;
+ let total = loop {
+ let next = match b.get(i) {
+ Some(0x3B) => break Some(frames),
+ Some(0x21) => skip(i + 2),
+ Some(0x2C) => {
+ frames = frames.saturating_add(1);
+ // Descriptor (10 bytes, packed fields last), local colour table, LZW code size.
+ b.get(i + 9).and_then(|&flags| skip(i + 11 + table(flags)))
+ }
+ _ => None,
+ };
+ match next {
+ Some(n) => i = n,
+ None => break None,
+ }
+ };
+ (frames > 1).then_some(DecodeWarning::MoreFrames { total })
+}
+
pub(crate) fn from_dynamic(f: Format, d: DynamicImage) -> Result<Image, CodecError> {
let (w, h) = (d.width(), d.height());
Ok(match d {
diff --git a/crates/codecs/src/codecs/webp.rs b/crates/codecs/src/codecs/webp.rs
index 103fa18d1..63733c49b 100644
--- a/crates/codecs/src/codecs/webp.rs
+++ b/crates/codecs/src/codecs/webp.rs
@@ -6,7 +6,7 @@ use std::io::Cursor;
use crate::Format;
use crate::error::CodecError;
use crate::fidelity::Plan;
-use crate::image::{ChannelLayout, Image, Metadata, SampleType};
+use crate::image::{ChannelLayout, DecodeWarning, Image, Metadata, SampleType};
use crate::options::{EncodeOptions, Limits};
const F: Format = Format::WebP;
@@ -30,6 +30,9 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError>
let mut img = Image::from_u8(w, h, layout, buf)?;
img.icc = icc;
img.meta = Metadata { exif, xmp, ..Default::default() };
+ if dec.is_animated() && dec.num_frames() > 1 {
+ img.warnings.push(DecodeWarning::MoreFrames { total: Some(dec.num_frames()) });
+ }
Ok(img)
}
diff --git a/crates/codecs/src/image.rs b/crates/codecs/src/image.rs
index b6dadd5ea..1aff7f5b4 100644
--- a/crates/codecs/src/image.rs
+++ b/crates/codecs/src/image.rs
@@ -4,7 +4,10 @@
//! in **native endianness**. Integer samples are unsigned and normalized to
//! `[0, max]`; float samples are nominally `[0, 1]` but may exceed it (HDR).
+use std::fmt;
+
use crate::error::CodecError;
+use crate::format::Format;
use half::f16;
/// Channel layout of an [`Image`]. Alpha, when present, is always the last
@@ -126,6 +129,33 @@ impl Metadata {
}
}
+/// Something a decoder noticed about the file that the decoded pixels don't show: the file
+/// held more than was decoded, or less than it should.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum DecodeWarning {
+ /// Only the first frame of an animation was decoded; `total` counts every frame when known.
+ MoreFrames { total: Option<u32> },
+ /// Only the first page of a multi-page file was decoded; `total` counts every page when known.
+ MorePages { total: Option<u32> },
+ /// The image data ends early (truncated or damaged file); the decoder filled in the rest
+ /// (a baseline JPEG's missing rows come out grey).
+ Truncated { format: Format },
+}
+
+impl fmt::Display for DecodeWarning {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ DecodeWarning::MoreFrames { total: Some(n) } => write!(f, "only the first of {n} frames was imported"),
+ DecodeWarning::MoreFrames { total: None } => write!(f, "only the first frame of the animation was imported"),
+ DecodeWarning::MorePages { total: Some(n) } => write!(f, "only the first of {n} pages was imported"),
+ DecodeWarning::MorePages { total: None } => write!(f, "only the first page of the file was imported"),
+ DecodeWarning::Truncated { format } => {
+ write!(f, "{} data ends early (the file is truncated or damaged); part of the image is missing", format.name())
+ }
+ }
+ }
+}
+
/// A single flat raster image.
#[derive(Debug, Clone, PartialEq)]
pub struct Image {
@@ -137,6 +167,9 @@ pub struct Image {
/// Embedded ICC profile (must describe `layout`'s colour model).
pub icc: Option<Vec<u8>>,
pub meta: Metadata,
+ /// What the decoder noticed about the file: empty for a complete, single image and for
+ /// images built in memory. Encoders ignore it.
+ pub warnings: Vec<DecodeWarning>,
}
fn byte_len(width: u32, height: u32, layout: ChannelLayout, sample: SampleType) -> Option<usize> {
@@ -147,7 +180,7 @@ impl Image {
/// A zero-filled image, or an error if the byte size overflows `usize`.
pub fn new(width: u32, height: u32, layout: ChannelLayout, sample: SampleType) -> Result<Self, CodecError> {
let len = byte_len(width, height, layout, sample).ok_or_else(|| CodecError::InvalidImage("image size overflows usize".into()))?;
- Ok(Image { width, height, layout, sample, data: vec![0; len], icc: None, meta: Metadata::default() })
+ Ok(Image { width, height, layout, sample, data: vec![0; len], icc: None, meta: Metadata::default(), warnings: Vec::new() })
}
/// Wrap raw interleaved, native-endian bytes.
@@ -156,7 +189,7 @@ impl Image {
if data.len() != expected {
return Err(CodecError::InvalidImage(format!("buffer has {} bytes, expected {expected} for {width}x{height} {layout:?} {sample:?}", data.len())));
}
- Ok(Image { width, height, layout, sample, data, icc: None, meta: Metadata::default() })
+ Ok(Image { width, height, layout, sample, data, icc: None, meta: Metadata::default(), warnings: Vec::new() })
}
pub fn from_u8(width: u32, height: u32, layout: ChannelLayout, data: Vec<u8>) -> Result<Self, CodecError> {
@@ -324,6 +357,7 @@ impl Image {
data,
icc: if layout.same_model(self.layout) { self.icc.clone() } else { None },
meta: self.meta.clone(),
+ warnings: self.warnings.clone(),
}
}
diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs
index 9b2fce25c..f63340f4e 100644
--- a/crates/codecs/src/lib.rs
+++ b/crates/codecs/src/lib.rs
@@ -26,7 +26,7 @@ pub use crate::codecs::png::encode_indexed as encode_png_indexed;
pub use crate::error::CodecError;
pub use crate::fidelity::{FidelityWarning, fidelity_warnings, fidelity_warnings_with};
pub use crate::format::{ASYMMETRIC_EXCEPTIONS, Format, FormatCaps, caps, detect, from_extension};
-pub use crate::image::{ChannelLayout, Image, Metadata, SampleType};
+pub use crate::image::{ChannelLayout, DecodeWarning, Image, Metadata, SampleType};
pub use crate::options::{DecodeOptions, EncodeOptions, ExrCompression, Limits, PngCompression, TiffCompression};
pub use crate::orientation::{exif_orientation, upright_exif, upright_xmp};
pub use half::f16;
diff --git a/crates/codecs/src/orientation.rs b/crates/codecs/src/orientation.rs
index 5e31d96fa..bd780429e 100644
--- a/crates/codecs/src/orientation.rs
+++ b/crates/codecs/src/orientation.rs
@@ -322,8 +322,9 @@ impl Image {
if swap {
meta.dpi = meta.dpi.map(|(x, y)| (y, x));
}
- let icc = self.icc.clone();
- Ok(Image::from_raw(ow as u32, oh as u32, layout, sample, data)?.with_icc(icc).with_meta(meta))
+ let mut out = Image::from_raw(ow as u32, oh as u32, layout, sample, data)?.with_icc(self.icc).with_meta(meta);
+ out.warnings = self.warnings;
+ Ok(out)
}
}
diff --git a/crates/codecs/tests/decode_warnings.rs b/crates/codecs/tests/decode_warnings.rs
new file mode 100644
index 000000000..5fc310104
--- /dev/null
+++ b/crates/codecs/tests/decode_warnings.rs
@@ -0,0 +1,309 @@
+//! Decode warnings: a file that holds more than was decoded (#523: animations, multi-page
+//! TIFF) or less than it should (#518: truncated JPEG) says so; complete single images don't.
+
+mod common;
+use common::*;
+use photocraft_codecs::*;
+
+const W: u32 = 24;
+const H: u32 = 16;
+
+fn solid(rgb: [u8; 3]) -> Image {
+ Image::from_u8(W, H, ChannelLayout::Rgb, rgb.repeat((W * H) as usize)).unwrap()
+}
+
+const COLOURS: [[u8; 3]; 3] = [[200, 30, 10], [10, 200, 30], [30, 10, 200]];
+
+// ---------------------------------------------------------------------------
+// #518: truncated JPEG
+// ---------------------------------------------------------------------------
+
+fn jpeg(layout: ChannelLayout, progressive: bool) -> Vec<u8> {
+ let img = synth(64, 48, layout, SampleType::U8, 3, 0.3);
+ let ct = match layout {
+ ChannelLayout::Gray => jpeg_encoder::ColorType::Luma,
+ ChannelLayout::Cmyk => jpeg_encoder::ColorType::Cmyk,
+ _ => jpeg_encoder::ColorType::Rgb,
+ };
+ let mut out = Vec::new();
+ let mut enc = jpeg_encoder::Encoder::new(&mut out, 90);
+ enc.set_progressive(progressive);
+ enc.encode(img.data(), 64, 48, ct).unwrap();
+ out
+}
+
+/// Offset of the first byte of entropy-coded data (just past the first SOS header).
+fn scan_start(b: &[u8]) -> usize {
+ let sos = b.windows(2).position(|w| w == [0xFF, 0xDA]).unwrap();
+ sos + 2 + u16::from_be_bytes([b[sos + 2], b[sos + 3]]) as usize
+}
+
+const TRUNCATED: DecodeWarning = DecodeWarning::Truncated { format: Format::Jpeg };
+
+#[test]
+fn truncated_jpeg_decodes_with_a_warning() {
+ for layout in [ChannelLayout::Gray, ChannelLayout::Rgb, ChannelLayout::Cmyk] {
+ for progressive in [false, true] {
+ let full = jpeg(layout, progressive);
+ assert_eq!(decode(&full).unwrap().warnings, [], "{layout:?} progressive {progressive}");
+ let half = decode(&full[..full.len() / 2]).unwrap();
+ assert_eq!(half.warnings, [TRUNCATED], "{layout:?} progressive {progressive}");
+ assert_eq!(half.dimensions(), (64, 48));
+ // One byte short: the end-of-image marker is incomplete.
+ assert_eq!(decode(&full[..full.len() - 1]).unwrap().warnings, [TRUNCATED]);
+ // A few bytes of scan data still decode, with the warning.
+ let start = scan_start(&full);
+ assert_eq!(decode(&full[..start + 8]).unwrap().warnings, [TRUNCATED]);
+ }
+ }
+}
+
+#[test]
+fn truncated_jpeg_message_names_the_problem() {
+ let s = TRUNCATED.to_string();
+ assert!(s.starts_with("JPEG data ends early") && s.contains("truncated"), "{s}");
+}
+
+#[test]
+fn jpeg_without_any_scan_data_is_an_error() {
+ let full = jpeg(ChannelLayout::Rgb, false);
+ let start = scan_start(&full);
+ for cut in [start - 3, start - 1, start] {
+ let e = decode(&full[..cut]).unwrap_err().to_string();
+ assert!(e.contains("before any image data"), "cut {cut}: {e}");
+ }
+}
+
+#[test]
+fn data_after_the_end_of_image_is_not_truncation() {
+ let mut b = jpeg(ChannelLayout::Rgb, false);
+ b.extend_from_slice(b"\0\0trailing bytes \xFF\xD8\xFF");
+ assert_eq!(decode(&b).unwrap().warnings, []);
+}
+
+#[test]
+fn an_end_marker_inside_metadata_does_not_hide_truncation() {
+ // An EXIF block holding FF D9 (as an embedded thumbnail does) must be skipped as a segment.
+ let mut img = synth(64, 48, ChannelLayout::Rgb, SampleType::U8, 3, 0.3);
+ let mut exif = sample_exif();
+ exif.extend_from_slice(&[0xFF, 0xD8, 0x00, 0xFF, 0xD9]);
+ img.meta.exif = Some(exif);
+ let full = encode(&img, Format::Jpeg, &EncodeOptions::default()).unwrap();
+ assert_eq!(decode(&full).unwrap().warnings, []);
+ assert_eq!(decode(&full[..full.len() * 2 / 3]).unwrap().warnings, [TRUNCATED]);
+}
+
+#[test]
+fn restart_markers_and_fill_bytes_are_scan_data() {
+ // Restart markers (FF D0–D7) and fill bytes (FF FF) inside a scan don't end it.
+ let full = jpeg(ChannelLayout::Rgb, false);
+ let start = scan_start(&full);
+ let mut b = full[..start].to_vec();
+ b.extend_from_slice(&[0x12, 0xFF, 0x00, 0x34, 0xFF, 0xD0, 0x56, 0xFF, 0xFF, 0xD7, 0x78]);
+ assert_eq!(decode(&b).unwrap().warnings, [TRUNCATED]);
+ b.extend_from_slice(&[0xFF, 0xFF, 0xD9]);
+ assert_eq!(decode(&b).unwrap().warnings, []);
+}
+
+// ---------------------------------------------------------------------------
+// #523: only the first frame or page is decoded
+// ---------------------------------------------------------------------------
+
+fn more_frames(n: u32) -> Vec<DecodeWarning> {
+ vec![DecodeWarning::MoreFrames { total: Some(n) }]
+}
+
+fn gif(frames: usize) -> Vec<u8> {
+ let mut out = Vec::new();
+ let mut enc = image::codecs::gif::GifEncoder::new(&mut out);
+ let frames = COLOURS.iter().take(frames).map(|c| image::Frame::new(image::RgbaImage::from_pixel(W, H, image::Rgba([c[0], c[1], c[2], 255]))));
+ enc.encode_frames(frames).unwrap();
+ drop(enc);
+ out
+}
+
+#[test]
+fn animated_gif_warns_and_keeps_the_first_frame() {
+ let one = decode(&gif(1)).unwrap();
+ assert_eq!(one.warnings, []);
+ for n in [2, 3] {
+ let img = decode(&gif(n)).unwrap();
+ assert_eq!(img.warnings, more_frames(n as u32));
+ assert_eq!(img.to_rgba8(), one.to_rgba8(), "{n} frames: first frame pixels");
+ }
+ // A single-frame GIF written by our own encoder.
+ let ours = encode(&solid(COLOURS[0]), Format::Gif, &EncodeOptions::default()).unwrap();
+ assert_eq!(decode(&ours).unwrap().warnings, []);
+}
+
+#[test]
+fn gif_without_a_trailer_warns_without_a_total() {
+ let b = gif(3);
+ assert_eq!(b.last(), Some(&0x3B));
+ let img = decode(&b[..b.len() - 1]).unwrap();
+ assert_eq!(img.warnings, [DecodeWarning::MoreFrames { total: None }]);
+ assert_eq!(img.warnings[0].to_string(), "only the first frame of the animation was imported");
+}
+
+/// An APNG of `frames` solid frames at 8 or 16 bits; with `separate_default` the IDAT image is
+/// an extra default image outside the animation.
+fn apng(frames: u32, sixteen: bool, separate_default: bool) -> Vec<u8> {
+ let mut out = Vec::new();
+ let mut enc = png::Encoder::new(&mut out, W, H);
+ enc.set_color(png::ColorType::Rgb);
+ enc.set_depth(if sixteen { png::BitDepth::Sixteen } else { png::BitDepth::Eight });
+ let images = frames + u32::from(separate_default);
+ if frames > 0 {
+ enc.set_animated(frames, 0).unwrap();
+ enc.set_sep_def_img(separate_default).unwrap();
+ }
+ let mut w = enc.write_header().unwrap();
+ for c in COLOURS.iter().cycle().take(images.max(1) as usize) {
+ let px: Vec<u8> = if sixteen { c.iter().flat_map(|&v| [v, v]).collect::<Vec<u8>>().repeat((W * H) as usize) } else { c.repeat((W * H) as usize) };
+ w.write_image_data(&px).unwrap();
+ }
+ w.finish().unwrap();
+ out
+}
+
+#[test]
+fn apng_warns_and_keeps_the_first_frame() {
+ for sixteen in [false, true] {
+ let still = decode(&apng(0, sixteen, false)).unwrap();
+ assert_eq!(still.warnings, []);
+ assert_eq!(decode(&apng(1, sixteen, false)).unwrap().warnings, [], "a one-frame APNG is a still");
+ let img = decode(&apng(3, sixteen, false)).unwrap();
+ assert_eq!(img.warnings, more_frames(3), "16-bit {sixteen}");
+ assert_eq!((img.sample_type(), img.data()), (still.sample_type(), still.data()), "16-bit {sixteen}: first frame pixels");
+ // Default image + 2 animation frames: three images, the default one kept.
+ let img = decode(&apng(2, sixteen, true)).unwrap();
+ assert_eq!(img.warnings, more_frames(3));
+ assert_eq!(img.data(), still.data());
+ }
+}
+
+fn chunk(id: &[u8; 4], data: &[u8]) -> Vec<u8> {
+ let mut c = id.to_vec();
+ c.extend_from_slice(&(data.len() as u32).to_le_bytes());
+ c.extend_from_slice(data);
+ if data.len() % 2 == 1 {
+ c.push(0);
+ }
+ c
+}
+
+fn u24(v: u32) -> [u8; 3] {
+ let b = v.to_le_bytes();
+ [b[0], b[1], b[2]]
+}
+
+/// An animated WebP: each frame is a full-canvas lossless still wrapped in an ANMF chunk.
+fn animated_webp(frames: &[Image]) -> Vec<u8> {
+ let mut body = b"WEBP".to_vec();
+ let mut vp8x = vec![0x02, 0, 0, 0]; // animation flag
+ vp8x.extend_from_slice(&u24(W - 1));
+ vp8x.extend_from_slice(&u24(H - 1));
+ body.extend(chunk(b"VP8X", &vp8x));
+ body.extend(chunk(b"ANIM", &[0, 0, 0, 0, 0, 0]));
+ for f in frames {
+ let still = encode(f, Format::WebP, &EncodeOptions::default()).unwrap();
+ let at = still.windows(4).position(|w| w == b"VP8L").unwrap();
+ let len = u32::from_le_bytes(still[at + 4..at + 8].try_into().unwrap()) as usize;
+ let mut anmf = vec![0; 6]; // frame x, y
+ anmf.extend_from_slice(&u24(W - 1));
+ anmf.extend_from_slice(&u24(H - 1));
+ anmf.extend_from_slice(&u24(100)); // duration
+ anmf.push(0);
+ anmf.extend(chunk(b"VP8L", &still[at + 8..at + 8 + len]));
+ body.extend(chunk(b"ANMF", &anmf));
+ }
+ let mut out = b"RIFF".to_vec();
+ out.extend_from_slice(&(body.len() as u32).to_le_bytes());
+ out.extend(body);
+ out
+}
+
+#[test]
+fn animated_webp_warns_and_keeps_the_first_frame() {
+ let frames: Vec<Image> = COLOURS.iter().map(|&c| solid(c)).collect();
+ let still = decode(&encode(&frames[0], Format::WebP, &EncodeOptions::default()).unwrap()).unwrap();
+ assert_eq!(still.warnings, []);
+ assert_eq!(decode(&animated_webp(&frames[..1])).unwrap().warnings, [], "a one-frame animation");
+ for n in [2, 3] {
+ let img = decode(&animated_webp(&frames[..n])).unwrap();
+ assert_eq!(img.warnings, more_frames(n as u32));
+ // The animation decoder composites the frame onto its canvas: within one level.
+ let (a, b) = (img.to_rgba8(), still.to_rgba8());
+ assert!(a.len() == b.len() && a.iter().zip(&b).all(|(x, y)| x.abs_diff(*y) <= 1), "{n} frames: first frame pixels");
+ }
+}
+
+/// A TIFF with one IFD per entry: `(NewSubfileType, sample type)`.
+fn tiff(ifds: &[(u32, SampleType)]) -> Vec<u8> {
+ use tiff::encoder::{TiffEncoder, colortype};
+ use tiff::tags::Tag;
+ let mut out = std::io::Cursor::new(Vec::new());
+ let mut enc = TiffEncoder::new(&mut out).unwrap();
+ let n = (W * H) as usize;
+ // Each page is a flat grey at its own level (`k`), written at `sample` depth.
+ for (k, &(kind, sample)) in ifds.iter().enumerate() {
+ macro_rules! page {
+ ($ct:ty, $data:expr) => {{
+ let mut im = enc.new_image::<$ct>(W, H).unwrap();
+ if kind != 0 {
+ im.encoder().write_tag(Tag::NewSubfileType, kind).unwrap();
+ }
+ im.write_data($data).unwrap();
+ }};
+ }
+ let v = 40 * k as u8 + 10;
+ match sample {
+ SampleType::U8 => page!(colortype::Gray8, &vec![v; n]),
+ SampleType::U16 => page!(colortype::Gray16, &vec![u16::from(v) * 257; n]),
+ _ => page!(colortype::Gray32Float, &vec![f32::from(v) / 255.0; n]),
+ }
+ }
+ out.into_inner()
+}
+
+#[test]
+fn multi_page_tiff_warns_and_keeps_the_first_page() {
+ for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ let one = decode(&tiff(&[(0, sample)])).unwrap();
+ assert_eq!(one.warnings, [], "{sample:?}");
+ let img = decode(&tiff(&[(0, sample), (2, sample)])).unwrap();
+ assert_eq!(img.warnings, [DecodeWarning::MorePages { total: Some(2) }], "{sample:?}");
+ assert_eq!(img.data(), one.data(), "{sample:?}: first page pixels");
+ let img = decode(&tiff(&[(0, sample), (0, sample), (0, sample)])).unwrap();
+ assert_eq!(img.warnings, [DecodeWarning::MorePages { total: Some(3) }], "{sample:?}");
+ assert_eq!(img.warnings[0].to_string(), "only the first of 3 pages was imported");
+ }
+}
+
+#[test]
+fn tiff_thumbnails_and_masks_are_not_pages() {
+ let u8 = SampleType::U8;
+ // A reduced-resolution copy (bit 0) or a transparency mask (bit 2) is part of the page.
+ assert_eq!(decode(&tiff(&[(0, u8), (1, u8)])).unwrap().warnings, []);
+ assert_eq!(decode(&tiff(&[(0, u8), (4, u8)])).unwrap().warnings, []);
+ assert_eq!(decode(&tiff(&[(0, u8), (1, u8), (0, u8)])).unwrap().warnings, [DecodeWarning::MorePages { total: Some(2) }]);
+}
+
+#[test]
+fn single_images_carry_no_warnings() {
+ for f in rw_formats() {
+ let img = synth(9, 7, ChannelLayout::Rgba, SampleType::U8, 5, 0.2);
+ let Ok(bytes) = encode(&img, f, &EncodeOptions::default()) else { continue };
+ assert_eq!(decode(&bytes).unwrap().warnings, [], "{f:?}");
+ }
+}
+
+#[test]
+fn warnings_survive_orientation() {
+ let mut img = synth(8, 4, ChannelLayout::Rgb, SampleType::U8, 1, 0.0);
+ img.warnings.push(DecodeWarning::MorePages { total: None });
+ for o in 1..=8 {
+ assert_eq!(img.clone().oriented(o).unwrap().warnings, img.warnings, "orientation {o}");
+ }
+ assert_eq!(img.convert(ChannelLayout::Rgba, SampleType::U16).warnings, img.warnings);
+}
diff --git a/crates/codecs/tests/malformed.rs b/crates/codecs/tests/malformed.rs
index cd0324413..d63fa650a 100644
--- a/crates/codecs/tests/malformed.rs
+++ b/crates/codecs/tests/malformed.rs
@@ -56,6 +56,13 @@ fn truncated_files_mostly_error() {
let r = decode_as_with(f, &bytes[..bytes.len() / 2], &tight());
assert!(r.is_err(), "{f:?} decoded half a file");
}
+ // JPEG decodes leniently (the missing part grey) but never silently (#518).
+ if f == Format::Jpeg {
+ match decode_as_with(f, &bytes[..bytes.len() / 2], &tight()) {
+ Ok(img) => assert_eq!(img.warnings, [DecodeWarning::Truncated { format: f }]),
+ Err(e) => assert!(e.to_string().contains("before any image data"), "{e}"),
+ }
+ }
}
}
diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs
index b6c07a7e2..5f9bab6b2 100644
--- a/crates/io/src/flat.rs
+++ b/crates/io/src/flat.rs
@@ -28,7 +28,8 @@ pub fn import_flat(name: &str, bytes: &[u8]) -> Result<ImportResult, IoError> {
/// A decoded flat image as a single-layer document.
pub(crate) fn image_to_document(name: &str, img: &Image) -> Result<ImportResult, IoError> {
- let mut warnings = Vec::new();
+ // What the decoder noticed (frames or pages left out, data ending early) comes first.
+ let mut warnings: Vec<String> = img.warnings.iter().map(ToString::to_string).collect();
let (mode, target_layout) = match img.layout() {
ChannelLayout::Gray | ChannelLayout::GrayA => (ColorMode::Grayscale, ChannelLayout::GrayA),
ChannelLayout::Rgb | ChannelLayout::Rgba => (ColorMode::Rgb, ChannelLayout::Rgba),
diff --git a/crates/io/tests/flat.rs b/crates/io/tests/flat.rs
index 0d3b3862d..d23eaad39 100644
--- a/crates/io/tests/flat.rs
+++ b/crates/io/tests/flat.rs
@@ -333,3 +333,36 @@ fn non_srgb_rgb_is_converted_to_srgb_for_formats_without_a_profile() {
assert_colors(&column_pixels(&back, cols.len()), &column_pixels(&d, cols.len()), 0.0, "sRGB bmp");
}
}
+
+/// #518: a JPEG cut off inside its image data opens with a warning, never silently.
+#[test]
+fn truncated_jpeg_imports_with_a_warning() {
+ for mode in [ColorMode::Rgb, ColorMode::Grayscale] {
+ let full = export(&smooth(mode), "jpg", &ExportOptions::default()).unwrap().bytes;
+ assert_eq!(import("x.jpg", &full).unwrap().warnings, Vec::<String>::new(), "{mode:?}");
+ // Cut inside the scan data (most of this small file is headers).
+ let r = import("x.jpg", &full[..full.len() - 4]).unwrap();
+ assert_eq!(r.document.size, photocraft_geom::Size::new(32, 16));
+ assert!(r.warnings.first().is_some_and(|w| w.starts_with("JPEG data ends early")), "{mode:?}: {:?}", r.warnings);
+ }
+}
+
+/// A GIF of `frames` identical 1x1 black frames.
+fn gif_frames(frames: usize) -> Vec<u8> {
+ let mut b = b"GIF89a\x01\0\x01\0\x80\0\0\0\0\0\xFF\xFF\xFF".to_vec();
+ for _ in 0..frames {
+ b.extend_from_slice(b"\x2C\0\0\0\0\x01\0\x01\0\0\x02\x02\x44\x01\0");
+ }
+ b.push(0x3B);
+ b
+}
+
+/// #523: an animation opens its first frame, unchanged, with a warning that the rest was left out.
+#[test]
+fn animation_imports_the_first_frame_with_a_warning() {
+ let one = import("a.gif", &gif_frames(1)).unwrap();
+ assert_eq!(one.warnings, Vec::<String>::new());
+ let three = import("a.gif", &gif_frames(3)).unwrap();
+ assert_eq!(three.warnings, ["only the first of 3 frames was imported"]);
+ pixels_eq(&one.document, &three.document, 0.0);
+}