PhotoCraft: An open-source, photo editor written by scratch in pure Rust
fix(codecs): read the resolution from EXIF, XMP and Photoshop APP13; write it consistently (#1691) (#1744)
Gert Pellin - GPE58289b28220a
diff --git a/crates/codecs/README.md b/crates/codecs/README.mdindex 8d6ae1f80..6e85d7f24 100644--- a/crates/codecs/README.md+++ b/crates/codecs/README.md@@ -106,6 +106,15 @@ the same.size (5–8 swap width and height), and the rotated buffer is allocated fallibly.`Image::oriented` turns any layout and depth in parallel bands (about 10 ms for 24 MP RGB8 inrelease).+* **Resolution** (#1691, module `resolution`): a file without a resolution of its own format+ (no PNG `pHYs`, a WebP, HEIF, …) takes it from its XMP `tiff:XResolution` / `YResolution` /+ `ResolutionUnit`, else from EXIF IFD0 (RATIONAL X/YResolution, unit 2 inch — the default when+ absent — or 3 cm; unit 1 or anything malformed counts as no resolution). A JPEG uses, like+ Photoshop, the first usable of: APP13 Photoshop ResolutionInfo (0x03ED), XMP, EXIF, and only+ then the JFIF density (cameras write EXIF only, many tools write a default JFIF 72). On export+ the EXIF and XMP resolution are rewritten to the image's (`export_exif`, `export_xmp`): the+ RATIONAL values in place, ResolutionUnit set to 2, an entry that can't be rewritten removed+ from IFD0 without moving any other data. IFD1 (the thumbnail's) is left as it is.* **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 comediff --git a/crates/codecs/src/codecs/jpeg.rs b/crates/codecs/src/codecs/jpeg.rsindex 06e983616..9c3762887 100644--- a/crates/codecs/src/codecs/jpeg.rs+++ b/crates/codecs/src/codecs/jpeg.rs@@ -1,7 +1,14 @@//! JPEG: decode via `zune-jpeg` (gray, YCbCr, CMYK, YCCK), encode via//! `jpeg-encoder` (gray, RGB, CMYK). Metadata (APP0 JFIF density, APP1-//! EXIF/XMP, APP2 multi-segment ICC, APP14 Adobe) is parsed by our own marker-//! scanner so behaviour does not depend on decoder internals.+//! EXIF/XMP, APP2 multi-segment ICC, APP13 Photoshop resources, APP14 Adobe) is+//! parsed by our own marker scanner so behaviour does not depend on decoder internals.+//!+//! **Resolution** (#1691) can be recorded four times; like Photoshop the first usable one of+//! 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.use zune_core::bytestream::ZCursor;use zune_core::colorspace::ColorSpace;@@ -12,12 +19,13 @@ use crate::error::CodecError;use crate::fidelity::Plan;use crate::image::{ChannelLayout, DecodeWarning, Image, Metadata, SampleType};use crate::options::{EncodeOptions, Limits};-use crate::orientation::{upright_exif, upright_xmp};+use crate::resolution::{exif_resolution, export_exif, export_xmp, photoshop_resolution, xmp_resolution};const F: Format = Format::Jpeg;const EXIF_HEADER: &[u8] = b"Exif\0\0";const XMP_HEADER: &[u8] = b"http://ns.adobe.com/xap/1.0/\0";const ICC_HEADER: &[u8] = b"ICC_PROFILE\0";+const PHOTOSHOP_HEADER: &[u8] = b"Photoshop 3.0\0";#[derive(Default, Debug)]pub(crate) struct JpegMeta {@@ -34,6 +42,9 @@ pub(crate) struct JpegMeta {pub(crate) fn scan_metadata(b: &[u8]) -> JpegMeta {let mut m = JpegMeta::default();let mut icc_parts: Vec<(u8, u8, &[u8])> = Vec::new();+ // Photoshop splits a large resource block over consecutive APP13 segments.+ let mut photoshop: Vec<u8> = Vec::new();+ let mut jfif_dpi = None;let mut i = 2;while i + 4 <= b.len() {if b[i] != 0xFF {@@ -62,7 +73,7 @@ pub(crate) fn scan_metadata(b: &[u8]) -> JpegMeta {let x = u16::from_be_bytes([seg[8], seg[9]]) as f32;let y = u16::from_be_bytes([seg[10], seg[11]]) as f32;if x > 0.0 && y > 0.0 {- m.dpi = match unit {+ jfif_dpi = match unit {1 => Some((x, y)),2 => Some((x * 2.54, y * 2.54)),_ => None,@@ -75,6 +86,9 @@ pub(crate) fn scan_metadata(b: &[u8]) -> JpegMeta {0xE1 if seg.starts_with(XMP_HEADER) && m.xmp.is_none() => {m.xmp = std::str::from_utf8(&seg[XMP_HEADER.len()..]).ok().map(|s| s.trim_end_matches('\0').to_owned());}+ 0xED if seg.starts_with(PHOTOSHOP_HEADER) && photoshop.len() < 1 << 24 => {+ photoshop.extend_from_slice(&seg[PHOTOSHOP_HEADER.len()..]);+ }0xE2 if seg.len() >= 14 && seg.starts_with(ICC_HEADER) => {icc_parts.push((seg[12], seg[13], &seg[14..]));}@@ -90,6 +104,10 @@ pub(crate) fn scan_metadata(b: &[u8]) -> JpegMeta {}i += 2 + len;}+ m.dpi = photoshop_resolution(&photoshop)+ .or_else(|| m.xmp.as_deref().and_then(xmp_resolution))+ .or_else(|| m.exif.as_deref().and_then(exif_resolution))+ .or(jfif_dpi);if !icc_parts.is_empty() {icc_parts.sort_by_key(|p| p.0);let total = icc_parts[0].1 as usize;@@ -250,10 +268,10 @@ 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(exif_segment) {+ if let Some(seg) = img.meta.exif.as_deref().and_then(|x| exif_segment(x, img.meta.dpi)) {enc.add_app_segment(1, &seg).map_err(e)?;}- if let Some(seg) = img.meta.xmp.as_deref().and_then(xmp_segment) {+ if let Some(seg) = img.meta.xmp.as_deref().and_then(|x| xmp_segment(x, img.meta.dpi)) {enc.add_app_segment(1, &seg).map_err(e)?;}}@@ -275,16 +293,17 @@ const MAX_SEGMENT: usize = 65533;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]) -> Option<Vec<u8>> {- // The pixels are written as they are shown: never let a viewer rotate them again.- let seg = [EXIF_HEADER, upright_exif(exif).as_ref()].concat();+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).+ let seg = [EXIF_HEADER, export_exif(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) -> Option<Vec<u8>> {- let xmp = upright_xmp(xmp);+pub(crate) fn xmp_segment(xmp: &str, dpi: Option<(f32, f32)>) -> Option<Vec<u8>> {+ let xmp = export_xmp(xmp, dpi);let seg = |x: &str| [XMP_HEADER, x.as_bytes()].concat();if XMP_HEADER.len() + xmp.len() <= MAX_SEGMENT {return Some(seg(&xmp));diff --git a/crates/codecs/src/codecs/png.rs b/crates/codecs/src/codecs/png.rsindex f4d299aa9..1afb21a79 100644--- a/crates/codecs/src/codecs/png.rs+++ b/crates/codecs/src/codecs/png.rs@@ -263,7 +263,7 @@ pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result<Veif opts.embed_metadata {if let Some(exif) = &img.meta.exif {// The pixels are written as they are shown: never let a viewer rotate them again.- info.exif_metadata = Some(crate::orientation::upright_exif(exif).into_owned().into());+ info.exif_metadata = Some(crate::resolution::export_exif(exif, img.meta.dpi).into_owned().into());}if let Some((x, y)) = img.meta.dpi&& x > 0.0@@ -296,7 +296,9 @@ pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result<Veres.map_err(|e| CodecError::encode(F, e))?;}if let Some(xmp) = &img.meta.xmp {- encoder.add_itxt_chunk(XMP_KEYWORD.into(), crate::orientation::upright_xmp(xmp).into_owned()).map_err(|e| CodecError::encode(F, e))?;+ encoder+ .add_itxt_chunk(XMP_KEYWORD.into(), crate::resolution::export_xmp(xmp, img.meta.dpi).into_owned())+ .map_err(|e| CodecError::encode(F, e))?;}}let mut writer = encoder.write_header().map_err(|e| CodecError::encode(F, e))?;diff --git a/crates/codecs/src/codecs/tiff.rs b/crates/codecs/src/codecs/tiff.rsindex 9069f166e..b2b315e26 100644--- a/crates/codecs/src/codecs/tiff.rs+++ b/crates/codecs/src/codecs/tiff.rs@@ -1129,7 +1129,7 @@ pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result<VeVec::new()};// TIFF writes no Orientation tag (= 1): keep the XMP from contradicting it.- let xmp = if opts.embed_metadata { img.meta.xmp.as_deref().map(crate::orientation::upright_xmp) } else { None };+ let xmp = if opts.embed_metadata { img.meta.xmp.as_deref().map(|x| crate::resolution::export_xmp(x, img.meta.dpi)) } else { None };let tags = TagSet {icc: if opts.embed_icc { img.icc.as_deref() } else { None },xmp: xmp.as_deref().map(str::as_bytes),diff --git a/crates/codecs/src/codecs/webp.rs b/crates/codecs/src/codecs/webp.rsindex fe2dc7c61..c26c10c8c 100644--- a/crates/codecs/src/codecs/webp.rs+++ b/crates/codecs/src/codecs/webp.rs@@ -60,10 +60,10 @@ pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result<Veif opts.embed_metadata {if let Some(exif) = &img.meta.exif {// The pixels are written as they are shown: never let a viewer rotate them again.- enc.set_exif_metadata(crate::orientation::upright_exif(exif).into_owned());+ enc.set_exif_metadata(crate::resolution::export_exif(exif, img.meta.dpi).into_owned());}if let Some(xmp) = &img.meta.xmp {- enc.set_xmp_metadata(crate::orientation::upright_xmp(xmp).as_bytes().to_vec());+ enc.set_xmp_metadata(crate::resolution::export_xmp(xmp, img.meta.dpi).as_bytes().to_vec());}}enc.encode(img.data(), img.width(), img.height(), ct).map_err(|e| CodecError::encode(F, e))?;@@ -92,8 +92,8 @@ fn encode_lossy(img: &Image, opts: &EncodeOptions) -> Result<Vec<u8>, CodecErrorNone};let icc = if opts.embed_icc { img.icc.as_deref() } else { None };- let exif = if opts.embed_metadata { img.meta.exif.as_deref().map(crate::orientation::upright_exif) } else { None };- let xmp = if opts.embed_metadata { img.meta.xmp.as_deref().map(crate::orientation::upright_xmp) } else { None };+ let exif = if opts.embed_metadata { img.meta.exif.as_deref().map(|e| crate::resolution::export_exif(e, img.meta.dpi)) } else { None };+ let xmp = if opts.embed_metadata { img.meta.xmp.as_deref().map(|x| crate::resolution::export_xmp(x, img.meta.dpi)) } else { None };Ok(riff(w, h, &frame, alpha.as_deref(), icc, exif.as_deref(), xmp.as_deref().map(str::as_bytes)))}diff --git a/crates/codecs/src/fidelity.rs b/crates/codecs/src/fidelity.rsindex c9ba037ed..720f9421a 100644--- a/crates/codecs/src/fidelity.rs+++ b/crates/codecs/src/fidelity.rs@@ -227,10 +227,10 @@ pub fn fidelity_warnings_with(image: &Image, format: Format, opts: &EncodeOptionw.push(W::XmpDropped);}if format == Format::Jpeg {- if let Some(exif) = m.exif.as_deref().filter(|e| crate::codecs::jpeg::exif_segment(e).is_none()) {+ if let Some(exif) = m.exif.as_deref().filter(|e| crate::codecs::jpeg::exif_segment(e, None).is_none()) {w.push(W::MetadataTooLarge { what: "EXIF", bytes: exif.len() });}- if let Some(xmp) = m.xmp.as_deref().filter(|x| crate::codecs::jpeg::xmp_segment(x).is_none()) {+ if let Some(xmp) = m.xmp.as_deref().filter(|x| crate::codecs::jpeg::xmp_segment(x, None).is_none()) {w.push(W::MetadataTooLarge { what: "XMP", bytes: xmp.len() });}}diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rsindex 5e2f7cbcb..d75e169cf 100644--- a/crates/codecs/src/lib.rs+++ b/crates/codecs/src/lib.rs@@ -20,6 +20,7 @@ mod format;mod image;mod options;pub mod orientation;+pub mod resolution;pub mod web;pub use crate::codecs::png::encode_indexed as encode_png_indexed;@@ -31,6 +32,7 @@ pub use crate::format::{ASYMMETRIC_EXCEPTIONS, Format, FormatCaps, caps, detect,pub use crate::image::{ChannelLayout, DecodeWarning, DeepChannel, DeepImage, 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 crate::resolution::{exif_resolution, export_exif, export_xmp, photoshop_resolution, xmp_resolution};pub use half::f16;use crate::codecs::{exr, heif, jpeg, png, pnm, tiff, via_image, webp};@@ -68,6 +70,13 @@ pub fn decode_as_with(format: Format, bytes: &[u8], opts: &DecodeOptions) -> ResFormat::Heif => heif::decode(bytes, l, opts.keep_orientation),Format::Gif | Format::Bmp | Format::Tga | Format::Ico | Format::Qoi | Format::Hdr | Format::Avif => via_image::decode(format, bytes, l),}?;+ // Without a resolution of the format's own (PNG pHYs, TIFF tags, JPEG's metadata), the+ // XMP or EXIF one counts, like Photoshop: a WebP, HEIF or PNG from a camera or phone+ // opens at its recorded resolution, not at the 72 ppi default.+ let mut img = img;+ if img.meta.dpi.is_none() && format != Format::Tiff {+ img.meta.dpi = resolution::from_metadata(img.meta.exif.as_deref(), img.meta.xmp.as_deref());+ }// Turn the pixels upright, like Photoshop: a TIFF records it in the decoded page's own// directory, the others in their EXIF block. The metadata is rewritten to Orientation = 1// on the way. HEIF keeps it in its container, and its decoder has already applied it.diff --git a/crates/codecs/src/orientation.rs b/crates/codecs/src/orientation.rsindex 01ad6190c..3d10d5dde 100644--- a/crates/codecs/src/orientation.rs+++ b/crates/codecs/src/orientation.rs@@ -36,13 +36,13 @@ const BIG_HEADER: usize = 16;/// Byte order of a TIFF structure.#[derive(Clone, Copy)]-enum Order {+pub(crate) enum Order {Little,Big,}impl Order {- fn u16(self, b: &[u8], at: usize) -> Option<u16> {+ pub(crate) fn u16(self, b: &[u8], at: usize) -> Option<u16> {let s: [u8; 2] = b.get(at..at.checked_add(2)?)?.try_into().ok()?;Some(match self {Order::Little => u16::from_le_bytes(s),@@ -50,7 +50,7 @@ impl Order {})}- fn u32(self, b: &[u8], at: usize) -> Option<u32> {+ pub(crate) fn u32(self, b: &[u8], at: usize) -> Option<u32> {let s: [u8; 4] = b.get(at..at.checked_add(4)?)?.try_into().ok()?;Some(match self {Order::Little => u32::from_le_bytes(s),@@ -58,7 +58,7 @@ impl Order {})}- fn u64(self, b: &[u8], at: usize) -> Option<u64> {+ pub(crate) fn u64(self, b: &[u8], at: usize) -> Option<u64> {let s: [u8; 8] = b.get(at..at.checked_add(8)?)?.try_into().ok()?;Some(match self {Order::Little => u64::from_le_bytes(s),@@ -68,7 +68,7 @@ impl Order {}/// The TIFF payload of an EXIF block (a JPEG-style `Exif\0\0` prefix is skipped).-fn tiff_body(b: &[u8]) -> &[u8] {+pub(crate) fn tiff_body(b: &[u8]) -> &[u8] {b.strip_prefix(b"Exif\0\0").unwrap_or(b)}@@ -76,7 +76,7 @@ fn tiff_body(b: &[u8]) -> &[u8] {////// The full table and next-IFD pointer must be present, and IFD0 must start/// after the corresponding TIFF or BigTIFF header.-fn ifd0_entries(b: &[u8]) -> Option<(Order, usize, usize, usize, bool)> {+pub(crate) fn ifd0_entries(b: &[u8]) -> Option<(Order, usize, usize, usize, bool)> {let (order, big_tiff) = match b.get(0..4)? {[b'I', b'I', 42, 0] => (Order::Little, false),[b'M', b'M', 0, 42] => (Order::Big, false),diff --git a/crates/codecs/src/resolution.rs b/crates/codecs/src/resolution.rsnew file mode 100644index 000000000..7cf5dcac0--- /dev/null+++ b/crates/codecs/src/resolution.rs@@ -0,0 +1,411 @@+//! Image resolution (pixels per inch) recorded in metadata blocks: EXIF / TIFF IFD0+//! (XResolution 282, YResolution 283, ResolutionUnit 296), XMP (`tiff:XResolution`,+//! `tiff:YResolution`, `tiff:ResolutionUnit`) and Photoshop's image resource+//! ResolutionInfo (`8BIM` resource 0x03ED); reading them, and rewriting the EXIF and XMP+//! copies on export so they agree with the resolution the file is written at.+//!+//! Implemented from TIFF 6.0 (section 8, "Baseline fields": XResolution / YResolution are+//! RATIONAL, ResolutionUnit is SHORT, 1 = no absolute unit, 2 = inch, 3 = centimetre,+//! default 2), EXIF 2.3 (same tags in the 0th IFD, same default) and the Adobe Photoshop File+//! Formats Specification (ResolutionInfo: Fixed 16.16 hRes in pixels per inch, then the+//! display units; the vertical resolution likewise).+//!+//! **Precedence** when a file carries several, as Photoshop resolves them: Photoshop's own+//! ResolutionInfo, then the XMP `tiff:` properties, then EXIF, and only then the format's own+//! density field when it is the generic JFIF one (see the JPEG decoder). JFIF density is last+//! because cameras record the real resolution in EXIF while many tools and libraries write a+//! default JFIF density of 72 (or a bare aspect ratio) without knowing it; Photoshop shows a+//! camera JPEG at its EXIF resolution whatever its JFIF header says. Formats whose own field is+//! written deliberately (PNG `pHYs`, TIFF tags) keep it first; the metadata blocks only fill in+//! when it is missing.+//!+//! Everything read here is untrusted: offsets and counts are bounds-checked, both byte orders+//! and BigTIFF-style EXIF are handled, and anything malformed reads as "no resolution" rather+//! than as a wrong one.++use std::borrow::Cow;++use crate::orientation::{Order, ifd0_entries, tiff_body, upright_exif, upright_xmp};++const TAG_X_RESOLUTION: u16 = 282;+const TAG_Y_RESOLUTION: u16 = 283;+const TAG_RESOLUTION_UNIT: u16 = 296;+const TYPE_SHORT: u16 = 3;+const TYPE_RATIONAL: u16 = 5;+const CM_PER_INCH: f64 = 2.54;+/// Photoshop's ResolutionInfo image resource.+const RESOLUTION_INFO: u16 = 0x03ED;+/// Resolutions above this (pixels per inch) are treated as damage, not data.+const MAX_PPI: f64 = 1_000_000.0;+/// Two resolutions this close (pixels per inch) are the same.+const SAME_PPI: f64 = 1e-3;++/// A usable resolution pair, or `None`.+fn ppi_pair(x: f64, y: f64) -> Option<(f32, f32)> {+ let ok = |v: f64| v.is_finite() && v > 0.0 && v <= MAX_PPI;+ (ok(x) && ok(y)).then_some((x as f32, y as f32))+}++fn same(a: (f32, f32), b: (f32, f32)) -> bool {+ (f64::from(a.0) - f64::from(b.0)).abs() < SAME_PPI && (f64::from(a.1) - f64::from(b.1)).abs() < SAME_PPI+}++/// `ppi` as a TIFF RATIONAL: a whole number over 1 when it is one, else over 1000.+fn rational(ppi: f32) -> (u32, u32) {+ let p = f64::from(ppi);+ if (p - p.round()).abs() < SAME_PPI { (p.round() as u32, 1) } else { ((p * 1000.0).round() as u32, 1000) }+}++/// One of the three resolution entries of IFD0.+#[derive(Clone, Copy)]+struct Field {+ /// Offset of the 12- (BigTIFF: 20-) byte entry.+ entry: usize,+ tag: u16,+ ty: u16,+ count: u64,+ /// Where the value bytes are, when the type is one we read and they lie inside the block.+ value: Option<usize>,+}++impl Field {+ fn short(&self, order: Order, b: &[u8]) -> Option<u16> {+ (self.ty == TYPE_SHORT && self.count == 1).then_some(())?;+ order.u16(b, self.value?)+ }++ fn rational(&self, order: Order, b: &[u8]) -> Option<f64> {+ (self.ty == TYPE_RATIONAL && self.count == 1).then_some(())?;+ let at = self.value?;+ let (n, d) = (order.u32(b, at)?, order.u32(b, at.checked_add(4)?)?);+ (d != 0).then(|| f64::from(n) / f64::from(d))+ }+}++/// IFD0's resolution entries.+struct Ifd0 {+ order: Order,+ big: bool,+ first: usize,+ count: usize,+ entry_bytes: usize,+ fields: Vec<Field>,+}++impl Ifd0 {+ fn parse(b: &[u8]) -> Option<Ifd0> {+ let (order, first, count, entry_bytes, big) = ifd0_entries(b)?;+ let mut fields = Vec::new();+ for i in 0..count {+ let e = first.checked_add(i.checked_mul(entry_bytes)?)?;+ let tag = order.u16(b, e)?;+ if !matches!(tag, TAG_X_RESOLUTION | TAG_Y_RESOLUTION | TAG_RESOLUTION_UNIT) {+ continue;+ }+ let ty = order.u16(b, e.checked_add(2)?)?;+ let count = if big { order.u64(b, e.checked_add(4)?)? } else { u64::from(order.u32(b, e.checked_add(4)?)?) };+ let value = value_at(order, b, e, big, ty, count);+ fields.push(Field { entry: e, tag, ty, count, value });+ }+ Some(Ifd0 { order, big, first, count, entry_bytes, fields })+ }++ fn first_of(&self, tag: u16) -> Option<&Field> {+ self.fields.iter().find(|f| f.tag == tag)+ }+}++/// Where an entry's SHORT or RATIONAL value bytes are: inline in the entry when they fit,+/// else at the offset it holds. `None` for other types or when they leave the block.+fn value_at(order: Order, b: &[u8], e: usize, big: bool, ty: u16, count: u64) -> Option<usize> {+ let size = match ty {+ TYPE_SHORT => 2u64,+ TYPE_RATIONAL => 8,+ _ => return None,+ }+ .checked_mul(count)?;+ let (field, inline) = if big { (e.checked_add(12)?, 8) } else { (e.checked_add(8)?, 4) };+ let at = if size <= inline {+ field+ } else if big {+ usize::try_from(order.u64(b, field)?).ok()?+ } else {+ usize::try_from(order.u32(b, field)?).ok()?+ };+ (at.checked_add(usize::try_from(size).ok()?)? <= b.len()).then_some(at)+}++/// The resolution (pixels per inch, horizontal and vertical) recorded in IFD0 of an EXIF block+/// (with or without the JPEG `Exif\0\0` prefix) or a TIFF structure.+///+/// Both XResolution and YResolution must be one RATIONAL each with a non-zero denominator.+/// ResolutionUnit 2 (inch, also when the tag is absent) is used as is, 3 (centimetre) is+/// converted; 1 (no absolute unit), any other value or a malformed unit entry gives `None`.+/// The first of duplicated entries wins.+pub fn exif_resolution(exif: &[u8]) -> Option<(f32, f32)> {+ let b = tiff_body(exif);+ let ifd = Ifd0::parse(b)?;+ let unit = match ifd.first_of(TAG_RESOLUTION_UNIT) {+ None => 2,+ Some(f) => f.short(ifd.order, b)?,+ };+ let scale = match unit {+ 2 => 1.0,+ 3 => CM_PER_INCH,+ _ => return None,+ };+ let x = ifd.first_of(TAG_X_RESOLUTION)?.rational(ifd.order, b)?;+ let y = ifd.first_of(TAG_Y_RESOLUTION)?.rational(ifd.order, b)?;+ 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.+///+/// 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.+pub fn exif_with_resolution(exif: &[u8], ppi: (f32, f32)) -> Cow<'_, [u8]> {+ if ppi_pair(f64::from(ppi.0), f64::from(ppi.1)).is_none() {+ return Cow::Borrowed(exif);+ }+ 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)) {+ return Cow::Borrowed(exif);+ }+ let order = ifd.order;+ let mut out = body.to_vec();+ let mut removed = Vec::new();+ for f in &ifd.fields {+ let bytes = match f.tag {+ TAG_RESOLUTION_UNIT if f.short(order, body).is_some() => put_u16(order, 2).to_vec(),+ TAG_X_RESOLUTION | TAG_Y_RESOLUTION if f.rational(order, body).is_some() => {+ let (n, d) = rational(if f.tag == TAG_X_RESOLUTION { ppi.0 } else { ppi.1 });+ [put_u32(order, n), put_u32(order, d)].concat()+ }+ _ => {+ removed.push(f.entry);+ continue;+ }+ };+ let slot = f.value.and_then(|at| out.get_mut(at..at.checked_add(bytes.len())?));+ match slot {+ Some(slot) => slot.copy_from_slice(&bytes),+ None => removed.push(f.entry),+ }+ }+ if !removed.is_empty() {+ remove_entries(&mut out, &ifd, &removed);+ }+ let mut full = exif.get(..prefix).unwrap_or_default().to_vec();+ full.extend_from_slice(&out);+ if full == exif { Cow::Borrowed(exif) } else { Cow::Owned(full) }+}++fn put_u16(order: Order, v: u16) -> [u8; 2] {+ match order {+ Order::Little => v.to_le_bytes(),+ Order::Big => v.to_be_bytes(),+ }+}++fn put_u32(order: Order, v: u32) -> [u8; 4] {+ match order {+ Order::Little => v.to_le_bytes(),+ Order::Big => v.to_be_bytes(),+ }+}++fn put_u64(order: Order, v: u64) -> [u8; 8] {+ match order {+ Order::Little => v.to_le_bytes(),+ Order::Big => v.to_be_bytes(),+ }+}++/// Removes the IFD0 entries at offsets `removed` (see [`exif_with_resolution`]).+fn remove_entries(b: &mut [u8], ifd: &Ifd0, removed: &[usize]) {+ let eb = ifd.entry_bytes;+ let next_bytes = if ifd.big { 8 } else { 4 };+ let count_bytes = if ifd.big { 8 } else { 2 };+ let Some(table_end) = ifd.count.checked_mul(eb).and_then(|n| ifd.first.checked_add(n)) else { return };+ let Some(old) = b.get(ifd.first..table_end.saturating_add(next_bytes)).map(<[u8]>::to_vec) else { return };+ let mut table = Vec::with_capacity(old.len());+ let mut kept = 0usize;+ for (i, entry) in old.chunks_exact(eb).take(ifd.count).enumerate() {+ if !removed.contains(&(ifd.first + i * eb)) {+ table.extend_from_slice(entry);+ kept += 1;+ }+ }+ table.extend_from_slice(old.get(ifd.count * eb..).unwrap_or_default());+ table.resize(old.len(), 0);+ let count: Vec<u8> = if ifd.big { put_u64(ifd.order, kept as u64).to_vec() } else { put_u16(ifd.order, kept as u16).to_vec() };+ let Some(count_at) = ifd.first.checked_sub(count_bytes) else { return };+ if let Some(slot) = b.get_mut(count_at..ifd.first) {+ slot.copy_from_slice(&count);+ }+ if let Some(slot) = b.get_mut(ifd.first..ifd.first + table.len()) {+ slot.copy_from_slice(&table);+ }+}++/// The resolution in a Photoshop image resource block (a sequence of `8BIM` resources, as in a+/// JPEG's APP13 "Photoshop 3.0" segment or TIFF tag 34377): its ResolutionInfo (0x03ED), whose+/// Fixed 16.16 hRes / vRes are pixels per inch whatever display unit follows them.+pub fn photoshop_resolution(resources: &[u8]) -> Option<(f32, f32)> {+ let be16 = |at: usize| resources.get(at..at.checked_add(2)?).map(|s| u16::from_be_bytes([s[0], s[1]]));+ let be32 = |at: usize| resources.get(at..at.checked_add(4)?).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]]));+ let mut i = 0usize;+ while i < resources.len() {+ let signature = resources.get(i..i.checked_add(4)?)?;+ let id = be16(i.checked_add(4)?)?;+ // Pascal name: length byte plus text, padded to an even size.+ let name_len = usize::from(*resources.get(i.checked_add(6)?)?);+ let name = (name_len + 1).next_multiple_of(2);+ let size_at = i.checked_add(6)?.checked_add(name)?;+ let size = usize::try_from(be32(size_at)?).ok()?;+ let data = size_at.checked_add(4)?;+ if signature == b"8BIM" && id == RESOLUTION_INFO {+ let info = resources.get(data..data.checked_add(size)?)?;+ if info.len() < 16 {+ return None;+ }+ let fixed = |at: usize| be32(data + at).map(|v| f64::from(v) / 65536.0);+ return ppi_pair(fixed(0)?, fixed(8)?);+ }+ i = data.checked_add(size)?.checked_add(size % 2)?;+ }+ None+}++/// The text ranges of every value of XMP property `key` (`key="v"`, `key='v'` or+/// `<key>v</key>`), in order.+fn xmp_values(xmp: &str, key: &str) -> Vec<(usize, usize)> {+ let mut out = Vec::new();+ let mut from = 0;+ while let Some(k) = xmp.get(from..).and_then(|s| s.find(key)).map(|k| k + from) {+ from = k + key.len();+ // An attribute or an opening tag of exactly this name (not `</key>`, not `xkey`).+ if !xmp.get(..k).and_then(|h| h.chars().next_back()).is_some_and(|c| c == '<' || c.is_ascii_whitespace()) {+ continue;+ }+ let rest = xmp.get(from..).unwrap_or_default();+ let after_key = rest.trim_start();+ let (value, close) = if let Some(r) = after_key.strip_prefix('=') {+ let r = r.trim_start();+ match r.chars().next() {+ Some(q @ ('"' | '\'')) => (r.get(1..).unwrap_or_default(), q),+ _ => continue,+ }+ } else if let Some(r) = rest.strip_prefix('>') {+ (r, '<')+ } else {+ continue;+ };+ let start = xmp.len() - value.len();+ let Some(len) = value.find(close) else { continue };+ out.push((start, start + len));+ }+ out+}++/// An XMP rational (`300/1`) or plain number.+fn xmp_number(s: &str) -> Option<f64> {+ let s = s.trim();+ match s.split_once('/') {+ Some((n, d)) => {+ let (n, d) = (n.trim().parse::<f64>().ok()?, d.trim().parse::<f64>().ok()?);+ (d != 0.0).then(|| n / d)+ }+ None => s.parse().ok(),+ }+}++const XMP_X: &str = "tiff:XResolution";+const XMP_Y: &str = "tiff:YResolution";+const XMP_UNIT: &str = "tiff:ResolutionUnit";++/// The resolution (pixels per inch) in an XMP packet's `tiff:XResolution` / `tiff:YResolution`+/// (with `tiff:ResolutionUnit`, 2 when absent, 3 converted from centimetres), or `None`.+pub fn xmp_resolution(xmp: &str) -> Option<(f32, f32)> {+ let first = |key: &str| xmp_values(xmp, key).first().and_then(|&(a, b)| xmp.get(a..b));+ let unit = match first(XMP_UNIT) {+ None => 2.0,+ Some(u) => xmp_number(u)?,+ };+ let scale = if unit == 2.0 {+ 1.0+ } else if unit == 3.0 {+ CM_PER_INCH+ } else {+ return None;+ };+ ppi_pair(xmp_number(first(XMP_X)?)? * scale, xmp_number(first(XMP_Y)?)? * scale)+}++/// `xmp` with its `tiff:` resolution properties set to `ppi` (and the unit to 2, inch),+/// borrowed when it has none or already says so.+pub fn xmp_with_resolution(xmp: &str, ppi: (f32, f32)) -> Cow<'_, str> {+ if ppi_pair(f64::from(ppi.0), f64::from(ppi.1)).is_none() || xmp_resolution(xmp).is_some_and(|r| same(r, ppi)) {+ return Cow::Borrowed(xmp);+ }+ let text = |v: f32| {+ let (n, d) = rational(v);+ format!("{n}/{d}")+ };+ let mut edits: Vec<(usize, usize, String)> = Vec::new();+ for (key, value) in [(XMP_X, text(ppi.0)), (XMP_Y, text(ppi.1)), (XMP_UNIT, "2".to_owned())] {+ edits.extend(xmp_values(xmp, key).into_iter().map(|(a, b)| (a, b, value.clone())));+ }+ if edits.is_empty() {+ return Cow::Borrowed(xmp);+ }+ edits.sort_by_key(|e| e.0);+ let mut out = String::with_capacity(xmp.len() + 16);+ let mut at = 0;+ for (a, b, v) in edits {+ // Overlapping ranges can only come from malformed markup; keep the first edit.+ if a < at {+ continue;+ }+ out.push_str(xmp.get(at..a).unwrap_or_default());+ out.push_str(&v);+ at = b;+ }+ out.push_str(xmp.get(at..).unwrap_or_default());+ if out == xmp { Cow::Borrowed(xmp) } else { Cow::Owned(out) }+}++/// The EXIF to write next to upright pixels at resolution `ppi`: Orientation 1 (see+/// [`upright_exif`]) and, when `ppi` is known, the resolution (see [`exif_with_resolution`]).+pub fn export_exif(exif: &[u8], ppi: Option<(f32, f32)>) -> Cow<'_, [u8]> {+ let up = upright_exif(exif);+ let Some(ppi) = ppi else { return up };+ if let Cow::Owned(v) = exif_with_resolution(&up, ppi) {+ return Cow::Owned(v);+ }+ up+}++/// The XMP to write next to upright pixels at resolution `ppi` (see [`upright_xmp`] and+/// [`xmp_with_resolution`]).+pub fn export_xmp(xmp: &str, ppi: Option<(f32, f32)>) -> Cow<'_, str> {+ let up = upright_xmp(xmp);+ let Some(ppi) = ppi else { return up };+ if let Cow::Owned(v) = xmp_with_resolution(&up, ppi) {+ return Cow::Owned(v);+ }+ up+}++/// The resolution a decoded file's metadata blocks record, in precedence order: XMP, then+/// EXIF (Photoshop's ResolutionInfo is format-specific and read by the decoder).+pub(crate) fn from_metadata(exif: Option<&[u8]>, xmp: Option<&str>) -> Option<(f32, f32)> {+ xmp.and_then(xmp_resolution).or_else(|| exif.and_then(exif_resolution))+}diff --git a/crates/codecs/src/web.rs b/crates/codecs/src/web.rsindex 48d1cf192..fcf8509b5 100644--- a/crates/codecs/src/web.rs+++ b/crates/codecs/src/web.rs@@ -316,6 +316,8 @@ pub fn encode_jpeg_rgb8(enc.set_density(jpeg_encoder::Density::Inch { x: v, y: v });}if let Some(x) = xmp {+ // Its `tiff:` resolution, if any, says what the JFIF density says (#1691).+ let x = crate::resolution::export_xmp(x, dpi.filter(|d| *d >= 1.0).map(|d| (d, d)));let mut seg = b"http://ns.adobe.com/xap/1.0/\0".to_vec();seg.extend_from_slice(x.as_bytes());enc.add_app_segment(1, &seg).map_err(e)?;@@ -412,6 +414,17 @@ mod tests {assert!(prog.windows(2).any(|w| w == [0xFF, 0xC2]));assert_eq!(crate::decode(&prog).unwrap().dimensions(), (64, 48));}++ /// #1691: the XMP resolution of a Save for Web JPEG says what its JFIF density says.+ #[test]+ fn web_jpeg_xmp_resolution_follows_the_density() {+ let rgb = vec![100u8; 8 * 8 * 3];+ let xmp = r#"<rdf:Description tiff:XResolution="300/1" tiff:YResolution="300/1"/>"#;+ let out = encode_jpeg_rgb8(8, 8, &rgb, 80, false, false, None, Some(72.0), Some(xmp)).unwrap();+ let img = crate::decode(&out).unwrap();+ assert_eq!(img.meta.dpi, Some((72.0, 72.0)));+ assert_eq!(img.meta.xmp.as_deref().and_then(crate::xmp_resolution), Some((72.0, 72.0)));+ }}#[cfg(test)]diff --git a/crates/codecs/tests/resolution.rs b/crates/codecs/tests/resolution.rsnew file mode 100644index 000000000..bfe418a80--- /dev/null+++ b/crates/codecs/tests/resolution.rs@@ -0,0 +1,438 @@+//! Resolution recorded in metadata (#1691): a camera JPEG keeps its resolution in EXIF only, and+//! Photoshop opens it at that resolution; Photoshop's own APP13 ResolutionInfo and the XMP+//! `tiff:` properties outrank EXIF, and the JFIF density comes last. Exports write the image's+//! resolution into JFIF, EXIF and XMP alike. Every file here is built by hand.++use std::borrow::Cow;++use photocraft_codecs::resolution::{exif_with_resolution, xmp_with_resolution};+use photocraft_codecs::*;+use proptest::prelude::{any, proptest};++const X: u16 = 282;+const Y: u16 = 283;+const UNIT: u16 = 296;+const SHORT: u16 = 3;+const LONG: u16 = 4;+const RATIONAL: u16 = 5;+const ASCII: u16 = 2;++/// One IFD0 entry: tag, type, count and the value bytes (in the block's byte order).+struct E(u16, u16, u32, Vec<u8>);++struct Exif {+ big: bool,+}++impl Exif {+ fn u16(&self, v: u16) -> [u8; 2] {+ if self.big { v.to_be_bytes() } else { v.to_le_bytes() }+ }+ fn u32(&self, v: u32) -> [u8; 4] {+ if self.big { v.to_be_bytes() } else { v.to_le_bytes() }+ }+ fn rational(&self, n: u32, d: u32) -> Vec<u8> {+ [self.u32(n), self.u32(d)].concat()+ }+ fn short(&self, v: u16) -> Vec<u8> {+ self.u16(v).to_vec()+ }+ fn x(&self, n: u32, d: u32) -> E {+ E(X, RATIONAL, 1, self.rational(n, d))+ }+ fn y(&self, n: u32, d: u32) -> E {+ E(Y, RATIONAL, 1, self.rational(n, d))+ }+ fn unit(&self, u: u16) -> E {+ E(UNIT, SHORT, 1, self.short(u))+ }+ fn make(&self) -> E {+ E(0x010F, ASCII, 6, b"NIKON\0".to_vec())+ }+ fn orientation(&self, o: u16) -> E {+ E(0x0112, SHORT, 1, self.short(o))+ }++ /// A TIFF-structured EXIF block: header, IFD0 at 8, then the out-of-line values.+ fn build(&self, entries: &[E]) -> Vec<u8> {+ let mut v = if self.big { b"MM\0*".to_vec() } else { b"II*\0".to_vec() };+ v.extend_from_slice(&self.u32(8));+ v.extend_from_slice(&self.u16(entries.len() as u16));+ let mut data_at = 8 + 2 + entries.len() * 12 + 4;+ let mut data = Vec::new();+ for E(tag, ty, count, value) in entries {+ v.extend_from_slice(&self.u16(*tag));+ v.extend_from_slice(&self.u16(*ty));+ v.extend_from_slice(&self.u32(*count));+ if value.len() <= 4 {+ let mut inline = value.clone();+ inline.resize(4, 0);+ v.extend_from_slice(&inline);+ } else {+ v.extend_from_slice(&self.u32(data_at as u32));+ data.extend_from_slice(value);+ data_at += value.len();+ }+ }+ v.extend_from_slice(&self.u32(0));+ v.extend_from_slice(&data);+ v+ }+}++const LE: Exif = Exif { big: false };+const BE: Exif = Exif { big: true };++/// A D3200-style block: Make, XResolution 300/1, YResolution 300/1, ResolutionUnit 2.+fn camera_exif(e: &Exif) -> Vec<u8> {+ e.build(&[e.make(), e.x(300, 1), e.y(300, 1), e.unit(2)])+}++fn segment(marker: u8, payload: &[u8]) -> Vec<u8> {+ let mut s = vec![0xFF, marker];+ s.extend_from_slice(&((payload.len() + 2) as u16).to_be_bytes());+ s.extend_from_slice(payload);+ s+}++fn jfif(unit: u8, x: u16, y: u16) -> Vec<u8> {+ let mut p = b"JFIF\0\x01\x02".to_vec();+ p.push(unit);+ p.extend_from_slice(&x.to_be_bytes());+ p.extend_from_slice(&y.to_be_bytes());+ p.extend_from_slice(&[0, 0]);+ segment(0xE0, &p)+}++fn exif_app1(exif: &[u8]) -> Vec<u8> {+ segment(0xE1, &[b"Exif\0\0".as_slice(), exif].concat())+}++fn xmp_app1(xmp: &str) -> Vec<u8> {+ segment(0xE1, &[b"http://ns.adobe.com/xap/1.0/\0".as_slice(), xmp.as_bytes()].concat())+}++/// An 8BIM resource block holding ResolutionInfo at `ppi` (display unit inch), after an+/// unrelated resource with an odd-length name and an odd-sized body.+fn irb(ppi: f64) -> Vec<u8> {+ let mut b = b"8BIM".to_vec();+ b.extend_from_slice(&0x0404u16.to_be_bytes());+ b.extend_from_slice(&[3, b'a', b'b', b'c']);+ b.extend_from_slice(&3u32.to_be_bytes());+ b.extend_from_slice(&[1, 2, 3, 0]);+ b.extend_from_slice(b"8BIM");+ b.extend_from_slice(&0x03EDu16.to_be_bytes());+ b.extend_from_slice(&[0, 0]);+ b.extend_from_slice(&16u32.to_be_bytes());+ let fixed = ((ppi * 65536.0).round() as u32).to_be_bytes();+ for _ in 0..2 {+ b.extend_from_slice(&fixed);+ b.extend_from_slice(&1u16.to_be_bytes());+ b.extend_from_slice(&2u16.to_be_bytes());+ }+ b+}++fn app13(resources: &[u8]) -> Vec<u8> {+ segment(0xED, &[b"Photoshop 3.0\0".as_slice(), resources].concat())+}++/// A 16×8 baseline JPEG whose APPn segments are exactly `segments` (the encoder's own JFIF+/// header is taken out).+fn jpeg_with(segments: &[Vec<u8>]) -> Vec<u8> {+ let img = Image::from_raw(16, 8, ChannelLayout::Gray, SampleType::U8, vec![128; 128]).unwrap();+ let base = encode(&img, Format::Jpeg, &EncodeOptions::default()).unwrap();+ let mut i = 2;+ while (0xE0..=0xEF).contains(&base[i + 1]) {+ i += 2 + u16::from_be_bytes([base[i + 2], base[i + 3]]) as usize;+ }+ let mut out = base[..2].to_vec();+ for s in segments {+ out.extend_from_slice(s);+ }+ out.extend_from_slice(&base[i..]);+ out+}++fn dpi_of(bytes: &[u8]) -> Option<(f32, f32)> {+ decode(bytes).unwrap().meta.dpi+}++fn near(got: Option<(f32, f32)>, want: f32) {+ let (x, y) = got.unwrap_or_else(|| panic!("no resolution, wanted {want}"));+ assert!((x - want).abs() < 0.01 && (y - want).abs() < 0.01, "got {x}×{y}, wanted {want}");+}++/// The APPn payloads of a JPEG: (marker, payload).+fn app_segments(b: &[u8]) -> Vec<(u8, Vec<u8>)> {+ let mut out = Vec::new();+ let mut i = 2;+ while i + 4 <= b.len() && b[i] == 0xFF && b[i + 1] != 0xDA {+ let len = u16::from_be_bytes([b[i + 2], b[i + 3]]) as usize;+ if (0xE0..=0xEF).contains(&b[i + 1]) {+ out.push((b[i + 1], b[i + 4..i + 2 + len].to_vec()));+ }+ i += 2 + len;+ }+ out+}++/// (unit, x, y) of a JPEG's JFIF header.+fn jfif_density(b: &[u8]) -> (u8, u16, u16) {+ let (_, p) = app_segments(b).into_iter().find(|(m, p)| *m == 0xE0 && p.starts_with(b"JFIF\0")).unwrap();+ (p[7], u16::from_be_bytes([p[8], p[9]]), u16::from_be_bytes([p[10], p[11]]))+}++fn exif_of(b: &[u8]) -> Vec<u8> {+ let (_, p) = app_segments(b).into_iter().find(|(m, p)| *m == 0xE1 && p.starts_with(b"Exif\0\0")).unwrap();+ p[6..].to_vec()+}++#[test]+fn exif_only_camera_jpeg_opens_at_its_exif_resolution() {+ for e in [&LE, &BE] {+ near(dpi_of(&jpeg_with(&[exif_app1(&camera_exif(e))])), 300.0);+ // ResolutionUnit absent: inch, the EXIF default.+ near(dpi_of(&jpeg_with(&[exif_app1(&e.build(&[e.x(300, 1), e.y(300, 1)]))])), 300.0);+ // Non-unit denominators.+ near(dpi_of(&jpeg_with(&[exif_app1(&e.build(&[e.x(3_000_000, 10_000), e.y(1200, 4), e.unit(2)]))])), 300.0);+ }+}++#[test]+fn exif_resolution_in_centimetres_is_converted() {+ for e in [&LE, &BE] {+ let exif = e.build(&[e.x(11811, 100), e.y(11811, 100), e.unit(3)]);+ near(exif_resolution(&exif), 299.9994);+ near(dpi_of(&jpeg_with(&[exif_app1(&exif)])), 299.9994);+ }+}++#[test]+fn jfif_aspect_ratio_only_with_exif_uses_exif() {+ near(dpi_of(&jpeg_with(&[jfif(0, 1, 1), exif_app1(&camera_exif(&LE))])), 300.0);+}++#[test]+fn exif_outranks_a_default_jfif_density() {+ near(dpi_of(&jpeg_with(&[jfif(1, 72, 72), exif_app1(&camera_exif(&LE))])), 300.0);+ near(dpi_of(&jpeg_with(&[jfif(1, 72, 72), exif_app1(&camera_exif(&BE))])), 300.0);+ // JFIF alone still counts, in either unit.+ near(dpi_of(&jpeg_with(&[jfif(1, 72, 72)])), 72.0);+ near(dpi_of(&jpeg_with(&[jfif(2, 100, 100)])), 254.0);+ assert_eq!(dpi_of(&jpeg_with(&[jfif(0, 1, 1)])), None);+}++#[test]+fn photoshop_resolution_info_wins_then_xmp_then_exif() {+ let xmp = r#"<x:xmpmeta><rdf:Description tiff:XResolution="200/1" tiff:YResolution="200/1" tiff:ResolutionUnit="2"/></x:xmpmeta>"#;+ let exif = exif_app1(&camera_exif(&LE));+ near(dpi_of(&jpeg_with(&[jfif(1, 72, 72), exif.clone(), xmp_app1(xmp), app13(&irb(240.0))])), 240.0);+ near(dpi_of(&jpeg_with(&[jfif(1, 72, 72), exif.clone(), xmp_app1(xmp)])), 200.0);+ // A fractional Photoshop resolution survives the 16.16 fixed point.+ near(dpi_of(&jpeg_with(&[jfif(1, 72, 72), exif, app13(&irb(299.5))])), 299.5);+ near(photoshop_resolution(&irb(150.0)), 150.0);+ // Element form, centimetres.+ let elem = "<tiff:XResolution>100/1</tiff:XResolution><tiff:YResolution>100</tiff:YResolution><tiff:ResolutionUnit>3</tiff:ResolutionUnit>";+ near(xmp_resolution(elem), 254.0);+}++#[test]+fn unusable_exif_falls_back_to_jfif() {+ let e = &LE;+ let bad = [+ // No absolute unit.+ e.build(&[e.x(300, 1), e.y(300, 1), e.unit(1)]),+ // Unknown unit, malformed unit entry.+ e.build(&[e.x(300, 1), e.y(300, 1), e.unit(9)]),+ e.build(&[e.x(300, 1), e.y(300, 1), E(UNIT, LONG, 1, e.u32(2).to_vec())]),+ // Zero denominator, zero value, wrong type, wrong count.+ e.build(&[e.x(300, 0), e.y(300, 1)]),+ e.build(&[e.x(0, 1), e.y(300, 1)]),+ e.build(&[E(X, SHORT, 1, e.short(300)), e.y(300, 1)]),+ e.build(&[E(X, RATIONAL, 2, [e.rational(300, 1), e.rational(300, 1)].concat()), e.y(300, 1)]),+ // Only one axis.+ e.build(&[e.x(300, 1)]),+ ];+ for exif in &bad {+ assert_eq!(exif_resolution(exif), None);+ near(dpi_of(&jpeg_with(&[jfif(1, 72, 72), exif_app1(exif)])), 72.0);+ }+ // A value offset pointing past the end.+ let mut far = camera_exif(e);+ let at = 8 + 2 + 12 + 8; // XResolution entry's value field+ far[at..at + 4].copy_from_slice(&e.u32(60_000));+ assert_eq!(exif_resolution(&far), None);+ near(dpi_of(&jpeg_with(&[jfif(1, 72, 72), exif_app1(&far)])), 72.0);+}++#[test]+fn truncated_metadata_never_panics_and_falls_back() {+ let exif = camera_exif(&BE);+ for n in 0..exif.len() {+ let _ = exif_resolution(&exif[..n]);+ let _ = exif_with_resolution(&exif[..n], (240.0, 240.0));+ let dpi = dpi_of(&jpeg_with(&[jfif(1, 72, 72), exif_app1(&exif[..n])]));+ assert!(dpi == Some((72.0, 72.0)) || dpi == Some((300.0, 300.0)), "{n}: {dpi:?}");+ }+ let r = irb(300.0);+ for n in 0..r.len() {+ assert_eq!(photoshop_resolution(&r[..n]), None, "{n}");+ near(dpi_of(&jpeg_with(&[jfif(1, 72, 72), app13(&r[..n])])), 72.0);+ }+ for x in ["tiff:XResolution=", "tiff:XResolution=\"", "tiff:XResolution=\"\" tiff:YResolution=\"5/0\"", "<tiff:XResolution>", "</tiff:XResolution>9<"] {+ assert_eq!(xmp_resolution(x), None, "{x}");+ let _ = xmp_with_resolution(x, (1.0, 1.0));+ }+}++proptest! {+ #[test]+ fn hostile_bytes_never_panic(bytes in proptest::collection::vec(any::<u8>(), 0..256), ppi in 0.0f32..2e6) {+ let _ = exif_resolution(&bytes);+ let _ = exif_with_resolution(&bytes, (ppi, ppi));+ let _ = photoshop_resolution(&bytes);+ let s = String::from_utf8_lossy(&bytes);+ let _ = xmp_resolution(&s);+ let _ = xmp_with_resolution(&s, (ppi, ppi));+ }++ #[test]+ fn mutated_exif_never_panics(i in 0usize..80, v in any::<u8>(), ppi in 1.0f32..10_000.0) {+ let mut exif = camera_exif(&LE);+ if let Some(b) = exif.get_mut(i) { *b = v; }+ let _ = exif_resolution(&exif);+ let fixed = exif_with_resolution(&exif, (ppi, ppi));+ let _ = exif_resolution(&fixed);+ let _ = exif_orientation(&fixed);+ }+}++#[test]+fn rewriting_keeps_every_other_byte() {+ for e in [&LE, &BE] {+ let src = e.build(&[e.make(), e.orientation(6), e.x(300, 1), e.y(300, 1), e.unit(3)]);+ let out = exif_with_resolution(&src, (240.0, 240.0)).into_owned();+ assert_eq!(out.len(), src.len());+ near(exif_resolution(&out), 240.0);+ let want = e.build(&[e.make(), e.orientation(6), e.x(240, 1), e.y(240, 1), e.unit(2)]);+ assert_eq!(out, want);+ // Fractions keep three decimals.+ near(exif_resolution(&exif_with_resolution(&src, (299.5, 72.25))).map(|(x, _)| (x, x)), 299.5);+ // Nothing to change: borrowed.+ assert!(matches!(exif_with_resolution(&camera_exif(e), (300.0, 300.0)), Cow::Borrowed(_)));+ let no_res = e.build(&[e.make()]);+ assert!(matches!(exif_with_resolution(&no_res, (240.0, 240.0)), Cow::Borrowed(_)));+ // With the JPEG prefix.+ let prefixed = [b"Exif\0\0".as_slice(), &src].concat();+ assert_eq!(exif_with_resolution(&prefixed, (240.0, 240.0)).as_ref(), [b"Exif\0\0".as_slice(), &want].concat());+ }+}++#[test]+fn entries_that_cannot_be_rewritten_are_removed() {+ for e in [&LE, &BE] {+ // XResolution as a SHORT and a LONG unit: both go, the rest stays readable.+ let src = e.build(&[e.make(), E(X, SHORT, 1, e.short(300)), e.y(300, 1), E(UNIT, LONG, 1, e.u32(2).to_vec()), e.orientation(6)]);+ let out = exif_with_resolution(&src, (240.0, 240.0)).into_owned();+ assert_eq!(out.len(), src.len());+ let count = if e.big { u16::from_be_bytes([out[8], out[9]]) } else { u16::from_le_bytes([out[8], out[9]]) };+ assert_eq!(count, 3);+ assert_eq!(exif_orientation(&out), 6);+ // Only YResolution is left (240): no X, so no resolution at all, and no stale 300.+ assert_eq!(exif_resolution(&out), None);+ let tags: Vec<u16> = (0..3)+ .map(|k| {+ let at = 10 + k * 12;+ if e.big { u16::from_be_bytes([out[at], out[at + 1]]) } else { u16::from_le_bytes([out[at], out[at + 1]]) }+ })+ .collect();+ assert_eq!(tags, vec![0x010F, Y, 0x0112]);+ // The next-IFD pointer followed the table, the freed entries are zero.+ assert_eq!(&out[10 + 36..10 + 40], &[0, 0, 0, 0]);+ assert!(out[10 + 40..10 + 64].iter().all(|&b| b == 0));+ // The Make string (out of line) did not move.+ assert!(out.windows(6).any(|w| w == b"NIKON\0"));+ }+}++#[test]+fn xmp_resolution_is_rewritten() {+ let attr = r#"<rdf:Description tiff:XResolution="300/1" tiff:YResolution='300/1' tiff:ResolutionUnit="3" tiff:Make="X"/>"#;+ assert_eq!(+ xmp_with_resolution(attr, (240.0, 240.0)),+ r#"<rdf:Description tiff:XResolution="240/1" tiff:YResolution='240/1' tiff:ResolutionUnit="2" tiff:Make="X"/>"#+ );+ let elem = "<tiff:XResolution>300/1</tiff:XResolution><tiff:YResolution>300/1</tiff:YResolution>";+ assert_eq!(xmp_with_resolution(elem, (72.5, 72.5)), "<tiff:XResolution>72500/1000</tiff:XResolution><tiff:YResolution>72500/1000</tiff:YResolution>");+ for same in [r#"tiff:XResolution="240" tiff:YResolution="240/1""#, "<x/>"] {+ assert!(matches!(xmp_with_resolution(same, (240.0, 240.0)), Cow::Borrowed(_)), "{same}");+ }+}++#[test]+fn jpeg_export_writes_one_resolution_everywhere() {+ for e in [&LE, &BE] {+ let xmp = r#"<rdf:Description tiff:XResolution="300/1" tiff:YResolution="300/1"/>"#;+ let src = jpeg_with(&[jfif(1, 72, 72), exif_app1(&camera_exif(e)), xmp_app1(xmp)]);+ let mut img = decode(&src).unwrap();+ near(img.meta.dpi, 300.0);+ img.meta.dpi = Some((240.0, 240.0));+ let out = encode(&img, Format::Jpeg, &EncodeOptions::default()).unwrap();+ assert_eq!(jfif_density(&out), (1, 240, 240));+ near(exif_resolution(&exif_of(&out)), 240.0);+ let (_, x) = app_segments(&out).into_iter().find(|(m, p)| *m == 0xE1 && p.starts_with(b"http://ns.adobe.com/xap/1.0/\0")).unwrap();+ near(xmp_resolution(std::str::from_utf8(&x).unwrap()), 240.0);+ near(dpi_of(&out), 240.0);+ // The rest of the EXIF came along.+ assert!(exif_of(&out).windows(6).any(|w| w == b"NIKON\0"));+ }+}++#[test]+fn other_formats_take_the_exif_resolution_when_they_have_none() {+ let mut img = Image::from_raw(4, 4, ChannelLayout::Rgb, SampleType::U8, vec![90; 48]).unwrap();+ img.meta.exif = Some(camera_exif(&LE));+ for fmt in [Format::WebP, Format::Png] {+ // Written at 240 with the 300 ppi EXIF: the EXIF follows the image.+ img.meta.dpi = Some((240.0, 240.0));+ let out = encode(&img, fmt, &EncodeOptions::default()).unwrap();+ let back = decode(&out).unwrap();+ near(back.meta.dpi, 240.0);+ near(back.meta.exif.as_deref().and_then(exif_resolution), 240.0);+ // Written without a resolution: the EXIF one is read back.+ img.meta.dpi = None;+ let out = encode(&img, fmt, &EncodeOptions::default()).unwrap();+ near(decode(&out).unwrap().meta.dpi, 300.0);+ }+}++fn crc32(data: &[u8]) -> u32 {+ let mut c = !0u32;+ for &b in data {+ c ^= u32::from(b);+ for _ in 0..8 {+ c = if c & 1 != 0 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 };+ }+ }+ !c+}++#[test]+fn png_phys_outranks_its_exif() {+ // eXIf says 300 ppi, then a pHYs chunk of 150 ppi (5906 px/m) goes in after IHDR.+ let mut img = Image::from_raw(4, 4, ChannelLayout::Rgb, SampleType::U8, vec![90; 48]).unwrap();+ img.meta.exif = Some(camera_exif(&LE));+ let png = encode(&img, Format::Png, &EncodeOptions::default()).unwrap();+ near(decode(&png).unwrap().meta.dpi, 300.0);+ let mut body = b"pHYs".to_vec();+ body.extend_from_slice(&5906u32.to_be_bytes());+ body.extend_from_slice(&5906u32.to_be_bytes());+ body.push(1);+ let mut chunk = 9u32.to_be_bytes().to_vec();+ chunk.extend_from_slice(&body);+ chunk.extend_from_slice(&crc32(&body).to_be_bytes());+ let ihdr_end = 8 + 8 + 13 + 4;+ let with_phys = [&png[..ihdr_end], &chunk, &png[ihdr_end..]].concat();+ near(decode(&with_phys).unwrap().meta.dpi, 150.0114);+}diff --git a/crates/engine/tests/jpeg_exif_resolution.rs b/crates/engine/tests/jpeg_exif_resolution.rsnew file mode 100644index 000000000..379d1bb46--- /dev/null+++ b/crates/engine/tests/jpeg_exif_resolution.rs@@ -0,0 +1,84 @@+//! #1691: a camera JPEG with its resolution only in EXIF opens at that resolution, and a JPEG+//! saved after Image Size (resolution only) carries the new resolution in JFIF and EXIF alike.++use photocraft_codecs::{ChannelLayout, EncodeOptions, Format, Image, Metadata, SampleType, exif_resolution};+use photocraft_engine::Session;+use photocraft_engine::file_cmds::open_bytes_as;+use serde_json::json;++/// Little-endian EXIF: Make "NIKON", XResolution 300/1, YResolution 300/1, ResolutionUnit 2.+fn camera_exif() -> Vec<u8> {+ let mut v = b"II*\0".to_vec();+ v.extend_from_slice(&8u32.to_le_bytes());+ v.extend_from_slice(&4u16.to_le_bytes());+ let data = 8 + 2 + 4 * 12 + 4;+ let entry = |v: &mut Vec<u8>, tag: u16, ty: u16, count: u32, value: u32| {+ v.extend_from_slice(&tag.to_le_bytes());+ v.extend_from_slice(&ty.to_le_bytes());+ v.extend_from_slice(&count.to_le_bytes());+ v.extend_from_slice(&value.to_le_bytes());+ };+ entry(&mut v, 0x010F, 2, 6, data as u32);+ entry(&mut v, 282, 5, 1, data as u32 + 6);+ entry(&mut v, 283, 5, 1, data as u32 + 14);+ entry(&mut v, 296, 3, 1, 2);+ v.extend_from_slice(&0u32.to_le_bytes());+ v.extend_from_slice(b"NIKON\0");+ for _ in 0..2 {+ v.extend_from_slice(&300u32.to_le_bytes());+ v.extend_from_slice(&1u32.to_le_bytes());+ }+ v+}++/// A camera-style JPEG: no JFIF header, the resolution only in EXIF.+fn camera_jpeg() -> Vec<u8> {+ let meta = Metadata { exif: Some(camera_exif()), ..Default::default() };+ let img = Image::from_raw(16, 8, ChannelLayout::Rgb, SampleType::U8, vec![120; 16 * 8 * 3]).unwrap().with_meta(meta);+ let b = photocraft_codecs::encode(&img, Format::Jpeg, &EncodeOptions::default()).unwrap();+ assert_eq!(&b[2..4], &[0xFF, 0xE0], "the encoder starts with JFIF");+ let len = u16::from_be_bytes([b[4], b[5]]) as usize;+ [&b[..2], &b[4 + len..]].concat()+}++/// (marker, payload) of each APPn segment.+fn app_segments(b: &[u8]) -> Vec<(u8, Vec<u8>)> {+ let mut out = Vec::new();+ let mut i = 2;+ while i + 4 <= b.len() && b[i] == 0xFF && b[i + 1] != 0xDA {+ let len = u16::from_be_bytes([b[i + 2], b[i + 3]]) as usize;+ if (0xE0..=0xEF).contains(&b[i + 1]) {+ out.push((b[i + 1], b[i + 4..i + 2 + len].to_vec()));+ }+ i += 2 + len;+ }+ out+}++#[test]+fn exif_resolution_opens_and_saves_consistently() {+ let src = camera_jpeg();+ assert!(app_segments(&src).iter().all(|(m, _)| *m != 0xE0));+ let mut s = Session::new();+ open_bytes_as(&mut s, "DSC_0001.JPG", &src, None, None).unwrap();+ assert_eq!(s.active().unwrap().doc.resolution_dpi, 300.0);++ s.execute("image.imageSize", json!({"resolution": 240, "resample": "none"})).unwrap();+ let d = &s.active().unwrap().doc;+ assert_eq!((d.resolution_dpi, d.size.width, d.size.height), (240.0, 16, 8));++ let dir = std::env::temp_dir().join(format!("photocraft-1691-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let out = dir.join("saved.jpg");+ s.execute("file.saveACopy", json!({"path": out.to_string_lossy()})).unwrap();+ let saved = std::fs::read(&out).unwrap();+ println!("saved {}", out.display());++ let segs = app_segments(&saved);+ let (_, jfif) = segs.iter().find(|(m, p)| *m == 0xE0 && p.starts_with(b"JFIF\0")).unwrap();+ assert_eq!((jfif[7], u16::from_be_bytes([jfif[8], jfif[9]]), u16::from_be_bytes([jfif[10], jfif[11]])), (1, 240, 240));+ let (_, exif) = segs.iter().find(|(m, p)| *m == 0xE1 && p.starts_with(b"Exif\0\0")).unwrap();+ assert_eq!(exif_resolution(exif), Some((240.0, 240.0)));+ assert!(exif.windows(6).any(|w| w == b"NIKON\0"), "the rest of the EXIF is kept");+ assert_eq!(photocraft_io::import("saved.jpg", &saved).unwrap().document.resolution_dpi, 240.0);+}diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rsindex 238431698..45dd05df5 100644--- a/crates/io/src/psd_export.rs+++ b/crates/io/src/psd_export.rs@@ -1271,12 +1271,14 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32) -if let Some(groups) = link_group_resource(&doc.layers) {resources.push(ImageResource::new(ids::LAYER_GROUP_INFO, groups));}+ // The pixels are saved as they are shown: never let a reader rotate them again. The XMP and+ // EXIF resolution follow the ResolutionInfo resource, so no copy contradicts it (#1691).+ let ppi = Some((doc.resolution_dpi, doc.resolution_dpi)).filter(|d| d.0 > 0.0);if let Some(x) = &doc.metadata.xmp {- // The pixels are saved as they are shown: never let a reader rotate them again.- resources.push(ImageResource::new(ids::XMP, photocraft_codecs::upright_xmp(x).as_bytes().to_vec()));+ resources.push(ImageResource::new(ids::XMP, photocraft_codecs::export_xmp(x, ppi).as_bytes().to_vec()));}if let Some(e) = &doc.metadata.exif {- resources.push(ImageResource::new(ids::EXIF, photocraft_codecs::upright_exif(e).into_owned()));+ resources.push(ImageResource::new(ids::EXIF, photocraft_codecs::export_exif(e, ppi).into_owned()));}let mut global_blocks = Vec::new();for (sig, key, data) in &ex.smart.finish(crate::annotations_map::export_blocks(doc, crate::pattern_map::export_global_blocks(doc))) {diff --git a/crates/io/tests/exif_resolution.rs b/crates/io/tests/exif_resolution.rsnew file mode 100644index 000000000..1dcd1687d--- /dev/null+++ b/crates/io/tests/exif_resolution.rs@@ -0,0 +1,44 @@+//! #1691: the EXIF resolution of an imported photo becomes the document's, and a PSD save keeps+//! its EXIF copy in step with the ResolutionInfo resource.++use photocraft_codecs::{ChannelLayout, EncodeOptions, Format, Image, Metadata, SampleType, exif_resolution};+use photocraft_io::*;++/// Big-endian EXIF: XResolution 300/1, YResolution 300/1, ResolutionUnit 2.+fn camera_exif() -> Vec<u8> {+ let mut v = b"MM\0*".to_vec();+ v.extend_from_slice(&8u32.to_be_bytes());+ v.extend_from_slice(&3u16.to_be_bytes());+ let data = 8 + 2 + 3 * 12 + 4;+ for (tag, ty, value) in [(282u16, 5u16, data as u32), (283, 5, data as u32 + 8)] {+ v.extend_from_slice(&tag.to_be_bytes());+ v.extend_from_slice(&ty.to_be_bytes());+ v.extend_from_slice(&1u32.to_be_bytes());+ v.extend_from_slice(&value.to_be_bytes());+ }+ v.extend_from_slice(&296u16.to_be_bytes());+ v.extend_from_slice(&3u16.to_be_bytes());+ v.extend_from_slice(&1u32.to_be_bytes());+ v.extend_from_slice(&[0, 2, 0, 0]);+ v.extend_from_slice(&0u32.to_be_bytes());+ for _ in 0..2 {+ v.extend_from_slice(&300u32.to_be_bytes());+ v.extend_from_slice(&1u32.to_be_bytes());+ }+ v+}++#[test]+fn webp_with_exif_resolution_imports_at_it_and_psd_save_follows_the_document() {+ let meta = Metadata { exif: Some(camera_exif()), ..Default::default() };+ let img = Image::from_raw(6, 4, ChannelLayout::Rgb, SampleType::U8, vec![50; 72]).unwrap().with_meta(meta);+ let webp = photocraft_codecs::encode(&img, Format::WebP, &EncodeOptions::default()).unwrap();+ let mut doc = import("photo.webp", &webp).unwrap().document;+ assert_eq!(doc.resolution_dpi, 300.0);++ doc.resolution_dpi = 240.0;+ let psd = export(&doc, "photo.psd", &ExportOptions::default()).unwrap().bytes;+ let back = import("photo.psd", &psd).unwrap().document;+ assert_eq!(back.resolution_dpi, 240.0);+ assert_eq!(back.metadata.exif.as_deref().and_then(|e| exif_resolution(e)), Some((240.0, 240.0)));+}