PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Layered TIFF: write PSD-style layer data unless a length overflows (Photoshop opened only the composite) (#5514)
llduyll10d5c7edacdf5c
diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rsindex 345406740..57e30380c 100644--- a/crates/io/src/psd_export.rs+++ b/crates/io/src/psd_export.rs@@ -29,6 +29,12 @@ const PSD_ESTIMATE_LAYER_OVERHEAD: u64 = 64 * 1024;pub struct PsdExportOptions {/// Write PSB even when the document fits PSD limits.pub force_psb: bool,+ /// Switch to PSB when the estimated encoded size exceeds PSD's 2 GB limit. The estimate+ /// counts every layer plane uncompressed, so a document with many canvas-sized layers can+ /// pass it while its real file is far smaller. A writer that can measure the real size+ /// instead turns this off: the layered TIFF writes PSD-style layer data and falls back to+ /// PSB only when a length really overflows 32 bits.+ pub size_limit_psb: bool,/// Matte the merged image against white where it is translucent, as Photoshop does/// (`false` keeps straight colour under the alpha: for containers that store the composite/// with its own alpha, such as a layered TIFF).@@ -48,7 +54,14 @@ pub struct PsdExportOptions {impl Default for PsdExportOptions {fn default() -> Self {- PsdExportOptions { force_psb: false, merged_matte: true, merged_compression: Compression::Rle, maximize_compatibility: true, document_path: None }+ PsdExportOptions {+ force_psb: false,+ size_limit_psb: true,+ merged_matte: true,+ merged_compression: Compression::Rle,+ maximize_compatibility: true,+ document_path: None,+ }}}@@ -1522,7 +1535,7 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, clet sample = fmt.sample;let cc = fmt.mode.color_channels();let big = doc.size.width > 30_000 || doc.size.height > 30_000;- let size_exceeds_limit = !opts.force_psb && !big && psd_size_exceeds_limit(doc);+ let size_exceeds_limit = opts.size_limit_psb && !opts.force_psb && !big && psd_size_exceeds_limit(doc);let version = psd_version(doc, opts.force_psb, size_exceeds_limit);let mut ex = Ex {fmt,diff --git a/crates/io/src/tiff_layers.rs b/crates/io/src/tiff_layers.rsindex 628517b6f..7da61fa46 100644--- a/crates/io/src/tiff_layers.rs+++ b/crates/io/src/tiff_layers.rs@@ -202,19 +202,38 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocrlet big = doc.size.width > 30_000 || doc.size.height > 30_000;// The PSD exporter renders the composite we need for the TIFF itself: unmatted (the TIFF// keeps straight alpha) and uncompressed (its planes are interleaved below).+ // Layer data is written PSD-style ("Adobe Photoshop Document Data Block", 4-byte lengths), as+ // Photoshop writes it: Photoshop does not read the PSB-style header ("... Data V0002") in a+ // TIFF and opens only the composite, as one locked Background. The exporter's size estimate+ // counts layer planes uncompressed, so a document with many canvas-sized layers passes 2 GB+ // while its real layer data is a small fraction of that; it is not used here. PSB-style data+ // is written only past 30000 px, when asked for, or when a length really overflows 32 bits.+ let force_psb = opts.force_psb || big;let psd_opts = PsdExportOptions {- force_psb: opts.force_psb || big,+ force_psb,+ size_limit_psb: false,merged_matte: false,merged_compression: Compression::Raw,maximize_compatibility: true,document_path: opts.document_path.clone(),};- let (file, w) = crate::with_span(ctl, 0.0, TIFF_MODEL_DONE, |ctl| crate::psd_export::document_to_psd_interruptible(doc, &psd_opts, ctl));+ let (mut file, w) = crate::with_span(ctl, 0.0, TIFF_MODEL_DONE, |ctl| crate::psd_export::document_to_psd_interruptible(doc, &psd_opts, ctl));// A cancelled conversion stops early with an incomplete model: never encode it.ctl.check().map_err(|_| IoError::Cancelled)?;warnings.extend(w);let order = if codecs::tiff_writes_little_endian() { ByteOrder::Little } else { ByteOrder::Big };- let (layers, w) = ImageSourceData::from_psd(&file).to_bytes(order)?;+ let (layers, w) = match ImageSourceData::from_psd(&file).to_bytes(order) {+ Err(photocraft_psd::PsdError::LimitExceeded(_)) if !force_psb => {+ let psb_opts = PsdExportOptions { force_psb: true, ..psd_opts };+ let (psb, w) = crate::with_span(ctl, 0.0, TIFF_MODEL_DONE, |ctl| crate::psd_export::document_to_psd_interruptible(doc, &psb_opts, ctl));+ ctl.check().map_err(|_| IoError::Cancelled)?;+ warnings.extend(w);+ warnings.push("layer data exceeds 4 GB; written with PSB-sized lengths, which some readers do not open".into());+ file = psb;+ ImageSourceData::from_psd(&file).to_bytes(order)?+ }+ r => r?,+ };ctl.check().map_err(|_| IoError::Cancelled)?;ctl.progress(TIFF_LAYERS_DONE);warnings.extend(w.into_iter().map(|w| format!("layer data: {w}")));@@ -284,3 +303,54 @@ pub fn strip_foreign_order_blocks(file: &mut photocraft_psd::PsdFile) -> Vec<Strstrip(&mut file.global_blocks, "document");warnings}++#[cfg(test)]+mod tests {+ use photocraft_doc::{Color, Document, Fill, FillCache, Layer, LayerContent};+ use photocraft_raster::Surface;++ use crate::{ExportOptions, export};++ /// Hidden solid fills on a 2048² canvas: the PSD size estimate counts each one as a+ /// canvas-sized plane (16 MiB at 8 bits), so 140 of them pass 2 GB, while their real pixels+ /// (the cached rendering, pruned to nothing) take almost no space. A layered TIFF of such a+ /// document must still carry PSD-style layer data: Photoshop does not read the PSB-style+ /// header in a TIFF and opens only the composite, as one locked Background.+ fn many_cheap_fills() -> Document {+ let mut doc = Document::new("many fills", photocraft_geom::Size::new(2048, 2048), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8);+ for i in 0..140 {+ let fill = Fill::Solid(Color::rgb(0.5, 0.25, 0.75));+ let mut l = Layer::new(format!("Fill {i}"), LayerContent::Fill(fill.clone()));+ l.visible = false;+ l.fill_cache = Some(FillCache { fill, surface: Surface::new(doc.pixel_format()) });+ doc.layers.push(l);+ }+ doc+ }++ #[test]+ fn layered_tiff_ignores_the_uncompressed_size_estimate() {+ let doc = many_cheap_fills();+ assert!(crate::psd_export::psd_size_exceeds_limit(&doc), "the fixture must pass the 2 GB estimate");++ let r = export(&doc, "x.tif", &ExportOptions { tiff_layers: true, ..Default::default() }).unwrap();+ let (_, layers) = photocraft_codecs::tiff_photoshop_tags(&r.bytes);+ let layers = layers.unwrap();+ assert!(layers.starts_with(photocraft_psd::tiff::SIGNATURE), "{:?}", String::from_utf8_lossy(&layers[..36.min(layers.len())]));+ assert!(!r.warnings.iter().any(|w| w.contains("PSB")), "{:?}", r.warnings);+ let back = crate::import("x.tif", &r.bytes).unwrap().document;+ assert_eq!(back.layers.len(), doc.layers.len());++ // A .psd save still switches to PSB on the estimate, as before.+ let psd = export(&doc, "x.psd", &ExportOptions::default()).unwrap();+ assert_eq!(psd.bytes.get(4..6), Some(&[0u8, 2][..]), "PSD saves keep the size-estimate switch");+ }++ #[test]+ fn forcing_psb_still_writes_psb_style_layer_data() {+ let doc = many_cheap_fills();+ let r = export(&doc, "x.tif", &ExportOptions { tiff_layers: true, force_psb: true, ..Default::default() }).unwrap();+ let (_, layers) = photocraft_codecs::tiff_photoshop_tags(&r.bytes);+ assert!(layers.unwrap().starts_with(photocraft_psd::tiff::SIGNATURE_PSB));+ }+}