Skip to content

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

Apply EXIF orientation on open, write Orientation = 1 on export (#285) (#318) (#318)

Brandon Thomas7ee4bb28583e
diff --git a/Cargo.lock b/Cargo.lock
index 02a98f91d..f0a106b9a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3478,6 +3478,7 @@ dependencies = [
"jpeg-encoder",
"png 0.18.1",
"proptest",
+ "rayon",
"thiserror 2.0.21",
"tiff",
"zune-core",
diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs
index 3283e61a5..7ac1f46fc 100644
--- a/crates/automation/src/server.rs
+++ b/crates/automation/src/server.rs
@@ -295,8 +295,10 @@ impl PhotocraftMcp {
fn downscale_png(png: &[u8], max_side: u32) -> Result<Option<Vec<u8>>, AutomationError> {
// A compressed reply's byte limit does not bound its decoded pixel allocation.
- let opts =
- photocraft_codecs::DecodeOptions { limits: photocraft_codecs::Limits { max_width: 8192, max_height: 8192, max_pixels: 16 << 20, max_alloc: 64 << 20 } };
+ let opts = photocraft_codecs::DecodeOptions {
+ limits: photocraft_codecs::Limits { max_width: 8192, max_height: 8192, max_pixels: 16 << 20, max_alloc: 64 << 20 },
+ ..Default::default()
+ };
let img = photocraft_codecs::decode_as_with(photocraft_codecs::Format::Png, png, &opts).map_err(|error| AutomationError::Other(error.to_string()))?;
let (w, h) = img.dimensions();
if max_side == 0 || w.max(h) <= max_side {
diff --git a/crates/codecs/Cargo.toml b/crates/codecs/Cargo.toml
index 7c65716f7..c9de3a5a3 100644
--- a/crates/codecs/Cargo.toml
+++ b/crates/codecs/Cargo.toml
@@ -27,6 +27,10 @@ zune-jpeg = "0.5"
zune-core = "0.5"
jpeg-encoder = "0.6"
+# Orientation is applied a band of rows per task on native; wasm stays single-threaded.
+[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
+rayon.workspace = true
+
[dev-dependencies]
proptest.workspace = true
# Oracle decoders for cross-checking in tests only.
diff --git a/crates/codecs/README.md b/crates/codecs/README.md
index 7c1891b07..e2109e6ee 100644
--- a/crates/codecs/README.md
+++ b/crates/codecs/README.md
@@ -76,7 +76,12 @@ the same.
containers that can hold more frames.
* **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.
-* **EXIF orientation** is preserved as data but not applied to the pixels.
+* **Orientation** (EXIF tag 274 in JPEG, PNG `eXIf` and WebP; the IFD0 tag in TIFF) is applied on
+ decode, like Photoshop: the pixels come back upright and the EXIF/XMP orientation is rewritten
+ to 1 (`DecodeOptions::keep_orientation` opts out). Encoders always write Orientation = 1
+ (`upright_exif`, `upright_xmp`), so upright pixels are never rotated twice. Malformed or
+ out-of-range values read as 1. `Image::oriented` turns any layout and depth in parallel bands
+ (about 10 ms for 24 MP RGB8 in release).
* **JPEG**
* 8-bit only. Neither decoder backend supports 12-bit.
* CMYK is always written 4:4:4 (subsampled CMYK is not portable) as Adobe-inverted CMYK with an
@@ -102,7 +107,7 @@ the same.
## Limits (decompression bombs)
-`DecodeOptions { limits: Limits { max_width, max_height, max_pixels, max_alloc } }` guards
+`DecodeOptions { limits: Limits { max_width, max_height, max_pixels, max_alloc }, .. }` guards
decoding. Header dimensions are checked before the pixel buffer is allocated, and the budget is
also passed to the underlying decoders. A violation returns `CodecError::LimitExceeded`. The
defaults are 262144 px per side, 2^30 pixels and 8 GiB (2 GiB on 32-bit targets such as wasm).
diff --git a/crates/codecs/fuzz/fuzz_targets/decode_any.rs b/crates/codecs/fuzz/fuzz_targets/decode_any.rs
index 18408efcd..c424f51f5 100644
--- a/crates/codecs/fuzz/fuzz_targets/decode_any.rs
+++ b/crates/codecs/fuzz/fuzz_targets/decode_any.rs
@@ -8,6 +8,7 @@ use photocraft_codecs::{decode_with, encode, DecodeOptions, EncodeOptions, Limit
fuzz_target!(|data: &[u8]| {
let opts = DecodeOptions {
limits: Limits { max_width: 4096, max_height: 4096, max_pixels: 1 << 22, max_alloc: 256 << 20 },
+ ..Default::default()
};
if let Ok(img) = decode_with(data, &opts)
&& let Some(f) = photocraft_codecs::detect(data)
diff --git a/crates/codecs/fuzz/fuzz_targets/decode_exr.rs b/crates/codecs/fuzz/fuzz_targets/decode_exr.rs
index 3f4ae6178..269ae8e00 100644
--- a/crates/codecs/fuzz/fuzz_targets/decode_exr.rs
+++ b/crates/codecs/fuzz/fuzz_targets/decode_exr.rs
@@ -6,6 +6,7 @@ use photocraft_codecs::{decode_as_with, DecodeOptions, Format, Limits};
fuzz_target!(|data: &[u8]| {
let opts = DecodeOptions {
limits: Limits { max_width: 4096, max_height: 4096, max_pixels: 1 << 22, max_alloc: 256 << 20 },
+ ..Default::default()
};
let _ = decode_as_with(Format::OpenExr, data, &opts);
});
diff --git a/crates/codecs/fuzz/fuzz_targets/decode_jpeg.rs b/crates/codecs/fuzz/fuzz_targets/decode_jpeg.rs
index b08017ee8..04b56de82 100644
--- a/crates/codecs/fuzz/fuzz_targets/decode_jpeg.rs
+++ b/crates/codecs/fuzz/fuzz_targets/decode_jpeg.rs
@@ -6,6 +6,7 @@ use photocraft_codecs::{decode_as_with, DecodeOptions, Format, Limits};
fuzz_target!(|data: &[u8]| {
let opts = DecodeOptions {
limits: Limits { max_width: 4096, max_height: 4096, max_pixels: 1 << 22, max_alloc: 256 << 20 },
+ ..Default::default()
};
let _ = decode_as_with(Format::Jpeg, data, &opts);
});
diff --git a/crates/codecs/fuzz/fuzz_targets/decode_png.rs b/crates/codecs/fuzz/fuzz_targets/decode_png.rs
index 5451640fe..3e04e2f4b 100644
--- a/crates/codecs/fuzz/fuzz_targets/decode_png.rs
+++ b/crates/codecs/fuzz/fuzz_targets/decode_png.rs
@@ -6,6 +6,7 @@ use photocraft_codecs::{decode_as_with, DecodeOptions, Format, Limits};
fuzz_target!(|data: &[u8]| {
let opts = DecodeOptions {
limits: Limits { max_width: 4096, max_height: 4096, max_pixels: 1 << 22, max_alloc: 256 << 20 },
+ ..Default::default()
};
let _ = decode_as_with(Format::Png, data, &opts);
});
diff --git a/crates/codecs/fuzz/fuzz_targets/decode_tiff.rs b/crates/codecs/fuzz/fuzz_targets/decode_tiff.rs
index 943502a0e..2673994f3 100644
--- a/crates/codecs/fuzz/fuzz_targets/decode_tiff.rs
+++ b/crates/codecs/fuzz/fuzz_targets/decode_tiff.rs
@@ -6,6 +6,7 @@ use photocraft_codecs::{decode_as_with, DecodeOptions, Format, Limits};
fuzz_target!(|data: &[u8]| {
let opts = DecodeOptions {
limits: Limits { max_width: 4096, max_height: 4096, max_pixels: 1 << 22, max_alloc: 256 << 20 },
+ ..Default::default()
};
let _ = decode_as_with(Format::Tiff, data, &opts);
});
diff --git a/crates/codecs/src/codecs/jpeg.rs b/crates/codecs/src/codecs/jpeg.rs
index d1119b020..fbe779309 100644
--- a/crates/codecs/src/codecs/jpeg.rs
+++ b/crates/codecs/src/codecs/jpeg.rs
@@ -12,6 +12,7 @@ use crate::error::CodecError;
use crate::fidelity::Plan;
use crate::image::{ChannelLayout, Image, Metadata, SampleType};
use crate::options::{EncodeOptions, Limits};
+use crate::orientation::{upright_exif, upright_xmp};
const F: Format = Format::Jpeg;
const EXIF_HEADER: &[u8] = b"Exif\0\0";
@@ -186,13 +187,14 @@ pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result<Ve
enc.set_density(jpeg_encoder::Density::Inch { x: x.round().min(65535.0) as u16, y: y.round().min(65535.0) as u16 });
}
if let Some(exif) = &img.meta.exif {
+ // The pixels are written as they are shown: never let a viewer rotate them again.
let mut seg = EXIF_HEADER.to_vec();
- seg.extend_from_slice(exif);
+ seg.extend_from_slice(&upright_exif(exif));
enc.add_app_segment(1, &seg).map_err(e)?;
}
if let Some(xmp) = &img.meta.xmp {
let mut seg = XMP_HEADER.to_vec();
- seg.extend_from_slice(xmp.as_bytes());
+ seg.extend_from_slice(upright_xmp(xmp).as_bytes());
enc.add_app_segment(1, &seg).map_err(e)?;
}
}
diff --git a/crates/codecs/src/codecs/png.rs b/crates/codecs/src/codecs/png.rs
index bf008213f..c2ab4f03f 100644
--- a/crates/codecs/src/codecs/png.rs
+++ b/crates/codecs/src/codecs/png.rs
@@ -131,7 +131,8 @@ pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result<Ve
}
if opts.embed_metadata {
if let Some(exif) = &img.meta.exif {
- info.exif_metadata = Some(exif.clone().into());
+ // 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());
}
if let Some((x, y)) = img.meta.dpi
&& x > 0.0
@@ -164,7 +165,7 @@ pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result<Ve
res.map_err(|e| CodecError::encode(F, e))?;
}
if let Some(xmp) = &img.meta.xmp {
- encoder.add_itxt_chunk(XMP_KEYWORD.into(), xmp.clone()).map_err(|e| CodecError::encode(F, e))?;
+ encoder.add_itxt_chunk(XMP_KEYWORD.into(), crate::orientation::upright_xmp(xmp).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.rs
index 2a9f5fc06..fe7609f8d 100644
--- a/crates/codecs/src/codecs/tiff.rs
+++ b/crates/codecs/src/codecs/tiff.rs
@@ -383,9 +383,11 @@ pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result<Ve
} else {
Vec::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 tags = TagSet {
icc: if opts.embed_icc { img.icc.as_deref() } else { None },
- xmp: if opts.embed_metadata { img.meta.xmp.as_deref().map(str::as_bytes) } else { None },
+ xmp: xmp.as_deref().map(str::as_bytes),
dpi: if opts.embed_metadata { img.meta.dpi.filter(|d| d.0 > 0.0 && d.1 > 0.0) } else { None },
text,
alpha: img.layout().has_alpha(),
diff --git a/crates/codecs/src/codecs/webp.rs b/crates/codecs/src/codecs/webp.rs
index c8d33fe60..103fa18d1 100644
--- a/crates/codecs/src/codecs/webp.rs
+++ b/crates/codecs/src/codecs/webp.rs
@@ -54,10 +54,11 @@ pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result<Ve
}
if opts.embed_metadata {
if let Some(exif) = &img.meta.exif {
- enc.set_exif_metadata(exif.clone());
+ // 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());
}
if let Some(xmp) = &img.meta.xmp {
- enc.set_xmp_metadata(xmp.as_bytes().to_vec());
+ enc.set_xmp_metadata(crate::orientation::upright_xmp(xmp).as_bytes().to_vec());
}
}
enc.encode(img.data(), img.width(), img.height(), ct).map_err(|e| CodecError::encode(F, e))?;
diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs
index c5301ccca..cf0852b10 100644
--- a/crates/codecs/src/lib.rs
+++ b/crates/codecs/src/lib.rs
@@ -19,6 +19,7 @@ mod fidelity;
mod format;
mod image;
mod options;
+pub mod orientation;
pub mod web;
pub use crate::codecs::png::encode_indexed as encode_png_indexed;
@@ -27,6 +28,7 @@ pub use crate::fidelity::{FidelityWarning, fidelity_warnings, fidelity_warnings_
pub use crate::format::{ASYMMETRIC_EXCEPTIONS, Format, FormatCaps, caps, detect, from_extension};
pub use crate::image::{ChannelLayout, 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;
use crate::codecs::{exr, jpeg, png, pnm, tiff, via_image, webp};
@@ -64,7 +66,16 @@ pub fn decode_as_with(format: Format, bytes: &[u8], opts: &DecodeOptions) -> Res
}?;
// Final guard for decoders whose header we could not pre-inspect.
l.check(img.width(), img.height(), img.layout(), img.sample_type())?;
- Ok(img)
+ if opts.keep_orientation {
+ return Ok(img);
+ }
+ // Turn the pixels upright, like Photoshop: a TIFF records it in its own IFD0, the others
+ // in their EXIF block. The metadata is rewritten to Orientation = 1 on the way.
+ let o = match format {
+ Format::Tiff => exif_orientation(bytes),
+ _ => img.meta.exif.as_deref().map_or(1, exif_orientation),
+ };
+ img.oriented(o)
}
/// Encode `image` as `format`. Conversions follow the same plan that
diff --git a/crates/codecs/src/options.rs b/crates/codecs/src/options.rs
index bbdcb1eca..515e7dac9 100644
--- a/crates/codecs/src/options.rs
+++ b/crates/codecs/src/options.rs
@@ -67,6 +67,10 @@ impl Limits {
#[derive(Debug, Clone, Default)]
pub struct DecodeOptions {
pub limits: Limits,
+ /// Keep the pixels as stored instead of applying the EXIF / TIFF
+ /// orientation (by default they are turned upright and the metadata's
+ /// orientation is rewritten to 1).
+ pub keep_orientation: bool,
}
/// PNG zlib effort.
diff --git a/crates/codecs/src/orientation.rs b/crates/codecs/src/orientation.rs
new file mode 100644
index 000000000..b8e35e2b3
--- /dev/null
+++ b/crates/codecs/src/orientation.rs
@@ -0,0 +1,273 @@
+//! EXIF / TIFF orientation (tag 274): reading it, applying it to the pixels,
+//! and rewriting it to 1 ("top-left", upright) once the pixels are upright.
+//!
+//! Decoders apply the orientation by default (like Photoshop and every photo
+//! viewer), so a document is always edited upright. Encoders then write
+//! Orientation = 1, so a viewer never rotates the already-upright pixels a
+//! second time.
+//!
+//! Orientation values (TIFF 6.0, EXIF 2.3): 1 = upright, 2 = mirrored, 3 =
+//! rotated 180°, 4 = flipped vertically, 5 = transposed, 6 = needs a 90°
+//! clockwise turn, 7 = transverse, 8 = needs a 90° counter-clockwise turn.
+//! Anything malformed, truncated or out of range reads as 1.
+
+use std::borrow::Cow;
+
+use crate::error::CodecError;
+use crate::image::Image;
+
+/// The TIFF/EXIF Orientation tag.
+const TAG_ORIENTATION: u16 = 274;
+/// TIFF field types that can hold the orientation.
+const TYPE_SHORT: u16 = 3;
+const TYPE_LONG: u16 = 4;
+/// IFD0 entries we look at, at most (real files have a few dozen).
+const MAX_ENTRIES: usize = 1024;
+
+/// Byte order of a TIFF structure.
+#[derive(Clone, Copy)]
+enum Order {
+ Little,
+ Big,
+}
+
+impl Order {
+ 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),
+ Order::Big => u16::from_be_bytes(s),
+ })
+ }
+
+ 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),
+ Order::Big => u32::from_be_bytes(s),
+ })
+ }
+}
+
+/// The TIFF payload of an EXIF block (a JPEG-style `Exif\0\0` prefix is skipped).
+fn tiff_body(b: &[u8]) -> &[u8] {
+ b.strip_prefix(b"Exif\0\0").unwrap_or(b)
+}
+
+/// Locates the Orientation entry in IFD0: `(byte order, value offset, field type)`.
+fn find_entry(b: &[u8]) -> Option<(Order, usize, u16)> {
+ let order = match b.get(0..4)? {
+ [b'I', b'I', 42, 0] => Order::Little,
+ [b'M', b'M', 0, 42] => Order::Big,
+ _ => return None,
+ };
+ let ifd = usize::try_from(order.u32(b, 4)?).ok()?;
+ let count = usize::from(order.u16(b, ifd)?).min(MAX_ENTRIES);
+ let first = ifd.checked_add(2)?;
+ for i in 0..count {
+ let e = first.checked_add(i.checked_mul(12)?)?;
+ let tag = order.u16(b, e)?;
+ if tag != TAG_ORIENTATION {
+ continue;
+ }
+ let ty = order.u16(b, e.checked_add(2)?)?;
+ let n = order.u32(b, e.checked_add(4)?)?;
+ if n == 0 || !matches!(ty, TYPE_SHORT | TYPE_LONG) {
+ return None;
+ }
+ // One SHORT or LONG always fits in the 4-byte value field.
+ return Some((order, e.checked_add(8)?, ty));
+ }
+ None
+}
+
+/// The orientation (1–8) recorded in a TIFF-structured block: an EXIF payload
+/// (with or without the `Exif\0\0` prefix) or a whole TIFF file. Missing,
+/// malformed or out-of-range values give 1.
+pub fn exif_orientation(exif: &[u8]) -> u16 {
+ let b = tiff_body(exif);
+ let value = find_entry(b).and_then(|(order, at, ty)| match ty {
+ TYPE_SHORT => order.u16(b, at),
+ _ => order.u32(b, at).and_then(|v| u16::try_from(v).ok()),
+ });
+ value.filter(|v| (1..=8).contains(v)).unwrap_or(1)
+}
+
+/// `exif` with its Orientation rewritten to 1, borrowed when there is nothing
+/// to change (no tag, already 1, or unparseable).
+pub fn upright_exif(exif: &[u8]) -> Cow<'_, [u8]> {
+ let prefix = exif.len() - tiff_body(exif).len();
+ let Some((order, at, ty)) = find_entry(tiff_body(exif)) else {
+ return Cow::Borrowed(exif);
+ };
+ let current = match ty {
+ TYPE_SHORT => order.u16(tiff_body(exif), at).map(u32::from),
+ _ => order.u32(tiff_body(exif), at),
+ };
+ if current == Some(1) {
+ return Cow::Borrowed(exif);
+ }
+ let one: Vec<u8> = match (ty, order) {
+ (TYPE_SHORT, Order::Little) => 1u16.to_le_bytes().to_vec(),
+ (TYPE_SHORT, Order::Big) => 1u16.to_be_bytes().to_vec(),
+ (_, Order::Little) => 1u32.to_le_bytes().to_vec(),
+ (_, Order::Big) => 1u32.to_be_bytes().to_vec(),
+ };
+ let mut out = exif.to_vec();
+ let Some(at) = prefix.checked_add(at) else { return Cow::Borrowed(exif) };
+ match at.checked_add(one.len()).and_then(|end| out.get_mut(at..end)) {
+ Some(slot) => {
+ slot.copy_from_slice(&one);
+ Cow::Owned(out)
+ }
+ None => Cow::Borrowed(exif),
+ }
+}
+
+/// `xmp` with any `tiff:Orientation` (attribute or element form) set to 1,
+/// borrowed when there is nothing to change.
+pub fn upright_xmp(xmp: &str) -> Cow<'_, str> {
+ const KEY: &str = "tiff:Orientation";
+ if !xmp.contains(KEY) {
+ return Cow::Borrowed(xmp);
+ }
+ let mut out = String::with_capacity(xmp.len());
+ let mut rest = xmp;
+ let mut changed = false;
+ while let Some(i) = rest.find(KEY) {
+ let (head, tail) = rest.split_at(i + KEY.len());
+ out.push_str(head);
+ rest = tail;
+ // `tiff:Orientation="6"`, `tiff:Orientation='6'` or `<tiff:Orientation>6<`.
+ let open = rest.char_indices().take_while(|&(_, c)| c.is_ascii_whitespace() || matches!(c, '=' | '"' | '\'' | '>')).last();
+ let Some((at, c)) = open else { continue };
+ if !matches!(c, '"' | '\'' | '>') {
+ continue;
+ }
+ let start = at + 1;
+ let digits = rest.get(start..).map_or(0, |s| s.bytes().take_while(u8::is_ascii_digit).count());
+ if digits == 0 || rest.get(start..start + digits) == Some("1") {
+ continue;
+ }
+ out.push_str(rest.get(..start).unwrap_or_default());
+ out.push('1');
+ rest = rest.get(start + digits..).unwrap_or_default();
+ changed = true;
+ }
+ out.push_str(rest);
+ if changed { Cow::Owned(out) } else { Cow::Borrowed(xmp) }
+}
+
+/// Source pixel index for output pixel `(0, y2)` and the step per output column, for
+/// orientation `o` of a `w`×`h` source (values 2–8; see the module docs).
+fn walk(o: u16, w: isize, h: isize, y2: isize) -> (isize, isize) {
+ match o {
+ 2 => (y2 * w + w - 1, -1),
+ 3 => ((h - 1 - y2) * w + w - 1, -1),
+ 4 => ((h - 1 - y2) * w, 1),
+ 5 => (y2, w),
+ 6 => ((h - 1) * w + y2, -w),
+ 7 => ((h - 1) * w + (w - 1 - y2), -w),
+ 8 => (w - 1 - y2, w),
+ _ => (y2 * w, 1),
+ }
+}
+
+/// Output columns per block: a block's source pixels (for a 90° turn, `BLOCK`
+/// rows × the band height) stay in cache while it is written.
+const BLOCK: usize = 64;
+/// Output rows per parallel band.
+const BAND: usize = 64;
+
+/// Writes the oriented pixels of one band of output rows, `N` bytes per pixel.
+fn band<const N: usize>(src: &[[u8; N]], dst: &mut [[u8; N]], o: u16, (w, h): (usize, usize), ow: usize, y0: usize) {
+ let (wi, hi) = (w as isize, h as isize);
+ let rows = dst.len() / ow.max(1);
+ for x0 in (0..ow).step_by(BLOCK) {
+ let x1 = (x0 + BLOCK).min(ow);
+ for r in 0..rows {
+ let (base, step) = walk(o, wi, hi, (y0 + r) as isize);
+ let Some(out) = dst.get_mut(r * ow + x0..r * ow + x1) else { return };
+ let mut i = base + x0 as isize * step;
+ for px in out {
+ if let Some(s) = usize::try_from(i).ok().and_then(|i| src.get(i)) {
+ *px = *s;
+ }
+ i += step;
+ }
+ }
+ }
+}
+
+/// Orients `src` (`N` bytes per pixel) into a new buffer, a band of rows per task.
+fn orient_n<const N: usize>(src: &[u8], o: u16, (w, h): (usize, usize), ow: usize) -> Vec<u8> {
+ let mut out = vec![0u8; src.len()];
+ let (s, _) = src.as_chunks::<N>();
+ let (d, _) = out.as_chunks_mut::<N>();
+ let per = (BAND * ow).max(1);
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ use rayon::prelude::*;
+ d.par_chunks_mut(per).enumerate().for_each(|(b, chunk)| band(s, chunk, o, (w, h), ow, b * BAND));
+ }
+ #[cfg(target_arch = "wasm32")]
+ for (b, chunk) in d.chunks_mut(per).enumerate() {
+ band(s, chunk, o, (w, h), ow, b * BAND);
+ }
+ out
+}
+
+/// Pixel-format-agnostic orientation: any byte size per pixel.
+fn orient_bytes(src: &[u8], bpp: usize, o: u16, (w, h): (usize, usize), ow: usize) -> Vec<u8> {
+ match bpp {
+ 1 => orient_n::<1>(src, o, (w, h), ow),
+ 2 => orient_n::<2>(src, o, (w, h), ow),
+ 3 => orient_n::<3>(src, o, (w, h), ow),
+ 4 => orient_n::<4>(src, o, (w, h), ow),
+ 5 => orient_n::<5>(src, o, (w, h), ow),
+ 6 => orient_n::<6>(src, o, (w, h), ow),
+ 8 => orient_n::<8>(src, o, (w, h), ow),
+ 10 => orient_n::<10>(src, o, (w, h), ow),
+ 12 => orient_n::<12>(src, o, (w, h), ow),
+ 16 => orient_n::<16>(src, o, (w, h), ow),
+ _ => orient_n::<20>(src, o, (w, h), ow),
+ }
+}
+
+impl Image {
+ /// The image turned upright for orientation `o` (1–8; anything else is
+ /// treated as 1 and returns the image unchanged). Width and height swap
+ /// for 5–8, as does the DPI, and the EXIF and XMP orientation are
+ /// rewritten to 1 so the result is not rotated again on display or export.
+ pub fn oriented(self, o: u16) -> Result<Image, CodecError> {
+ if !(2..=8).contains(&o) {
+ return Ok(self);
+ }
+ let (w, h) = (self.width() as usize, self.height() as usize);
+ let swap = o >= 5;
+ let (ow, oh) = if swap { (h, w) } else { (w, h) };
+ let (layout, sample) = (self.layout(), self.sample_type());
+ let bpp = layout.channels() * sample.bytes();
+ // Every layout/sample pair is 1–20 bytes per pixel and has a fixed-size path.
+ if !matches!(bpp, 1..=6 | 8 | 10 | 12 | 16 | 20) || w == 0 || h == 0 {
+ return Err(CodecError::InvalidImage(format!("cannot orient {layout:?} {sample:?} {w}x{h}")));
+ }
+ let data = orient_bytes(self.data(), bpp, o, (w, h), ow);
+ let mut meta = self.meta.clone();
+ if let Some(e) = &mut meta.exif
+ && let Cow::Owned(fixed) = upright_exif(e)
+ {
+ *e = fixed;
+ }
+ if let Some(x) = &mut meta.xmp
+ && let Cow::Owned(fixed) = upright_xmp(x)
+ {
+ *x = fixed;
+ }
+ 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))
+ }
+}
diff --git a/crates/codecs/tests/limits.rs b/crates/codecs/tests/limits.rs
index 22a7a82e4..17f9ebcc2 100644
--- a/crates/codecs/tests/limits.rs
+++ b/crates/codecs/tests/limits.rs
@@ -5,7 +5,7 @@ use common::*;
use photocraft_codecs::*;
fn opts(l: Limits) -> DecodeOptions {
- DecodeOptions { limits: l }
+ DecodeOptions { limits: l, ..Default::default() }
}
fn is_limit(r: Result<Image, CodecError>) -> bool {
diff --git a/crates/codecs/tests/malformed.rs b/crates/codecs/tests/malformed.rs
index d92e6fda5..cd0324413 100644
--- a/crates/codecs/tests/malformed.rs
+++ b/crates/codecs/tests/malformed.rs
@@ -6,7 +6,7 @@ use photocraft_codecs::*;
use proptest::prelude::*;
fn tight() -> DecodeOptions {
- DecodeOptions { limits: Limits { max_width: 4096, max_height: 4096, max_pixels: 1 << 22, max_alloc: 64 << 20 } }
+ DecodeOptions { limits: Limits { max_width: 4096, max_height: 4096, max_pixels: 1 << 22, max_alloc: 64 << 20 }, ..Default::default() }
}
fn samples() -> Vec<(Format, Vec<u8>)> {
diff --git a/crates/codecs/tests/orientation.rs b/crates/codecs/tests/orientation.rs
new file mode 100644
index 000000000..7010288fa
--- /dev/null
+++ b/crates/codecs/tests/orientation.rs
@@ -0,0 +1,389 @@
+//! EXIF / TIFF orientation (#285): files are opened upright, and every export
+//! writes Orientation = 1 so the upright pixels are never rotated twice.
+
+mod common;
+use common::*;
+use photocraft_codecs::*;
+use proptest::prelude::{any, prop_assert, prop_assert_eq, proptest};
+
+/// A minimal EXIF (TIFF-structured) block: a filler tag, then Orientation.
+fn exif(o: u32, big: bool, long: bool) -> Vec<u8> {
+ let u16b = |v: u16| if big { v.to_be_bytes() } else { v.to_le_bytes() };
+ let u32b = |v: u32| if big { v.to_be_bytes() } else { v.to_le_bytes() };
+ let mut v = if big { b"MM\0*".to_vec() } else { b"II*\0".to_vec() };
+ v.extend_from_slice(&u32b(8));
+ v.extend_from_slice(&u16b(2));
+ // ImageDescription-ish filler (ASCII, 4 bytes inline).
+ v.extend_from_slice(&u16b(0x010E));
+ v.extend_from_slice(&u16b(2));
+ v.extend_from_slice(&u32b(4));
+ v.extend_from_slice(b"abc\0");
+ v.extend_from_slice(&u16b(0x0112));
+ if long {
+ v.extend_from_slice(&u16b(4));
+ v.extend_from_slice(&u32b(1));
+ v.extend_from_slice(&u32b(o));
+ } else {
+ v.extend_from_slice(&u16b(3));
+ v.extend_from_slice(&u32b(1));
+ v.extend_from_slice(&u16b(o as u16));
+ v.extend_from_slice(&[0, 0]);
+ }
+ v.extend_from_slice(&u32b(0));
+ v
+}
+
+/// The "upright" test picture: `w`×`h` gray values, distinct per pixel.
+fn upright(w: usize, h: usize, value: impl Fn(usize, usize) -> u8) -> Vec<u8> {
+ (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).map(|(x, y)| value(x, y)).collect()
+}
+
+/// What a camera stores for orientation `o` when the scene is `up` (`w`×`h`): the inverse
+/// of the turn a viewer applies. Returns the stored pixels and their size.
+fn stored(up: &[u8], w: usize, h: usize, o: u16) -> (Vec<u8>, usize, usize) {
+ let (sw, sh) = if o >= 5 { (h, w) } else { (w, h) };
+ let mut s = vec![0u8; up.len()];
+ for y in 0..h {
+ for x in 0..w {
+ // Where upright pixel (x, y) sits in the stored image.
+ let (sx, sy) = match o {
+ 1 => (x, y),
+ 2 => (w - 1 - x, y), // mirrored horizontally
+ 3 => (w - 1 - x, h - 1 - y), // rotated 180°
+ 4 => (x, h - 1 - y), // mirrored vertically
+ 5 => (y, x), // transposed
+ 6 => (y, w - 1 - x), // viewer turns it 90° clockwise
+ 7 => (h - 1 - y, w - 1 - x), // transverse
+ 8 => (h - 1 - y, x), // viewer turns it 90° counter-clockwise
+ _ => unreachable!(),
+ };
+ s[sy * sw + sx] = up[y * w + x];
+ }
+ }
+ (s, sw, sh)
+}
+
+/// Inserts a JPEG APP1 EXIF segment right after SOI.
+fn jpeg_with_exif(jpeg: &[u8], exif: &[u8]) -> Vec<u8> {
+ let mut seg = b"Exif\0\0".to_vec();
+ seg.extend_from_slice(exif);
+ let mut out = jpeg[..2].to_vec();
+ out.extend_from_slice(&[0xFF, 0xE1]);
+ out.extend_from_slice(&((seg.len() + 2) as u16).to_be_bytes());
+ out.extend_from_slice(&seg);
+ out.extend_from_slice(&jpeg[2..]);
+ out
+}
+
+/// Inserts a PNG eXIf chunk before the first IDAT.
+fn png_with_exif(png: &[u8], exif: &[u8]) -> Vec<u8> {
+ let at = png.windows(4).position(|w| w == b"IDAT").unwrap() - 4;
+ let mut chunk = (exif.len() as u32).to_be_bytes().to_vec();
+ let mut body = b"eXIf".to_vec();
+ body.extend_from_slice(exif);
+ let mut crc = flate2::Crc::new();
+ crc.update(&body);
+ chunk.extend_from_slice(&body);
+ chunk.extend_from_slice(&crc.sum().to_be_bytes());
+ let mut out = png[..at].to_vec();
+ out.extend_from_slice(&chunk);
+ out.extend_from_slice(&png[at..]);
+ out
+}
+
+fn tiff_with_orientation(data: &[u8], w: u32, h: u32, o: u16) -> Vec<u8> {
+ use tiff::encoder::{TiffEncoder, colortype::Gray8};
+ let mut cursor = std::io::Cursor::new(Vec::new());
+ let mut enc = TiffEncoder::new(&mut cursor).unwrap();
+ let mut im = enc.new_image::<Gray8>(w, h).unwrap();
+ im.encoder().write_tag(tiff::tags::Tag::Orientation, o).unwrap();
+ im.write_data(data).unwrap();
+ cursor.into_inner()
+}
+
+fn gray(w: usize, h: usize, px: Vec<u8>) -> Image {
+ Image::from_u8(w as u32, h as u32, ChannelLayout::Gray, px).unwrap()
+}
+
+/// Exact pixels: distinct values per pixel.
+fn exact_scene(w: usize, h: usize) -> Vec<u8> {
+ upright(w, h, |x, y| (y * w + x) as u8 * 3 + 1)
+}
+
+#[test]
+fn reads_orientation_in_every_encoding() {
+ for o in 1..=8 {
+ for big in [false, true] {
+ for long in [false, true] {
+ let e = exif(o, big, long);
+ assert_eq!(exif_orientation(&e), o as u16, "o={o} big={big} long={long}");
+ let mut prefixed = b"Exif\0\0".to_vec();
+ prefixed.extend_from_slice(&e);
+ assert_eq!(exif_orientation(&prefixed), o as u16);
+ let fixed = upright_exif(&prefixed);
+ assert_eq!(exif_orientation(&fixed), 1);
+ assert_eq!(fixed.len(), prefixed.len(), "rewritten in place");
+ assert_eq!(&fixed[..6], b"Exif\0\0");
+ }
+ }
+ }
+ // Already upright, no tag, or garbage: borrowed unchanged.
+ assert!(matches!(upright_exif(&exif(1, false, false)), std::borrow::Cow::Borrowed(_)));
+ assert!(matches!(upright_exif(&sample_exif()), std::borrow::Cow::Borrowed(_)));
+ assert!(matches!(upright_exif(b"nonsense"), std::borrow::Cow::Borrowed(_)));
+}
+
+#[test]
+fn malformed_or_out_of_range_orientation_reads_as_1() {
+ for bad in [0, 9, 255, 0xFFFF, 0x1_0006] {
+ assert_eq!(exif_orientation(&exif(bad, false, true)), 1, "{bad}");
+ }
+ let good = exif(6, false, false);
+ for n in 0..good.len() {
+ let o = exif_orientation(&good[..n]);
+ assert!(o == 1 || o == 6, "truncated at {n}: {o}");
+ let _ = upright_exif(&good[..n]);
+ }
+ // IFD offset past the end, a huge entry count, a wrong field type.
+ let mut far = good.clone();
+ far[4..8].copy_from_slice(&u32::MAX.to_le_bytes());
+ assert_eq!(exif_orientation(&far), 1);
+ let mut many = good.clone();
+ many[8..10].copy_from_slice(&u16::MAX.to_le_bytes());
+ assert_eq!(exif_orientation(&many), 6, "entries past the end are ignored, the real one still found");
+ let mut typed = good.clone();
+ typed[24..26].copy_from_slice(&2u16.to_le_bytes()); // ASCII
+ assert_eq!(exif_orientation(&typed), 1);
+ assert_eq!(exif_orientation(&[]), 1);
+ assert_eq!(exif_orientation(b"II*\0"), 1);
+}
+
+proptest! {
+ #[test]
+ fn random_exif_never_panics(bytes in proptest::collection::vec(any::<u8>(), 0..256), le in any::<bool>()) {
+ let mut b = if le { b"II*\0\x08\0\0\0".to_vec() } else { b"MM\0*\0\0\0\x08".to_vec() };
+ b.extend_from_slice(&bytes);
+ let o = exif_orientation(&b);
+ prop_assert!((1..=8).contains(&o));
+ prop_assert_eq!(exif_orientation(&upright_exif(&b)), 1);
+ let _ = exif_orientation(&bytes);
+ let _ = upright_exif(&bytes);
+ }
+
+ #[test]
+ fn random_xmp_never_panics(s in ".{0,64}", tail in ".{0,16}") {
+ let x = format!("{s}tiff:Orientation{tail}");
+ let _ = upright_xmp(&x);
+ }
+}
+
+#[test]
+fn xmp_orientation_is_rewritten() {
+ let attr = r#"<rdf:Description tiff:Orientation="6" tiff:Make="X"/>"#;
+ assert_eq!(upright_xmp(attr), r#"<rdf:Description tiff:Orientation="1" tiff:Make="X"/>"#);
+ let elem = "<tiff:Orientation>8</tiff:Orientation><tiff:Orientation>3</tiff:Orientation>";
+ assert_eq!(upright_xmp(elem), "<tiff:Orientation>1</tiff:Orientation><tiff:Orientation>1</tiff:Orientation>");
+ assert_eq!(upright_xmp("tiff:Orientation='12'"), "tiff:Orientation='1'");
+ for same in [r#"tiff:Orientation="1""#, "no orientation", "tiff:Orientation", "tiff:Orientation=\"\"", "tiff:Orientation: 6"] {
+ assert!(matches!(upright_xmp(same), std::borrow::Cow::Borrowed(_)), "{same}");
+ }
+}
+
+#[test]
+fn png_opens_upright_for_every_orientation() {
+ let (w, h) = (5, 3);
+ let up = exact_scene(w, h);
+ for o in 1..=8u16 {
+ let (s, sw, sh) = stored(&up, w, h, o);
+ let png = encode(&gray(sw, sh, s.clone()), Format::Png, &EncodeOptions::default()).unwrap();
+ let file = png_with_exif(&png, &exif(u32::from(o), o % 2 == 0, false));
+ let img = decode(&file).unwrap();
+ assert_eq!(img.dimensions(), (w as u32, h as u32), "o={o}");
+ assert_eq!(img.data(), &up[..], "o={o}");
+ assert_eq!(exif_orientation(img.meta.exif.as_deref().unwrap()), 1, "o={o}: metadata says upright");
+ // Opting out keeps the stored pixels and the tag.
+ let raw = decode_with(&file, &DecodeOptions { keep_orientation: true, ..Default::default() }).unwrap();
+ assert_eq!((raw.dimensions(), raw.data()), ((sw as u32, sh as u32), &s[..]), "o={o}");
+ assert_eq!(exif_orientation(raw.meta.exif.as_deref().unwrap()), o);
+ }
+}
+
+#[test]
+fn tiff_opens_upright_for_every_orientation() {
+ let (w, h) = (4, 7);
+ let up = exact_scene(w, h);
+ for o in 1..=8u16 {
+ let (s, sw, sh) = stored(&up, w, h, o);
+ let img = decode(&tiff_with_orientation(&s, sw as u32, sh as u32, o)).unwrap();
+ assert_eq!(img.dimensions(), (w as u32, h as u32), "o={o}");
+ assert_eq!(img.data(), &up[..], "o={o}");
+ }
+}
+
+#[test]
+fn webp_opens_upright() {
+ let (w, h) = (6, 2);
+ let up = exact_scene(w, h);
+ for o in [3, 6, 8] {
+ let (s, sw, sh) = stored(&up, w, h, o);
+ let mut out = Vec::new();
+ let mut enc = image_webp::WebPEncoder::new(&mut out);
+ enc.set_exif_metadata(exif(u32::from(o), false, false));
+ enc.encode(&s, sw as u32, sh as u32, image_webp::ColorType::L8).unwrap();
+ // WebP has no gray mode: it comes back as RGB.
+ let img = decode(&out).unwrap().convert(ChannelLayout::Gray, SampleType::U8);
+ assert_eq!((img.dimensions(), img.data()), ((w as u32, h as u32), &up[..]), "o={o}");
+ }
+}
+
+/// 8×8-block scene so JPEG keeps each block's value: block (bx, by) is distinct.
+fn block_scene(w: usize, h: usize) -> Vec<u8> {
+ upright(w, h, |x, y| (20 + 25 * (x / 8 + (w / 8) * (y / 8))) as u8)
+}
+
+fn assert_blocks(img: &Image, up: &[u8], w: usize, h: usize, what: &str) {
+ assert_eq!(img.dimensions(), (w as u32, h as u32), "{what}");
+ let d = img.data();
+ for by in 0..h / 8 {
+ for bx in 0..w / 8 {
+ let i = (by * 8 + 4) * w + bx * 8 + 4;
+ assert!((i32::from(d[i]) - i32::from(up[i])).abs() <= 4, "{what}: block ({bx},{by}) is {} not {}", d[i], up[i]);
+ }
+ }
+}
+
+#[test]
+fn jpeg_opens_upright_for_every_orientation() {
+ let (w, h) = (32, 16);
+ let up = block_scene(w, h);
+ for o in 1..=8u16 {
+ let (s, sw, sh) = stored(&up, w, h, o);
+ let jpeg = encode(&gray(sw, sh, s), Format::Jpeg, &EncodeOptions { jpeg_quality: 100, ..Default::default() }).unwrap();
+ let file = jpeg_with_exif(&jpeg, &exif(u32::from(o), o > 4, o == 7));
+ let img = decode(&file).unwrap();
+ assert_blocks(&img, &up, w, h, &format!("o={o}"));
+ assert_eq!(exif_orientation(img.meta.exif.as_deref().unwrap()), 1);
+ }
+}
+
+#[test]
+fn rgb_jpeg_with_dpi_swaps_resolution_on_a_quarter_turn() {
+ let img = Image::from_u8(16, 8, ChannelLayout::Rgb, vec![128; 16 * 8 * 3]).unwrap().with_meta(Metadata { dpi: Some((300.0, 150.0)), ..Default::default() });
+ let jpeg = encode(&img, Format::Jpeg, &EncodeOptions::default()).unwrap();
+ let back = decode(&jpeg_with_exif(&jpeg, &exif(6, false, false))).unwrap();
+ assert_eq!(back.dimensions(), (8, 16));
+ assert_eq!(back.meta.dpi, Some((150.0, 300.0)));
+}
+
+#[test]
+fn export_writes_orientation_1_and_keeps_pixels() {
+ let (w, h) = (32, 16);
+ let up = block_scene(w, h);
+ let (s, sw, sh) = stored(&up, w, h, 6);
+ let jpeg = encode(&gray(sw, sh, s), Format::Jpeg, &EncodeOptions { jpeg_quality: 100, ..Default::default() }).unwrap();
+ let opened = decode(&jpeg_with_exif(&jpeg, &exif(6, false, false))).unwrap();
+ assert_blocks(&opened, &up, w, h, "opened");
+
+ // Even an image whose metadata still claims 6 (e.g. from a PSD) is written as 1.
+ let mut stale = opened.clone();
+ stale.meta.exif = Some(exif(6, true, false));
+ stale.meta.xmp = Some(r#"<x tiff:Orientation="6"/>"#.into());
+ for format in [Format::Png, Format::Jpeg, Format::WebP, Format::Tiff] {
+ let bytes = encode(&stale, format, &EncodeOptions { jpeg_quality: 100, ..Default::default() }).unwrap();
+ let raw = decode_with(&bytes, &DecodeOptions { keep_orientation: true, ..Default::default() }).unwrap();
+ if let Some(e) = &raw.meta.exif {
+ assert_eq!(exif_orientation(e), 1, "{format:?}");
+ }
+ if let Some(x) = &raw.meta.xmp {
+ assert!(x.contains(r#"tiff:Orientation="1""#), "{format:?}: {x}");
+ }
+ assert_eq!(exif_orientation(&bytes), 1, "{format:?} file");
+ // Pixels as shown, both with and without applying orientation on reopen.
+ let back = decode(&bytes).unwrap();
+ assert_eq!(back.dimensions(), raw.dimensions(), "{format:?}");
+ if format == Format::Jpeg {
+ assert_blocks(&back, &up, w, h, "jpeg reopen");
+ } else {
+ assert_eq!(back.convert(ChannelLayout::Gray, SampleType::U8).data(), opened.data(), "{format:?} lossless");
+ }
+ }
+}
+
+#[test]
+fn round_trip_open_save_reopen_is_stable() {
+ let (w, h) = (24, 16);
+ let up = block_scene(w, h);
+ for o in 1..=8u16 {
+ let (s, sw, sh) = stored(&up, w, h, o);
+ let jpeg = encode(&gray(sw, sh, s), Format::Jpeg, &EncodeOptions { jpeg_quality: 100, ..Default::default() }).unwrap();
+ let first = decode(&jpeg_with_exif(&jpeg, &exif(u32::from(o), false, false))).unwrap();
+ let saved = encode(&first, Format::Jpeg, &EncodeOptions { jpeg_quality: 100, ..Default::default() }).unwrap();
+ let second = decode(&saved).unwrap();
+ assert_blocks(&second, &up, w, h, &format!("reopened o={o}"));
+ assert_eq!(exif_orientation(second.meta.exif.as_deref().unwrap()), 1);
+ }
+}
+
+#[test]
+fn malformed_exif_in_a_jpeg_opens_as_stored() {
+ let img = gray(16, 8, vec![90; 128]);
+ let jpeg = encode(&img, Format::Jpeg, &EncodeOptions::default()).unwrap();
+ let mut rng = Rng::new(285);
+ let mut cases = vec![Vec::new(), b"II*\0".to_vec(), b"MM\0*\xff\xff\xff\xff".to_vec(), exif(6, false, false)[..20].to_vec()];
+ cases.extend((0..64).map(|i| {
+ let mut b = if i % 2 == 0 { b"II*\0\x08\0\0\0".to_vec() } else { b"MM\0*\0\0\0\x08".to_vec() };
+ b.extend(rng.bytes(i * 7));
+ b
+ }));
+ for e in cases {
+ let back = decode(&jpeg_with_exif(&jpeg, &e)).unwrap();
+ let o = exif_orientation(&e);
+ let want = if o >= 5 { (8, 16) } else { (16, 8) };
+ assert_eq!(back.dimensions(), want, "{e:?}");
+ }
+}
+
+#[test]
+fn every_layout_and_depth_orients_and_inverts() {
+ let inverse = |o: u16| match o {
+ 6 => 8,
+ 8 => 6,
+ o => o,
+ };
+ for layout in ChannelLayout::ALL {
+ for sample in SampleType::ALL {
+ let img = test_image(layout, sample);
+ for o in 0..=9u16 {
+ let turned = img.clone().oriented(o).unwrap();
+ if (2..=8).contains(&o) && o >= 5 {
+ assert_eq!(turned.dimensions(), (img.height(), img.width()));
+ } else {
+ assert_eq!(turned.dimensions(), img.dimensions());
+ }
+ let back = turned.oriented(inverse(o)).unwrap();
+ assert_eq!(back.data(), img.data(), "{layout:?} {sample:?} o={o}");
+ }
+ }
+ }
+}
+
+/// #285 performance budget: turning a 24 MP photo upright on open adds ≤ 50 ms
+/// (release build: `cargo test --release -p photocraft-codecs --test orientation -- --ignored`).
+#[test]
+#[ignore = "timing; run in release"]
+fn rotating_24_mp_is_fast() {
+ let (w, h) = (6000u32, 4000u32);
+ let img = Image::from_u8(w, h, ChannelLayout::Rgb, (0..w as usize * h as usize * 3).map(|i| i as u8).collect()).unwrap();
+ for o in [6u16, 3, 8] {
+ let mut best = f64::MAX;
+ for _ in 0..5 {
+ let c = img.clone();
+ let t = std::time::Instant::now();
+ let r = c.oriented(o).unwrap();
+ best = best.min(t.elapsed().as_secs_f64() * 1000.0);
+ std::hint::black_box(r);
+ }
+ eprintln!("orientation {o}: 24 MP RGB8 in {best:.1} ms");
+ assert!(best <= 50.0, "orientation {o} took {best:.1} ms");
+ }
+}
diff --git a/crates/engine/src/file_cmds/tests.rs b/crates/engine/src/file_cmds/tests.rs
index 1fa71ef67..762cd018f 100644
--- a/crates/engine/src/file_cmds/tests.rs
+++ b/crates/engine/src/file_cmds/tests.rs
@@ -158,6 +158,37 @@ fn place_embedded_centres_fits_and_embeds() {
}
}
+/// A 40×20 JPEG (left half red, right half blue) tagged EXIF Orientation = 6: shown upright it
+/// is 20×40, red on top.
+fn rotated_jpeg(dir: &str) -> String {
+ let px: Vec<u8> = (0..20).flat_map(|_| (0..40).flat_map(|x| if x < 20 { [230, 20, 20] } else { [20, 20, 230] })).collect();
+ let img = photocraft_codecs::Image::from_u8(40, 20, photocraft_codecs::ChannelLayout::Rgb, px).unwrap();
+ let jpeg = photocraft_codecs::encode(&img, photocraft_codecs::Format::Jpeg, &Default::default()).unwrap();
+ let mut seg = b"Exif\0\0II*\0\x08\0\0\0\x01\0\x12\x01\x03\0\x01\0\0\0\x06\0\0\0\0\0\0\0".to_vec();
+ let mut file = vec![0xFF, 0xD8, 0xFF, 0xE1];
+ file.extend_from_slice(&((seg.len() + 2) as u16).to_be_bytes());
+ file.append(&mut seg);
+ file.extend_from_slice(&jpeg[2..]);
+ let path = join(dir, "IMG_0001.jpg");
+ std::fs::write(&path, file).unwrap();
+ path
+}
+
+#[test]
+fn rotated_jpegs_open_and_place_upright() {
+ let dir = tmp("orientation");
+ let path = rotated_jpeg(&dir);
+ let mut s = Session::new();
+ s.execute("file.openAs", json!({"path": path, "as": "jpg"})).unwrap();
+ assert_eq!((doc(&s).size.width, doc(&s).size.height), (20, 40));
+ assert!(composite(&s, 10, 5)[0] > 0.8 && composite(&s, 10, 35)[2] > 0.8, "red on top, blue below");
+ // Placed as a smart object: upright too, and it renders upright from its embedded bytes.
+ let mut s = session(100, 100, 8);
+ let r = s.execute("file.placeEmbedded", json!({"path": path})).unwrap();
+ assert_eq!(r["bounds"], json!([40.0, 30.0, 60.0, 70.0]));
+ assert!(composite(&s, 50, 35)[0] > 0.8 && composite(&s, 50, 65)[2] > 0.8);
+}
+
#[test]
fn file_info_round_trips_through_xmp_and_psd() {
let mut s = session(8, 8, 8);
diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs
index fcf947ec0..6a927ce73 100644
--- a/crates/io/src/psd_export.rs
+++ b/crates/io/src/psd_export.rs
@@ -1107,10 +1107,11 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32) -
resources.push(ImageResource::new(ids::LAYER_GROUP_INFO, groups));
}
if let Some(x) = &doc.metadata.xmp {
- resources.push(ImageResource::new(ids::XMP, x.as_bytes().to_vec()));
+ // 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()));
}
if let Some(e) = &doc.metadata.exif {
- resources.push(ImageResource::new(ids::EXIF, e.to_vec()));
+ resources.push(ImageResource::new(ids::EXIF, photocraft_codecs::upright_exif(e).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/src/raw.rs b/crates/io/src/raw.rs
index 2220db771..7d046d4fd 100644
--- a/crates/io/src/raw.rs
+++ b/crates/io/src/raw.rs
@@ -22,6 +22,17 @@ fn limits() -> Limits {
Limits { max_width: l.max_width, max_height: l.max_height, max_pixels: l.max_pixels, max_alloc: l.max_alloc }
}
+/// A raw file's embedded JPEG preview, turned upright. Its own EXIF orientation wins when it
+/// has one; otherwise the raw's IFD0 orientation applies (TIFF-based raws record it there, and
+/// their previews are usually stored as the sensor reads out). Developed raws are oriented by
+/// `photocraft-raw` and carry no EXIF, so nothing is turned twice.
+fn upright_preview(raw: &[u8], jpeg: &[u8]) -> Result<Image, IoError> {
+ let img = codecs::decode_as_with(Format::Jpeg, jpeg, &codecs::DecodeOptions { keep_orientation: true, ..Default::default() })?;
+ let own = img.meta.exif.as_deref().map_or(1, codecs::exif_orientation);
+ let o = if own != 1 { own } else { codecs::exif_orientation(raw) };
+ Ok(img.oriented(o)?)
+}
+
/// Develops a raw file with the default settings.
pub fn import_raw(name: &str, bytes: &[u8]) -> Result<ImportResult, IoError> {
import_raw_with(name, bytes, &DevelopOptions { limits: limits(), ..Default::default() })
@@ -51,7 +62,7 @@ pub fn import_raw_with(name: &str, bytes: &[u8], opts: &DevelopOptions) -> Resul
}
Err(RawError::Unsupported(reason)) => match photocraft_raw::embedded_preview(bytes) {
Some(p) => {
- let img = codecs::decode_as(Format::Jpeg, p.jpeg)?;
+ let img = upright_preview(bytes, p.jpeg)?;
let mut r = image_to_document(name, &img)?;
r.warnings.insert(
0,
diff --git a/crates/io/tests/orientation.rs b/crates/io/tests/orientation.rs
new file mode 100644
index 000000000..0832df237
--- /dev/null
+++ b/crates/io/tests/orientation.rs
@@ -0,0 +1,173 @@
+//! EXIF orientation through the document layer (#285): an iPhone-style JPEG
+//! (stored landscape, Orientation = 6) opens as an upright portrait document,
+//! and every export writes Orientation = 1 so it is never rotated twice.
+
+use photocraft_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType, decode, exif_orientation};
+use photocraft_io::{ExportOptions, export, import};
+use photocraft_raw::testgen::{TiffBuilder, Val};
+
+/// EXIF block with only an Orientation tag.
+fn exif(o: u16) -> Vec<u8> {
+ let mut v = b"II*\0\x08\0\0\0\x01\0\x12\x01\x03\0\x01\0\0\0".to_vec();
+ v.extend_from_slice(&o.to_le_bytes());
+ v.extend_from_slice(&[0, 0, 0, 0, 0, 0]);
+ v
+}
+
+fn jpeg_with_exif(jpeg: &[u8], exif: &[u8]) -> Vec<u8> {
+ let mut seg = b"Exif\0\0".to_vec();
+ seg.extend_from_slice(exif);
+ let mut out = jpeg[..2].to_vec();
+ out.extend_from_slice(&[0xFF, 0xE1]);
+ out.extend_from_slice(&((seg.len() + 2) as u16).to_be_bytes());
+ out.extend_from_slice(&seg);
+ out.extend_from_slice(&jpeg[2..]);
+ out
+}
+
+/// Upright 16×32 portrait: red top-left quarter, green top-right, blue bottom half.
+fn upright_color(x: usize, y: usize) -> [u8; 3] {
+ match (x < 8, y < 16) {
+ (true, true) => [230, 20, 20],
+ (false, true) => [20, 230, 20],
+ _ => [20, 20, 230],
+ }
+}
+
+/// The same scene as a camera stores it for Orientation = 6 (32×16 landscape).
+fn stored_orientation_6() -> Image {
+ let (w, h) = (16, 32);
+ let mut px = vec![0u8; w * h * 3];
+ for y in 0..h {
+ for x in 0..w {
+ // Upright (x, y) sits at stored (y, w - 1 - x) in a 32-wide image.
+ let (sx, sy) = (y, w - 1 - x);
+ px[(sy * h + sx) * 3..][..3].copy_from_slice(&upright_color(x, y));
+ }
+ }
+ Image::from_u8(h as u32, w as u32, ChannelLayout::Rgb, px).unwrap()
+}
+
+fn iphone_jpeg() -> Vec<u8> {
+ let jpeg = photocraft_codecs::encode(
+ &stored_orientation_6(),
+ Format::Jpeg,
+ &EncodeOptions { jpeg_quality: 100, jpeg_chroma_subsampling: false, ..Default::default() },
+ )
+ .unwrap();
+ jpeg_with_exif(&jpeg, &exif(6))
+}
+
+fn assert_upright(img: &Image, what: &str) {
+ assert_eq!(img.dimensions(), (16, 32), "{what}");
+ let img = img.convert(ChannelLayout::Rgb, SampleType::U8);
+ for (x, y) in [(3, 4), (12, 4), (3, 28), (12, 28)] {
+ let i = (y * 16 + x) * 3;
+ let got = &img.data()[i..i + 3];
+ let want = upright_color(x, y);
+ assert!(got.iter().zip(want).all(|(a, b)| (i32::from(*a) - i32::from(b)).abs() <= 12), "{what} ({x},{y}): {got:?} vs {want:?}");
+ }
+}
+
+#[test]
+fn rotated_jpeg_opens_upright_and_exports_with_orientation_1() {
+ let r = import("IMG_0001.JPG", &iphone_jpeg()).unwrap();
+ let d = &r.document;
+ assert_eq!((d.size.width, d.size.height), (16, 32), "portrait, like Photoshop");
+ assert_eq!(exif_orientation(d.metadata.exif.as_deref().unwrap()), 1, "the document's EXIF says upright");
+
+ for ext in ["jpg", "png", "tif", "webp"] {
+ let out = export(d, ext, &ExportOptions::default()).unwrap().bytes;
+ assert_eq!(exif_orientation(&out), 1, "{ext}: a TIFF file's own tag");
+ let back = decode(&out).unwrap();
+ if let Some(e) = &back.meta.exif {
+ assert_eq!(exif_orientation(e), 1, "{ext}");
+ }
+ assert_upright(&back, ext);
+ // Open → save → reopen: the same upright document.
+ let again = import(&format!("again.{ext}"), &out).unwrap().document;
+ assert_eq!((again.size.width, again.size.height), (16, 32), "{ext}");
+ }
+}
+
+#[test]
+fn stale_orientation_in_document_metadata_is_never_exported() {
+ // A document whose EXIF still says 6 (a PSD from elsewhere, or rotated by hand as in #285).
+ let mut d = import("IMG_0001.JPG", &iphone_jpeg()).unwrap().document;
+ d.metadata.exif = Some(std::sync::Arc::new(exif(6)));
+ d.metadata.xmp = Some(r#"<rdf:Description tiff:Orientation="6"/>"#.into());
+ let jpg = export(&d, "jpg", &ExportOptions::default()).unwrap().bytes;
+ let back = decode(&jpg).unwrap();
+ assert_eq!(exif_orientation(back.meta.exif.as_deref().unwrap()), 1);
+ assert!(back.meta.xmp.as_deref().unwrap().contains(r#"tiff:Orientation="1""#));
+ assert_upright(&back, "jpg");
+
+ let psd = export(&d, "psd", &ExportOptions::default()).unwrap().bytes;
+ let file = photocraft_psd::PsdFile::from_bytes(&psd).unwrap();
+ let e = file.resources.iter().find(|r| r.id == 1058).expect("EXIF resource");
+ assert_eq!(exif_orientation(&e.data), 1);
+ let x = file.resources.iter().find(|r| r.id == 1060).expect("XMP resource");
+ assert!(String::from_utf8_lossy(&x.data).contains(r#"tiff:Orientation="1""#));
+}
+
+/// A NEF-like raw that `photocraft-raw` can't develop yet, with IFD0 Orientation and a
+/// baseline JPEG preview stored as the sensor reads out.
+fn nef(ifd0_orientation: u16, preview: Vec<u8>) -> Vec<u8> {
+ let mut t = TiffBuilder::default();
+ let strip = t.blob(vec![0; 64]);
+ let len = preview.len() as u32;
+ let preview = t.blob(preview);
+ let raw = t.ifd(vec![
+ (256, Val::Long(vec![8])),
+ (257, Val::Long(vec![8])),
+ (258, Val::Short(vec![12])),
+ (259, Val::Short(vec![34713])),
+ (262, Val::Short(vec![32803])),
+ (273, Val::Blobs(vec![strip])),
+ (279, Val::Long(vec![64])),
+ (33421, Val::Short(vec![2, 2])),
+ (33422, Val::Byte(vec![0, 1, 1, 2])),
+ ]);
+ let ifd0 = t.ifd(vec![
+ (271, Val::Ascii("NIKON CORPORATION".into())),
+ (274, Val::Short(vec![ifd0_orientation])),
+ (330, Val::Ifds(vec![raw])),
+ (513, Val::Blobs(vec![preview])),
+ (514, Val::Long(vec![len])),
+ ]);
+ t.chain = vec![ifd0];
+ t.build()
+}
+
+#[test]
+fn raw_preview_is_turned_upright_exactly_once() {
+ let plain = photocraft_codecs::encode(
+ &stored_orientation_6(),
+ Format::Jpeg,
+ &EncodeOptions { jpeg_quality: 100, jpeg_chroma_subsampling: false, ..Default::default() },
+ )
+ .unwrap();
+ // The raw's IFD0 orientation applies to a preview without its own.
+ let r = import("DSC_0001.NEF", &nef(6, plain.clone())).unwrap();
+ let png = export(&r.document, "png", &ExportOptions::default()).unwrap().bytes;
+ assert_upright(&decode(&png).unwrap(), "IFD0 orientation");
+ // A preview with its own EXIF orientation is not turned a second time by IFD0's.
+ let r = import("DSC_0002.NEF", &nef(6, jpeg_with_exif(&plain, &exif(6)))).unwrap();
+ let png = export(&r.document, "png", &ExportOptions::default()).unwrap().bytes;
+ assert_upright(&decode(&png).unwrap(), "preview orientation");
+ // Upright raws stay as they are.
+ let r = import("DSC_0003.NEF", &nef(1, plain)).unwrap();
+ assert_eq!((r.document.size.width, r.document.size.height), (32, 16));
+}
+
+#[test]
+fn malformed_exif_opens_without_panicking() {
+ let jpeg = photocraft_codecs::encode(&stored_orientation_6(), Format::Jpeg, &EncodeOptions::default()).unwrap();
+ let mut huge = exif(6);
+ huge[8..10].copy_from_slice(&u16::MAX.to_le_bytes());
+ huge.truncate(14);
+ for e in [Vec::new(), b"MM\0*".to_vec(), exif(0), exif(9), exif(u16::MAX), huge] {
+ let r = import("x.jpg", &jpeg_with_exif(&jpeg, &e)).unwrap();
+ assert_eq!((r.document.size.width, r.document.size.height), (32, 16), "{e:?} reads as Orientation 1");
+ }
+}