Skip to content

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

Fix: omit JFIF APP0 from CMYK JPEG (#8008)

Sir Starchf10194c02814
diff --git a/crates/codecs/src/codecs/jpeg.rs b/crates/codecs/src/codecs/jpeg.rs
index a300de4bd..909c1519b 100644
--- a/crates/codecs/src/codecs/jpeg.rs
+++ b/crates/codecs/src/codecs/jpeg.rs
@@ -7,8 +7,9 @@
//! these wins: the APP13 Photoshop ResolutionInfo, the XMP `tiff:` resolution, the EXIF IFD0
//! resolution, and last the JFIF density (a unit-0 JFIF density is only an aspect ratio and
//! never counts). Cameras record their resolution in EXIF only, and many tools write a default
-//! 72 into JFIF, so JFIF can't outrank EXIF (see [`crate::resolution`]). On export the JFIF
-//! density, the EXIF and the XMP resolution are all written as the image's resolution.
+//! 72 into JFIF, so JFIF can't outrank EXIF (see [`crate::resolution`]). On export RGB and gray
+//! images carry density in JFIF; CMYK omits JFIF APP0, which is invalid for four components, and
+//! carries an available density in EXIF instead.
use zune_core::bytestream::ZCursor;
use zune_core::colorspace::ColorSpace;
@@ -263,7 +264,8 @@ pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result<Ve
enc.set_sampling_factor(sampling);
let e = |e: jpeg_encoder::EncodingError| CodecError::encode(F, e);
if opts.embed_metadata {
- if let Some((x, y)) = img.meta.dpi
+ if img.layout() != ChannelLayout::Cmyk
+ && let Some((x, y)) = img.meta.dpi
&& x >= 1.0
&& y >= 1.0
{
@@ -271,7 +273,16 @@ pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result<Ve
}
// Metadata too large for its one segment is left out (and reported by the fidelity
// warnings) rather than failing the whole export.
- if let Some(seg) = img.meta.exif.as_deref().and_then(|x| exif_segment(x, img.meta.dpi)) {
+ let exif = if img.layout() == ChannelLayout::Cmyk {
+ match img.meta.exif.as_deref() {
+ Some(exif) => exif_segment_with_resolution(exif, img.meta.dpi),
+ None if usable_dpi(img.meta.dpi) => exif_segment_with_resolution(&[], img.meta.dpi),
+ None => None,
+ }
+ } else {
+ img.meta.exif.as_deref().and_then(|x| exif_segment(x, img.meta.dpi))
+ };
+ if let Some(seg) = exif {
enc.add_app_segment(1, &seg).map_err(e)?;
}
if let Some(seg) = img.meta.xmp.as_deref().and_then(|x| xmp_segment(x, img.meta.dpi)) {
@@ -284,9 +295,57 @@ pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result<Ve
enc.add_icc_profile(icc).map_err(e)?;
}
enc.encode(img.data(), w16, h16, ct).map_err(e)?;
+ if img.layout() == ChannelLayout::Cmyk {
+ strip_jfif_app0(&mut out);
+ }
Ok(out)
}
+/// JFIF APP0 requires one or three image components. A four-component CMYK JPEG must not carry
+/// that marker; keep Adobe APP14, which identifies the CMYK encoding instead.
+fn strip_jfif_app0(bytes: &mut Vec<u8>) {
+ if !bytes.starts_with(&[0xff, 0xd8]) {
+ return;
+ }
+ let mut i = 2usize;
+ loop {
+ if bytes.get(i) != Some(&0xff) {
+ return;
+ }
+ let Some(&marker) = bytes.get(i.saturating_add(1)) else { return };
+ if matches!(marker, 0xda | 0xd9) {
+ return;
+ }
+ if marker == 0xff {
+ i = i.saturating_add(1);
+ continue;
+ }
+ if marker == 0x01 || (0xd0..=0xd8).contains(&marker) {
+ i = i.saturating_add(2);
+ continue;
+ }
+ let Some(length_bytes) = i.checked_add(2).and_then(|at| bytes.get(at..at.checked_add(2)?)) else { return };
+ let Ok(length_bytes) = <[u8; 2]>::try_from(length_bytes) else { return };
+ let length = usize::from(u16::from_be_bytes(length_bytes));
+ if length < 2 {
+ return;
+ }
+ let Some(end) = i.checked_add(2).and_then(|at| at.checked_add(length)) else { return };
+ if end > bytes.len() {
+ return;
+ }
+ if marker == 0xe0 && bytes.get(i.saturating_add(4)..i.saturating_add(9)) == Some(b"JFIF\0") {
+ bytes.drain(i..end);
+ } else {
+ i = end;
+ }
+ }
+}
+
+fn usable_dpi(dpi: Option<(f32, f32)>) -> bool {
+ dpi.is_some_and(|(x, y)| x.is_finite() && y.is_finite() && (1.0..=1_000_000.0).contains(&x) && (1.0..=1_000_000.0).contains(&y))
+}
+
/// The most data one APP segment holds (its 16-bit length counts its own two bytes).
const MAX_SEGMENT: usize = 65533;
@@ -297,12 +356,17 @@ const LAYERED_ONLY_XMP: [&str; 2] = ["DocumentAncestors", "TextLayers"];
/// The EXIF APP1 segment, or `None` when it doesn't fit in one segment.
pub(crate) fn exif_segment(exif: &[u8], dpi: Option<(f32, f32)>) -> Option<Vec<u8>> {
- // The pixels are written as they are shown: never let a viewer rotate them again; and the
- // resolution is the one written to JFIF, not the source's (#1691).
+ // The pixels are written as they are shown: never let a viewer rotate them again; and store
+ // the output resolution, not the source's (#1691).
let seg = [EXIF_HEADER, export_exif(exif, dpi).as_ref()].concat();
(seg.len() <= MAX_SEGMENT).then_some(seg)
}
+fn exif_segment_with_resolution(exif: &[u8], dpi: Option<(f32, f32)>) -> Option<Vec<u8>> {
+ let seg = [EXIF_HEADER, crate::resolution::export_exif_adding_missing_resolution(exif, dpi).as_ref()].concat();
+ (seg.len() <= MAX_SEGMENT).then_some(seg)
+}
+
/// The XMP APP1 segment. When the packet doesn't fit in one segment, the layered-document
/// properties are left out; `None` when it still doesn't fit.
pub(crate) fn xmp_segment(xmp: &str, dpi: Option<(f32, f32)>) -> Option<Vec<u8>> {
@@ -347,3 +411,67 @@ fn remove_element(xmp: &str, name: &str) -> String {
out.push_str(rest);
out
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::{Format, Metadata};
+
+ fn empty_tiff() -> Vec<u8> {
+ // Little-endian TIFF with an empty IFD0 and no next IFD.
+ b"II*\0\x08\0\0\0\0\0\0\0\0\0\0\0".to_vec()
+ }
+
+ fn has_jfif_app0(bytes: &[u8]) -> bool {
+ bytes.get(2..11) == Some(b"\xff\xe0\0\x10JFIF\0")
+ }
+
+ #[test]
+ fn cmyk_jpeg_omits_jfif_but_keeps_adobe_cmyk_marker() {
+ let img = Image::from_raw(2, 1, ChannelLayout::Cmyk, SampleType::U8, vec![0, 32, 64, 96, 255, 224, 192, 160]).unwrap();
+ let bytes = crate::encode(&img, Format::Jpeg, &EncodeOptions::default()).unwrap();
+
+ let meta = scan_metadata(&bytes);
+ assert!(!has_jfif_app0(&bytes));
+ assert_eq!(meta.frame, Some((2, 1, 4)));
+ assert_eq!(meta.adobe_transform, Some(0));
+ assert_eq!(crate::decode_as(Format::Jpeg, &bytes).unwrap().layout(), ChannelLayout::Cmyk);
+ }
+
+ #[test]
+ fn cmyk_jpeg_preserves_dpi_without_source_exif() {
+ let mut img = Image::from_raw(1, 1, ChannelLayout::Cmyk, SampleType::U8, vec![0, 0, 0, 0]).unwrap();
+ img.meta.dpi = Some((300.0, 150.0));
+ let bytes = crate::encode(&img, Format::Jpeg, &EncodeOptions::default()).unwrap();
+
+ assert!(!has_jfif_app0(&bytes));
+ assert_eq!(crate::decode_as(Format::Jpeg, &bytes).unwrap().meta.dpi, Some((300.0, 150.0)));
+ }
+
+ #[test]
+ fn cmyk_jpeg_preserves_dpi_with_source_exif_without_resolution_tags() {
+ let mut img = Image::from_raw(1, 1, ChannelLayout::Cmyk, SampleType::U8, vec![0, 0, 0, 0]).unwrap();
+ img.meta = Metadata { exif: Some(empty_tiff()), dpi: Some((240.0, 120.0)), ..Default::default() };
+ let bytes = crate::encode(&img, Format::Jpeg, &EncodeOptions::default()).unwrap();
+
+ assert_eq!(crate::decode_as(Format::Jpeg, &bytes).unwrap().meta.dpi, Some((240.0, 120.0)));
+ }
+
+ #[test]
+ fn exif_with_resolution_adds_missing_ifd0_entries() {
+ let exif = empty_tiff();
+ let rewritten = crate::resolution::export_exif_adding_missing_resolution(&exif, Some((240.0, 120.0)));
+
+ assert_eq!(crate::resolution::exif_resolution(&rewritten), Some((240.0, 120.0)));
+ }
+
+ #[test]
+ fn rgb_jpeg_keeps_jfif_density() {
+ let mut img = Image::from_raw(1, 1, ChannelLayout::Rgb, SampleType::U8, vec![12, 34, 56]).unwrap();
+ img.meta.dpi = Some((96.0, 96.0));
+ let bytes = crate::encode(&img, Format::Jpeg, &EncodeOptions::default()).unwrap();
+
+ assert!(has_jfif_app0(&bytes));
+ assert_eq!(scan_metadata(&bytes).dpi, Some((96.0, 96.0)));
+ }
+}
diff --git a/crates/codecs/src/resolution.rs b/crates/codecs/src/resolution.rs
index 049a00eaa..468b1e37c 100644
--- a/crates/codecs/src/resolution.rs
+++ b/crates/codecs/src/resolution.rs
@@ -159,23 +159,50 @@ pub fn exif_resolution(exif: &[u8]) -> Option<(f32, f32)> {
ppi_pair(x * scale, y * scale)
}
-/// `exif` with its IFD0 resolution set to `ppi` (pixels per inch), borrowed when there is
-/// nothing to change: no resolution entries, already that resolution, or not parseable.
+/// `exif` with its IFD0 resolution set to `ppi` (pixels per inch), borrowed when it has no
+/// resolution entries, already records that resolution, or cannot be parsed.
///
-/// Every well-formed XResolution / YResolution (one RATIONAL) gets the new value in place and
-/// every well-formed ResolutionUnit (one SHORT) becomes 2 (inch); all other bytes are kept.
-/// A resolution entry that can't be rewritten safely (another type or count, or a value outside
-/// the block) is removed from IFD0 instead, so no stale value survives: the later entries move
-/// up, the entry count and next-IFD pointer follow, and the freed bytes at the table's end are
-/// zeroed. Nothing else moves, so every offset in the block stays valid.
+/// Existing well-formed XResolution / YResolution (one RATIONAL) entries are rewritten in place,
+/// and every well-formed ResolutionUnit (one SHORT) becomes 2 (inch). Malformed entries are
+/// removed from IFD0 instead, so no stale value survives; all other bytes are kept.
pub fn exif_with_resolution(exif: &[u8], ppi: (f32, f32)) -> Cow<'_, [u8]> {
+ exif_with_resolution_inner(exif, ppi, false)
+}
+
+/// Like [`exif_with_resolution`], but adds X/Y resolution tags when a valid IFD0 has none.
+/// Existing TIFF data stays in place, so its offsets remain valid. Used by CMYK JPEG, which
+/// cannot carry a JFIF density marker.
+pub(crate) fn exif_with_resolution_adding_missing(exif: &[u8], ppi: (f32, f32)) -> Cow<'_, [u8]> {
+ exif_with_resolution_inner(exif, ppi, true)
+}
+
+fn exif_with_resolution_inner(exif: &[u8], ppi: (f32, f32), add_missing: bool) -> Cow<'_, [u8]> {
if ppi_pair(f64::from(ppi.0), f64::from(ppi.1)).is_none() {
return Cow::Borrowed(exif);
}
+ if exif.is_empty() {
+ if !add_missing {
+ return Cow::Borrowed(exif);
+ }
+ // An image with DPI but no source EXIF still needs a valid EXIF block when the output
+ // format cannot carry resolution in its own header (CMYK JPEG has no valid JFIF marker).
+ return Cow::Owned(exif_with_resolution_inner(b"II*\0\x08\0\0\0\0\0\0\0\0\0\0", ppi, true).into_owned());
+ }
let body = tiff_body(exif);
let prefix = exif.len() - body.len();
let Some(ifd) = Ifd0::parse(body) else { return Cow::Borrowed(exif) };
- if ifd.fields.is_empty() || exif_resolution(body).is_some_and(|r| same(r, ppi)) {
+ if exif_resolution(body).is_some_and(|r| same(r, ppi)) {
+ return Cow::Borrowed(exif);
+ }
+ let missing_xy = ifd.first_of(TAG_X_RESOLUTION).and_then(|f| f.rational(ifd.order, body)).is_none()
+ || ifd.first_of(TAG_Y_RESOLUTION).and_then(|f| f.rational(ifd.order, body)).is_none();
+ if add_missing && missing_xy {
+ let Some(body) = append_resolution_ifd(body, &ifd, ppi) else { return Cow::Borrowed(exif) };
+ let mut full = exif.get(..prefix).unwrap_or_default().to_vec();
+ full.extend_from_slice(&body);
+ return Cow::Owned(full);
+ }
+ if ifd.fields.is_empty() {
return Cow::Borrowed(exif);
}
let order = ifd.order;
@@ -207,6 +234,97 @@ pub fn exif_with_resolution(exif: &[u8], ppi: (f32, f32)) -> Cow<'_, [u8]> {
if full == exif { Cow::Borrowed(exif) } else { Cow::Owned(full) }
}
+/// Append a replacement IFD0 with fresh resolution tags. Every other entry keeps its original
+/// bytes and offsets, since the TIFF block's existing data remains where it was.
+fn append_resolution_ifd(body: &[u8], ifd: &Ifd0, ppi: (f32, f32)) -> Option<Vec<u8>> {
+ let (count_bytes, next_bytes, alignment) = if ifd.big { (8usize, 8usize, 8usize) } else { (2usize, 4usize, 2usize) };
+ let mut entries = Vec::with_capacity(ifd.count.saturating_add(3));
+ for index in 0..ifd.count {
+ let entry = ifd.first.checked_add(index.checked_mul(ifd.entry_bytes)?)?;
+ let tag = ifd.order.u16(body, entry)?;
+ if matches!(tag, TAG_X_RESOLUTION | TAG_Y_RESOLUTION | TAG_RESOLUTION_UNIT) {
+ continue;
+ }
+ entries.push((tag, body.get(entry..entry.checked_add(ifd.entry_bytes)?)?.to_vec()));
+ }
+ let count = entries.len().checked_add(3)?;
+ if !ifd.big && count > usize::from(u16::MAX) {
+ return None;
+ }
+
+ let new_ifd = align_up(body.len(), alignment)?;
+ let table_end = new_ifd.checked_add(count_bytes)?.checked_add(count.checked_mul(ifd.entry_bytes)?)?;
+ let next_at = ifd.first.checked_add(ifd.count.checked_mul(ifd.entry_bytes)?)?;
+ let next_ifd = body.get(next_at..next_at.checked_add(next_bytes)?)?;
+ let rational_at = align_up(table_end.checked_add(next_bytes)?, if ifd.big { 8 } else { 4 })?;
+ let y_rational_at = rational_at.checked_add(8)?;
+ if !ifd.big && (new_ifd > u32::MAX as usize || y_rational_at.checked_add(8)? > u32::MAX as usize) {
+ return None;
+ }
+
+ entries.push((TAG_X_RESOLUTION, resolution_entry(ifd.order, ifd.big, TAG_X_RESOLUTION, u64::try_from(rational_at).ok()?)?));
+ entries.push((TAG_Y_RESOLUTION, resolution_entry(ifd.order, ifd.big, TAG_Y_RESOLUTION, u64::try_from(y_rational_at).ok()?)?));
+ entries.push((TAG_RESOLUTION_UNIT, resolution_entry(ifd.order, ifd.big, TAG_RESOLUTION_UNIT, 2)?));
+ entries.sort_by_key(|(tag, _)| *tag);
+
+ let mut out = body.to_vec();
+ out.resize(new_ifd, 0);
+ if ifd.big {
+ out.extend_from_slice(&put_u64(ifd.order, count as u64));
+ } else {
+ out.extend_from_slice(&put_u16(ifd.order, count as u16));
+ }
+ for (_, entry) in entries {
+ out.extend_from_slice(&entry);
+ }
+ out.extend_from_slice(next_ifd);
+ out.resize(rational_at, 0);
+ let (xn, xd) = rational(ppi.0);
+ let (yn, yd) = rational(ppi.1);
+ out.extend_from_slice(&put_u32(ifd.order, xn));
+ out.extend_from_slice(&put_u32(ifd.order, xd));
+ out.extend_from_slice(&put_u32(ifd.order, yn));
+ out.extend_from_slice(&put_u32(ifd.order, yd));
+
+ let offset_at: usize = if ifd.big { 8 } else { 4 };
+ if ifd.big {
+ out.get_mut(offset_at..offset_at.checked_add(8)?)?.copy_from_slice(&put_u64(ifd.order, new_ifd as u64));
+ } else {
+ out.get_mut(offset_at..offset_at.checked_add(4)?)?.copy_from_slice(&put_u32(ifd.order, u32::try_from(new_ifd).ok()?));
+ }
+ Some(out)
+}
+
+/// One IFD entry. Rational fields store an offset; the SHORT unit is inline.
+fn resolution_entry(order: Order, big: bool, tag: u16, value: u64) -> Option<Vec<u8>> {
+ let entry_bytes = if big { 20 } else { 12 };
+ let count_at = 4;
+ let value_at = if big { 12 } else { 8 };
+ let mut entry = vec![0; entry_bytes];
+ entry.get_mut(..2)?.copy_from_slice(&put_u16(order, tag));
+ entry.get_mut(2..4)?.copy_from_slice(&put_u16(order, if tag == TAG_RESOLUTION_UNIT { TYPE_SHORT } else { TYPE_RATIONAL }));
+ if big {
+ entry.get_mut(count_at..count_at + 8)?.copy_from_slice(&put_u64(order, 1));
+ if tag == TAG_RESOLUTION_UNIT {
+ entry.get_mut(value_at..value_at + 2)?.copy_from_slice(&put_u16(order, value as u16));
+ } else {
+ entry.get_mut(value_at..value_at + 8)?.copy_from_slice(&put_u64(order, value));
+ }
+ } else {
+ entry.get_mut(count_at..count_at + 4)?.copy_from_slice(&put_u32(order, 1));
+ if tag == TAG_RESOLUTION_UNIT {
+ entry.get_mut(value_at..value_at + 2)?.copy_from_slice(&put_u16(order, value as u16));
+ } else {
+ entry.get_mut(value_at..value_at + 4)?.copy_from_slice(&put_u32(order, u32::try_from(value).ok()?));
+ }
+ }
+ Some(entry)
+}
+
+fn align_up(value: usize, alignment: usize) -> Option<usize> {
+ value.checked_add((alignment - value % alignment) % alignment)
+}
+
fn put_u16(order: Order, v: u16) -> [u8; 2] {
match order {
Order::Little => v.to_le_bytes(),
@@ -407,13 +525,24 @@ fn exif_without_thumbnail(exif: &[u8]) -> Option<Vec<u8>> {
/// [`upright_exif`]), no thumbnail of the source image (see [`exif_without_thumbnail`]) and,
/// when `ppi` is known, the resolution (see [`exif_with_resolution`]).
pub fn export_exif(exif: &[u8], ppi: Option<(f32, f32)>) -> Cow<'_, [u8]> {
+ export_exif_inner(exif, ppi, false)
+}
+
+/// Export EXIF for a format without its own resolution field, adding missing X/Y resolution
+/// entries to valid metadata when necessary.
+pub(crate) fn export_exif_adding_missing_resolution(exif: &[u8], ppi: Option<(f32, f32)>) -> Cow<'_, [u8]> {
+ export_exif_inner(exif, ppi, true)
+}
+
+fn export_exif_inner(exif: &[u8], ppi: Option<(f32, f32)>, add_missing: bool) -> Cow<'_, [u8]> {
let up = upright_exif(exif);
let up = match exif_without_thumbnail(&up) {
Some(v) => Cow::Owned(v),
None => up,
};
let Some(ppi) = ppi else { return up };
- if let Cow::Owned(v) = exif_with_resolution(&up, ppi) {
+ let result = if add_missing { exif_with_resolution_adding_missing(&up, ppi) } else { exif_with_resolution(&up, ppi) };
+ if let Cow::Owned(v) = result {
return Cow::Owned(v);
}
up