mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
TIFF: open images over 2^30 px, decoded a group of rows at a time into the layer (#8169)
The 117,504 x 22,464 px banner from #8456 failed with "2639609856 pixels exceed max 1073741824": the decoder built the whole image in one buffer and the importer copied it into tiles, so the decode was capped at 2^30 px. - codecs: decode_ifd split into prepare + decode; new TiffBands decodes ~64 MiB groups of bands in parallel and hands each group, upright, to the caller. Limits::banded(): 300,000 px a side on 64-bit, max_alloc per group; 32-bit targets keep the whole-image check. - raster: Surface::try_write_interleaved (fallible, tiles on all cores). - io: import_tiff_page decodes flat pages through TiffBands straight into the layer, converting pieces of rows on all cores; layered TIFFs keep the whole-image path. Release, 20 threads: 36 MP 220 -> 52 ms; 30,000^2 6.8 s / 6.43 GB peak -> 1.1 s / 3.86 GB; 35,000^2 and the 2.64 GP banner now open (1.5 s, 3.3 s). Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01XNm5ZNBFtLZ2cZNaPnYsXV
This commit is contained in:
1 parent
78b46b1a99
commit
4001a3092a
11 files changed
+867
-93
No files matched your search
@@ -18,6 +18,8 @@
|
||||
//! output's layout is decoded in place; anything else goes through one strip- or tile-sized
|
||||
//! scratch buffer per worker, so no second full-size buffer exists. Image data cut off by the
|
||||
//! end of the file leaves the missing chunks empty and adds a [`DecodeWarning::Truncated`].
|
||||
//! [`TiffBands`] runs the same decode a group of bands at a time and hands each group to its
|
||||
//! caller, so a document can be filled without the image ever existing whole (#8169).
|
||||
//!
|
||||
//! Photoshop's private tags are carried as opaque bytes in [`Metadata`]: 34377 (image
|
||||
//! resources) and 37724 (`ImageSourceData`, the layers of a layered TIFF). They are read with
|
||||
@@ -234,6 +236,16 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError>
|
||||
/// carries the page's metadata, a [`DecodeWarning::MorePages`] when the file holds more
|
||||
/// full-resolution pages, and a [`DecodeWarning::Truncated`] when image data is cut off.
|
||||
pub(crate) fn decode_page(bytes: &[u8], page: Option<usize>, limits: &Limits) -> Result<Image, CodecError> {
|
||||
let (file, dir, more) = open_page(bytes, page)?;
|
||||
let mut img = decode_ifd(&file, &dir, limits)?;
|
||||
img.meta = metadata(&file, &dir, &mut img.icc);
|
||||
img.warnings.extend(more);
|
||||
Ok(img)
|
||||
}
|
||||
|
||||
/// The file, page `page`'s directory (`None`: the default page) and the
|
||||
/// [`DecodeWarning::MorePages`] the page opens with when the file holds more.
|
||||
fn open_page(bytes: &[u8], page: Option<usize>) -> Result<(File<'_>, Ifd, Option<DecodeWarning>), CodecError> {
|
||||
if camera_raw(bytes) {
|
||||
return Err(CodecError::unsupported(F, "camera raw files (such as CR2, NEF, ARW or DNG) are not flat images; decode them with photocraft-raw"));
|
||||
}
|
||||
@@ -248,13 +260,150 @@ pub(crate) fn decode_page(bytes: &[u8], page: Option<usize>, limits: &Limits) ->
|
||||
.get(index)
|
||||
.ok_or_else(|| CodecError::InvalidImage(format!("TIFF page {index} does not exist (the file has {} directories)", info.pages.len())))?;
|
||||
let dir = file.ifd(p.ifd_offset).ok_or_else(|| err("image directory cut off"))?;
|
||||
let mut img = decode_ifd(&file, &dir, limits)?;
|
||||
img.meta = metadata(&file, &dir, &mut img.icc);
|
||||
let pages = info.page_count();
|
||||
if pages > 1 {
|
||||
img.warnings.push(DecodeWarning::MorePages { total: info.complete.then_some(u32::try_from(pages).unwrap_or(u32::MAX)) });
|
||||
let more = (pages > 1).then(|| DecodeWarning::MorePages { total: info.complete.then_some(u32::try_from(pages).unwrap_or(u32::MAX)) });
|
||||
Ok((file, dir, more))
|
||||
}
|
||||
|
||||
/// Output bytes [`TiffBands::decode`] aims to decode at once (at least one band per worker): small
|
||||
/// next to the document the rows are written into, and to the copy a caller may convert them to.
|
||||
const GROUP_BYTES: usize = 64 << 20;
|
||||
|
||||
/// A TIFF page opened for decoding a group of bands at a time, for images too large to hold
|
||||
/// twice (#8169): [`TiffBands::decode`] hands each group to its caller, who writes it into the
|
||||
/// document, so only one group exists beside the document. The pixels, layout and metadata are
|
||||
/// those [`decode_page`] returns; [`TiffBands::upright`] applies the orientation as
|
||||
/// [`Image::oriented`] does.
|
||||
pub struct TiffBands<'a> {
|
||||
b: &'a [u8],
|
||||
p: Prepared,
|
||||
/// The page's Orientation tag (1–8).
|
||||
stored: u16,
|
||||
/// The orientation the bands are turned by (1: as stored).
|
||||
turn: u16,
|
||||
/// `Limits::max_alloc`: the most one group of bands may take.
|
||||
cap: u64,
|
||||
pub icc: Option<Vec<u8>>,
|
||||
pub meta: Metadata,
|
||||
/// What the decoder noticed: more pages, and after [`TiffBands::decode`] data cut off.
|
||||
pub warnings: Vec<DecodeWarning>,
|
||||
}
|
||||
|
||||
impl<'a> TiffBands<'a> {
|
||||
/// Opens page `page` (`None`: the page [`decode_page`] opens by default) and checks it
|
||||
/// against `limits`; on 64-bit targets its `max_alloc` bounds each group of bands, not the
|
||||
/// whole image.
|
||||
pub fn open(bytes: &'a [u8], page: Option<usize>, limits: &Limits) -> Result<Self, CodecError> {
|
||||
let (file, dir, more) = open_page(bytes, page)?;
|
||||
// On 32-bit targets the whole image must still fit `max_alloc`, as it did before: the
|
||||
// document holding it shares the same small address space (wasm32: 4 GiB).
|
||||
let p = prepare(&file, &dir, limits, cfg!(target_pointer_width = "32"))?;
|
||||
let band = p.band_bytes()?;
|
||||
if band as u64 > limits.max_alloc {
|
||||
return Err(CodecError::LimitExceeded(format!(
|
||||
"one strip or row of tiles of this {}x{} image decodes to {band} bytes, over the {} byte limit",
|
||||
p.w, p.h, limits.max_alloc
|
||||
)));
|
||||
}
|
||||
let mut icc = None;
|
||||
let meta = metadata(&file, &dir, &mut icc);
|
||||
let stored = ifd::orientation_of(&file, &dir);
|
||||
Ok(TiffBands { b: bytes, p, stored, turn: 1, cap: limits.max_alloc, icc, meta, warnings: more.into_iter().collect() })
|
||||
}
|
||||
|
||||
/// The bands turned upright for the page's Orientation tag, as [`Image::oriented`] turns a
|
||||
/// whole image: the size and resolution swap for 5–8, and the EXIF and XMP orientation are
|
||||
/// rewritten to 1.
|
||||
pub fn upright(mut self) -> Self {
|
||||
let o = self.stored;
|
||||
if !(2..=8).contains(&o) || self.turn == o {
|
||||
return self;
|
||||
}
|
||||
self.turn = o;
|
||||
if let Some(e) = &mut self.meta.exif
|
||||
&& let Cow::Owned(fixed) = crate::orientation::upright_exif(e)
|
||||
{
|
||||
*e = fixed;
|
||||
}
|
||||
if let Some(x) = &mut self.meta.xmp
|
||||
&& let Cow::Owned(fixed) = crate::orientation::upright_xmp(x)
|
||||
{
|
||||
*x = fixed;
|
||||
}
|
||||
if o >= 5 {
|
||||
self.meta.dpi = self.meta.dpi.map(|(x, y)| (y, x));
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// The page's Orientation tag (1–8; 1 when absent or invalid).
|
||||
pub fn orientation(&self) -> u16 {
|
||||
self.stored
|
||||
}
|
||||
|
||||
/// The size of the image the bands make up (upright when [`TiffBands::upright`] was applied).
|
||||
pub fn dimensions(&self) -> (u32, u32) {
|
||||
if self.turn >= 5 { (self.p.h, self.p.w) } else { (self.p.w, self.p.h) }
|
||||
}
|
||||
|
||||
pub fn layout(&self) -> ChannelLayout {
|
||||
self.p.lay.out_layout
|
||||
}
|
||||
|
||||
pub fn sample_type(&self) -> SampleType {
|
||||
self.p.lay.out
|
||||
}
|
||||
|
||||
/// Decodes the image a group of bands at a time, in order, handing each group to `sink`
|
||||
/// with the position of its top-left pixel in the image [`TiffBands::dimensions`] gives. A
|
||||
/// group is about 64 MiB (at least one strip or row of tiles per worker, at most `max_alloc`). Data
|
||||
/// cut off by the end of the file adds a [`DecodeWarning::Truncated`] to `warnings`.
|
||||
pub fn decode<E: From<CodecError>>(&mut self, mut sink: impl FnMut(u32, u32, &Image) -> Result<(), E>) -> Result<(), E> {
|
||||
let p = &self.p;
|
||||
let band = p.band_bytes()?.max(1);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let workers = rayon::current_num_threads();
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let workers = 1;
|
||||
let cap = usize::try_from(self.cap).unwrap_or(usize::MAX);
|
||||
let per_group = (GROUP_BYTES / band).max(workers).min(cap / band).max(1);
|
||||
let bands = (p.h as usize).div_ceil(p.band_rows.max(1));
|
||||
let mut buf: Vec<u8> = Vec::new();
|
||||
let mut tally = Tally::default();
|
||||
let mut first = 0;
|
||||
while first < bands {
|
||||
let n = per_group.min(bands - first);
|
||||
let y0 = first * p.band_rows;
|
||||
let rows = (n * p.band_rows).min(p.h as usize - y0);
|
||||
let len = p.lay.out_row().checked_mul(rows).ok_or_else(|| CodecError::LimitExceeded("band size".into()))?;
|
||||
// Missing chunks leave their rows as they are: they must start empty in every group.
|
||||
buf = refill_zeroed(buf, len)?;
|
||||
tally = tally + decode_bands(p, self.b, &mut buf, band, first)?;
|
||||
if let Some(signed) = p.lab {
|
||||
convert_ab(&mut buf, p.lay.out_channels(), p.lay.out, signed, false);
|
||||
}
|
||||
let rows = u32::try_from(rows).map_err(|_| err("band too tall"))?;
|
||||
let y0 = u32::try_from(y0).map_err(|_| err("band out of range"))?;
|
||||
let group = Image::from_raw(p.w, rows, p.lay.out_layout, p.lay.out, std::mem::take(&mut buf))?;
|
||||
let (x, y) = match self.turn {
|
||||
3 | 4 => (0, p.h.saturating_sub(y0 + rows)),
|
||||
5 | 8 => (y0, 0),
|
||||
6 | 7 => (p.h.saturating_sub(y0 + rows), 0),
|
||||
_ => (0, y0),
|
||||
};
|
||||
let group = group.oriented(self.turn)?;
|
||||
sink(x, y, &group)?;
|
||||
buf = group.into_data();
|
||||
first += n;
|
||||
}
|
||||
if tally.decoded == 0 && tally.missing > 0 {
|
||||
return Err(err("the image data is missing (cut off or past the end of the file)").into());
|
||||
}
|
||||
if tally.missing > 0 {
|
||||
self.warnings.push(DecodeWarning::Truncated { format: F });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Ok(img)
|
||||
}
|
||||
|
||||
/// The Orientation (1–8) of page `page` (`None`: the default page); 1 when absent, malformed
|
||||
@@ -451,8 +600,54 @@ fn is_eof(e: &tiff::TiffError) -> bool {
|
||||
matches!(e, tiff::TiffError::IoError(io) if io.kind() == io::ErrorKind::UnexpectedEof)
|
||||
}
|
||||
|
||||
/// A directory checked and laid out for decoding, before any pixel is read.
|
||||
struct Prepared {
|
||||
w: u32,
|
||||
h: u32,
|
||||
lay: Layout,
|
||||
/// Rows per band: one strip, or one row of tiles.
|
||||
band_rows: usize,
|
||||
patches: Vec<(u64, Vec<u8>)>,
|
||||
tl: tiff::decoder::Limits,
|
||||
/// Lab samples: `Some(true)` for CIELab (a* and b* stored signed), `Some(false)` for ICCLab.
|
||||
lab: Option<bool>,
|
||||
}
|
||||
|
||||
impl Prepared {
|
||||
/// A decoder over `b` (the file the directory was read from) that opens the directory.
|
||||
fn open<'a>(&'a self, b: &'a [u8]) -> Result<Decoder<Patched<'a>>, CodecError> {
|
||||
Decoder::new(Patched { b, patches: &self.patches, pos: 0 }).map(|d| d.with_limits(self.tl.clone())).map_err(map_err)
|
||||
}
|
||||
|
||||
/// Output bytes of one full band.
|
||||
fn band_bytes(&self) -> Result<usize, CodecError> {
|
||||
self.lay.out_row().checked_mul(self.band_rows).ok_or_else(|| CodecError::LimitExceeded("band size".into()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes the pixels of one directory.
|
||||
fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result<Image, CodecError> {
|
||||
let p = prepare(f, dir, limits, true)?;
|
||||
// The output, allocated once and fallibly.
|
||||
let len = p.lay.out_row().checked_mul(p.h as usize).ok_or_else(|| CodecError::LimitExceeded("image size".into()))?;
|
||||
let mut data = zeroed(len)?;
|
||||
let tally = decode_bands(&p, f.b, &mut data, p.band_bytes()?, 0)?;
|
||||
if tally.decoded == 0 && tally.missing > 0 {
|
||||
return Err(err("the image data is missing (cut off or past the end of the file)"));
|
||||
}
|
||||
if let Some(signed) = p.lab {
|
||||
convert_ab(&mut data, p.lay.out_channels(), p.lay.out, signed, false);
|
||||
}
|
||||
let mut img = Image::from_raw(p.w, p.h, p.lay.out_layout, p.lay.out, data)?;
|
||||
if tally.missing > 0 {
|
||||
img.warnings.push(DecodeWarning::Truncated { format: F });
|
||||
}
|
||||
Ok(img)
|
||||
}
|
||||
|
||||
/// Checks one directory and lays it out for decoding. `whole`: the image is decoded into one
|
||||
/// buffer, which `limits.max_alloc` bounds; otherwise only its size is checked here.
|
||||
fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result<Prepared, CodecError> {
|
||||
// The values the `tiff` crate reads must exist: a count past the end of the file is
|
||||
// neither allocated nor read.
|
||||
if let Some(e) = dir.entries.iter().find(|e| ifd::STRUCTURAL_TAGS.contains(&e.tag) && f.data(e).is_none()) {
|
||||
@@ -581,8 +776,7 @@ fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result<Image, CodecEr
|
||||
l.intermediate_buffer_size = f.b.len().max(1);
|
||||
l
|
||||
};
|
||||
let open = || Decoder::new(Patched { b: f.b, patches: &patches, pos: 0 }).map(|d| d.with_limits(tl.clone())).map_err(map_err);
|
||||
let mut dec = open()?;
|
||||
let mut dec = Decoder::new(Patched { b: f.b, patches: &patches, pos: 0 }).map(|d| d.with_limits(tl.clone())).map_err(map_err)?;
|
||||
if dec.dimensions().map_err(map_err)? != (w, h) || (dec.get_chunk_type() == ChunkType::Tile) != tiled {
|
||||
return Err(err("inconsistent image directory"));
|
||||
}
|
||||
@@ -626,7 +820,11 @@ fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result<Image, CodecEr
|
||||
(Some(_), _) => SampleType::U8,
|
||||
_ => src.out(),
|
||||
};
|
||||
limits.check(w, h, out_layout, out)?;
|
||||
if whole {
|
||||
limits.check(w, h, out_layout, out)?;
|
||||
} else {
|
||||
limits.check_size(w, h)?;
|
||||
}
|
||||
// Decompression-bomb guard: no compression method expands data by more than a few thousand
|
||||
// times (Deflate at most ~1032:1, LZW ~2730:1, PackBits 128:1), so a file far too small for
|
||||
// its declared size is refused before the image is allocated. Uncompressed data may be up
|
||||
@@ -648,6 +846,7 @@ fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result<Image, CodecEr
|
||||
let chunks_per_plane = across.checked_mul(down).ok_or_else(|| err("too many tiles"))?;
|
||||
let planes_in_file = if planar { spp as usize } else { 1 };
|
||||
let total = if tiled { dec.tile_count() } else { dec.strip_count() }.map_err(map_err)?;
|
||||
drop(dec);
|
||||
if Some(total as usize) != chunks_per_plane.checked_mul(planes_in_file) {
|
||||
return Err(err("strip or tile count does not match the image size"));
|
||||
}
|
||||
@@ -678,25 +877,7 @@ fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result<Image, CodecEr
|
||||
palette,
|
||||
scratch_cap,
|
||||
};
|
||||
|
||||
// The output, allocated once and fallibly.
|
||||
let out_row = lay.out_row();
|
||||
let len = out_row.checked_mul(hu).ok_or_else(|| CodecError::LimitExceeded("image size".into()))?;
|
||||
let mut data = zeroed(len)?;
|
||||
let band_bytes = out_row.checked_mul(ch.min(hu)).ok_or_else(|| CodecError::LimitExceeded("band size".into()))?;
|
||||
|
||||
let tally = decode_bands(&lay, &mut data, band_bytes, &mut dec, &open)?;
|
||||
if tally.decoded == 0 && tally.missing > 0 {
|
||||
return Err(err("the image data is missing (cut off or past the end of the file)"));
|
||||
}
|
||||
if lab {
|
||||
convert_ab(&mut data, out_layout.channels(), out, photometric == 8, false);
|
||||
}
|
||||
let mut img = Image::from_raw(w, h, out_layout, out, data)?;
|
||||
if tally.missing > 0 {
|
||||
img.warnings.push(DecodeWarning::Truncated { format: F });
|
||||
}
|
||||
Ok(img)
|
||||
Ok(Prepared { w, h, lay, band_rows: ch.min(hu), patches, tl, lab: lab.then_some(photometric == 8) })
|
||||
}
|
||||
|
||||
/// The a* and b* samples (1 and 2 of every pixel) of a Lab image between the file's encoding and
|
||||
@@ -745,6 +926,23 @@ fn zeroed(len: usize) -> Result<Vec<u8>, CodecError> {
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// `v` refilled with `len` zero bytes, reusing its allocation when it is large enough.
|
||||
fn refill_zeroed(mut v: Vec<u8>, len: usize) -> Result<Vec<u8>, CodecError> {
|
||||
if v.capacity() < len {
|
||||
drop(v);
|
||||
return zeroed(len);
|
||||
}
|
||||
v.clear();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
use rayon::prelude::*;
|
||||
v.par_extend(rayon::iter::repeat_n(0u8, len));
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
v.resize(len, 0);
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Chunks decoded and chunks whose data ended early.
|
||||
#[derive(Default, Clone, Copy)]
|
||||
struct Tally {
|
||||
@@ -759,36 +957,31 @@ impl std::ops::Add for Tally {
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes every band into `data`, in parallel on native targets (one decoder and scratch
|
||||
/// buffer per worker).
|
||||
/// Decodes the bands from `first` on into `data` (`band_bytes` each), in parallel on native
|
||||
/// targets (one decoder and scratch buffer per worker).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn decode_bands<'a, O>(lay: &Layout, data: &mut [u8], band_bytes: usize, _first: &mut Decoder<Patched<'a>>, open: &O) -> Result<Tally, CodecError>
|
||||
where
|
||||
O: Fn() -> Result<Decoder<Patched<'a>>, CodecError> + Sync,
|
||||
{
|
||||
fn decode_bands(p: &Prepared, b: &[u8], data: &mut [u8], band_bytes: usize, first: usize) -> Result<Tally, CodecError> {
|
||||
use rayon::prelude::*;
|
||||
data.par_chunks_mut(band_bytes.max(1))
|
||||
.enumerate()
|
||||
.map_init(
|
||||
|| open().map(|d| (d, Vec::new())).map_err(|e| e.to_string()),
|
||||
|worker, (b, band)| {
|
||||
|| p.open(b).map(|d| (d, Vec::new())).map_err(|e| e.to_string()),
|
||||
|worker, (i, band)| {
|
||||
let (dec, scratch) = worker.as_mut().map_err(|e| err(e.clone()))?;
|
||||
decode_band(lay, dec, scratch, b, band)
|
||||
decode_band(&p.lay, dec, scratch, first + i, band)
|
||||
},
|
||||
)
|
||||
.try_reduce(Tally::default, |a, b| Ok(a + b))
|
||||
}
|
||||
|
||||
/// Decodes every band into `data`, one after the other.
|
||||
/// Decodes the bands from `first` on into `data` (`band_bytes` each), one after the other.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn decode_bands<'a, O>(lay: &Layout, data: &mut [u8], band_bytes: usize, first: &mut Decoder<Patched<'a>>, _open: &O) -> Result<Tally, CodecError>
|
||||
where
|
||||
O: Fn() -> Result<Decoder<Patched<'a>>, CodecError> + Sync,
|
||||
{
|
||||
fn decode_bands(p: &Prepared, b: &[u8], data: &mut [u8], band_bytes: usize, first: usize) -> Result<Tally, CodecError> {
|
||||
let mut dec = p.open(b)?;
|
||||
let mut scratch = Vec::new();
|
||||
let mut tally = Tally::default();
|
||||
for (b, band) in data.chunks_mut(band_bytes.max(1)).enumerate() {
|
||||
tally = tally + decode_band(lay, first, &mut scratch, b, band)?;
|
||||
for (i, band) in data.chunks_mut(band_bytes.max(1)).enumerate() {
|
||||
tally = tally + decode_band(&p.lay, &mut dec, &mut scratch, first + i, band)?;
|
||||
}
|
||||
Ok(tally)
|
||||
}
|
||||
|
||||
@@ -30,7 +30,9 @@ pub use crate::cicp::Cicp;
|
||||
pub use crate::codecs::exr_cryptomatte::{cryptomatte_id, cryptomatte_key, cryptomatte_preview_color};
|
||||
pub use crate::codecs::gif_frames::{AnimationFrame, MAX_GIF_FRAMES};
|
||||
pub use crate::codecs::png::{PngPalette, encode_indexed as encode_png_indexed, palette as png_palette, stereo as png_stereo};
|
||||
pub use crate::codecs::tiff::{PhotoshopTags as TiffPhotoshopTags, photoshop_tags as tiff_photoshop_tags, writes_little_endian as tiff_writes_little_endian};
|
||||
pub use crate::codecs::tiff::{
|
||||
PhotoshopTags as TiffPhotoshopTags, TiffBands, photoshop_tags as tiff_photoshop_tags, writes_little_endian as tiff_writes_little_endian,
|
||||
};
|
||||
pub use crate::codecs::tiff_ifd::{TiffInfo, TiffPage, TiffPageKind};
|
||||
pub use crate::error::CodecError;
|
||||
pub use crate::exif_color::{EXIF_COLOR_SPACE_SRGB, exif_color_space};
|
||||
|
||||
@@ -30,6 +30,15 @@ impl Default for Limits {
|
||||
}
|
||||
|
||||
impl Limits {
|
||||
/// For a decoder that writes a band of rows at a time into the document's tiles instead of
|
||||
/// one buffer (TIFF, #8169): Photoshop's largest document, 300,000 px a side, on 64-bit
|
||||
/// targets, with `max_alloc` bounding each group of bands. 32-bit targets keep the
|
||||
/// [`Default`] limits: wasm32's 4 GiB address space can't hold a larger document anyway.
|
||||
pub fn banded() -> Self {
|
||||
let l = Limits::default();
|
||||
if cfg!(target_pointer_width = "64") { Limits { max_width: 300_000, max_height: 300_000, max_pixels: 300_000 * 300_000, ..l } } else { l }
|
||||
}
|
||||
|
||||
/// Effectively unlimited (still bounded by `usize` overflow checks).
|
||||
pub fn none() -> Self {
|
||||
Limits { max_width: u32::MAX, max_height: u32::MAX, max_pixels: u64::MAX, max_alloc: u64::MAX }
|
||||
@@ -42,6 +51,20 @@ impl Limits {
|
||||
}
|
||||
|
||||
pub(crate) fn check_bytes(&self, width: u32, height: u32, bytes_per_pixel: u64) -> Result<(), CodecError> {
|
||||
self.check_size(width, height)?;
|
||||
let bytes = (width as u64 * height as u64).saturating_mul(bytes_per_pixel);
|
||||
if bytes > self.max_alloc {
|
||||
return Err(CodecError::LimitExceeded(format!("{bytes} bytes exceed max_alloc {}", self.max_alloc)));
|
||||
}
|
||||
if usize::try_from(bytes).is_err() {
|
||||
return Err(CodecError::LimitExceeded(format!("{bytes} bytes do not fit in memory")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The dimension and pixel-count checks of [`Limits::check`], for a decoder that never holds
|
||||
/// the whole image in one buffer (`max_alloc` then bounds each piece it decodes).
|
||||
pub(crate) fn check_size(&self, width: u32, height: u32) -> Result<(), CodecError> {
|
||||
if width == 0 || height == 0 {
|
||||
return Err(CodecError::InvalidImage(format!("zero-sized image {width}x{height}")));
|
||||
}
|
||||
@@ -52,13 +75,6 @@ impl Limits {
|
||||
if pixels > self.max_pixels {
|
||||
return Err(CodecError::LimitExceeded(format!("{pixels} pixels exceed max {}", self.max_pixels)));
|
||||
}
|
||||
let bytes = pixels.saturating_mul(bytes_per_pixel);
|
||||
if bytes > self.max_alloc {
|
||||
return Err(CodecError::LimitExceeded(format!("{bytes} bytes exceed max_alloc {}", self.max_alloc)));
|
||||
}
|
||||
if usize::try_from(bytes).is_err() {
|
||||
return Err(CodecError::LimitExceeded(format!("{bytes} bytes do not fit in memory")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
//! `TiffBands` (#8169): decoding a TIFF a group of bands at a time gives exactly the image the
|
||||
//! whole-image decoder does, for every layout the decoder reads, every orientation, and groups of
|
||||
//! any size; and it opens images whose single buffer the whole-image decoder refuses.
|
||||
|
||||
mod common;
|
||||
|
||||
use common::tiffgen::*;
|
||||
use photocraft_codecs::*;
|
||||
|
||||
/// A deterministic byte pattern.
|
||||
fn noise(n: usize, seed: u32) -> Vec<u8> {
|
||||
let mut x = seed.wrapping_mul(2_654_435_761).max(1);
|
||||
(0..n)
|
||||
.map(|_| {
|
||||
x ^= x << 13;
|
||||
x ^= x >> 17;
|
||||
x ^= x << 5;
|
||||
(x >> 24) as u8
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The image `TiffBands` decodes, assembled from its groups.
|
||||
fn banded(bytes: &[u8], page: Option<usize>, limits: &Limits, upright: bool) -> Result<Image, CodecError> {
|
||||
let mut t = TiffBands::open(bytes, page, limits)?;
|
||||
if upright {
|
||||
t = t.upright();
|
||||
}
|
||||
let (w, h) = t.dimensions();
|
||||
let mut out = Image::new(w, h, t.layout(), t.sample_type())?;
|
||||
let bpp = t.layout().channels() * t.sample_type().bytes();
|
||||
let mut groups = 0;
|
||||
t.decode(|x, y, g: &Image| -> Result<(), CodecError> {
|
||||
groups += 1;
|
||||
assert_eq!((g.layout(), g.sample_type()), (out.layout(), out.sample_type()));
|
||||
let (gw, gh) = g.dimensions();
|
||||
assert!(x + gw <= w && y + gh <= h, "group {gw}x{gh} at {x},{y} outside {w}x{h}");
|
||||
let row = gw as usize * bpp;
|
||||
for r in 0..gh as usize {
|
||||
let dst = ((y as usize + r) * w as usize + x as usize) * bpp;
|
||||
out.data_mut()[dst..dst + row].copy_from_slice(&g.data()[r * row..(r + 1) * row]);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
assert!(groups >= 1);
|
||||
out.icc = t.icc.clone();
|
||||
out.meta = t.meta.clone();
|
||||
out.warnings = t.warnings.clone();
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The whole-image decode of the same page.
|
||||
fn whole(bytes: &[u8], page: Option<usize>, upright: bool) -> Image {
|
||||
let opts = DecodeOptions { keep_orientation: !upright, ..Default::default() };
|
||||
match page {
|
||||
Some(p) => decode_tiff_page(bytes, p, &opts).unwrap(),
|
||||
None => decode_with(bytes, &opts).unwrap(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Limits whose `max_alloc` makes each group `bands` bands of `band_bytes`.
|
||||
fn grouped(band_bytes: usize, bands: usize) -> Limits {
|
||||
Limits { max_alloc: (band_bytes * bands) as u64, ..Limits::banded() }
|
||||
}
|
||||
|
||||
fn assert_same(bytes: &[u8], band_bytes: usize, what: &str) {
|
||||
for upright in [false, true] {
|
||||
let want = whole(bytes, None, upright);
|
||||
for limits in [Limits::banded(), grouped(band_bytes, 1), grouped(band_bytes, 2), grouped(band_bytes, 3)] {
|
||||
let got = banded(bytes, None, &limits, upright).unwrap_or_else(|e| panic!("{what}: {e}"));
|
||||
assert_eq!(got.dimensions(), want.dimensions(), "{what}");
|
||||
assert_eq!((got.layout(), got.sample_type()), (want.layout(), want.sample_type()), "{what}");
|
||||
assert!(got.data() == want.data(), "{what}: pixels differ (max_alloc {})", limits.max_alloc);
|
||||
assert_eq!(got.icc, want.icc, "{what}");
|
||||
assert_eq!(got.meta, want.meta, "{what}");
|
||||
assert_eq!(got.warnings, want.warnings, "{what}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `n / 1` as a little-endian RATIONAL value.
|
||||
fn rational(n: u64) -> u64 {
|
||||
n | 1 << 32
|
||||
}
|
||||
|
||||
const W: u32 = 37;
|
||||
const H: u32 = 29;
|
||||
|
||||
#[test]
|
||||
fn every_layout_matches_the_whole_image_decoder() {
|
||||
let n = (W * H) as usize;
|
||||
let rows = 4u32;
|
||||
let row = |spp: usize, bps: usize| W as usize * spp * bps;
|
||||
let cases: Vec<(&str, Dir, usize)> = vec![
|
||||
("rgb8 strips", strips(W, H, 8, 3, 2, rows, &noise(n * 3, 1)), row(3, 1) * rows as usize),
|
||||
("gray8 WhiteIsZero", strips(W, H, 8, 1, 0, rows, &noise(n, 2)), row(1, 1) * rows as usize),
|
||||
("gray16 big-endian", strips(W, H, 16, 1, 1, rows, &noise(n * 2, 3)), row(1, 2) * rows as usize),
|
||||
("cmyk8", strips(W, H, 8, 4, 5, rows, &noise(n * 4, 4)), row(4, 1) * rows as usize),
|
||||
("cielab8", strips(W, H, 8, 3, 8, rows, &noise(n * 3, 5)), row(3, 1) * rows as usize),
|
||||
("rgba16 associated alpha", strips(W, H, 16, 4, 2, rows, &noise(n * 8, 6)).tag(338, SHORT, &[1]), row(4, 2) * rows as usize),
|
||||
(
|
||||
"gray f32",
|
||||
strips(W, H, 32, 1, 1, rows, &f32s(&noise(n, 7).iter().map(|&b| f32::from(b) / 255.0).collect::<Vec<_>>(), true)).tag(339, SHORT, &[3]),
|
||||
row(1, 4) * rows as usize,
|
||||
),
|
||||
(
|
||||
"palette 4-bit",
|
||||
strips(W, H, 4, 1, 3, rows, &noise((W as usize).div_ceil(2) * H as usize, 8)).tag(320, SHORT, &(0..48u64).map(|i| i * 1365).collect::<Vec<_>>()),
|
||||
row(3, 1) * rows as usize,
|
||||
),
|
||||
("gray 1-bit", strips(W, H, 1, 1, 1, rows, &noise((W as usize).div_ceil(8) * H as usize, 9)), row(1, 1) * rows as usize),
|
||||
];
|
||||
for (what, dir, band) in cases {
|
||||
// Both byte orders: the generator writes multi-byte samples as given, so the
|
||||
// big-endian files hold different values; each is compared against its own decode.
|
||||
for little in [true, false] {
|
||||
assert_same(&build(little, false, std::slice::from_ref(&dir), &[0]).bytes, band, what);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiles_and_planar_data_match() {
|
||||
let (w, h) = (W as usize, H as usize);
|
||||
let px = noise(w * h * 3 * 2, 11);
|
||||
let tiled = |planar: bool| {
|
||||
let mut d = Dir { entries: base(W, H, 16, 3, 2), chunks: tile_split(&px, w, h, 3, 2, 16, 16, planar), tiled: true }.tag(322, SHORT, &[16]).tag(
|
||||
323,
|
||||
SHORT,
|
||||
&[16],
|
||||
);
|
||||
if planar {
|
||||
d = d.tag(284, SHORT, &[2]);
|
||||
}
|
||||
d
|
||||
};
|
||||
let band = w * 3 * 2 * 16;
|
||||
assert_same(&build(true, false, &[tiled(false)], &[0]).bytes, band, "chunky tiles");
|
||||
assert_same(&build(true, true, &[tiled(true)], &[0]).bytes, band, "planar tiles, BigTIFF");
|
||||
let planar = Dir { entries: base(W, H, 16, 3, 2), chunks: planar_strips(&px, w, h, 3, 2, 5), tiled: false }.tag(278, LONG, &[5]).tag(284, SHORT, &[2]);
|
||||
assert_same(&build(true, false, &[planar], &[0]).bytes, w * 3 * 2 * 5, "planar strips");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_orientation_matches() {
|
||||
let n = (W * H) as usize;
|
||||
for o in 1..=8u64 {
|
||||
let dir = strips(W, H, 8, 3, 2, 3, &noise(n * 3, 20 + o as u32))
|
||||
.tag(274, SHORT, &[o])
|
||||
.tag(282, RATIONAL, &[rational(300)])
|
||||
.tag(283, RATIONAL, &[rational(150)])
|
||||
.tag(296, SHORT, &[2]);
|
||||
let bytes = build(true, false, &[dir], &[0]).bytes;
|
||||
assert_same(&bytes, W as usize * 3 * 3, &format!("orientation {o}"));
|
||||
let t = TiffBands::open(&bytes, None, &Limits::banded()).unwrap();
|
||||
assert_eq!(t.orientation(), o as u16);
|
||||
let up = t.upright();
|
||||
let swapped = o >= 5;
|
||||
assert_eq!(up.dimensions(), if swapped { (H, W) } else { (W, H) }, "orientation {o}");
|
||||
assert_eq!(up.meta.dpi, Some(if swapped { (150.0, 300.0) } else { (300.0, 150.0) }), "orientation {o}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cut_off_data_matches_and_warns() {
|
||||
let n = (W * H) as usize;
|
||||
let built = build(true, false, &[strips(W, H, 8, 3, 2, 4, &noise(n * 3, 30))], &[0]);
|
||||
// The last four of eight strips point past the end of the file: their data is missing.
|
||||
let mut built = built;
|
||||
let past = built.bytes.len() as u64 + 4096;
|
||||
for i in 4..8 {
|
||||
patch_value(&mut built, true, false, 0, 273, i, past);
|
||||
}
|
||||
assert_same(&built.bytes, W as usize * 3 * 4, "cut off");
|
||||
let img = banded(&built.bytes, None, &Limits::banded(), true).unwrap();
|
||||
assert!(img.warnings.contains(&DecodeWarning::Truncated { format: Format::Tiff }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_pages_and_the_more_pages_warning_match() {
|
||||
let n = (W * H) as usize;
|
||||
let a = strips(W, H, 8, 1, 1, 5, &noise(n, 40));
|
||||
let b = strips(W, H, 8, 3, 2, 5, &noise(n * 3, 41));
|
||||
let bytes = build(true, false, &[a, b], &[0, 1]).bytes;
|
||||
for page in [None, Some(0), Some(1)] {
|
||||
let want = whole(&bytes, page, false);
|
||||
let got = banded(&bytes, page, &Limits::banded(), false).unwrap();
|
||||
assert!(got.data() == want.data(), "page {page:?}");
|
||||
assert_eq!(got.warnings, want.warnings, "page {page:?}");
|
||||
}
|
||||
assert!(matches!(TiffBands::open(&bytes, Some(9), &Limits::banded()), Err(CodecError::InvalidImage(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(target_pointer_width = "64")]
|
||||
fn opens_an_image_over_the_whole_image_budget() {
|
||||
// The whole-image decoder needs the image in one buffer; the banded one only a band (on
|
||||
// 64-bit targets: 32-bit ones still check the whole image).
|
||||
let n = (W * H) as usize;
|
||||
let bytes = build(true, false, &[strips(W, H, 8, 3, 2, 2, &noise(n * 3, 50))], &[0]).bytes;
|
||||
let band = W as u64 * 3 * 2;
|
||||
let tight = Limits { max_alloc: band * 3, ..Limits::banded() };
|
||||
let refused = decode_with(&bytes, &DecodeOptions { limits: tight, keep_orientation: false });
|
||||
assert!(matches!(refused, Err(CodecError::LimitExceeded(_))), "{refused:?}");
|
||||
let got = banded(&bytes, None, &tight, true).unwrap();
|
||||
assert!(got.data() == whole(&bytes, None, true).data());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn size_limits_still_apply() {
|
||||
let n = (W * H) as usize;
|
||||
let bytes = build(true, false, &[strips(W, H, 8, 3, 2, 4, &noise(n * 3, 60))], &[0]).bytes;
|
||||
let few_pixels = Limits { max_pixels: u64::from(W * H) - 1, ..Limits::banded() };
|
||||
assert!(matches!(TiffBands::open(&bytes, None, &few_pixels), Err(CodecError::LimitExceeded(_))));
|
||||
let narrow = Limits { max_width: W - 1, ..Limits::banded() };
|
||||
assert!(matches!(TiffBands::open(&bytes, None, &narrow), Err(CodecError::LimitExceeded(_))));
|
||||
// One strip is more than `max_alloc`: refused before decoding, with the image size.
|
||||
let tiny = Limits { max_alloc: 10, ..Limits::banded() };
|
||||
match TiffBands::open(&bytes, None, &tiny) {
|
||||
Err(CodecError::LimitExceeded(m)) => assert!(m.contains(&format!("{W}x{H}")), "{m}"),
|
||||
other => panic!("{:?}", other.map(|t| t.dimensions())),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn banded_limits_allow_photoshops_largest_document() {
|
||||
let l = Limits::banded();
|
||||
if cfg!(target_pointer_width = "64") {
|
||||
assert_eq!((l.max_width, l.max_height), (300_000, 300_000));
|
||||
assert!(l.max_pixels >= 300_000 * 300_000);
|
||||
// The banner from #8456 / #8169: 136 ft × 26 ft at 72 ppi.
|
||||
assert!(117_504u64 * 22_464 > Limits::default().max_pixels);
|
||||
assert!(117_504u64 * 22_464 <= l.max_pixels);
|
||||
} else {
|
||||
assert_eq!(l, Limits::default());
|
||||
}
|
||||
assert_eq!(l.max_alloc, Limits::default().max_alloc);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hostile_header_is_refused_before_allocating() {
|
||||
// 300000² declared in a file of a few kilobytes: one 270 GB strip, which neither the
|
||||
// decompression-bomb guard nor the per-group budget lets through.
|
||||
let mut built = build(true, true, &[strips(1000, 4, 8, 3, 2, 4, &noise(12_000, 70))], &[0]);
|
||||
for tag in [256, 257, 278] {
|
||||
patch_value(&mut built, true, true, 0, tag, 0, 300_000);
|
||||
}
|
||||
assert!(matches!(TiffBands::open(&built.bytes, None, &Limits::banded()), Err(CodecError::Malformed { .. } | CodecError::LimitExceeded(_))));
|
||||
// Past Photoshop's 300000 px a side.
|
||||
let mut wide = build(true, true, &[strips(1000, 4, 8, 3, 2, 4, &noise(12_000, 71))], &[0]);
|
||||
patch_value(&mut wide, true, true, 0, 256, 0, 300_001);
|
||||
assert!(matches!(TiffBands::open(&wide.bytes, None, &Limits::banded()), Err(CodecError::LimitExceeded(_))));
|
||||
}
|
||||
+111
-36
@@ -215,23 +215,97 @@ pub fn tga_alpha_channel_to_transparency(doc: &mut Document) {
|
||||
|
||||
/// Opens one page of a TIFF or BigTIFF file: `None` is the page Photoshop opens (the first
|
||||
/// full-resolution one), `Some(i)` an index into [`codecs::tiff_info`]'s pages (every IFD and
|
||||
/// SubIFD). A page with Photoshop layer data opens layered.
|
||||
/// SubIFD). A page with Photoshop layer data opens layered. Any other page is decoded a group of
|
||||
/// rows at a time straight into the layer's tiles, so it opens up to Photoshop's 300,000 px a
|
||||
/// side without a second full-size copy (#8169).
|
||||
pub fn import_tiff_page(name: &str, bytes: &[u8], page: Option<usize>) -> Result<ImportResult, IoError> {
|
||||
// The orientation is applied after the layer check: rotating the composite but not the
|
||||
// layers would misalign them, so a layered TIFF keeps its stored orientation.
|
||||
let bands = codecs::TiffBands::open(bytes, page, &codecs::Limits::banded())?;
|
||||
if bands.meta.photoshop_layers.as_deref().is_some_and(|l| !l.is_empty()) {
|
||||
return import_layered_tiff(name, bytes, page);
|
||||
}
|
||||
tiff_to_document(name, bands.upright())
|
||||
}
|
||||
|
||||
/// A layered TIFF, decoded whole: its layers are built from the composite.
|
||||
fn import_layered_tiff(name: &str, bytes: &[u8], page: Option<usize>) -> Result<ImportResult, IoError> {
|
||||
// The orientation is ignored: rotating the composite but not the layers would misalign them,
|
||||
// so a layered TIFF keeps its stored orientation.
|
||||
let keep = codecs::DecodeOptions { keep_orientation: true, ..Default::default() };
|
||||
let (img, orientation) = match page {
|
||||
None => (codecs::decode_with(bytes, &keep)?, codecs::tiff_orientation(bytes)),
|
||||
Some(p) => (codecs::decode_tiff_page(bytes, p, &keep)?, codecs::tiff_page_orientation(bytes, p)),
|
||||
};
|
||||
if let Some(layers) = img.meta.photoshop_layers.as_deref().filter(|l| !l.is_empty()) {
|
||||
let mut r = crate::tiff_layers::import_layered(name, &img, layers)?;
|
||||
if orientation != 1 {
|
||||
r.warnings.push("the TIFF's orientation tag was ignored so the layers stay aligned with the image".to_string());
|
||||
}
|
||||
return Ok(r);
|
||||
let layers = img.meta.photoshop_layers.clone().unwrap_or_default();
|
||||
let mut r = crate::tiff_layers::import_layered(name, &img, &layers)?;
|
||||
if orientation != 1 {
|
||||
r.warnings.push("the TIFF's orientation tag was ignored so the layers stay aligned with the image".to_string());
|
||||
}
|
||||
image_to_document(name, &img.oriented(orientation)?)
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// A flat TIFF page as a single-layer document, decoded a group of rows at a time into the
|
||||
/// layer's tiles: only one group exists beside the document.
|
||||
fn tiff_to_document(name: &str, mut bands: codecs::TiffBands<'_>) -> Result<ImportResult, IoError> {
|
||||
let (w, h) = bands.dimensions();
|
||||
let (layout, sample) = (bands.layout(), bands.sample_type());
|
||||
let f = document_format(layout, sample);
|
||||
let fmt = PixelFormat::new(f.mode, f.depth, true);
|
||||
let mut s = Surface::new(fmt);
|
||||
let out_of_memory = |e: photocraft_raster::AllocationError| {
|
||||
let gb = (u64::from(w) * u64::from(h)).saturating_mul(fmt.bytes_per_pixel() as u64) as f64 / 1e9;
|
||||
IoError::Unsupported(format!("not enough memory to open this {w} × {h} px image: it needs about {gb:.1} GB ({e})"))
|
||||
};
|
||||
bands.decode(|x, y, group: &Image| -> Result<(), IoError> {
|
||||
let (gw, gh) = group.dimensions();
|
||||
let (x, y) = (x as i32, y as i32);
|
||||
let rect = |rows: &std::ops::Range<usize>| Rect::new(x, y + rows.start as i32, x.saturating_add(gw as i32), y + rows.end as i32);
|
||||
if layout == f.layout && sample == f.sample {
|
||||
return s.try_write_interleaved(rect(&(0..gh as usize)), group.data()).map_err(out_of_memory);
|
||||
}
|
||||
// Converted in pieces of rows on all cores, then each piece written (on all cores too).
|
||||
let row = group.data().len() / (gh.max(1) as usize);
|
||||
let pieces = crate::pixels::par_map(crate::pixels::bands(gh as usize), |rows| {
|
||||
let part = group.data().get(rows.start * row..rows.end * row).unwrap_or_default().to_vec();
|
||||
Image::from_raw(gw, rows.len() as u32, layout, sample, part).map(|p| (rows, p.convert(f.layout, f.sample)))
|
||||
});
|
||||
for piece in pieces {
|
||||
let (rows, part) = piece?;
|
||||
s.try_write_interleaved(rect(&rows), part.data()).map_err(out_of_memory)?;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
s.prune();
|
||||
let mut warnings: Vec<String> = bands.warnings.iter().map(ToString::to_string).collect();
|
||||
warnings.extend(f.warning.clone());
|
||||
let meta = std::mem::take(&mut bands.meta);
|
||||
Ok(single_layer_document(name, (w, h), f, layout.has_alpha(), s, bands.icc.take(), meta, warnings))
|
||||
}
|
||||
|
||||
/// How a decoded image's pixels are kept in a document.
|
||||
struct DocumentFormat {
|
||||
mode: ColorMode,
|
||||
depth: SampleType,
|
||||
/// The layer's layout (always with alpha) and sample type, as the codec names them.
|
||||
layout: ChannelLayout,
|
||||
sample: CSample,
|
||||
/// What the conversion loses.
|
||||
warning: Option<String>,
|
||||
}
|
||||
|
||||
fn document_format(layout: ChannelLayout, sample: CSample) -> DocumentFormat {
|
||||
let (mode, layout) = match layout {
|
||||
ChannelLayout::Gray | ChannelLayout::GrayA => (ColorMode::Grayscale, ChannelLayout::GrayA),
|
||||
ChannelLayout::Rgb | ChannelLayout::Rgba => (ColorMode::Rgb, ChannelLayout::Rgba),
|
||||
ChannelLayout::Cmyk | ChannelLayout::CmykA => (ColorMode::Cmyk, ChannelLayout::CmykA),
|
||||
ChannelLayout::Lab | ChannelLayout::LabA => (ColorMode::Lab, ChannelLayout::LabA),
|
||||
};
|
||||
let (depth, sample, warning) = match sample {
|
||||
CSample::U8 => (SampleType::U8, CSample::U8, None),
|
||||
CSample::U16 => (SampleType::U16, CSample::U16, None),
|
||||
CSample::F16 => (SampleType::F32, CSample::F32, Some("16-bit float samples are stored as 32-bit float".to_string())),
|
||||
CSample::F32 => (SampleType::F32, CSample::F32, None),
|
||||
};
|
||||
DocumentFormat { mode, depth, layout, sample, warning }
|
||||
}
|
||||
|
||||
/// A decoded flat image as a single-layer document: a locked "Background" when it is opaque, a
|
||||
@@ -239,29 +313,30 @@ pub fn import_tiff_page(name: &str, bytes: &[u8], page: Option<usize>) -> Result
|
||||
pub(crate) fn image_to_document(name: &str, img: &Image) -> Result<ImportResult, IoError> {
|
||||
// What the decoder noticed (frames or pages left out, data ending early) comes first.
|
||||
let mut warnings: Vec<String> = img.warnings.iter().map(ToString::to_string).collect();
|
||||
let (mode, target_layout) = match img.layout() {
|
||||
ChannelLayout::Gray | ChannelLayout::GrayA => (ColorMode::Grayscale, ChannelLayout::GrayA),
|
||||
ChannelLayout::Rgb | ChannelLayout::Rgba => (ColorMode::Rgb, ChannelLayout::Rgba),
|
||||
ChannelLayout::Cmyk | ChannelLayout::CmykA => (ColorMode::Cmyk, ChannelLayout::CmykA),
|
||||
ChannelLayout::Lab | ChannelLayout::LabA => (ColorMode::Lab, ChannelLayout::LabA),
|
||||
};
|
||||
let (depth, csample) = match img.sample_type() {
|
||||
CSample::U8 => (SampleType::U8, CSample::U8),
|
||||
CSample::U16 => (SampleType::U16, CSample::U16),
|
||||
CSample::F16 => {
|
||||
warnings.push("16-bit float samples are stored as 32-bit float".to_string());
|
||||
(SampleType::F32, CSample::F32)
|
||||
}
|
||||
CSample::F32 => (SampleType::F32, CSample::F32),
|
||||
};
|
||||
let (w, h) = img.dimensions();
|
||||
let mut doc = Document::new(name, Size::new(w, h), mode, depth);
|
||||
let mut s = image_surface(img, target_layout, csample)?;
|
||||
let f = document_format(img.layout(), img.sample_type());
|
||||
warnings.extend(f.warning.clone());
|
||||
let mut s = image_surface(img, f.layout, f.sample)?;
|
||||
s.prune();
|
||||
Ok(single_layer_document(name, img.dimensions(), f, img.layout().has_alpha(), s, img.icc.clone(), img.meta.clone(), warnings))
|
||||
}
|
||||
|
||||
/// The document of one layer holding `s`, with the image's profile and metadata.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn single_layer_document(
|
||||
name: &str,
|
||||
(w, h): (u32, u32),
|
||||
f: DocumentFormat,
|
||||
alpha: bool,
|
||||
s: Surface,
|
||||
icc: Option<Vec<u8>>,
|
||||
meta: codecs::Metadata,
|
||||
mut warnings: Vec<String>,
|
||||
) -> ImportResult {
|
||||
let mut doc = Document::new(name, Size::new(w, h), f.mode, f.depth);
|
||||
// As in Photoshop: an opaque image opens as the locked Background layer, one with
|
||||
// transparency (an alpha channel, or a tRNS chunk the decoder expands to one) as a normal
|
||||
// layer named "Layer 0", since a Background can't hold transparency.
|
||||
let layer = if img.layout().has_alpha() {
|
||||
let layer = if alpha {
|
||||
Layer::new("Layer 0", LayerContent::Raster(s))
|
||||
} else {
|
||||
let mut bg = Layer::new("Background", LayerContent::Raster(s));
|
||||
@@ -270,20 +345,20 @@ pub(crate) fn image_to_document(name: &str, img: &Image) -> Result<ImportResult,
|
||||
bg
|
||||
};
|
||||
doc.layers.push(layer);
|
||||
doc.icc_profile = img.icc.clone().map(Arc::new);
|
||||
doc.metadata.exif = img.meta.exif.clone().map(Arc::new);
|
||||
doc.metadata.xmp = img.meta.xmp.clone();
|
||||
doc.metadata.text = img.meta.text.clone();
|
||||
if let Some((x, y)) = img.meta.dpi {
|
||||
doc.icc_profile = icc.map(Arc::new);
|
||||
doc.metadata.exif = meta.exif.map(Arc::new);
|
||||
doc.metadata.xmp = meta.xmp;
|
||||
doc.metadata.text = meta.text;
|
||||
if let Some((x, y)) = meta.dpi {
|
||||
doc.resolution_dpi = x;
|
||||
warnings.extend(crate::unequal_resolution_warning(f64::from(x), f64::from(y)));
|
||||
}
|
||||
// Guides in the Photoshop resources a JPEG (APP13) or TIFF carries: resource 1032.
|
||||
let guides = img.meta.photoshop_resources.as_deref().and_then(|r| photocraft_psd::tiff::resources_from_bytes(r).ok());
|
||||
let guides = meta.photoshop_resources.as_deref().and_then(|r| photocraft_psd::tiff::resources_from_bytes(r).ok());
|
||||
if let Some(g) = guides.as_ref().and_then(|(res, _)| res.iter().find(|r| r.id == 1032)) {
|
||||
crate::psd_import::parse_guides(&g.data, &mut doc);
|
||||
}
|
||||
Ok(ImportResult { document: doc, warnings, source_read_only: false, preview_only: false })
|
||||
ImportResult { document: doc, warnings, source_read_only: false, preview_only: false }
|
||||
}
|
||||
|
||||
/// The pixels of a decoded image as a surface of `fmt`, converting layout and sample type a
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
//! TIFFs open a group of rows at a time straight into the layer's tiles (#8169): the document
|
||||
//! is the one decoding the whole image gives, for every layout and depth, and an image over the
|
||||
//! old 2^30 px limit opens.
|
||||
|
||||
use photocraft_codecs::{self as codecs, ChannelLayout, EncodeOptions, Format, Image, SampleType, TiffCompression};
|
||||
use photocraft_doc::LayerContent;
|
||||
|
||||
/// A smooth pattern with some detail, in `layout` and `sample`.
|
||||
fn pattern(w: u32, h: u32, layout: ChannelLayout, sample: SampleType) -> Image {
|
||||
let ch = layout.channels();
|
||||
let px: Vec<f32> = (0..h).flat_map(|y| (0..w).flat_map(move |x| (0..ch).map(move |c| ((x * 7 + y * 13 + c as u32 * 29) % 256) as f32 / 255.0))).collect();
|
||||
Image::from_normalized(w, h, layout, sample, &px).unwrap()
|
||||
}
|
||||
|
||||
fn tiff(img: &Image, compression: TiffCompression) -> Vec<u8> {
|
||||
codecs::encode(img, Format::Tiff, &EncodeOptions { tiff_compression: compression, ..Default::default() }).unwrap()
|
||||
}
|
||||
|
||||
/// The layer's pixels as the codec's interleaved bytes.
|
||||
fn layer_bytes(r: &photocraft_io::ImportResult) -> Vec<u8> {
|
||||
let d = &r.document;
|
||||
let [layer] = &d.layers[..] else { panic!("{} layers", d.layers.len()) };
|
||||
let LayerContent::Raster(s) = &layer.content else { panic!("not a raster layer") };
|
||||
s.to_interleaved(d.bounds())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_layout_opens_as_the_whole_image_decode_does() {
|
||||
let cases = [
|
||||
(ChannelLayout::Rgb, SampleType::U8),
|
||||
(ChannelLayout::Rgba, SampleType::U16),
|
||||
(ChannelLayout::Gray, SampleType::U8),
|
||||
(ChannelLayout::GrayA, SampleType::F32),
|
||||
(ChannelLayout::Cmyk, SampleType::U8),
|
||||
(ChannelLayout::CmykA, SampleType::U16),
|
||||
(ChannelLayout::Lab, SampleType::U16),
|
||||
(ChannelLayout::Rgb, SampleType::F16),
|
||||
];
|
||||
for (layout, sample) in cases {
|
||||
for compression in [TiffCompression::None, TiffCompression::Lzw] {
|
||||
let what = format!("{layout:?} {sample:?} {compression:?}");
|
||||
let img = pattern(301, 257, layout, sample);
|
||||
let bytes = tiff(&img, compression);
|
||||
let r = photocraft_io::import("t.tif", &bytes).unwrap_or_else(|e| panic!("{what}: {e}"));
|
||||
let decoded = codecs::decode(&bytes).unwrap();
|
||||
let target = match layout {
|
||||
ChannelLayout::Gray | ChannelLayout::GrayA => ChannelLayout::GrayA,
|
||||
ChannelLayout::Cmyk | ChannelLayout::CmykA => ChannelLayout::CmykA,
|
||||
ChannelLayout::Lab | ChannelLayout::LabA => ChannelLayout::LabA,
|
||||
_ => ChannelLayout::Rgba,
|
||||
};
|
||||
let stored = decoded.sample_type();
|
||||
let depth = if stored == SampleType::F16 { SampleType::F32 } else { stored };
|
||||
assert!(layer_bytes(&r) == decoded.convert(target, depth).data(), "{what}: pixels");
|
||||
let d = &r.document;
|
||||
assert_eq!((d.size.width, d.size.height), (301, 257), "{what}");
|
||||
assert_eq!(d.layers[0].name, if layout.has_alpha() { "Layer 0" } else { "Background" }, "{what}");
|
||||
assert_eq!(d.icc_profile.as_deref().map(Vec::as_slice), decoded.icc.as_deref(), "{what}");
|
||||
assert_eq!(r.warnings.iter().any(|w| w.contains("16-bit float")), stored == SampleType::F16, "{what}: {:?}", r.warnings);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Peak resident memory of this process so far (Linux), in bytes.
|
||||
fn peak_rss() -> Option<u64> {
|
||||
let status = std::fs::read_to_string("/proc/self/status").ok()?;
|
||||
let kb: u64 = status.lines().find(|l| l.starts_with("VmHWM:"))?.split_whitespace().nth(1)?.parse().ok()?;
|
||||
Some(kb * 1024)
|
||||
}
|
||||
|
||||
/// An RGB8 TIFF of `w`×`h` with Deflate strips of 64 rows, written a strip at a time: a few
|
||||
/// horizontal bands of colour with a ramp, which compresses well.
|
||||
fn big_rgb_tiff(w: u32, h: u32) -> Vec<u8> {
|
||||
use flate2::{Compression, write::ZlibEncoder};
|
||||
use std::io::Write;
|
||||
let rows = 64u32;
|
||||
let mut f = b"II*\0\0\0\0\0".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
let mut counts = Vec::new();
|
||||
let mut row = vec![0u8; w as usize * 3];
|
||||
for y0 in (0..h).step_by(rows as usize) {
|
||||
let mut z = ZlibEncoder::new(Vec::new(), Compression::fast());
|
||||
for y in y0..(y0 + rows).min(h) {
|
||||
let band = (y / 997) as u8;
|
||||
for (x, px) in row.as_chunks_mut::<3>().0.iter_mut().enumerate() {
|
||||
px.copy_from_slice(&[band.wrapping_mul(40), (x / 1024) as u8, 200]);
|
||||
}
|
||||
z.write_all(&row).unwrap();
|
||||
}
|
||||
let strip = z.finish().unwrap();
|
||||
offsets.push(f.len() as u32);
|
||||
counts.push(strip.len() as u32);
|
||||
f.extend_from_slice(&strip);
|
||||
}
|
||||
let arrays_at = f.len() as u32;
|
||||
for v in offsets.iter().chain(&counts) {
|
||||
f.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
let bits_at = f.len() as u32;
|
||||
f.extend_from_slice(&[8, 0, 8, 0, 8, 0]);
|
||||
let ifd = f.len() as u32;
|
||||
f[4..8].copy_from_slice(&ifd.to_le_bytes());
|
||||
let n = offsets.len() as u32;
|
||||
let entries: [(u16, u16, u32, u32); 10] = [
|
||||
(256, 4, 1, w),
|
||||
(257, 4, 1, h),
|
||||
(258, 3, 3, bits_at),
|
||||
(259, 3, 1, 8),
|
||||
(262, 3, 1, 2),
|
||||
(273, 4, n, arrays_at),
|
||||
(277, 3, 1, 3),
|
||||
(278, 4, 1, rows),
|
||||
(279, 4, n, arrays_at + 4 * n),
|
||||
(284, 3, 1, 1),
|
||||
];
|
||||
f.extend_from_slice(&(entries.len() as u16).to_le_bytes());
|
||||
for (tag, ty, count, v) in entries {
|
||||
f.extend_from_slice(&tag.to_le_bytes());
|
||||
f.extend_from_slice(&ty.to_le_bytes());
|
||||
f.extend_from_slice(&count.to_le_bytes());
|
||||
f.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
f.extend_from_slice(&0u32.to_le_bytes());
|
||||
f
|
||||
}
|
||||
|
||||
/// Opt-in, release: `cargo test --release -p photocraft-io --test tiff_banded_import -- --ignored
|
||||
/// --nocapture`. Opens a 35,000 × 35,000 px TIFF (1.2 GP, the size from #8169's second report;
|
||||
/// it failed with "1225000000 pixels exceed max 1073741824"). `BANNER=1` opens the 117,504 ×
|
||||
/// 22,464 px banner from #8456 instead (2.64 GP; about 11 GB of RAM), `SIZE=<w>x<h>` any size.
|
||||
#[test]
|
||||
#[ignore = "needs about 5 GB of RAM (11 GB with BANNER=1); run in release"]
|
||||
fn opens_a_tiff_over_a_gigapixel() {
|
||||
let size = std::env::var("SIZE").ok().and_then(|s| s.split_once('x').and_then(|(w, h)| Some((w.parse().ok()?, h.parse().ok()?))));
|
||||
let (w, h): (u32, u32) = size.unwrap_or(if std::env::var_os("BANNER").is_some() { (117_504, 22_464) } else { (35_000, 35_000) });
|
||||
let t = std::time::Instant::now();
|
||||
let bytes = big_rgb_tiff(w, h);
|
||||
eprintln!("built a {w}x{h} TIFF of {} MB in {:.1?}", bytes.len() / 1_000_000, t.elapsed());
|
||||
let before = peak_rss();
|
||||
let t = std::time::Instant::now();
|
||||
let r = photocraft_io::import("big.tif", &bytes).unwrap();
|
||||
let took = t.elapsed();
|
||||
let d = &r.document;
|
||||
assert_eq!((d.size.width, d.size.height), (w, h));
|
||||
let LayerContent::Raster(s) = &d.layers[0].content else { panic!() };
|
||||
for (x, y) in [(0, 0), (w - 1, h - 1), (w / 2, h / 2), (5000.min(w - 1), 21_000.min(h - 1))] {
|
||||
let band = (y / 997) as u8;
|
||||
let want = [band.wrapping_mul(40), (x / 1024) as u8, 200, 255];
|
||||
assert_eq!(s.to_interleaved(photocraft_geom::Rect::new(x as i32, y as i32, x as i32 + 1, y as i32 + 1)), want, "pixel {x},{y}");
|
||||
}
|
||||
let layer_gb = u64::from(w) * u64::from(h) * 4;
|
||||
eprintln!(
|
||||
"opened in {took:.1?}; peak RSS {:.2} GB before, {:.2} GB after; the RGBA layer is {:.2} GB",
|
||||
before.unwrap_or(0) as f64 / 1e9,
|
||||
peak_rss().unwrap_or(0) as f64 / 1e9,
|
||||
layer_gb as f64 / 1e9
|
||||
);
|
||||
}
|
||||
@@ -245,6 +245,37 @@ fn convert_tiles(tiles: &mut [(TileCoord, Arc<Tile>)], r: Rect, data: &[f32], w:
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies the rows of `r` (interleaved `bytes`, `w` px wide, `bpp` bytes per pixel) into one
|
||||
/// tile, first copying it fallibly when an undo snapshot still shares it.
|
||||
fn copy_tile(tc: TileCoord, t: &mut Arc<Tile>, r: Rect, bytes: &[u8], w: usize, bpp: usize) -> Result<(), AllocationError> {
|
||||
if Arc::get_mut(t).is_none() {
|
||||
*t = Arc::new(t.try_clone()?);
|
||||
}
|
||||
let t = Arc::get_mut(t).ok_or(AllocationError::SizeOverflow)?;
|
||||
let tr = tc.rect().intersect(&r);
|
||||
let span = tr.width() as usize * bpp;
|
||||
for y in tr.y0..tr.y1 {
|
||||
let src = (((y - r.y0) as usize) * w + (tr.x0 - r.x0) as usize) * bpp;
|
||||
let dst = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (tr.x0 - tc.tx * TILE_SIZE) as usize) * bpp;
|
||||
let (Some(d), Some(s)) = (t.data.get_mut(dst..dst + span), bytes.get(src..src + span)) else { return Err(AllocationError::SizeOverflow) };
|
||||
d.copy_from_slice(s);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The tiles of an interleaved write, on all cores: each writes only its own bytes.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn copy_tiles(tiles: &mut [(TileCoord, Arc<Tile>)], r: Rect, bytes: &[u8], w: usize, bpp: usize) -> Result<(), AllocationError> {
|
||||
use rayon::prelude::*;
|
||||
tiles.par_iter_mut().try_for_each(|(tc, t)| copy_tile(*tc, t, r, bytes, w, bpp))
|
||||
}
|
||||
|
||||
/// Serial counterpart, for the web build.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn copy_tiles(tiles: &mut [(TileCoord, Arc<Tile>)], r: Rect, bytes: &[u8], w: usize, bpp: usize) -> Result<(), AllocationError> {
|
||||
tiles.iter_mut().try_for_each(|(tc, t)| copy_tile(*tc, t, r, bytes, w, bpp))
|
||||
}
|
||||
|
||||
impl Surface {
|
||||
/// Reads a region into a newly allocated buffer, returning an error instead of aborting if
|
||||
/// the requested pixel buffer cannot be represented or reserved.
|
||||
@@ -815,6 +846,25 @@ impl Surface {
|
||||
}
|
||||
}
|
||||
|
||||
/// Fallible counterpart to [`Surface::write_interleaved`], writing the tiles on all cores
|
||||
/// (native targets): a length that doesn't match `r` is an error, not a panic, and a tile that
|
||||
/// can't be allocated stops the write with [`AllocationError::NotEnoughMemory`] (the tiles
|
||||
/// written so far keep their new pixels).
|
||||
///
|
||||
/// This enters Rayon, as [`Surface::write_region_par`] does.
|
||||
pub fn try_write_interleaved(&mut self, r: Rect, bytes: &[u8]) -> Result<(), AllocationError> {
|
||||
let bpp = self.format.bytes_per_pixel();
|
||||
let w = r.width() as usize;
|
||||
let expected = w.checked_mul(r.height() as usize).and_then(|v| v.checked_mul(bpp)).ok_or(AllocationError::SizeOverflow)?;
|
||||
if bytes.len() != expected {
|
||||
return Err(AllocationError::SizeOverflow);
|
||||
}
|
||||
let mut tiles = self.try_take_tiles(r)?;
|
||||
let written = copy_tiles(&mut tiles, r, bytes, w, bpp);
|
||||
self.put_tiles(tiles);
|
||||
written
|
||||
}
|
||||
|
||||
/// Read `r` as interleaved encoded bytes in the surface's format.
|
||||
pub fn to_interleaved(&self, r: Rect) -> Vec<u8> {
|
||||
let bpp = self.format.bytes_per_pixel();
|
||||
@@ -1510,6 +1560,29 @@ mod tests {
|
||||
assert_eq!(surface, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fallible_interleaved_write_matches_the_infallible_one_and_rejects_bad_lengths() {
|
||||
for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F] {
|
||||
// Across tile edges, at a negative origin.
|
||||
let r = Rect::new(-3, 250, 300, 517);
|
||||
let bytes: Vec<u8> = (0..r.width() as usize * r.height() as usize * fmt.bytes_per_pixel()).map(|i| (i * 31 % 251) as u8).collect();
|
||||
let mut a = Surface::new(fmt);
|
||||
a.write_interleaved(r, &bytes);
|
||||
let mut b = Surface::new(fmt);
|
||||
b.try_write_interleaved(r, &bytes).unwrap();
|
||||
assert_eq!(a, b);
|
||||
let before = b.clone();
|
||||
assert_eq!(b.try_write_interleaved(r, &bytes[1..]), Err(AllocationError::SizeOverflow));
|
||||
assert_eq!(b, before);
|
||||
// Tiles an undo snapshot shares are copied, not written through.
|
||||
let again: Vec<u8> = bytes.iter().map(|v| v ^ 0x5a).collect();
|
||||
b.try_write_interleaved(r, &again).unwrap();
|
||||
a.write_interleaved(r, &again);
|
||||
assert_eq!(a, b);
|
||||
assert_eq!(before.to_interleaved(r), bytes);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fallible_tile_edits_move_weakly_cached_pixels_and_copy_shared_pixels() {
|
||||
for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F] {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# File-format parity
|
||||
|
||||
> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-15 · **Change:** minor (Photoshop mixed-order TIFF type geometry, #4758; DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); PSD smart filters: 45 filters (31 more: Blur, Surface Blur, Smart Sharpen, Diffuse, Wind, Offset, Mezzotint, Clouds, Difference Clouds, Fibers, Lens Flare and others) plus Hue/Saturation and Perspective Warp mapped both ways, #6296, #6298, #6300, #6302, #6304, #6314, #6316, #6267, #6268, FILE-215-2; large-file fixtures: a 20 MP layered PSD, a 150-layer layout, a 2 GB PSD and a 4.4 GB PSB generated at test time and round-tripped, FILE-216-2 done, #5107; earlier: PNG `sTER` stereo pairing kept on save, #6063; PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; earlier: CMYK Invert, Posterize and Threshold on the inks; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026
|
||||
> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-22 · **Change:** minor (TIFFs up to 300,000 px a side open, decoded a group of rows at a time into the layer, #8169; earlier: Photoshop mixed-order TIFF type geometry, #4758; DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); PSD smart filters: 45 filters (31 more: Blur, Surface Blur, Smart Sharpen, Diffuse, Wind, Offset, Mezzotint, Clouds, Difference Clouds, Fibers, Lens Flare and others) plus Hue/Saturation and Perspective Warp mapped both ways, #6296, #6298, #6300, #6302, #6304, #6314, #6316, #6267, #6268, FILE-215-2; large-file fixtures: a 20 MP layered PSD, a 150-layer layout, a 2 GB PSD and a 4.4 GB PSB generated at test time and round-tripped, FILE-216-2 done, #5107; earlier: PNG `sTER` stereo pairing kept on save, #6063; PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; earlier: CMYK Invert, Posterize and Threshold on the inks; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026
|
||||
|
||||
Every format Photoshop 2026 (27.11.0) reads or writes, with PhotoCraft's support, fidelity and
|
||||
tests. Photoshop's list comes from its `Info.plist` `CFBundleDocumentTypes`, the PiPL read/write
|
||||
@@ -24,7 +24,7 @@ XL are missing (gap G10). Remaining: 300–500 h including PSD fidelity.
|
||||
| PSD | R/W | yes | yes | 1/8/16/32-bit; Bitmap, Gray, Indexed, RGB, CMYK, Multichannel, Lab, Duotone; layers, groups, masks, vector masks, adjustment and fill layers, effects, text, shapes, smart objects (SoLd/lnk2; CS2 PlLd/lnkD read with their warp, kept as is or re-saved as SoLd once edited), smart filters (45 mapped, among them Clouds, Difference Clouds, Fibers and Lens Flare, plus Hue/Saturation, Perspective Warp, Filter Gallery with Chrome and a Camera Raw subset, rest verbatim), slices, comps, Advanced Blending. Oracle floors: Photoshop-authored 188/258, io 148/170, psd-tools 249/309; round trip ≥ 169/170, 308/309, 258/256. Known failures: #1281, #2469 (#2374, text layers, closed 2026-10-10; #2465, CS2 `PlLd`-only smart objects, fixed 2026-10-12) |
|
||||
| PSB | R/W | yes | yes | Auto-switches above 2 GB (REL-212-2); generated 20 MP, 150-layer, 2 GB PSD and 4.4 GB PSB fixtures opened, saved and re-opened by io tests/large_files.rs (FILE-216-2, 2026-10-13; the 4.4 GB PSB opens on Windows); > 4 GB from the app's File › Open on Windows: #375 |
|
||||
| Cloud PSD (.psdc) | R/W | no | no | Out of scope (Adobe cloud) |
|
||||
| TIFF | R/W | yes | yes | 8/16/32f, Gray/RGB/CMYK, BigTIFF, every IFD, banded parallel decode; layered TIFF both byte orders, including Photoshop mixed-order type blocks (#4758); undecodable type keeps saved pixels (FILE-215-7: extra alpha channels not written) |
|
||||
| TIFF | R/W | yes | yes | 8/16/32f, Gray/RGB/CMYK, BigTIFF, every IFD, banded parallel decode; flat pages up to 300,000 px a side (Photoshop's limit) open a group of rows at a time into the layer, with no full-size copy (#8169); layered TIFF both byte orders, including Photoshop mixed-order type blocks (#4758); undecodable type keeps saved pixels (FILE-215-7: extra alpha channels not written) |
|
||||
| JPEG | R/W | yes | yes | 8-bit Gray/RGB/CMYK, ICC/EXIF/XMP; Save keeps the opened file's quality (estimated from its quantisation tables, #2399); no JPEG Options dialog (quality 0–12, baseline/progressive) (FILE-215-19) |
|
||||
| PNG | R/W | yes | yes | 8/16-bit, ICC/text; APNG first frame only; alpha channels on open (#2225); palette PNGs open in Indexed Color mode with their transparent entry (#4804); Save keeps a stereo PNG's `sTER` pairing (#6063) |
|
||||
| GIF | R/W | yes | yes | File › Open keeps the first frame; New Video Layer from File and Video Frames to Layers take every frame, with the timeline rate from the delays (#572). Per-frame delays and keeping the frames in `.pcraft` are not done |
|
||||
@@ -142,6 +142,7 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-22 | minor | TIFF: flat pages up to 300,000 px a side open (was 2^30 px, about 32,768²): `codecs::TiffBands` decodes a group of rows at a time into the layer's tiles. The 117,504 × 22,464 px banner from #8456 opens in 3.3 s at 11.45 GB peak for a 10.56 GB layer; 30,000² 6.8 s / 6.43 GB → 1.1 s / 3.86 GB; 36 MP 220 → 52 ms. Layered TIFFs still decode whole (#8169) |
|
||||
| 2026-10-15 | minor | PSD smart filters: Clouds, Difference Clouds, Fibers and Lens Flare open as editable filters with their seeds, colours and lens, and save like Photoshop (checked against a Photoshop 27 file); render filters on a smart object work within the object, so a flare sits where Photoshop puts it |
|
||||
| 2026-10-15 | minor | DDS textures save (#1327): uncompressed or BC1/BC2/BC3 (DXT1/3/5) from a clean-room block encoder, optional box-filtered mip chain, legacy header; DDS Options in Save As and Save a Copy, `ddsCompression`/`ddsMipmaps` for scripts, the CLI and MCP |
|
||||
| 2026-10-16 | minor | PSD smart filters: Perspective Warp (`perspectiveWarpTransform`: `vertices`, `warpedVertices`, `quads` of vertex indices, document pixels) opens as `layer.smartObjects.perspectiveWarp`, one plane per quad, and re-renders warped; save writes the original item with only the geometry rewritten, or a new one in Photoshop's layout; inconsistent descriptors stay verbatim (FILE-215-2, #6268) |
|
||||
|
||||
+5
-2
@@ -1,6 +1,6 @@
|
||||
# Where PhotoCraft falls short of Photoshop
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-18 · **Change:** minor (G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed) · **Target:** Adobe Photoshop 2026
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-22 · **Change:** minor (G1: TIFFs over 2^30 px open, up to 300,000 px a side, #8169; G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed) · **Target:** Adobe Photoshop 2026
|
||||
|
||||
Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact
|
||||
on the way to beta. This is the work list agents pick from: take the highest-ranked entry that
|
||||
@@ -52,7 +52,9 @@ what an agent can't finish alone.
|
||||
re-saved unmodified would not reopen (#2374, closed 2026-10-10), Photoshop 26.6 cannot reopen our files (#1281), "PSD not
|
||||
opening in Photoshop" (#2469), a CS2-era smart object unavailable (#2465, fixed 2026-10-12), PSB smart object
|
||||
blank (#1764), perspective placed layers flattened (#579, fixed by #426), PSB > 4 GB fails on Windows (#375; a generated 4.38 GB PSB opens, saves and re-opens
|
||||
through io on Windows, io tests/large_files.rs, 2026-10-13).
|
||||
through io on Windows, io tests/large_files.rs, 2026-10-13), a 117,504 × 22,464 px print TIFF
|
||||
refused at 2^30 px (#8456, #8169; opens since 2026-10-22, decoded a group of rows at a time into
|
||||
the layer; layered TIFFs over the limit and huge PSBs still decode whole).
|
||||
No test opens our exports in a third-party editor (FILE-216-4).
|
||||
- **Impact:** PSD is the format professionals exchange. Beta requires it to be reliable.
|
||||
- **Estimate:** 150–250 h. **Human:** opening exports in Photoshop on the owner's Mac (or a
|
||||
@@ -290,6 +292,7 @@ what an agent can't finish alone.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-22 | minor | G1: flat TIFFs up to 300,000 px a side open (was 2^30 px); the #8456 banner (117,504 × 22,464 px) opens in 3.3 s; 30,000² opens in 1.1 s at 3.86 GB peak (was 6.8 s, 6.43 GB); #8169; no estimate changed |
|
||||
| 2026-10-15 | minor | G1 / #5972 A1: render only provably constant-RGB `GdFl` noise fills; variable noise synthesis remains open |
|
||||
| 2026-10-18 | minor | G9: with no selection, Copy takes fill and adjustment layers whole and Paste recreates them (#2344); UI-217-23 stays partial (a single pixel layer copies its pixels only); estimate unchanged |
|
||||
| 2026-10-15 | minor | G2: a cancelled 24 MP Gaussian Blur job stops within 44 ms max (P25, budget 200 ms; was about 400 ms; local runs, baseline not re-run), the uncancelled job on a locked-transparency layer about 40% faster; #6205 |
|
||||
|
||||
+1
-1
@@ -109,7 +109,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t
|
||||
| FILE-215-5 | Smart Filter rows: collapse, mask thumb, blend icon, drag reorder, context menu, live preview | partial | [#215](https://github.com/storytold/photocraft/issues/215) | smart_ui.rs:31 rows + visibility + editor; no collapse, drag or context menu |
|
||||
| FILE-215-6 | Smart Object corner skew and perspective (quad or homography transform) | done | [#215](https://github.com/storytold/photocraft/issues/215) | #426: SmartObject.perspective holds the projective map (transform keeps its affine approximation); Distort / Perspective on a smart object set it (transform_cmds.rs, smart_cmds::set_placement), it re-renders from the source through the homography, Warp composes with it, and the PSD placement reads and writes nonAffineTransform / Trnf (io/blocks.rs placed_projective, smart_map.rs); tests distort_survives_edit_contents, warp_on_a_distorted_smart_object_follows_the_corners, placement survives the save |
|
||||
| FILE-215-7 | Layered TIFF read and write (tag 37724), honouring the ask-before-saving pref | partial | [#215](https://github.com/storytold/photocraft/issues/215) | psd tiff.rs (ImageSourceData, both byte orders), io tiff_layers.rs, ui tiff_options_ui.rs (Discard Layers and Save a Copy); extra alpha channels and a Quick Mask are not written (the TIFF codec holds one transparency sample) |
|
||||
| FILE-215-8 | Large and BigTIFF import with banded decode across all IFDs | done | [#215](https://github.com/storytold/photocraft/issues/215) | codecs tiff_ifd.rs (bounds-checked IFD chain + SubIFD walk, classic and BigTIFF, cycle-safe; tiff_info / decode_tiff_page), tiff.rs banded parallel strip/tile decode, planar 1 and 2, BigTIFF write (tiff_bigtiff or > 4 GiB); io import_tiff_page; 30 MP RGB8 Deflate 345 -> 32 ms; no page picker in the UI yet |
|
||||
| FILE-215-8 | Large and BigTIFF import with banded decode across all IFDs | done | [#215](https://github.com/storytold/photocraft/issues/215) | codecs tiff_ifd.rs (bounds-checked IFD chain + SubIFD walk, classic and BigTIFF, cycle-safe; tiff_info / decode_tiff_page), tiff.rs banded parallel strip/tile decode, planar 1 and 2, BigTIFF write (tiff_bigtiff or > 4 GiB); io import_tiff_page; 30 MP RGB8 Deflate 345 -> 32 ms; flat pages up to 300000 px a side decode a group of rows at a time into the layer (codecs TiffBands, #8169): the 117504 x 22464 px banner from #8456 opens in 3.3 s at 11.45 GB peak; layered TIFFs still decode whole; no page picker in the UI yet |
|
||||
| FILE-215-9 | SVG opens and places as shape layers or a vector Smart Object | done | [#215](https://github.com/storytold/photocraft/issues/215) | io svg.rs: paths, groups, text outlines as shape layers (gradients approximated; clip/mask/filter/pattern/image subtrees rasterised); smart_cmds.rs renders an SVG source at its placement scale |
|
||||
| FILE-215-10 | Multi-page PDF save, PDF presentation, layer comps to PDF, vector/text output, PDF import | partial | [#215](https://github.com/storytold/photocraft/issues/215) | io pdf.rs: Save As / Save a Copy / CLI write one flattened RGB/Gray/CMYK page with ICC (#3401); print PDFs in print_cmds. Multi-page save, presentation, comps, vector/text output and PDF import (#2541) remain |
|
||||
| FILE-215-11 | RAW: lossy DNG, highlight modes, .xmp sidecars, RAW prefs wired, per-camera corpus | missing | [#215](https://github.com/storytold/photocraft/issues/215) | raw sensor.rs:210 lossy DNG unsupported; raw_defaults unread; no xmp |
|
||||
|
||||
@@ -59,7 +59,7 @@ id = "FILE-215-8"
|
||||
target = "Large and BigTIFF import with banded decode across all IFDs"
|
||||
status = "done"
|
||||
issue = 215
|
||||
note = "codecs tiff_ifd.rs (bounds-checked IFD chain + SubIFD walk, classic and BigTIFF, cycle-safe; tiff_info / decode_tiff_page), tiff.rs banded parallel strip/tile decode, planar 1 and 2, BigTIFF write (tiff_bigtiff or > 4 GiB); io import_tiff_page; 30 MP RGB8 Deflate 345 -> 32 ms; no page picker in the UI yet"
|
||||
note = "codecs tiff_ifd.rs (bounds-checked IFD chain + SubIFD walk, classic and BigTIFF, cycle-safe; tiff_info / decode_tiff_page), tiff.rs banded parallel strip/tile decode, planar 1 and 2, BigTIFF write (tiff_bigtiff or > 4 GiB); io import_tiff_page; 30 MP RGB8 Deflate 345 -> 32 ms; flat pages up to 300000 px a side decode a group of rows at a time into the layer (codecs TiffBands, #8169): the 117504 x 22464 px banner from #8456 opens in 3.3 s at 11.45 GB peak; layered TIFFs still decode whole; no page picker in the UI yet"
|
||||
|
||||
[[item]]
|
||||
id = "FILE-215-9"
|
||||
|
||||
Reference in new issue
Block a user