From ec6a4c1a50327a3424daf7280496d5b3df31cd54 Mon Sep 17 00:00:00 2001 From: zuujiscom Date: Wed, 21 Oct 2026 08:09:59 +0530 Subject: [PATCH] Save: stop doubling the encoded file in memory (#6607) Saving needed about 4x the file's size in extra RAM: the whole encoded file was buffered in memory before it hit the disk. Now PSD/PSB and layered TIFF stream into the destination as they are encoded. - format: atomic_write_stream_progress hands the encoder a writer that goes through the temp file, so bytes are freed as they are written; ZipWriter reserves the estimate only where output can exceed it, and gives back the unused part of a reserved buffer after compressing. - psd: PsdFile::save streams layer by layer (ImageSourceData::take_from_psd moves rather than copies), and the TIFF encoder writes rows out as they are compressed instead of holding the uncompressed plane. - io/codecs: layered TIFF export streams the interleaved composite, the app's save and export paths pass a progress callback through the stream. A 24 MB PSD/PSB or layered TIFF now saves with a few MB of working set instead of a second copy of the file; on wasm32 the memory is returned, on Windows it is no longer counted as committed. Co-Authored-By: Claude Opus 5.5 --- apps/photocraft/src/services.rs | 60 +++++++-- crates/codecs/src/codecs/tiff.rs | 22 ++- crates/codecs/tests/roundtrip.rs | 14 ++ crates/format/src/atomic.rs | 96 +++++++++++++- crates/format/src/atomic/tests.rs | 93 +++++++++++++ crates/format/src/lib.rs | 2 +- crates/format/src/store.rs | 12 +- crates/format/src/zip.rs | 60 +++++++++ crates/io/src/lib.rs | 95 +++++++++++-- crates/io/src/psd_export.rs | 43 +++++- crates/io/src/tiff_layers.rs | 11 +- crates/io/tests/export_progress.rs | 21 +++ crates/psd/src/compression.rs | 118 ++++++++++------- crates/psd/src/error.rs | 17 +++ crates/psd/src/file.rs | 206 ++++++++++++++++++++++++----- crates/psd/src/io.rs | 117 ++++++++++++++++ crates/psd/src/layer.rs | 101 ++++++++++---- crates/psd/src/tagged.rs | 25 +++- crates/psd/src/tiff.rs | 128 ++++++++++++++++-- 19 files changed, 1087 insertions(+), 154 deletions(-) diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index 999952f186..0bf5d86d71 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -324,9 +324,15 @@ fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), String> { photocraft_format::atomic_write(path, bytes).map_err(|e| e.to_string()) } -/// [`write_atomic`] reporting the fraction written (a background save's progress, #3389). -fn write_atomic_progress(path: &Path, bytes: &[u8], progress: &dyn Fn(f32)) -> Result<(), String> { - photocraft_format::atomic_write_progress(path, bytes, progress).map_err(|e| e.to_string()) +/// [`write_atomic`] for an encoded save, reporting the fraction written (a background save's +/// progress, #3389). A PSD/PSB is serialized straight into the temporary file, so the whole file +/// is never held in memory next to its model (#6607). +fn write_encoded_atomic(path: &Path, encoded: &photocraft_io::Encoded, progress: &dyn Fn(f32)) -> Result<(), String> { + match encoded { + photocraft_io::Encoded::Bytes(bytes) => photocraft_format::atomic_write_progress(path, bytes, progress), + photocraft_io::Encoded::Psd(_) => photocraft_format::atomic_write_stream_progress(path, encoded.len_hint(), progress, &mut |w| encoded.write_to(w)), + } + .map_err(|e| e.to_string()) } fn export_options(settings: &photocraft_ui_egui::ExportSettings) -> photocraft_io::ExportOptions { @@ -338,26 +344,26 @@ fn export_options(settings: &photocraft_ui_egui::ExportSettings) -> photocraft_i const ENCODE_SHARE: f32 = 0.85; /// A save on a worker thread (`Services::save_file` and `Services::automation_save`, #2017): -/// encode, then write through `write`. Cancelling while encoding leaves the target untouched; -/// once writing starts the save can't be cancelled. The encoder's progress fills the first +/// encode, then write through `write` (a PSD/PSB is serialized as it is written). Cancelling +/// while encoding leaves the target untouched; once writing starts the save can't be cancelled. The encoder's progress fills the first /// [`ENCODE_SHARE`] of the job's progress, so the status bar and tab read "Saving NN%" (#3389). fn save_through( doc: &Document, path: &str, settings: &photocraft_ui_egui::ExportSettings, ctl: &photocraft_ui_egui::jobs_ui::SaveCtl, - write: impl Fn(&str, &[u8], &dyn Fn(f32)) -> Result<(), String>, + write: impl Fn(&str, &photocraft_io::Encoded, &dyn Fn(f32)) -> Result<(), String>, ) -> Result, String> { ctl.progress(0.0, "Encoding"); let opts = export_options(settings); let cancelled = || ctl.check().is_err(); let progress = |f: f32| ctl.progress(f * ENCODE_SHARE, ""); let interrupt = photocraft_raster::Interrupt::new(&cancelled, &progress); - let r = crate::crash_guard::guard("Save", || photocraft_io::export_with(doc, path, &opts, &interrupt).map_err(|e| e.to_string()))?; + let r = crate::crash_guard::guard("Save", || photocraft_io::encode_with(doc, path, &opts, &interrupt).map_err(|e| e.to_string()))?; ctl.commit()?; ctl.progress(ENCODE_SHARE, "Writing"); // The last bit is the flush and rename after the last chunk: 100% only once they're done. - write(path, &r.bytes, &|f| ctl.progress(ENCODE_SHARE + (0.99 - ENCODE_SHARE) * f, ""))?; + write(path, &r.encoded, &|f| ctl.progress(ENCODE_SHARE + (0.99 - ENCODE_SHARE) * f, ""))?; ctl.progress(1.0, ""); Ok(r.warnings) } @@ -368,7 +374,7 @@ fn save_file( settings: &photocraft_ui_egui::ExportSettings, ctl: &photocraft_ui_egui::jobs_ui::SaveCtl, ) -> Result, String> { - save_through(doc, path, settings, ctl, |p, b, progress| write_atomic_progress(Path::new(p), b, progress)) + save_through(doc, path, settings, ctl, |p, encoded, progress| write_encoded_atomic(Path::new(p), encoded, progress)) } type SharedRecovery = Rc>>; @@ -515,7 +521,7 @@ pub fn native(automation: Option) -> }); let automation_save = automation.clone().map(|workspace| { std::sync::Arc::new(move |doc: &Document, path: &str, settings: &photocraft_ui_egui::ExportSettings, ctl: &photocraft_ui_egui::jobs_ui::SaveCtl| { - save_through(doc, path, settings, ctl, |p, b, _| workspace.write(p, b).map_err(|e| e.to_string())) + save_through(doc, path, settings, ctl, |p, encoded, _| workspace.write(p, &encoded.bytes().map_err(|e| e.to_string())?).map_err(|e| e.to_string())) }) as photocraft_ui_egui::SaveFileFn }); let step: fn(&str, &serde_json::Value) -> photocraft_engine::Result<()> = photocraft_automation::workspace::authorize_desktop_engine_step; @@ -713,6 +719,40 @@ mod tests { use photocraft_ui_egui::{PhotocraftApp, prefs_ui}; use serde_json::{Value, json}; + /// #6607: a PSD/PSB save streams the file model into the temporary file, which then holds + /// exactly the exported bytes; a serializer error halfway leaves the old file and no + /// temporary file behind. + #[test] + fn a_psd_save_streams_the_exported_bytes_and_keeps_the_old_file_on_error() { + let dir = temp("stream"); + let mut doc = Document::new("streamed", Size::new(64, 48), ColorMode::Rgb, SampleType::U8); + let fmt = doc.pixel_format(); + let px: Vec = (0..64 * 48 * fmt.bytes_per_pixel()).map(|i| (i * 7 % 251) as u8).collect(); + doc.layers.push(Layer::new("A", photocraft_doc::LayerContent::Raster(photocraft_raster::Surface::from_interleaved(fmt, doc.bounds(), &px)))); + let opts = photocraft_io::ExportOptions::default(); + for name in ["a.psd", "a.psb"] { + let path = dir.join(name); + std::fs::write(&path, b"old").unwrap(); + let want = photocraft_io::export(&doc, name, &opts).unwrap().bytes; + let r = photocraft_io::encode_with(&doc, name, &opts, &photocraft_raster::Interrupt::NONE).unwrap(); + let photocraft_io::Encoded::Psd(mut file) = r.encoded else { panic!("{name}: not streamed") }; + let seen = std::cell::RefCell::new(Vec::new()); + write_encoded_atomic(&path, &photocraft_io::Encoded::Psd(file.clone()), &|f| seen.borrow_mut().push(f)).unwrap(); + assert!(std::fs::read(&path).unwrap() == want, "{name}: the saved file differs from the export"); + assert_eq!(seen.borrow().last().copied(), Some(1.0), "{name}"); + + let info = file.layer_info.as_mut().unwrap(); + let layer = info.layers[0].clone(); + info.layers = vec![layer; 32768]; + let e = write_encoded_atomic(&path, &photocraft_io::Encoded::Psd(file), &|_| {}).unwrap_err(); + assert!(e.contains("32767") && e.contains("not changed"), "{name}: {e}"); + assert!(std::fs::read(&path).unwrap() == want, "{name}: a failed save replaced the file"); + let temps: Vec<_> = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name()).filter(|n| n.to_string_lossy().ends_with(".tmp")).collect(); + assert!(temps.is_empty(), "{name}: left behind {temps:?}"); + } + let _ = std::fs::remove_dir_all(&dir); + } + /// #6121: the file type picked in the save dialog gives the name its extension where the /// dialog left the one it opened with, and only there. #[test] diff --git a/crates/codecs/src/codecs/tiff.rs b/crates/codecs/src/codecs/tiff.rs index 9528fec9c8..be096a35b8 100644 --- a/crates/codecs/src/codecs/tiff.rs +++ b/crates/codecs/src/codecs/tiff.rs @@ -1241,8 +1241,18 @@ pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result tiff::TiffResult> { - let mut cursor = Cursor::new(Vec::new()); + // An uncompressed file is allocated once at its estimated size: grown as written, the + // buffer would double near the end and copy the file (#6607). Compressed output is + // usually a fraction of the estimate, so it grows as written instead: reserving the + // estimate would hold a second full-size buffer while encoding, which wasm32 never + // returns and Windows counts as committed memory. + let mut out = Vec::new(); + if matches!(opts.tiff_compression, TiffCompression::None) { + let _ = out.try_reserve(usize::try_from(estimate).unwrap_or(usize::MAX)); + } + let mut cursor = Cursor::new(out); if big { let mut enc = TiffEncoder::new_big(&mut cursor)?.with_compression(compression).with_predictor(predictor); write_image::(&mut enc, &img, &tags)?; @@ -1250,9 +1260,15 @@ pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result(&mut enc, &img, &tags)?; } - Ok(cursor.into_inner()) + // Growth (or an estimate that was too high) can leave spare capacity: give it back + // instead of holding it while the file is saved. + let mut out = cursor.into_inner(); + if out.capacity() - out.len() > out.len() / 8 { + out.shrink_to_fit(); + } + Ok(out) }; - let big = opts.tiff_bigtiff || estimated_size(&img, &tags) > CLASSIC_LIMIT; + let big = opts.tiff_bigtiff || estimate > CLASSIC_LIMIT; match write(big) { Ok(v) => Ok(v), Err(tiff::TiffError::IntSizeError) if !big => write(true).map_err(|e| CodecError::encode(F, e)), diff --git a/crates/codecs/tests/roundtrip.rs b/crates/codecs/tests/roundtrip.rs index 9c6cb8cb6f..7338719e21 100644 --- a/crates/codecs/tests/roundtrip.rs +++ b/crates/codecs/tests/roundtrip.rs @@ -213,6 +213,20 @@ fn tiff_all_compressions_lossless() { } } +#[test] +fn compressed_tiff_does_not_keep_the_uncompressed_reservation() { + // The encoder reserves the uncompressed size up front (#6607). A smooth image compresses + // to a fraction of it, and the returned file must not hold the rest. + let (w, h) = (512u32, 512u32); + let px: Vec = (0..h).flat_map(|y| (0..w).flat_map(move |x| [(x / 2) as u8, (y / 2) as u8, 128])).collect(); + let img = Image::from_u8(w, h, ChannelLayout::Rgb, px).unwrap(); + for comp in [TiffCompression::Lzw, TiffCompression::Deflate] { + let v = encode(&img, Format::Tiff, &EncodeOptions { tiff_compression: comp, ..Default::default() }).unwrap(); + assert!(v.len() < img.data().len() / 2, "{comp:?}: the image should compress well ({} bytes)", v.len()); + assert!(v.capacity() - v.len() <= v.len() / 8, "{comp:?}: {} bytes kept for a {} byte file", v.capacity(), v.len()); + } +} + #[test] fn png_all_compressions_lossless() { let img = test_image(ChannelLayout::Rgba, SampleType::U16); diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index 3a4aeca6c0..4581b8486d 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -34,7 +34,7 @@ pub mod meta; -use std::io::{self, Write}; +use std::io::{self, Seek, Write}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; @@ -55,6 +55,15 @@ pub trait AtomicFs { let _ = progress; self.write_new(tmp, bytes) } + /// Create `tmp` (it must not exist), let `write` fill it as it serializes, and flush it + /// ([`sync_file`]). By default the bytes are collected in memory and handed to + /// [`write_new`](Self::write_new) (test doubles); [`RealFs`] streams them into the file, so the + /// whole file never sits in memory (#6607). + fn write_new_stream(&self, tmp: &Path, write: &mut StreamWriter<'_>) -> io::Result<()> { + let mut bytes = io::Cursor::new(Vec::new()); + write(&mut bytes)?; + self.write_new(tmp, bytes.get_ref()) + } /// Rename `from` over `to`, replacing it. fn rename(&self, from: &Path, to: &Path) -> io::Result<()>; /// Remove a (temporary) file. @@ -73,6 +82,13 @@ pub trait AtomicFs { } } +/// A stream [`atomic_write_stream`]'s writer fills: the temporary file (or, in tests, memory). +pub trait WriteSeek: Write + Seek {} +impl WriteSeek for T {} + +/// Fills the temporary file of a streaming atomic write, starting at its beginning. +pub type StreamWriter<'a> = dyn FnMut(&mut dyn WriteSeek) -> io::Result<()> + 'a; + /// The real file system. #[derive(Debug, Clone, Copy, Default)] pub struct RealFs; @@ -94,6 +110,13 @@ impl AtomicFs for RealFs { } sync_file(&f) } + fn write_new_stream(&self, tmp: &Path, write: &mut StreamWriter<'_>) -> io::Result<()> { + let f = std::fs::OpenOptions::new().write(true).create_new(true).open(tmp)?; + let mut out = io::BufWriter::new(f); + write(&mut out)?; + let f = out.into_inner().map_err(io::IntoInnerError::into_error)?; + sync_file(&f) + } fn rename(&self, from: &Path, to: &Path) -> io::Result<()> { std::fs::rename(from, to) } @@ -191,6 +214,75 @@ pub fn atomic_write_with(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, byt /// [`atomic_write_with`] reporting write progress (see [`atomic_write_progress`]). pub fn atomic_write_with_progress(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, bytes: &[u8], progress: &dyn Fn(f32)) -> io::Result<()> { + replace_with(fs, retry, path, &mut |tmp| fs.write_new_progress(tmp, bytes, progress)) +} + +/// [`atomic_write`] for a file serialized as it is written (#6607): `write` fills the temporary +/// file beside `path` from its start (it may seek back to patch lengths), then the file is +/// flushed and renamed over `path` with [`atomic_write`]'s retries and errors. If `write` fails, +/// the temporary file is removed and `path` is left as it was. `write` runs once (again only if +/// a temporary name collided before anything was written). +pub fn atomic_write_stream(path: &Path, write: &mut StreamWriter<'_>) -> io::Result<()> { + atomic_write_stream_with(&RealFs, RenameRetry::platform(), path, write) +} + +/// [`atomic_write_stream`] reporting the fraction written to `progress` as it goes: the furthest +/// position reached over `expected_len` (an estimate; capped below 1.0 until `write` is done). +pub fn atomic_write_stream_progress(path: &Path, expected_len: u64, progress: &dyn Fn(f32), write: &mut StreamWriter<'_>) -> io::Result<()> { + atomic_write_stream_with(&RealFs, RenameRetry::platform(), path, &mut |w| { + let mut counted = Progress { w, pos: 0, reached: 0, reported: 0, expected: expected_len.max(1), progress }; + write(&mut counted)?; + progress(1.0); + Ok(()) + }) +} + +/// [`atomic_write_stream`] through an explicit file system and retry policy. +pub fn atomic_write_stream_with(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, write: &mut StreamWriter<'_>) -> io::Result<()> { + replace_with(fs, retry, path, &mut |tmp| fs.write_new_stream(tmp, write)) +} + +/// A stream reporting how far it has got (see [`atomic_write_stream_progress`]), every +/// [`WRITE_CHUNK`] bytes. +struct Progress<'a, 'p> { + w: &'a mut dyn WriteSeek, + /// Tracked here: asking a buffered file for its position flushes it. + pos: u64, + reached: u64, + reported: u64, + expected: u64, + progress: &'p dyn Fn(f32), +} + +impl Write for Progress<'_, '_> { + fn write(&mut self, b: &[u8]) -> io::Result { + let n = self.w.write(b)?; + self.pos += n as u64; + let at = self.pos; + if at > self.reached { + self.reached = at; + if at - self.reported >= WRITE_CHUNK as u64 { + self.reported = at; + (self.progress)((at as f64 / self.expected as f64).min(0.999) as f32); + } + } + Ok(n) + } + fn flush(&mut self) -> io::Result<()> { + self.w.flush() + } +} + +impl Seek for Progress<'_, '_> { + fn seek(&mut self, to: io::SeekFrom) -> io::Result { + self.pos = self.w.seek(to)?; + Ok(self.pos) + } +} + +/// The steps every atomic write shares: `write_tmp` fills a fresh temporary file beside the +/// target, which is then renamed over it. +fn replace_with(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, write_tmp: &mut dyn FnMut(&Path) -> io::Result<()>) -> io::Result<()> { let target = resolve_symlink(path).map_err(|e| context(e, format!("cannot save {}", path.display())))?; let name = target.file_name().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("{}: not a file path", path.display())))?; let dir = match target.parent() { @@ -207,7 +299,7 @@ pub fn atomic_write_with_progress(fs: &dyn AtomicFs, retry: RenameRetry, path: & let mut tmp = None; for _ in 0..8 { let candidate = dir.join(temp_name(&name.to_string_lossy())); - match fs.write_new_progress(&candidate, bytes, progress) { + match write_tmp(&candidate) { Ok(()) => { tmp = Some(candidate); break; diff --git a/crates/format/src/atomic/tests.rs b/crates/format/src/atomic/tests.rs index d4381705a0..71af1deb00 100644 --- a/crates/format/src/atomic/tests.rs +++ b/crates/format/src/atomic/tests.rs @@ -105,6 +105,99 @@ fn reports_write_progress() { assert_no_temp(&d.0); } +/// Writes "head", a 4-byte placeholder, `len` bytes, then patches the placeholder by seeking back. +fn patched_writer(len: usize) -> impl FnMut(&mut dyn WriteSeek) -> io::Result<()> { + move |w| { + w.write_all(b"head")?; + let at = w.stream_position()?; + w.write_all(&[0; 4])?; + w.write_all(&vec![9u8; len])?; + w.seek(io::SeekFrom::Start(at))?; + w.write_all(&(len as u32).to_be_bytes())?; + w.seek(io::SeekFrom::End(0))?; + Ok(()) + } +} + +fn patched_bytes(len: usize) -> Vec { + let mut v = b"head".to_vec(); + v.extend_from_slice(&(len as u32).to_be_bytes()); + v.extend(std::iter::repeat_n(9u8, len)); + v +} + +/// #6607: a streamed save replaces the file with what its writer wrote, seeks included, and leaves +/// no temporary file. +#[test] +fn streamed_write_replaces_and_creates() { + let d = TempDir::new("stream"); + let p = d.0.join("doc.psd"); + atomic_write_stream(&p, &mut patched_writer(3)).unwrap(); + assert_eq!(std::fs::read(&p).unwrap(), patched_bytes(3)); + atomic_write_stream(&p, &mut patched_writer(100_000)).unwrap(); + assert!(std::fs::read(&p).unwrap() == patched_bytes(100_000)); + assert_no_temp(&d.0); +} + +/// #6607: a writer that fails halfway (a serializer error, a full disk) leaves the original as it +/// was, with the same message as a buffered save. +#[test] +fn streamed_write_failure_halfway_keeps_original() { + let d = TempDir::new("stream-fail"); + let p = d.0.join("doc.psd"); + std::fs::write(&p, ORIGINAL).unwrap(); + let e = atomic_write_stream(&p, &mut |w| { + w.write_all(&[1; 70_000])?; + Err(io::Error::new(io::ErrorKind::StorageFull, "injected: no space left on device")) + }) + .unwrap_err(); + assert_eq!(e.kind(), io::ErrorKind::StorageFull); + assert!(e.to_string().contains("the disk is full") && e.to_string().contains("not changed"), "{e}"); + assert_eq!(std::fs::read(&p).unwrap(), ORIGINAL); + assert_no_temp(&d.0); +} + +/// A streamed save renames like a buffered one: retried while locked, the original kept when the +/// lock outlasts the retries. +#[test] +fn streamed_write_retries_a_locked_rename() { + let d = TempDir::new("stream-locked"); + let p = d.0.join("doc.psd"); + std::fs::write(&p, ORIGINAL).unwrap(); + let fs = Faulty { locked_renames: Cell::new(2), ..Default::default() }; + atomic_write_stream_with(&fs, RenameRetry { attempts: 3, first_delay_ms: 1 }, &p, &mut patched_writer(10)).unwrap(); + assert_eq!(std::fs::read(&p).unwrap(), patched_bytes(10)); + assert_eq!(fs.renames.get(), 3); + let fs = Faulty { locked_renames: Cell::new(10), ..Default::default() }; + let e = atomic_write_stream_with(&fs, RenameRetry { attempts: 1, first_delay_ms: 1 }, &p, &mut patched_writer(20)).unwrap_err(); + assert!(e.to_string().contains("locked"), "{e}"); + assert_eq!(std::fs::read(&p).unwrap(), patched_bytes(10)); + assert_no_temp(&d.0); +} + +/// A streamed save reports the furthest position over the expected length, chunk by chunk, and +/// 1.0 once the writer is done. +#[test] +fn streamed_write_reports_progress() { + let d = TempDir::new("stream-progress"); + let p = d.0.join("big.psd"); + let len = WRITE_CHUNK * 2 + 123; + let seen = std::sync::Mutex::new(Vec::new()); + let mut write = |w: &mut dyn WriteSeek| { + for chunk in patched_bytes(len).chunks(WRITE_CHUNK / 4) { + w.write_all(chunk)?; + } + Ok(()) + }; + atomic_write_stream_progress(&p, len as u64 + 8, &|f| seen.lock().unwrap().push(f), &mut write).unwrap(); + let seen = seen.into_inner().unwrap(); + assert_eq!(seen.len(), 3, "two chunks, then done: {seen:?}"); + assert!(seen.windows(2).all(|w| w[0] < w[1]), "monotonic: {seen:?}"); + assert_eq!(seen.last().copied(), Some(1.0)); + assert!(std::fs::read(&p).unwrap() == patched_bytes(len)); + assert_no_temp(&d.0); +} + #[test] fn creates_missing_parent_folders() { let d = TempDir::new("parent"); diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 0c87720212..5f5187e8fb 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -37,7 +37,7 @@ use std::path::Path; use photocraft_doc::Document; use photocraft_raster::Rgba8Image; -pub use atomic::{atomic_write, atomic_write_progress}; +pub use atomic::{atomic_write, atomic_write_progress, atomic_write_stream, atomic_write_stream_progress}; #[cfg(not(target_arch = "wasm32"))] pub use autosave::RecoveryStore; pub use autosave::{Autosaver, RecoveryEntry, discard_recovery, list_recovery, recover}; diff --git a/crates/format/src/store.rs b/crates/format/src/store.rs index 7da5dd6b53..988e7d29e2 100644 --- a/crates/format/src/store.rs +++ b/crates/format/src/store.rs @@ -771,15 +771,19 @@ impl PcraftWriter { pub fn save_zip(&mut self, doc: &Document, opts: &SaveOptions) -> Result<(Vec, SaveStats)> { let p = self.prepare(doc, opts)?; let mut stats = p.stats; - let mut z = ZipWriter::new(); + // New objects are compressed on all cores first (zstd dominates a full save). + let todo: Vec<(&String, &Object)> = p.objects.iter().filter(|(path, _)| !self.compressed.contains_key(*path)).collect(); + let mut fresh: HashMap<&String, Arc>> = par_compress(&todo)?.into_iter().collect(); + // Every entry's size is known now: the archive is allocated once (#6607). + let sizes = p.objects.keys().map(|path| (path.as_str(), self.compressed.get(path).or_else(|| fresh.get(path)).map_or(0, |d| d.len()))); + let mut z = ZipWriter::for_entries( + std::iter::once((MANIFEST, p.manifest.len())).chain(p.previews.iter().map(|(name, data)| (*name, data.len()))).chain(sizes), + )?; z.add(MANIFEST, &p.manifest)?; for (name, data) in &p.previews { z.add(name, data)?; } let mut next = HashMap::with_capacity(p.objects.len()); - // New objects are compressed on all cores first (zstd dominates a full save). - let todo: Vec<(&String, &Object)> = p.objects.iter().filter(|(path, _)| !self.compressed.contains_key(*path)).collect(); - let mut fresh: HashMap<&String, Arc>> = par_compress(&todo)?.into_iter().collect(); for (path, obj) in &p.objects { let data = match self.compressed.get(path) { Some(d) => { diff --git a/crates/format/src/zip.rs b/crates/format/src/zip.rs index 9ec92c2fba..345194ffe4 100644 --- a/crates/format/src/zip.rs +++ b/crates/format/src/zip.rs @@ -11,6 +11,11 @@ use crate::FormatError; const LOCAL_SIG: u32 = 0x0403_4b50; const CENTRAL_SIG: u32 = 0x0201_4b50; const EOCD_SIG: u32 = 0x0605_4b50; +/// Fixed sizes of a local file header, a central directory entry (both before the name) and the +/// end-of-central-directory record. +const LOCAL_HEADER: usize = 30; +const CENTRAL_HEADER: usize = 46; +const END_RECORD: usize = 22; /// CRC-32 (IEEE), as stored in ZIP headers. pub fn crc32(data: &[u8]) -> u32 { @@ -35,6 +40,35 @@ impl ZipWriter { ZipWriter { out: Vec::new(), central: Vec::new(), count: 0 } } + /// A writer whose output is allocated once for `entries` (name, data length): growing it as + /// entries come in would double the buffer near the end, copying the whole archive (#6607). + /// Fails, before allocating, on entries that [`Self::add`] or [`Self::finish`] would refuse, + /// or when there is not enough memory. + pub fn for_entries<'a>(entries: impl IntoIterator) -> Result { + let (mut out, mut central, mut count) = (0usize, 0usize, 0usize); + for (name, len) in entries { + if u32::try_from(len).is_err() { + return Err(FormatError::Unsupported("zip entry over 4 GiB".into())); + } + out = out.saturating_add(LOCAL_HEADER + name.len()).saturating_add(len); + central = central.saturating_add(CENTRAL_HEADER + name.len()); + count += 1; + } + if count > usize::from(u16::MAX) { + return Err(FormatError::Unsupported("more than 65535 zip entries (ZIP64 not supported)".into())); + } + // The central directory starts where the entries end, at an offset that must fit 32 bits. + if u32::try_from(out).is_err() { + return Err(FormatError::Unsupported("zip over 4 GiB".into())); + } + let no_memory = |_| FormatError::LimitExceeded("not enough memory for the archive".into()); + let mut w = Self::new(); + // Room for the central directory and its end record too: `finish` appends them. + w.out.try_reserve_exact(out.saturating_add(central).saturating_add(END_RECORD)).map_err(no_memory)?; + w.central.try_reserve_exact(central).map_err(no_memory)?; + Ok(w) + } + pub fn add(&mut self, name: &str, data: &[u8]) -> Result<(), FormatError> { if self.count == u16::MAX { return Err(FormatError::Unsupported("more than 65535 zip entries (ZIP64 not supported)".into())); @@ -243,6 +277,32 @@ impl<'a> ZipReader<'a> { mod tests { use super::*; + /// #6607: an archive written through `for_entries` is never reallocated while written. + #[test] + fn an_archive_sized_for_its_entries_fills_its_buffer_exactly() { + let entries: Vec<(String, Vec)> = (0..50).map(|i| (format!("objects/{i:03}.zst"), vec![i as u8; i * 997])).collect(); + let mut z = ZipWriter::for_entries(entries.iter().map(|(n, d)| (n.as_str(), d.len()))).unwrap(); + for (n, d) in &entries { + z.add(n, d).unwrap(); + } + let bytes = z.finish().unwrap(); + assert_eq!(bytes.capacity(), bytes.len()); + let r = ZipReader::new(&bytes).unwrap(); + assert_eq!(r.entries.len(), entries.len()); + assert_eq!(r.read_by_name("objects/049.zst", usize::MAX).unwrap(), entries[49].1); + } + + /// Sizes `add` or `finish` would refuse fail up front, before anything is allocated. + #[test] + fn unsupported_sizes_are_refused_before_reserving() { + let big = u32::MAX as usize; + assert!(matches!(ZipWriter::for_entries([("x", usize::MAX)]), Err(FormatError::Unsupported(_)))); + assert!(matches!(ZipWriter::for_entries([("x", big + 1)]), Err(FormatError::Unsupported(_)))); + assert!(matches!(ZipWriter::for_entries([("a", big / 2), ("b", big / 2 + 1)]), Err(FormatError::Unsupported(_)))); + let names = vec!["n"; usize::from(u16::MAX) + 1]; + assert!(matches!(ZipWriter::for_entries(names.into_iter().map(|n| (n, 0))), Err(FormatError::Unsupported(_)))); + } + #[test] fn crc_known_value() { assert_eq!(crc32(b"123456789"), 0xCBF4_3926); diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 946abfbc75..6843432afb 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -179,6 +179,67 @@ pub struct ExportResult { pub warnings: Vec, } +/// What [`encode_with`] produced: the file's bytes, or for PSD/PSB the file model, which +/// [`Encoded::write_to`] serializes straight into the file, so a save never holds the whole +/// encoded file next to the model (#6607). Either way the bytes are exactly [`export`]'s. +#[derive(Debug, Clone)] +pub enum Encoded { + /// The encoded file. + Bytes(Vec), + /// A PSD/PSB file, serialized when written. + Psd(Box), +} + +impl Encoded { + /// The file's bytes, serializing a PSD/PSB model in memory. + pub fn into_bytes(self) -> Result, IoError> { + match self { + Encoded::Bytes(b) => Ok(b), + Encoded::Psd(file) => Ok(file.to_bytes()?), + } + } + + /// [`Self::into_bytes`] without giving up the model. + pub fn bytes(&self) -> Result, IoError> { + match self { + Encoded::Bytes(b) => Ok(std::borrow::Cow::Borrowed(b)), + Encoded::Psd(file) => Ok(std::borrow::Cow::Owned(file.to_bytes()?)), + } + } + + /// The written length for progress: exact for bytes, an upper bound for PSD/PSB. + pub fn len_hint(&self) -> u64 { + match self { + Encoded::Bytes(b) => b.len() as u64, + Encoded::Psd(file) => file.size_bound() as u64, + } + } + + /// Writes the file into `w` from its current position (PSD/PSB seeks back to patch lengths). + /// A PSD/PSB serializer error comes back as `InvalidData`. + pub fn write_to(&self, w: &mut W) -> std::io::Result<()> { + match self { + Encoded::Bytes(b) => w.write_all(b), + Encoded::Psd(file) => file.write_to(w), + } + } +} + +/// Result of [`encode_with`]. +#[derive(Debug, Clone)] +pub struct EncodedExport { + /// The file, ready to write. + pub encoded: Encoded, + /// Human-readable notes about anything approximated or dropped. + pub warnings: Vec, +} + +impl From for EncodedExport { + fn from(r: ExportResult) -> Self { + EncodedExport { encoded: Encoded::Bytes(r.bytes), warnings: r.warnings } + } +} + /// Which part of the document's XMP packet and free-form text a flat export embeds. /// PSD/PSB always keep XMP; `.pcraft` keeps both. Save As and conversions keep the whole packet, as /// Photoshop's Save As does; Export As starts at `None`, because the packet lists the text of @@ -396,6 +457,18 @@ pub fn export(doc: &Document, name_or_ext: &str, opts: &ExportOptions) -> Result /// layered TIFF, in coarse steps for the other formats) and checks it between stages. A cancelled /// export fails with [`IoError::Cancelled`]; otherwise the bytes are exactly [`export`]'s. pub fn export_with(doc: &Document, name_or_ext: &str, opts: &ExportOptions, ctl: &photocraft_raster::Interrupt) -> Result { + ctl.check().map_err(|_| IoError::Cancelled)?; + let r = export_stages(doc, name_or_ext, opts, ctl)?; + let bytes = r.encoded.into_bytes()?; + ctl.check().map_err(|_| IoError::Cancelled)?; + ctl.progress(1.0); + Ok(ExportResult { bytes, warnings: r.warnings }) +} + +/// [`export_with`] up to the point where the file can be written: PSD/PSB stop at the file model, +/// which [`Encoded::write_to`] serializes into the file as it goes (#6607); every other format is +/// encoded. Reports progress up to `1.0` once the result is ready. +pub fn encode_with(doc: &Document, name_or_ext: &str, opts: &ExportOptions, ctl: &photocraft_raster::Interrupt) -> Result { ctl.check().map_err(|_| IoError::Cancelled)?; let r = export_stages(doc, name_or_ext, opts, ctl)?; ctl.check().map_err(|_| IoError::Cancelled)?; @@ -418,7 +491,7 @@ const PCRAFT_PREVIEWS_DONE: f32 = 0.4; /// before its bytes are assembled: about 2.7 s of 3.0 s for a 24 MP, 5-layer RGB/8 document. const PSD_MODEL_DONE: f32 = 0.9; -fn export_stages(doc: &Document, name_or_ext: &str, opts: &ExportOptions, ctl: &photocraft_raster::Interrupt) -> Result { +fn export_stages(doc: &Document, name_or_ext: &str, opts: &ExportOptions, ctl: &photocraft_raster::Interrupt) -> Result { let ext = extension(name_or_ext); if ext == "pdn" { return Err(IoError::Unsupported("PDN is import-only; save as .pcraft to preserve all layers and blend modes".into())); @@ -430,10 +503,10 @@ fn export_stages(doc: &Document, name_or_ext: &str, opts: &ExportOptions, ctl: & return Err(IoError::Unsupported("Krita files are import-only; save as .ora to open the layers in Krita, or .pcraft to keep everything".into())); } if ext == "ora" { - return ora::export(doc); + return ora::export(doc).map(EncodedExport::from); } if ext == "pdf" { - return pdf::export(doc); + return pdf::export(doc).map(EncodedExport::from); } if ext == photocraft_format::EXTENSION { let doc = named_for_file(doc, name_or_ext); @@ -444,7 +517,7 @@ fn export_stages(doc: &Document, name_or_ext: &str, opts: &ExportOptions, ctl: & ctl.check().map_err(|_| IoError::Cancelled)?; ctl.progress(PCRAFT_PREVIEWS_DONE); let previews = photocraft_format::SaveOptions { thumbnail, composite }; - return Ok(ExportResult { bytes: photocraft_format::save_to_bytes(doc.as_ref(), &previews)?, warnings: Vec::new() }); + return Ok(ExportResult { bytes: photocraft_format::save_to_bytes(doc.as_ref(), &previews)?, warnings: Vec::new() }.into()); } if ext == "psd" || ext == "psb" { let o = PsdExportOptions { @@ -453,6 +526,9 @@ fn export_stages(doc: &Document, name_or_ext: &str, opts: &ExportOptions, ctl: & document_path: opts.document_path.clone(), ..Default::default() }; + // The preview is rendered first, while only the document is in memory: its full-size + // render would otherwise come on top of the finished file model (#6607). + let preview = opts.image_previews.then(|| psd_thumbnail::resource(doc)); let (mut file, mut warnings) = with_span(ctl, 0.0, PSD_MODEL_DONE, |ctl| psd_export::document_to_psd_interruptible(doc, &o, ctl)); // A cancelled conversion stops early with an incomplete model: never write it. ctl.check().map_err(|_| IoError::Cancelled)?; @@ -460,8 +536,8 @@ fn export_stages(doc: &Document, name_or_ext: &str, opts: &ExportOptions, ctl: & warnings.push("free-form text metadata is not supported by PSD/PSB; it will be dropped".into()); } warnings.extend(tiff_layers::strip_foreign_order_blocks(&mut file)); - if opts.image_previews { - match psd_thumbnail::resource(doc) { + if let Some(preview) = preview { + match preview { // Beside the other resources Photoshop writes ahead of the version info. Ok(r) => { let at = file.resources.iter().position(|r| r.id == photocraft_psd::resources::ids::VERSION_INFO).unwrap_or(file.resources.len()); @@ -472,14 +548,13 @@ fn export_stages(doc: &Document, name_or_ext: &str, opts: &ExportOptions, ctl: & } // Never write a header the reader would refuse (e.g. a zero-sized canvas). file.header.validate()?; - let bytes = file.to_bytes()?; - return Ok(ExportResult { bytes, warnings }); + return Ok(EncodedExport { encoded: Encoded::Psd(Box::new(file)), warnings }); } let format = photocraft_codecs::from_extension(&ext).ok_or_else(|| IoError::UnknownFormat(name_or_ext.to_string()))?; if format == photocraft_codecs::Format::Tiff && opts.tiff_layers && tiff_layers::would_write_layers(doc) { - return tiff_layers::export_layered(doc, opts, ctl); + return tiff_layers::export_layered(doc, opts, ctl).map(EncodedExport::from); } - flat::export_flat_with(doc, format, opts, ctl) + flat::export_flat_with(doc, format, opts, ctl).map(EncodedExport::from) } /// The PSD's merged composite as straight RGBA floats (row-major), converted diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index 9ad93bdf66..e4303edac9 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -1301,11 +1301,22 @@ fn cmyk_of(fmt: &PixelFormat) -> bool { fmt.mode == ColorMode::Cmyk } +/// Pixels per band of the merged composite: an eighth of [`photocraft_compose::BAND_PIXELS`]. The +/// planes it fills hold the whole image already, so a band's float pixels and their converted +/// parts are the save's peak on top of them (#6607); smaller bands cut that and render the same +/// pixels (bands are whole tiles). +const MERGED_BAND_PIXELS: u64 = photocraft_compose::BAND_PIXELS / 8; + /// The merged image's planes (colour channels, then alpha), big-endian, matted against white /// when `matte`; with whether any pixel needs the alpha channel and whether any is below 1. /// `ctl` gets the fraction of rows done after each band; once it is cancelled the rest of the /// image is left blank (the caller discards it). fn merged_planes(doc: &Document, fmt: &PixelFormat, cmyk: bool, matte: bool, ctl: &Interrupt) -> (Vec, bool, bool) { + merged_planes_in_bands(doc, fmt, cmyk, matte, MERGED_BAND_PIXELS, ctl) +} + +/// [`merged_planes`] rendered in bands of about `band_pixels`. +fn merged_planes_in_bands(doc: &Document, fmt: &PixelFormat, cmyk: bool, matte: bool, band_pixels: u64, ctl: &Interrupt) -> (Vec, bool, bool) { let sample = fmt.sample; let cc = fmt.mode.color_channels(); let bps = sample.bytes(); @@ -1319,7 +1330,8 @@ fn merged_planes(doc: &Document, fmt: &PixelFormat, cmyk: bool, matte: bool, ctl let space = photocraft_compose::cmyk_space(doc); let lab16 = fmt.mode == ColorMode::Lab && sample == SampleType::U16; let rows = canvas.height().max(1) as f32; - let _ = photocraft_compose::render_bands(doc, canvas, 0, |band| -> Result<(), ()> { + let band_rows = (band_pixels / u64::from(canvas.width().max(1))).max(1) as i32; + let _ = photocraft_compose::render_bands(doc, canvas, band_rows, |band| -> Result<(), ()> { if ctl.cancelled() { return Err(()); } @@ -1890,6 +1902,35 @@ mod tests { Document::new("size estimate", photocraft_geom::Size::new(width, height), ColorMode::Rgb, SampleType::U8) } + /// #6607: the merged composite is rendered in smaller bands than the default to keep a save's + /// peak down; the planes are the same however tall the bands are, effects that reach across a + /// band's edge (shadows, glows, strokes) and translucent pixels included. + #[test] + fn the_merged_image_is_the_same_in_any_band_height() { + use photocraft_doc::{Effect, Shadow}; + let mut doc = document(300, 1100); + let fmt = photocraft_color::PixelFormat::RGBA8; + for (i, y) in [240, 500, 760].into_iter().enumerate() { + let mut l = Layer::raster(format!("blob {i}"), fmt); + let (x, f) = (60 * i as i32, i as f32); + l.surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(30 + x, y, 150 + x, y + 40), &[0.8, 0.2 * f, 0.1, 0.6 + 0.2 * f]); + let shadow = |distance: f32, size: f32| match Effect::default_drop_shadow() { + Effect::DropShadow(s) => Effect::DropShadow(Shadow { distance, size, angle: 90.0, use_global_light: false, ..s }), + other => other, + }; + l.effects.items = vec![shadow(24.0, 18.0), shadow(9.0, 40.0)]; + doc.layers.push(l); + } + let dfmt = doc.pixel_format(); + let tall = merged_planes_in_bands(&doc, &dfmt, false, true, photocraft_compose::BAND_PIXELS, &Interrupt::NONE); + assert_eq!(photocraft_compose::band_rows_for(300, (photocraft_compose::BAND_PIXELS / 300) as i32), 28160, "one band"); + for band_pixels in [1, 300 * 256, 300 * 512, MERGED_BAND_PIXELS] { + let banded = merged_planes_in_bands(&doc, &dfmt, false, true, band_pixels, &Interrupt::NONE); + assert!(banded == tall, "{band_pixels} px bands changed the merged image"); + } + assert!(tall.1 && tall.2, "the test image has translucent pixels"); + } + /// Photoshop opens a PSD's bottom layer as its Background only when that layer has no /// transparency channel (measured on Photoshop 27.11: with the channel written, re-exported /// files reopened with the Background as an ordinary layer). diff --git a/crates/io/src/tiff_layers.rs b/crates/io/src/tiff_layers.rs index 91011c6eb1..c80c0bed5f 100644 --- a/crates/io/src/tiff_layers.rs +++ b/crates/io/src/tiff_layers.rs @@ -232,7 +232,10 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocr 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) = match ImageSourceData::from_psd(&file).to_bytes(order) { + let mut has_alpha = file.layer_info.as_ref().is_some_and(|l| l.merged_alpha); + // The layers move out of the model rather than being copied, and are freed once written + // (#6607). + let (layers, w) = match ImageSourceData::take_from_psd(&mut file).into_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)); @@ -240,7 +243,8 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocr 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)? + has_alpha = file.layer_info.as_ref().is_some_and(|l| l.merged_alpha); + ImageSourceData::take_from_psd(&mut file).into_bytes(order)? } r => r?, }; @@ -255,7 +259,6 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocr let fmt = doc.pixel_format(); let cc = fmt.mode.color_channels(); - let has_alpha = file.layer_info.as_ref().is_some_and(|l| l.merged_alpha); let channels = cc + usize::from(has_alpha); let extra = usize::from(file.header.channels).saturating_sub(channels); if extra > 0 { @@ -265,6 +268,8 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocr let (w, h) = (doc.size.width, doc.size.height); let cmyk = fmt.mode == ColorMode::Cmyk; let data = interleave(&file.image_data.data, w, h, channels, cc, sample, cmyk)?; + // Likewise the planar composite, now interleaved. + drop(file); ctl.check().map_err(|_| IoError::Cancelled)?; ctl.progress(TIFF_COMPOSITE_DONE); let layout = layout_for(fmt.mode, has_alpha); diff --git a/crates/io/tests/export_progress.rs b/crates/io/tests/export_progress.rs index 8f372db4b2..a474efc075 100644 --- a/crates/io/tests/export_progress.rs +++ b/crates/io/tests/export_progress.rs @@ -91,3 +91,24 @@ fn a_cancelled_export_stops_with_cancelled() { assert!(matches!(r, Err(IoError::Cancelled)), "{name} midway: {:?}", r.map(|r| r.bytes.len())); } } + +/// #6607: a PSD/PSB save stops at the file model, which is serialized into the file as it is +/// written; streamed into a file it holds exactly the exported bytes. Other formats come back as +/// their bytes. +#[test] +fn encoded_saves_write_exactly_the_exported_bytes() { + for depth in [SampleType::U8, SampleType::U16] { + let doc = layered(depth); + for name in ["a.psd", "a.psb", "a.png"] { + let opts = ExportOptions::default(); + let want = photocraft_io::export(&doc, name, &opts).unwrap().bytes; + let r = photocraft_io::encode_with(&doc, name, &opts, &Interrupt::NONE).unwrap(); + assert_eq!(matches!(r.encoded, photocraft_io::Encoded::Psd(_)), !name.ends_with(".png"), "{name}"); + assert!(r.encoded.len_hint() >= want.len() as u64, "{name} {depth:?}: the length hint is short"); + let mut file = std::io::Cursor::new(Vec::new()); + r.encoded.write_to(&mut file).unwrap(); + assert!(file.into_inner() == want, "{name} {depth:?}: the streamed file differs from the export"); + assert!(r.encoded.into_bytes().unwrap() == want, "{name} {depth:?}"); + } + } +} diff --git a/crates/psd/src/compression.rs b/crates/psd/src/compression.rs index 68782464ad..0c5ae79e0b 100644 --- a/crates/psd/src/compression.rs +++ b/crates/psd/src/compression.rs @@ -357,62 +357,69 @@ fn encode_rle(decoded: &[u8], layout: &PlaneLayout) -> Result> { if rows == 0 { return Ok(Vec::new()); } - // Rows are independent, so they pack in parallel chunks and concatenate in order. + // Rows are independent, so they pack in parallel chunks of rows. Two passes: the first only + // measures each packed row, so the output is allocated once at its exact size and the second + // packs every row straight into its place. Collecting packed chunks and then copying them into + // the output held the encoded image twice, with growth slack, at the save's peak (#6607). let threads = if cfg!(target_arch = "wasm32") { 1 } else { std::thread::available_parallelism().map_or(1, |v| v.get()).clamp(1, 32) }; let chunk_rows = rows.div_ceil(threads).max(1); - struct Chunk { - counts: Vec, - packed: Vec, - } - let pack_chunk = |first: usize, count: usize| -> Result { - let mut chunk = Chunk { counts: vec![0u8; count * cs], packed: Vec::new() }; - for row in first..first + count { - let start = chunk.packed.len(); - packbits::encode(&decoded[row * rb..(row + 1) * rb], &mut chunk.packed); - let n = chunk.packed.len() - start; - if cs == 2 { - let n = u16::try_from(n).map_err(|_| PsdError::LimitExceeded("RLE row exceeds 65535 bytes (use PSB)"))?; - chunk.counts[(row - first) * 2..(row - first) * 2 + 2].copy_from_slice(&n.to_be_bytes()); - } else { - let n = u32::try_from(n).map_err(|_| PsdError::LimitExceeded("RLE row too large"))?; - chunk.counts[(row - first) * 4..(row - first) * 4 + 4].copy_from_slice(&n.to_be_bytes()); - } + let row = |r: usize| &decoded[r * rb..(r + 1) * rb]; + let mut lens = vec![0usize; rows]; + for_each_chunk(threads, lens.chunks_mut(chunk_rows).enumerate().collect(), |(c, lens): (usize, &mut [usize])| { + let mut scratch = Vec::with_capacity(rb + rb.div_ceil(128)); + for (i, len) in lens.iter_mut().enumerate() { + scratch.clear(); + packbits::encode(row(c * chunk_rows + i), &mut scratch); + *len = scratch.len(); + } + })?; + let mut out = vec![0u8; rows * cs + lens.iter().sum::()]; + let (counts, mut packed) = out.split_at_mut(rows * cs); + for (count, &n) in counts.chunks_exact_mut(cs).zip(&lens) { + if cs == 2 { + let n = u16::try_from(n).map_err(|_| PsdError::LimitExceeded("RLE row exceeds 65535 bytes (use PSB)"))?; + count.copy_from_slice(&n.to_be_bytes()); + } else { + let n = u32::try_from(n).map_err(|_| PsdError::LimitExceeded("RLE row too large"))?; + count.copy_from_slice(&n.to_be_bytes()); } - Ok(chunk) - }; - let chunk_list: Vec = if threads == 1 { - vec![pack_chunk(0, rows)?] - } else { - std::thread::scope(|scope| -> Result> { - let handles: Vec<_> = (0..threads) - .map(|t| { - let first = t * chunk_rows; - let count = chunk_rows.min(rows.saturating_sub(first)); - scope.spawn(move || pack_chunk(first, count)) - }) - .collect(); - // Join every worker first, then surface the first error like the sequential - // path would instead of aborting the scope with a thread panic. - let mut all = Vec::with_capacity(threads); - for h in handles { - all.push(h.join().map_err(|_| PsdError::LimitExceeded("an RLE worker panicked"))??); - } - Ok(all) - })? - }; - let packed_total: usize = chunk_list.iter().map(|c| c.packed.len()).sum(); - let mut out = vec![0u8; rows * cs + packed_total]; - let mut counts_at = 0usize; - let mut packed_at = rows * cs; - for chunk in &chunk_list { - out[counts_at..counts_at + chunk.counts.len()].copy_from_slice(&chunk.counts); - counts_at += chunk.counts.len(); - out[packed_at..packed_at + chunk.packed.len()].copy_from_slice(&chunk.packed); - packed_at += chunk.packed.len(); } + let mut parts = Vec::with_capacity(threads); + for (c, lens) in lens.chunks(chunk_rows).enumerate() { + let (part, rest) = packed.split_at_mut(lens.iter().sum()); + parts.push((c, lens, part)); + packed = rest; + } + for_each_chunk(threads, parts, |(c, lens, mut part): (usize, &[usize], &mut [u8])| { + let mut scratch = Vec::with_capacity(rb + rb.div_ceil(128)); + for (i, &n) in lens.iter().enumerate() { + scratch.clear(); + packbits::encode(row(c * chunk_rows + i), &mut scratch); + let (dst, rest) = std::mem::take(&mut part).split_at_mut(n); + dst.copy_from_slice(&scratch); + part = rest; + } + })?; Ok(out) } +/// Runs `f` on every item, each on its own thread unless `threads` is 1 (wasm32). +fn for_each_chunk(threads: usize, items: Vec, f: impl Fn(T) + Sync) -> Result<()> { + if threads == 1 { + items.into_iter().for_each(f); + return Ok(()); + } + std::thread::scope(|scope| { + let handles: Vec<_> = items.into_iter().map(|item| scope.spawn(|| f(item))).collect(); + // Join every worker instead of aborting the scope with a thread panic. + let mut ok = true; + for h in handles { + ok &= h.join().is_ok(); + } + if ok { Ok(()) } else { Err(PsdError::LimitExceeded("an RLE worker panicked")) } + }) +} + /// zlib-compresses `data` at the default level. pub fn zip_compress(data: &[u8]) -> Vec { let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); @@ -944,9 +951,22 @@ mod parallel_rle_equivalence { let parallel = encode_rle(&data, &layout).expect("parallel encode"); let sequential = encode_rle_sequential(&data, &layout).expect("sequential encode"); assert_eq!(parallel, sequential, "rows {rows} rb {rb}"); + // #6607: measured first, then packed in place: one allocation, exactly the file's size. + assert_eq!(parallel.capacity(), parallel.len(), "rows {rows} rb {rb}: the output grew or was over-allocated"); } } + /// A row too long for a PSD's 16-bit RLE count is the same error from the two-pass encoder. + #[test] + fn rle_rows_past_sixteen_bits_are_refused_in_psd() { + let layout_for = |rows: usize, rb: usize, version: Version| PlaneLayout { planes: 1, width: rb, height: rows, depth: 8, version }; + let rb = 70_000; + let layout = layout_for(3, rb, Version::Psd); + let noise: Vec = (0..3 * rb).map(|i| (i * 31 % 251) as u8).collect(); + assert_eq!(encode_rle(&noise, &layout), Err(PsdError::LimitExceeded("RLE row exceeds 65535 bytes (use PSB)"))); + assert_eq!(encode_rle(&noise, &layout_for(3, rb, Version::Psb)), encode_rle_sequential(&noise, &layout_for(3, rb, Version::Psb))); + } + /// The pre-parallel encoder, kept as the oracle. fn encode_rle_sequential(decoded: &[u8], layout: &PlaneLayout) -> Result> { let rows = layout.rows()?; diff --git a/crates/psd/src/error.rs b/crates/psd/src/error.rs index da519e6698..58e4ad9e8a 100644 --- a/crates/psd/src/error.rs +++ b/crates/psd/src/error.rs @@ -46,6 +46,23 @@ impl PsdError { pub(crate) fn invalid(msg: impl Into) -> Self { PsdError::Invalid(msg.into()) } + + /// The error a streaming write ([`crate::PsdFile::write_to`]) failed with: the serializer's + /// own error when it was one, otherwise the I/O error's text. + pub(crate) fn from_io(e: std::io::Error) -> Self { + let text = e.to_string(); + match e.into_inner().map(|inner| inner.downcast::()) { + Some(Ok(e)) => *e, + _ => PsdError::Invalid(format!("write failed: {text}")), + } + } +} + +/// A serializer error inside a streaming write ([`crate::PsdFile::write_to`]), as `InvalidData`. +impl From for std::io::Error { + fn from(e: PsdError) -> Self { + std::io::Error::new(std::io::ErrorKind::InvalidData, e) + } } /// Convenience alias. diff --git a/crates/psd/src/file.rs b/crates/psd/src/file.rs index fab262732b..7dd145a3cb 100644 --- a/crates/psd/src/file.rs +++ b/crates/psd/src/file.rs @@ -1,13 +1,15 @@ //! The top-level [`PsdFile`] model, parser and writer. +use std::io::{Seek, Write}; + use crate::compression::{Compression, MAX_DECODED_BYTES, decode_planes, validate_planes}; use crate::error::{PsdError, Result}; use crate::header::{ColorMode, Header, Version}; use crate::image_data::ImageData; -use crate::io::{Reader, WriteExt}; +use crate::io::{Reader, Sink, WriteExt}; use crate::layer::{LayerInfo, LayerRecord}; use crate::resources::{self, ImageResource, ResourceData, ids}; -use crate::tagged::{TaggedBlock, read_blocks_with, uses_long_length, write_blocks}; +use crate::tagged::{TaggedBlock, read_blocks_with, uses_long_length, write_blocks_to}; /// Where the layer info was stored in the file. #[derive(Debug, Clone, PartialEq, Eq, Default)] @@ -231,17 +233,44 @@ impl PsdFile { /// Serializes the file. pub fn to_bytes(&self) -> Result> { - let v = self.header.version; - let psb = v.is_psb(); - // Reserve the pixel data up front: appending it to an empty Vec reallocates and copies - // repeatedly. Everything else (headers, resources, records) is small by comparison. - let hint = self.layer_info.as_ref().map_or(0, LayerInfo::channel_data_len).saturating_add(self.image_data.data.len()); + // Reserve the whole file up front: appending to an empty Vec reallocates and copies + // repeatedly, and a reserve that is a few bytes short makes the last append double the + // buffer, copying the whole file once more (2x the file's size, #6607). + let hint = self.size_bound(); let mut out = Vec::new(); out.try_reserve(hint).map_err(|_| PsdError::LimitExceeded("not enough memory to serialize the file"))?; - self.header.write(&mut out); - out.put_len(self.color_mode_data.len() as u64, false)?; - out.put(&self.color_mode_data); - resources::write_section(&mut out, &self.resources)?; + self.write_to(&mut std::io::Cursor::new(&mut out)).map_err(PsdError::from_io)?; + Ok(out) + } + + /// Serializes the file into `w` as it goes, starting at its current position: the bytes of + /// [`Self::to_bytes`] without ever holding them all (#6607). Length fields are back-patched + /// by seeking. A serializer error (a section too large for PSD, too many layers) comes back + /// as `InvalidData` carrying the [`PsdError`]; `w` then holds a partial file. + pub fn write_to(&self, w: &mut W) -> std::io::Result<()> { + let mut out = Sink::new(w)?; + self.write_staging(&mut out)?; + out.finish() + } + + /// [`Self::write_to`] writing out every `stage` staged bytes (tests: tiny stages make every + /// length field a back-patch through the stream). + #[cfg(test)] + pub(crate) fn write_to_staging(&self, w: &mut W, stage: usize) -> std::io::Result<()> { + let mut out = Sink::staging(w, stage)?; + self.write_staging(&mut out)?; + out.finish() + } + + fn write_staging(&self, out: &mut Sink<'_, W>) -> std::io::Result<()> { + let v = self.header.version; + let psb = v.is_psb(); + out.small(|o| { + self.header.write(o); + o.put_len(self.color_mode_data.len() as u64, false) + })?; + out.put(&self.color_mode_data)?; + out.small(|o| resources::write_section(o, &self.resources))?; let in_block = matches!(self.layer_info_placement, LayerInfoPlacement::GlobalBlock { .. }); // An entirely empty section is written as a zero length. (A section @@ -249,48 +278,71 @@ impl PsdFile { // the model and is normalized to this form.) let section_empty = self.layer_info.is_none() && self.global_layer_mask.is_none() && self.global_blocks.is_empty() && self.layer_mask_trailing.is_empty(); - let at = out.begin_len(psb); + let at = out.begin_len(psb)?; if !section_empty { - let li = out.begin_len(psb); + let li = out.begin_len(psb)?; if let (Some(info), false) = (&self.layer_info, in_block) { - info.write_body(&mut out, v)?; + info.write_body_to(out, v)?; } out.end_len(li, psb)?; let need_mask_field = self.global_layer_mask.is_some() || !self.global_blocks.is_empty() || (in_block && self.layer_info.is_some()); if need_mask_field { let gm = self.global_layer_mask.as_ref().map_or(&[][..], |g| &g.data[..]); - out.put_len(gm.len() as u64, false)?; - out.put(gm); + out.small(|o| o.put_len(gm.len() as u64, false))?; + out.put(gm)?; } match (&self.layer_info, &self.layer_info_placement) { (Some(info), LayerInfoPlacement::GlobalBlock { index, signature, key, padding }) => { let (before, after) = self.global_blocks.split_at((*index).min(self.global_blocks.len())); - write_blocks(&mut out, before, v, 4)?; - // Write into the final buffer: a temporary LayerInfo payload and a clone - // of all neighboring opaque blocks otherwise double the save's memory. - out.put(signature); - out.put(key); + write_blocks_to(out, before, v, 4)?; + // Written in place: a temporary LayerInfo payload and a clone of all + // neighboring opaque blocks otherwise double the save's memory. + out.put(signature)?; + out.put(key)?; let long = uses_long_length(v, key); - let at = out.begin_len(long); - let start = out.len(); - info.write_body(&mut out, v)?; - let len = out.len() - start; + let at = out.begin_len(long)?; + let start = out.pos(); + info.write_body_to(out, v)?; + let len = out.pos() - start; out.end_len(at, long)?; match padding { - Some(bytes) => out.put(bytes), - None => out.extend(std::iter::repeat_n(0u8, (4 - len % 4) % 4)), + Some(bytes) => out.put(bytes)?, + None => out.zeros(((4 - len % 4) % 4) as usize)?, } - write_blocks(&mut out, after, v, 4)?; + write_blocks_to(out, after, v, 4)?; } - _ => write_blocks(&mut out, &self.global_blocks, v, 4)?, + _ => write_blocks_to(out, &self.global_blocks, v, 4)?, } - out.put(&self.layer_mask_trailing); + out.put(&self.layer_mask_trailing)?; } out.end_len(at, psb)?; - out.put_u16(self.image_data.compression.as_u16()); - out.put(&self.image_data.data); - Ok(out) + out.small(|o| { + o.put_u16(self.image_data.compression.as_u16()); + Ok(()) + })?; + out.put(&self.image_data.data)?; + Ok(()) + } + + /// An upper bound of [`Self::to_bytes`]'s length: the pixel data plus every variable-length + /// part, each with generous room for its fixed fields, lengths and padding. Saturates. + pub fn size_bound(&self) -> usize { + // Per item: signature, key or id, length fields and padding fit easily. + const ITEM: usize = 32; + let blocks = |b: &[crate::tagged::TaggedBlock]| { + b.iter().fold(0usize, |n, t| n.saturating_add(t.data.len()).saturating_add(t.padding.as_ref().map_or(0, Vec::len)).saturating_add(ITEM)) + }; + let mut n: usize = 1024; // file header and section lengths + n = n.saturating_add(self.color_mode_data.len()); + n = self.resources.iter().fold(n, |n, r| n.saturating_add(r.data.len()).saturating_add(r.name.len()).saturating_add(ITEM)); + n = n.saturating_add(self.layer_info.as_ref().map_or(0, LayerInfo::size_bound)); + n = n.saturating_add(self.global_layer_mask.as_ref().map_or(0, |g| g.data.len())); + n = n.saturating_add(blocks(&self.global_blocks)).saturating_add(self.layer_mask_trailing.len()); + if let LayerInfoPlacement::GlobalBlock { padding: Some(p), .. } = &self.layer_info_placement { + n = n.saturating_add(p.len()).saturating_add(ITEM); + } + n.saturating_add(self.image_data.data.len()) } /// Layer records in file order (bottom-most first); empty if none. @@ -432,6 +484,94 @@ mod write_tests { use super::*; use crate::{Compression, testgen}; + /// #6607: the output is allocated once. A reserve a few bytes short of the file made the last + /// append double the buffer, copying the whole file once more at the save's peak. + #[test] + fn serializing_allocates_the_output_once() { + for case in testgen::all_cases() { + let bound = case.file.size_bound(); + let bytes = case.file.to_bytes().unwrap(); + assert!(bytes.len() <= bound, "{}: {} > bound {bound}", case.name, bytes.len()); + assert_eq!(bytes.capacity(), bound, "{}: the buffer grew past its first allocation", case.name); + } + } + + /// A stream that records the length of every write it gets. + struct Recorder { + inner: std::io::Cursor>, + writes: Vec, + } + + impl Write for Recorder { + fn write(&mut self, b: &[u8]) -> std::io::Result { + self.writes.push(b.len()); + self.inner.write(b) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + impl Seek for Recorder { + fn seek(&mut self, to: std::io::SeekFrom) -> std::io::Result { + self.inner.seek(to) + } + } + + /// #6607: streaming into a file writes exactly the bytes of `to_bytes`, wherever the stream + /// starts and however little is staged, so every length field is back-patched through the + /// stream (both placements of the layer info, PSD and PSB, every mode and depth). + #[test] + fn streaming_writes_the_same_bytes_with_lengths_patched_by_seeking() { + for case in testgen::all_cases() { + let want = case.file.to_bytes().unwrap(); + for stage in [0, 1, 7, 4096] { + let mut w = std::io::Cursor::new(b"pre".to_vec()); + w.set_position(3); + case.file.write_to_staging(&mut w, stage).unwrap(); + assert_eq!(&w.get_ref()[..3], b"pre", "{} stage {stage}", case.name); + assert!(w.get_ref()[3..] == want[..], "{} stage {stage}: streamed bytes differ", case.name); + assert_eq!(w.position(), 3 + want.len() as u64, "{} stage {stage}: the stream must end at the file's end", case.name); + } + let mut w = std::io::Cursor::new(Vec::new()); + case.file.write_to(&mut w).unwrap(); + assert!(w.into_inner() == want, "{}: write_to differs from to_bytes", case.name); + } + } + + /// #6607: pixel data goes to the stream as it is, never through a staging copy, so a save + /// holds the model and a short buffer, not a second copy of the file. + #[test] + fn streaming_passes_channel_and_merged_data_straight_through() { + let mut file = testgen::small(Version::Psd, Compression::Raw); + let big = 3 * crate::io::STAGE_FOR_TESTS; + file.image_data.data = vec![5; big]; + let info = file.layer_info.as_mut().unwrap(); + info.layers[0].channels[0] = crate::layer::ChannelData { id: 0, compression: Some(Compression::Raw), data: vec![6; big + 1] }; + let mut w = Recorder { inner: std::io::Cursor::new(Vec::new()), writes: Vec::new() }; + file.write_to(&mut w).unwrap(); + assert!(w.writes.contains(&big), "merged image data was staged: {:?}", w.writes); + assert!(w.writes.contains(&(big + 1)), "channel data was staged: {:?}", w.writes); + assert!(w.writes.iter().filter(|&&n| n != big && n != big + 1).all(|&n| n < crate::io::STAGE_FOR_TESTS * 2), "{:?}", w.writes); + let bytes = w.inner.into_inner(); + assert_eq!(PsdFile::from_bytes(&bytes).unwrap(), file); + assert!(bytes == file.to_bytes().unwrap()); + } + + /// A serializer error in the middle of a stream comes back as the same `PsdError` `to_bytes` + /// reports, inside an `InvalidData` I/O error. + #[test] + fn streaming_reports_serializer_errors() { + let mut file = testgen::small(Version::Psd, Compression::Raw); + let info = file.layer_info.as_mut().unwrap(); + let layer = info.layers[0].clone(); + info.layers = vec![layer; 32768]; + let want = file.to_bytes().unwrap_err(); + let e = file.write_to(&mut std::io::Cursor::new(Vec::new())).unwrap_err(); + assert_eq!(e.kind(), std::io::ErrorKind::InvalidData); + assert_eq!(PsdError::from_io(e), want); + } + #[test] fn global_blocks_default_to_four_byte_padding() { for version in [Version::Psd, Version::Psb] { diff --git a/crates/psd/src/io.rs b/crates/psd/src/io.rs index a7c7e3d8ee..95ed9c1f47 100644 --- a/crates/psd/src/io.rs +++ b/crates/psd/src/io.rs @@ -1,5 +1,7 @@ //! Bounds-checked big-endian reader and writer helpers. +use std::io::{Seek, SeekFrom, Write}; + use crate::error::{PsdError, Result}; /// A name as UTF-16 code units, capped at `max` **without ever splitting a surrogate pair**. @@ -209,6 +211,121 @@ impl WriteExt for Vec { } } +/// Staged bytes [`Sink`] collects before writing them out in one call. +const STAGE: usize = 64 << 10; +#[cfg(test)] +pub(crate) const STAGE_FOR_TESTS: usize = STAGE; + +/// Writes the file to a seekable stream as it is serialized (#6607): the small parts (headers, +/// records, lengths) are staged in a short buffer, while pixel data and other long slices go +/// straight to the stream, so the whole file never sits in memory. A length placeholder +/// ([`Sink::begin_len`]) that was already written out is back-patched by seeking. The bytes are +/// exactly the ones the `Vec` writers ([`WriteExt`]) produce. +pub(crate) struct Sink<'w, W: Write + Seek + ?Sized> { + w: &'w mut W, + /// Bytes not yet written; they start at stream position `base`. + buf: Vec, + base: u64, + /// Staged bytes that trigger a write ([`STAGE`]; tests use less). + stage: usize, +} + +impl<'w, W: Write + Seek + ?Sized> Sink<'w, W> { + /// A sink writing at `w`'s current position. + pub(crate) fn new(w: &'w mut W) -> std::io::Result { + Self::staging(w, STAGE) + } + + /// [`Self::new`] writing out once `stage` bytes are staged. + pub(crate) fn staging(w: &'w mut W, stage: usize) -> std::io::Result { + let base = w.stream_position()?; + Ok(Sink { w, buf: Vec::new(), base, stage }) + } + + /// The stream position of the next byte. + pub(crate) fn pos(&self) -> u64 { + self.base + self.buf.len() as u64 + } + + /// Appends a small part built by `f` with the `Vec` writers. Lengths `f` back-patches stay + /// inside what it appends. + pub(crate) fn small(&mut self, f: impl FnOnce(&mut Vec) -> Result<()>) -> std::io::Result<()> { + f(&mut self.buf)?; + if self.buf.len() >= self.stage { self.flush() } else { Ok(()) } + } + + /// Appends `b`, straight to the stream when it is long. + pub(crate) fn put(&mut self, b: &[u8]) -> std::io::Result<()> { + if self.buf.len() + b.len() < self.stage { + self.buf.extend_from_slice(b); + return Ok(()); + } + self.flush()?; + self.w.write_all(b)?; + self.base += b.len() as u64; + Ok(()) + } + + /// `n` zero bytes (padding, at most a few). + pub(crate) fn zeros(&mut self, n: usize) -> std::io::Result<()> { + self.small(|b| { + b.extend(std::iter::repeat_n(0u8, n)); + Ok(()) + }) + } + + /// Reserves a length placeholder (4 or 8 bytes), returning its stream position. + pub(crate) fn begin_len(&mut self, long: bool) -> std::io::Result { + let at = self.pos(); + self.zeros(if long { 8 } else { 4 })?; + Ok(at) + } + + /// Back-patches the placeholder at `at` with the number of bytes written since. + pub(crate) fn end_len(&mut self, at: u64, long: bool) -> std::io::Result<()> { + let hdr = if long { 8 } else { 4 }; + let n = self.pos() - at - hdr; + let bytes = if long { + n.to_be_bytes().to_vec() + } else { + u32::try_from(n).map_err(|_| PsdError::LimitExceeded("section too large for 32-bit length (use PSB)"))?.to_be_bytes().to_vec() + }; + if at >= self.base { + let i = (at - self.base) as usize; + self.buf[i..i + bytes.len()].copy_from_slice(&bytes); + return Ok(()); + } + self.flush()?; + self.w.seek(SeekFrom::Start(at))?; + self.w.write_all(&bytes)?; + self.w.seek(SeekFrom::Start(self.base))?; + Ok(()) + } + + fn flush(&mut self) -> std::io::Result<()> { + self.w.write_all(&self.buf)?; + self.base += self.buf.len() as u64; + self.buf.clear(); + Ok(()) + } + + /// Writes out what is still staged. Dropping a sink without it loses those bytes. + pub(crate) fn finish(mut self) -> std::io::Result<()> { + self.flush()?; + self.w.flush() + } +} + +/// Runs a streaming writer on the end of `out`, the `Vec` writers' way of sharing it. +pub(crate) fn append_with(out: &mut Vec, f: impl FnOnce(&mut Sink<'_, std::io::Cursor<&mut Vec>>) -> std::io::Result<()>) -> Result<()> { + let at = out.len() as u64; + let mut c = std::io::Cursor::new(out); + c.set_position(at); + let mut s = Sink::new(&mut c).map_err(PsdError::from_io)?; + f(&mut s).map_err(PsdError::from_io)?; + s.finish().map_err(PsdError::from_io) +} + /// Reads a Pascal string (length byte + bytes) whose total size is padded to /// a multiple of `align`. Returns the raw name bytes. pub(crate) fn read_pascal(r: &mut Reader<'_>, align: usize) -> Result> { diff --git a/crates/psd/src/layer.rs b/crates/psd/src/layer.rs index 5b11411dfb..39d591c558 100644 --- a/crates/psd/src/layer.rs +++ b/crates/psd/src/layer.rs @@ -4,7 +4,7 @@ use crate::blend::BlendMode; use crate::compression::{Compression, PlaneLayout, decode_planes, encode_planes}; use crate::error::{PsdError, Result}; use crate::header::{MAX_DIMENSION, Version}; -use crate::io::{Reader, WriteExt, decode_legacy_name, read_pascal, write_pascal}; +use crate::io::{Reader, Sink, WriteExt, append_with, decode_legacy_name, read_pascal, write_pascal}; use crate::tagged::{BlockData, SectionDivider, SectionType, TaggedBlock, read_blocks, uses_long_length, write_blocks}; /// Channel id of the transparency mask. @@ -598,6 +598,15 @@ impl LayerRecord { Ok((LayerRecord { rect, channels, blend_mode, opacity, clipping, flags, filler, mask, blending_ranges, name, blocks, extra_trailing }, lens)) } + /// Bytes of the mask data (without its length field). + fn mask_len(&self) -> u64 { + match &self.mask { + MaskData::None => 0, + MaskData::Mask(mask) => mask.encoded_len(), + MaskData::Raw(b) => b.len() as u64, + } + } + /// Bytes [`Self::write`] produces, computed without serializing. Errors where `write` would. fn encoded_len(&self, version: Version) -> Result { let too_big = || PsdError::LimitExceeded("section too large for 32-bit length (use PSB)"); @@ -606,11 +615,7 @@ impl LayerRecord { if !version.is_psb() && self.channels.iter().any(|c| u32::try_from(c.stored_len()).is_err()) { return Err(too_big()); } - let mask = match &self.mask { - MaskData::None => 0, - MaskData::Mask(mask) => mask.encoded_len(), - MaskData::Raw(b) => b.len() as u64, - }; + let mask = self.mask_len(); u32::try_from(mask).map_err(|_| too_big())?; let ranges = self.blending_ranges.data.len() as u64; u32::try_from(ranges).map_err(|_| too_big())?; @@ -743,37 +748,68 @@ impl LayerInfo { self.layers.iter().flat_map(|l| &l.channels).filter(|c| c.compression.is_some()).fold(0usize, |n, c| n.saturating_add(2).saturating_add(c.data.len())) } + /// An upper bound of the body's length: the channel data plus every record, each with + /// generous room for its fixed fields (rect, blend mode, flags, lengths). + /// Saturates. Reserving it keeps a writer from doubling its buffer at the end (#6607). + pub(crate) fn size_bound(&self) -> usize { + const RECORD: usize = 256; + const ITEM: usize = 32; + let n = self.channel_data_len().saturating_add(self.padding.as_ref().map_or(0, Vec::len)).saturating_add(ITEM); + self.layers.iter().fold(n, |n, l| { + let blocks = + l.blocks.iter().fold(0usize, |n, t| n.saturating_add(t.data.len()).saturating_add(t.padding.as_ref().map_or(0, Vec::len)).saturating_add(ITEM)); + n.saturating_add(RECORD) + .saturating_add(l.channels.len().saturating_mul(ITEM)) + .saturating_add(l.name.len()) + .saturating_add(l.blending_ranges.data.len()) + .saturating_add(blocks) + .saturating_add(l.extra_trailing.len()) + .saturating_add(usize::try_from(l.mask_len()).unwrap_or(usize::MAX)) + }) + } + /// Serializes the body without any trailing padding (the padding field is ignored). pub(crate) fn write_unpadded(&self, out: &mut Vec, version: Version) -> Result<()> { + append_with(out, |s| self.write_unpadded_to(s, version)) + } + + /// Serializes the body (without a length field). + #[cfg(test)] + pub(crate) fn write_body(&self, out: &mut Vec, version: Version) -> Result<()> { + append_with(out, |s| self.write_body_to(s, version)) + } + + /// [`Self::write_unpadded`] to a streaming [`Sink`]: the records are staged, the channel data + /// goes straight through. + pub(crate) fn write_unpadded_to(&self, out: &mut Sink<'_, W>, version: Version) -> std::io::Result<()> { let n = i16::try_from(self.layers.len()).map_err(|_| PsdError::LimitExceeded("more than 32767 layers"))?; - out.put_i16(if self.merged_alpha { -n } else { n }); + out.small(|o| { + o.put_i16(if self.merged_alpha { -n } else { n }); + Ok(()) + })?; for l in &self.layers { - l.write(out, version)?; + out.small(|o| l.write(o, version))?; } - for l in &self.layers { - for c in &l.channels { - if let Some(comp) = c.compression { - out.put_u16(comp.as_u16()); - out.put(&c.data); - } + for c in self.layers.iter().flat_map(|l| &l.channels) { + if let Some(comp) = c.compression { + out.small(|o| { + o.put_u16(comp.as_u16()); + Ok(()) + })?; + out.put(&c.data)?; } } Ok(()) } - /// Serializes the body (without a length field). - pub(crate) fn write_body(&self, out: &mut Vec, version: Version) -> Result<()> { - let start = out.len(); - self.write_unpadded(out, version)?; + /// [`Self::write_body`] to a streaming [`Sink`]. + pub(crate) fn write_body_to(&self, out: &mut Sink<'_, W>, version: Version) -> std::io::Result<()> { + let start = out.pos(); + self.write_unpadded_to(out, version)?; match &self.padding { Some(p) => out.put(p), - None => { - if (out.len() - start) % 2 == 1 { - out.put_u8(0); - } - } + None => out.zeros(((out.pos() - start) % 2) as usize), } - Ok(()) } } @@ -1115,6 +1151,23 @@ mod tests { } } + /// Large kept mask data (unparsed, or bytes after a parsed mask) is inside the size bound. + #[test] + fn size_bound_counts_mask_data() { + for version in [Version::Psd, Version::Psb] { + let mut mask = LayerMask::new(Rect::from_xywh(1, 2, 3, 4), 0, 0); + mask.trailing = vec![7; 4000]; + let layers = vec![ + LayerRecord { mask: MaskData::Raw(vec![5; 4000]), ..Default::default() }, + LayerRecord { mask: MaskData::Mask(mask), ..Default::default() }, + ]; + let info = LayerInfo { layers, ..Default::default() }; + let mut out = Vec::new(); + info.write_unpadded(&mut out, version).unwrap(); + assert!(info.size_bound() >= out.len(), "{version:?}: bound {} for {} bytes", info.size_bound(), out.len()); + } + } + /// Padding without cloning the layers writes the same bytes as `pad_to` on a clone, and the /// channel data length hint is exact. #[test] diff --git a/crates/psd/src/tagged.rs b/crates/psd/src/tagged.rs index 7728d53fd1..67006d4dcd 100644 --- a/crates/psd/src/tagged.rs +++ b/crates/psd/src/tagged.rs @@ -9,7 +9,7 @@ use crate::blend::BlendMode; use crate::descriptor::UnicodeString; use crate::error::{PsdError, Result}; use crate::header::Version; -use crate::io::{Reader, WriteExt}; +use crate::io::{Reader, Sink, WriteExt}; /// Keys whose length field is 8 bytes in PSB files: the thirteen the Adobe /// specification lists, plus keys Photoshop also writes with 8-byte lengths @@ -495,6 +495,29 @@ pub(crate) fn write_blocks(out: &mut Vec, blocks: &[TaggedBlock], version: V Ok(()) } +/// [`write_blocks`] to a streaming [`Sink`]: each block's data goes straight through, so a large +/// opaque block (an embedded smart object) is never copied whole. +pub(crate) fn write_blocks_to( + out: &mut Sink<'_, W>, + blocks: &[TaggedBlock], + version: Version, + alignment: usize, +) -> std::io::Result<()> { + for b in blocks { + out.small(|o| { + o.put(&b.signature); + o.put(&b.key); + o.put_len(b.data.len() as u64, uses_long_length(version, &b.key)) + })?; + out.put(&b.data)?; + match &b.padding { + Some(p) => out.put(p)?, + None => out.zeros(TaggedBlock::default_padding(b.data.len(), alignment))?, + } + } + Ok(()) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/psd/src/tiff.rs b/crates/psd/src/tiff.rs index 31c85d4885..74ecebcb4d 100644 --- a/crates/psd/src/tiff.rs +++ b/crates/psd/src/tiff.rs @@ -152,16 +152,49 @@ impl ImageSourceData { /// Serializes the data in `order`. Returns the bytes and warnings about blocks that were /// dropped because they could not be converted to a little-endian layout. pub fn to_bytes(&self, order: ByteOrder) -> Result<(Vec, Vec)> { + Self::finish(self.body()?, self.version, order) + } + + /// [`Self::to_bytes`] that frees the layers once their block is written, before the bytes + /// are converted to `order` (a copy of them all): a layered TIFF save holds them one time + /// fewer (#6607). + pub fn into_bytes(self, order: ByteOrder) -> Result<(Vec, Vec)> { + let (body, version) = (self.body()?, self.version); + drop(self); + Self::finish(body, version, order) + } + + /// The blocks in big-endian order, without the signature. + fn body(&self) -> Result> { let version = self.version; + // Reserved whole, as each buffer below holds all the layers' pixels: one that is a few + // bytes short doubles at its last append, copying them once more (#6607). + let blocks = self + .global_blocks + .iter() + .fold(0usize, |n, b| n.saturating_add(b.data.len()).saturating_add(b.padding.as_ref().map_or(0, Vec::len)).saturating_add(32)); let mut body = Vec::new(); + body.try_reserve( + self.layer_info + .as_ref() + .map_or(0, LayerInfo::size_bound) + .saturating_add(self.global_layer_mask.as_ref().map_or(0, |m| m.data.len())) + .saturating_add(blocks) + .saturating_add(self.trailing.len()) + .saturating_add(64), + ) + .map_err(|_| PsdError::LimitExceeded("not enough memory for the layer data"))?; if let Some(info) = &self.layer_info { - // Pad to 4 without cloning the layers (and all their pixel data) just to set `padding`. + // Written straight into the body, padded to 4 inside its length (as a padded copy + // would be): a separate buffer for it would hold all the pixels a second time. let pad = info.pad_len(version, 4)?; - let mut data = Vec::new(); - data.try_reserve(info.channel_data_len().saturating_add(pad)).map_err(|_| PsdError::LimitExceeded("not enough memory for the layer data"))?; - info.write_unpadded(&mut data, version)?; - data.resize(data.len() + pad, 0); - padded_block(self.layer_info_key, data).write(&mut body, version, 4)?; + let long = uses_long_length(version, &self.layer_info_key); + body.put(b"8BIM"); + body.put(&self.layer_info_key); + let at = body.begin_len(long); + info.write_unpadded(&mut body, version)?; + body.resize(body.len() + pad, 0); + body.end_len(at, long)?; } // Blocks without explicit padding are padded to 4 as they are written (alignment 4), so // the global mask and blocks are written from the model, without a copy of their data. @@ -173,12 +206,23 @@ impl ImageSourceData { b.write(&mut body, version, 4)?; } body.put(&self.trailing); - let (body, warnings) = - if order.is_little() { transcode::transcode_blocks(&body, version, ByteOrder::Big, ByteOrder::Little)? } else { (body, Vec::new()) }; - let mut out = Vec::with_capacity(36 + body.len()); - out.put(if version.is_psb() { SIGNATURE_PSB } else { SIGNATURE }); - out.put(&body); - Ok((out, warnings)) + Ok(body) + } + + /// The `body` converted to `order`, behind its signature. + fn finish(body: Vec, version: Version, order: ByteOrder) -> Result<(Vec, Vec)> { + let signature = if version.is_psb() { SIGNATURE_PSB } else { SIGNATURE }; + if order.is_little() { + // Converted behind the signature: the converted body fills the buffer it is given, + // so adding the signature afterwards would move (copy) it. + return transcode::transcode_blocks_after(signature, &body, version, ByteOrder::Big, ByteOrder::Little); + } + // The signature goes in front of the body in place, not by copying the body into a new + // buffer beside it. + let mut out = body; + out.try_reserve_exact(signature.len()).map_err(|_| PsdError::LimitExceeded("not enough memory for the layer data"))?; + out.splice(0..0, signature.iter().copied()); + Ok((out, Vec::new())) } /// The layers, global mask and global blocks of a PSD as image source data (byte order Big). @@ -198,6 +242,25 @@ impl ImageSourceData { } } + /// [`Self::from_psd`] that moves the layers, global mask and global blocks out of `file` + /// instead of copying them: a layered TIFF save would otherwise hold every layer's pixels + /// twice (#6607). `file` keeps its header, resources and merged image. + pub fn take_from_psd(file: &mut PsdFile) -> Self { + let key = match &file.layer_info_placement { + LayerInfoPlacement::GlobalBlock { key, .. } => *key, + LayerInfoPlacement::Section => layer_info_key(file.header.depth), + }; + ImageSourceData { + version: file.header.version, + byte_order: ByteOrder::Big, + layer_info: file.layer_info.take(), + layer_info_key: key, + global_layer_mask: file.global_layer_mask.take(), + global_blocks: std::mem::take(&mut file.global_blocks), + trailing: std::mem::take(&mut file.layer_mask_trailing), + } + } + /// Assembles a PSD model from this data plus the parts a TIFF stores natively: the header /// (dimensions, depth, colour mode, channel count), the image resources (tag 34377) and the /// merged image (the TIFF's pixels). @@ -222,6 +285,7 @@ impl ImageSourceData { } /// A block padded to a multiple of 4, as Photoshop writes them in TIFFs. +#[cfg(test)] fn padded_block(key: [u8; 4], data: Vec) -> TaggedBlock { let pad = (4 - data.len() % 4) % 4; TaggedBlock { signature: *b"8BIM", key, data, padding: Some(vec![0; pad]) } @@ -278,6 +342,15 @@ pub mod transcode { Ok(t.finish()) } + /// [`transcode_blocks`] written after `prefix`, in one buffer sized for both. + pub fn transcode_blocks_after(prefix: &[u8], data: &[u8], version: Version, from: ByteOrder, to: ByteOrder) -> Result<(Vec, Vec)> { + let mut out = Vec::with_capacity(prefix.len().saturating_add(data.len())); + out.extend_from_slice(prefix); + let mut t = Tx::appending(out, data, version, from, to); + t.blocks()?; + Ok(t.finish()) + } + /// Converts a layer-info body (the data of a `Layr` / `Lr16` / `Lr32` block) between orders. pub fn transcode_layer_info(data: &[u8], version: Version, from: ByteOrder, to: ByteOrder) -> Result<(Vec, Vec)> { let mut t = Tx::new(data, version, from, to); @@ -332,8 +405,13 @@ pub mod transcode { impl<'a> Tx<'a> { fn new(data: &'a [u8], version: Version, from: ByteOrder, to: ByteOrder) -> Self { + Self::appending(Vec::with_capacity(data.len()), data, version, from, to) + } + + /// A walker that appends to `out`. + fn appending(out: Vec, data: &'a [u8], version: Version, from: ByteOrder, to: ByteOrder) -> Self { let r = if from.is_little() { Reader::new_little(data) } else { Reader::new(data) }; - Tx { r, out: Vec::with_capacity(data.len()), from, to, version, warnings: Vec::new(), depth: 0 } + Tx { r, out, from, to, version, warnings: Vec::new(), depth: 0 } } fn finish(self) -> (Vec, Vec) { @@ -1631,6 +1709,25 @@ mod tests { /// Keys the generator plants that the transcoder (rightly) does not know. const UNKNOWN: [&[u8; 4]; 3] = [b"zOdd", b"zNop", b"Txt2"]; + /// #6607: moving the layers out of the model and freeing them before the conversion writes + /// the same bytes as copying them, in both byte orders, and leaves the rest of the model. + #[test] + fn taking_the_layers_writes_the_same_bytes_as_copying_them() { + for case in testgen::all_cases() { + for order in [ByteOrder::Big, ByteOrder::Little] { + let copied = ImageSourceData::from_psd(&case.file).to_bytes(order); + let mut file = case.file.clone(); + let taken = ImageSourceData::take_from_psd(&mut file).into_bytes(order); + match (copied, taken) { + (Ok(a), Ok(b)) => assert_eq!(a, b, "{} {order:?}", case.name), + (a, b) => assert_eq!(a.is_err(), b.is_err(), "{} {order:?}", case.name), + } + assert!(file.layer_info.is_none() && file.global_blocks.is_empty(), "{}", case.name); + assert_eq!(file.image_data, case.file.image_data, "{}", case.name); + } + } + } + /// `d` without the blocks a little-endian round trip drops, and without the layer-info /// padding (which follows the body length, so it changes when blocks are dropped). fn known(d: &ImageSourceData) -> ImageSourceData { @@ -2393,6 +2490,11 @@ mod tests { assert_eq!(d.to_bytes(ByteOrder::Big).unwrap().0, [signature, &body[..]].concat()); let (little, _) = transcode_blocks(&body, version, ByteOrder::Big, ByteOrder::Little).unwrap(); assert_eq!(d.to_bytes(ByteOrder::Little).unwrap().0, [signature, &little[..]].concat()); + // Converted behind the signature in the buffer it starts with: never grown (growing + // would at least double it), so the body is not moved to make room. + let (after, _) = transcode::transcode_blocks_after(signature, &body, version, ByteOrder::Big, ByteOrder::Little).unwrap(); + assert_eq!(after, [signature, &little[..]].concat()); + assert_eq!(after.capacity(), signature.len() + body.len()); } }