diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index cabd2196d6..d9ddcf64d8 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -361,9 +361,20 @@ 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(_) => { + // Only the progress bar's scale: a model whose length can't be worked out fails the + // write the same way, through the atomic write's "not changed" error. + let len = encoded.encoded_len().unwrap_or(0); + photocraft_format::atomic_write_stream_progress(path, len, progress, &mut |w| encoded.write_to(w)) + } + } + .map_err(|e| e.to_string()) } /// Whether `a` and `b` reach the same file: the same device and inode on Unix, the same final path @@ -413,26 +424,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) } @@ -443,7 +454,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>>; @@ -674,7 +685,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; diff --git a/apps/photocraft/src/services/tests.rs b/apps/photocraft/src/services/tests.rs index a0a91aa118..3f8c6a142a 100644 --- a/apps/photocraft/src/services/tests.rs +++ b/apps/photocraft/src/services/tests.rs @@ -4,6 +4,41 @@ use photocraft_format::list_recovery; 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", photocraft_geom::Size::new(64, 48), photocraft_doc::ColorMode::Rgb, photocraft_color::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(photocraft_doc::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); +} + /// #6601: a chosen path whose name isn't valid Unicode is reported, never handed on lossily /// (Open would fail with "No such file", Save would write a second, renamed file). #[test] diff --git a/crates/codecs/src/codecs/tiff/encode.rs b/crates/codecs/src/codecs/tiff/encode.rs index a0b7539b86..5c0e25b1b2 100644 --- a/crates/codecs/src/codecs/tiff/encode.rs +++ b/crates/codecs/src/codecs/tiff/encode.rs @@ -481,8 +481,19 @@ fn encode_ready(img: &Image, opts: &EncodeOptions) -> Result, CodecError // BigTIFF when asked, or when the file could pass the 4 GiB a classic TIFF can address. A // classic write that still runs out of 32-bit offsets (compression grew the data) is redone // as BigTIFF. + let estimate = estimated_size(img, &tags); let write = |big: bool| -> 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) { + // Best effort: without the room the buffer grows as before. + 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)?; @@ -490,9 +501,15 @@ fn encode_ready(img: &Image, opts: &EncodeOptions) -> Result, CodecError let mut enc = TiffEncoder::new(&mut cursor)?.with_compression(compression).with_predictor(predictor); write_image::(&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/it/roundtrip.rs b/crates/codecs/tests/it/roundtrip.rs index acbd16c5db..5a0175bbc2 100644 --- a/crates/codecs/tests/it/roundtrip.rs +++ b/crates/codecs/tests/it/roundtrip.rs @@ -213,6 +213,23 @@ fn tiff_all_compressions_lossless() { } } +#[test] +fn compressed_tiff_does_not_keep_the_uncompressed_reservation() { + // The encoder reserves the uncompressed size up front for an uncompressed file (#6607). A + // smooth image compresses to a fraction of it, and no returned file holds much spare room. + 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::None, TiffCompression::Lzw, TiffCompression::Deflate] { + let v = encode(&img, Format::Tiff, &EncodeOptions { tiff_compression: comp, ..Default::default() }).unwrap(); + if !matches!(comp, TiffCompression::None) { + 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()); + assert_eq!(decode(&v).unwrap().data(), img.data(), "{comp:?}"); + } +} + #[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 8cd349efff..de28655f08 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -35,7 +35,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}; @@ -56,6 +56,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. @@ -74,6 +83,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; @@ -95,6 +111,16 @@ 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); + // `AlreadyExists` means a temporary name collided, which makes the caller retry with + // another name and leave this one alone: from the writer, once the file is ours, it is + // a plain failure (the partial file is removed, the writer is not run again). + write(&mut out).map_err(|e| if e.kind() == io::ErrorKind::AlreadyExists { io::Error::other(e) } else { e })?; + 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) } @@ -207,6 +233,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() { @@ -223,7 +318,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 c768044e06..2baba46fac 100644 --- a/crates/format/src/atomic/tests.rs +++ b/crates/format/src/atomic/tests.rs @@ -148,6 +148,119 @@ 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 writer failing with `AlreadyExists` (from whatever it reads) is a failed save, not a +/// temporary name collision: it runs once and its partial file is removed. +#[test] +fn streamed_write_failing_with_already_exists_runs_once() { + let d = TempDir::new("stream-exists"); + let p = d.0.join("doc.psd"); + std::fs::write(&p, ORIGINAL).unwrap(); + let runs = Cell::new(0); + let e = atomic_write_stream(&p, &mut |w| { + runs.set(runs.get() + 1); + w.write_all(&[1; 70_000])?; + Err(io::Error::new(io::ErrorKind::AlreadyExists, "injected")) + }) + .unwrap_err(); + assert_eq!(runs.get(), 1); + assert!(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 b1e889c1b8..696b52cb72 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -41,7 +41,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/io/src/lib.rs b/crates/io/src/lib.rs index c3bdcefeb8..965d626b1a 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -204,6 +204,68 @@ 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 exact length [`Self::write_to`] writes. Fails, as the write would, for a PSD/PSB + /// model its writer refuses. + pub fn encoded_len(&self) -> Result { + match self { + Encoded::Bytes(b) => Ok(b.len() as u64), + Encoded::Psd(file) => Ok(file.encoded_len()?), + } + } + + /// 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 @@ -608,6 +670,28 @@ 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 { + let r = checked_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. Every pixel is read from the document (scratch included, and checked as +/// [`export_with`] checks it) before this returns: the model holds the encoded channels, never a +/// reference to the document's tiles. 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 { + let r = checked_stages(doc, name_or_ext, opts, ctl)?; + ctl.check().map_err(|_| IoError::Cancelled)?; + ctl.progress(1.0); + Ok(r) +} + +/// [`export_stages`] refused when the document's scratch was, or became, unreadable while its +/// pixels were read (previews included): their placeholders must never be saved. +fn checked_stages(doc: &Document, name_or_ext: &str, opts: &ExportOptions, ctl: &photocraft_raster::Interrupt) -> Result { ctl.check().map_err(|_| IoError::Cancelled)?; photocraft_compose::discard_unreadable_pixel_caches(); doc.scratch_health().map_err(IoError::Unsupported)?; @@ -616,7 +700,6 @@ pub fn export_with(doc: &Document, name_or_ext: &str, opts: &ExportOptions, ctl: photocraft_raster::spill::check_since(scratch_generation).map_err(IoError::Unsupported)?; doc.scratch_health().map_err(IoError::Unsupported)?; ctl.check().map_err(|_| IoError::Cancelled)?; - ctl.progress(1.0); Ok(r) } @@ -639,7 +722,7 @@ const PCRAFT_FULL_COMPOSITE_PIXELS: u64 = 1 << 26; /// 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())); @@ -656,10 +739,10 @@ fn export_stages(doc: &Document, name_or_ext: &str, opts: &ExportOptions, ctl: & )); } 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); @@ -681,7 +764,7 @@ fn export_stages(doc: &Document, name_or_ext: &str, opts: &ExportOptions, ctl: & Some(cache) => cache.encode(doc.as_ref(), &previews)?, None => photocraft_format::save_to_bytes(doc.as_ref(), &previews)?, }; - return Ok(ExportResult { bytes, warnings: Vec::new() }); + return Ok(ExportResult { bytes, warnings: Vec::new() }.into()); } if ext == "psd" || ext == "psb" { let o = PsdExportOptions { @@ -691,6 +774,9 @@ fn export_stages(doc: &Document, name_or_ext: &str, opts: &ExportOptions, ctl: & read_linked_files: opts.read_linked_files, ..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)?; @@ -698,8 +784,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()); @@ -710,14 +796,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 flattened document at its canvas size, in 8-bit RGBA like a `.pcraft` file's two previews, diff --git a/crates/io/src/psd_export/merged.rs b/crates/io/src/psd_export/merged.rs index 94b7bc4014..c70965dda9 100644 --- a/crates/io/src/psd_export/merged.rs +++ b/crates/io/src/psd_export/merged.rs @@ -12,6 +12,17 @@ pub(super) fn merged_planes(doc: &Document, fmt: &PixelFormat, cmyk: bool, matte if cmyk && let Some(planes) = merged_ink_planes(doc, fmt.sample, matte, ctl) { return planes; } + merged_planes_in_bands(doc, fmt, cmyk, matte, MERGED_BAND_PIXELS, ctl) +} + +/// 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; + +/// [`merged_planes`] (its composite path) 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(); @@ -25,7 +36,8 @@ pub(super) fn merged_planes(doc: &Document, fmt: &PixelFormat, cmyk: bool, matte 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 = i32::try_from((band_pixels / u64::from(canvas.width().max(1))).max(1)).unwrap_or(i32::MAX); + let _ = photocraft_compose::render_bands(doc, canvas, band_rows, |band| -> Result<(), ()> { if ctl.cancelled() { return Err(()); } @@ -270,4 +282,33 @@ mod tests { } } } + + /// #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) 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::new("bands", photocraft_geom::Size::new(300, 1100), ColorMode::Rgb, SampleType::U8); + 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!(photocraft_compose::band_rows_for(300, (photocraft_compose::BAND_PIXELS / 300) as i32) >= 1100, "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"); + } } diff --git a/crates/io/src/tiff_layers.rs b/crates/io/src/tiff_layers.rs index 664355ef5b..f001b6a265 100644 --- a/crates/io/src/tiff_layers.rs +++ b/crates/io/src/tiff_layers.rs @@ -282,7 +282,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 tiff_image_source(doc, &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); the model keeps its header, resources and composite for the image below. + let (layers, w) = match tiff_image_source(doc, &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)); @@ -290,7 +293,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; - tiff_image_source(doc, &file).to_bytes(order)? + has_alpha = file.layer_info.as_ref().is_some_and(|l| l.merged_alpha); + tiff_image_source(doc, &mut file).into_bytes(order)? } r => r?, }; @@ -304,7 +308,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_n = usize::from(file.header.channels).saturating_sub(channels); let kept = extra_n.min(codecs::MAX_EXTRA_SAMPLES); @@ -351,6 +354,8 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocr let cmyk = fmt.mode == ColorMode::Cmyk; let data = interleave(&file.image_data.data, w, h, ifd_channels, cc, sample, cmyk)?; let extras = native_extra_planes(&file.image_data.data, w, h, channels, kept, sample)?; + // 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, write_alpha); @@ -373,17 +378,18 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocr } /// The layer data (`ImageSourceData`) of a layered TIFF saved from `file`, adjusted the way -/// Photoshop writes it. -fn tiff_image_source(doc: &Document, file: &photocraft_psd::PsdFile) -> ImageSourceData { +/// Photoshop writes it. The layers, global mask and global blocks move out of `file` (the +/// export's own model), which keeps its header, resources and merged image. +fn tiff_image_source(doc: &Document, file: &mut photocraft_psd::PsdFile) -> ImageSourceData { // Photoshop pairs alpha-name resources with samples past the colour channels and ignores // the ExtraSamples kind. The merged transparency must not occupy that first slot when a // spot is also stored. Layer transparency stays in each layer's channel −1. - let mut isd = ImageSourceData::from_psd(file); let spot_extras = file.header.channels as usize > { let cc = doc.pixel_format().mode.color_channels(); let alpha = file.layer_info.as_ref().is_some_and(|l| l.merged_alpha); cc + usize::from(alpha) }; + let mut isd = ImageSourceData::take_from_psd(file); // Positive layer count: the merged image's first extra sample is not transparency // (Photoshop's own spot TIFF does this; a negative count would claim the spot plane is alpha). if spot_extras && let Some(info) = &mut isd.layer_info { diff --git a/crates/io/tests/it/export_progress.rs b/crates/io/tests/it/export_progress.rs index 8f372db4b2..d7c3b48856 100644 --- a/crates/io/tests/it/export_progress.rs +++ b/crates/io/tests/it/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_eq!(r.encoded.encoded_len().unwrap(), want.len() as u64, "{name} {depth:?}: the encoded length"); + 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 08ff28b881..5a49284c44 100644 --- a/crates/psd/src/compression.rs +++ b/crates/psd/src/compression.rs @@ -235,18 +235,6 @@ pub(crate) fn rle_widening(data: &[u8], rows: usize) -> Result { Ok(table as u64) } -/// Writes a PSD RLE stream (two-byte row counts) as the PSB one (four-byte row counts): the packed -/// rows are the same in both versions, only the count table widens. -pub(crate) fn put_widened_rle(out: &mut Vec, data: &[u8], rows: usize) -> Result<()> { - let table_len = usize::try_from(rle_widening(data, rows)?).map_err(|_| PsdError::LimitExceeded("row count overflow"))?; - let (table, packed) = data.split_at_checked(table_len).ok_or_else(|| PsdError::invalid("RLE row-count table out of range"))?; - for count in table.as_chunks::<2>().0 { - out.extend_from_slice(&[0, 0, count[0], count[1]]); - } - out.extend_from_slice(packed); - Ok(()) -} - /// Encodes planar data (excluding the 2-byte compression field). pub fn encode_planes(compression: Compression, decoded: &[u8], layout: &PlaneLayout) -> Result> { let total = layout.decoded_len()?; @@ -379,62 +367,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()); @@ -612,9 +607,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 6009def21f..2e4f87d849 100644 --- a/crates/psd/src/error.rs +++ b/crates/psd/src/error.rs @@ -53,6 +53,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 f2aeb902c0..1e2c60f827 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 crate::compression::{Compression, MAX_DECODED_BYTES, decode_planes, put_widened_rle, rle_widening, validate_planes}; +use std::io::{Seek, Write}; + +use crate::compression::{Compression, MAX_DECODED_BYTES, decode_planes, rle_widening, 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)] @@ -288,27 +290,48 @@ impl PsdFile { /// Serializes the file. pub fn to_bytes(&self) -> Result> { + // Reserve the whole file up front, at its exact length: 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 (#6607). + let len = usize::try_from(self.encoded_len()?).map_err(|_| PsdError::OutOfMemory("not enough memory to serialize the file"))?; + let mut out = Vec::new(); + out.try_reserve_exact(len).map_err(|_| PsdError::OutOfMemory("not enough memory to serialize the file"))?; + 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, widen) = self.write_form(); 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 widened = if widen { self.rle_widening()? } else { 0 }; - let hint = self - .layer_info - .as_ref() - .map_or(0, LayerInfo::channel_data_len) - .saturating_add(usize::try_from(self.image_data.encoded_len()).unwrap_or(usize::MAX)) - .saturating_add(usize::try_from(widened).unwrap_or(usize::MAX)); - let mut out = Vec::new(); - out.try_reserve(hint).map_err(|_| PsdError::OutOfMemory("not enough memory to serialize the file"))?; - if widen { - Header { version: v, ..self.header.clone() }.write(&mut out); - } else { - 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)?; + out.small(|o| { + if widen { + Header { version: v, ..self.header.clone() }.write(o); + } else { + 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 @@ -316,51 +339,54 @@ 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_as(&mut out, v, widen)?; + info.write_body_to(out, v, widen)?; } 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_as(&mut out, v, widen)?; - let len = out.len() - start; + let at = out.begin_len(long)?; + let start = out.pos(); + info.write_body_to(out, v, widen)?; + 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.small(|o| { + o.put_u16(self.image_data.compression.as_u16()); + Ok(()) + })?; + let merged = self.image_data.encoded()?; match self.merged_widened_rows(widen)? { - 0 => out.put(&self.image_data.encoded()?), - rows => put_widened_rle(&mut out, &self.image_data.encoded()?, rows)?, + 0 => out.put(&merged), + rows => out.put_widened_rle(&merged, rows), } - Ok(out) } /// The version the file is written as, and whether its RLE count tables widen on the way @@ -609,6 +635,129 @@ impl PsdFile { mod write_tests { use super::*; use crate::{Compression, testgen}; + use std::io::{Seek, Write}; + + /// #6607: the output is allocated once, at its exact length. A reserve a few bytes short of + /// the file made the last append double the buffer, copying the whole file once more. + #[test] + fn serializing_allocates_the_output_once() { + for case in testgen::all_cases() { + let bytes = case.file.to_bytes().unwrap(); + assert_eq!(bytes.capacity(), bytes.len(), "{}: 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) + } + } + + /// The bytes `file` streams with `stage`-byte staging, after a 3-byte prefix that must stay. + fn streamed(file: &PsdFile, stage: usize) -> Vec { + let mut w = std::io::Cursor::new(b"pre".to_vec()); + w.set_position(3); + file.write_to_staging(&mut w, stage).unwrap(); + let end = w.position(); + let mut bytes = w.into_inner(); + assert_eq!(&bytes[..3], b"pre"); + assert_eq!(end, bytes.len() as u64, "the stream must end at the file's end"); + bytes.drain(..3); + bytes + } + + /// #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] { + assert!(streamed(&case.file, stage) == want, "{} stage {stage}: streamed bytes differ", 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); + } + } + + /// A PSD model written as PSB (its RLE count tables widened on the way out) and a model read + /// lazily from a source (its pixel data not in memory) stream the bytes `to_bytes` writes. + #[test] + fn promoted_and_source_backed_files_stream_the_same_bytes() { + for case in testgen::all_cases() { + let mut promoted = case.file.clone(); + if promoted.header.version == Version::Psd { + promoted.promote_to_psb().unwrap(); + let want = promoted.to_bytes().unwrap(); + for stage in [0, 1, 7, 4096] { + assert!(streamed(&promoted, stage) == want, "{} promoted, stage {stage}", case.name); + } + } + let bytes = case.file.to_bytes().unwrap(); + let lazy = PsdFile::from_source(crate::Source::new(bytes.clone())).unwrap(); + for stage in [0, 1, 4096] { + assert!(streamed(&lazy, stage) == bytes, "{} source-backed, stage {stage}", 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 = ImageData::new(Compression::Raw, vec![5; big]); + let info = file.layer_info.as_mut().unwrap(); + info.layers[0].channels[0] = crate::layer::ChannelData::new(0, Some(Compression::Raw), 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); + // A damaged count table of a promoted file fails the stream as it fails `to_bytes`. + let mut file = testgen::small(Version::Psd, Compression::Rle); + file.promote_to_psb().unwrap(); + file.image_data.data.truncate(3); + let want = file.to_bytes().unwrap_err(); + let e = file.write_to(&mut std::io::Cursor::new(Vec::new())).unwrap_err(); + assert_eq!(PsdError::from_io(e), want); + } /// `encoded_len` is exactly what `to_bytes` writes, for every generated file and both layer /// info placements, with and without padding (#5285). diff --git a/crates/psd/src/io.rs b/crates/psd/src/io.rs index a7c7e3d8ee..eb7185bde2 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,138 @@ 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(()) + } + + /// Appends RLE channel data whose 2-byte row-count table widens to 4 bytes (a PSD model + /// written as PSB): the table is widened in staged pieces, the packed rows go straight + /// through: each two-byte count becomes `00 00` and the count, the packed rows are unchanged. + pub(crate) fn put_widened_rle(&mut self, data: &[u8], rows: usize) -> std::io::Result<()> { + let table_len = usize::try_from(crate::compression::rle_widening(data, rows)?).map_err(|_| PsdError::LimitExceeded("row count overflow"))?; + let (table, packed) = data.split_at_checked(table_len).ok_or_else(|| PsdError::invalid("RLE row-count table out of range"))?; + for part in table.chunks(STAGE / 2) { + self.small(|o| { + for count in part.as_chunks::<2>().0 { + o.extend_from_slice(&[0, 0, count[0], count[1]]); + } + Ok(()) + })?; + } + self.put(packed) + } + + /// `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 cbc4ccb424..fc1a3ff571 100644 --- a/crates/psd/src/layer.rs +++ b/crates/psd/src/layer.rs @@ -3,10 +3,10 @@ use std::borrow::Cow; use crate::blend::BlendMode; -use crate::compression::{Compression, PlaneLayout, decode_planes, encode_planes, put_widened_rle, rle_widening}; +use crate::compression::{Compression, PlaneLayout, decode_planes, encode_planes, rle_widening}; 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::source::Stored; use crate::tagged::{BlockData, SectionDivider, SectionType, TaggedBlock, read_blocks, uses_long_length, write_blocks}; @@ -813,6 +813,8 @@ impl LayerInfo { /// Bytes of channel data and their compression fields: the part of the body worth reserving up /// front (the records are small next to the pixels). Saturates instead of overflowing. + /// (Saves reserve their exact length now, #6607; the tests still check it as a lower bound.) + #[cfg(test)] pub(crate) fn channel_data_len(&self) -> usize { self.layers .iter() @@ -823,24 +825,43 @@ impl LayerInfo { /// Serializes the body without any trailing padding (the padding field is ignored). pub(crate) fn write_unpadded(&self, out: &mut Vec, version: Version) -> Result<()> { - self.write_unpadded_as(out, version, false) + append_with(out, |s| self.write_unpadded_to(s, version, false)) } - /// [`Self::write_unpadded`], widening the RLE count tables of a PSD model written as PSB - /// (`widen`) on the way out. - fn write_unpadded_as(&self, out: &mut Vec, version: Version, widen: bool) -> Result<()> { + /// 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, false)) + } + + /// [`Self::write_unpadded`] to a streaming [`Sink`], widening the RLE count tables of a PSD + /// model written as PSB (`widen`) on the way out: the records are staged, the channel data + /// goes straight through (#6607). + pub(crate) fn write_unpadded_to( + &self, + out: &mut Sink<'_, W>, + version: Version, + widen: bool, + ) -> 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, widen)?; + out.small(|o| l.write(o, version, widen))?; } for l in &self.layers { for c in &l.channels { if let Some(comp) = c.compression { - out.put_u16(comp.as_u16()); + out.small(|o| { + o.put_u16(comp.as_u16()); + Ok(()) + })?; + let data = c.encoded()?; match l.widened_rows(c, widen)? { - 0 => out.put(&c.encoded()?), - rows => put_widened_rle(out, &c.encoded()?, rows)?, + 0 => out.put(&data)?, + rows => out.put_widened_rle(&data, rows)?, } } } @@ -848,25 +869,20 @@ impl LayerInfo { Ok(()) } - /// Serializes the body (without a length field). - #[cfg(test)] - pub(crate) fn write_body(&self, out: &mut Vec, version: Version) -> Result<()> { - self.write_body_as(out, version, false) - } - - /// [`Self::write_body`], widening RLE count tables when `widen` (see [`Self::write_unpadded_as`]). - pub(crate) fn write_body_as(&self, out: &mut Vec, version: Version, widen: bool) -> Result<()> { - let start = out.len(); - self.write_unpadded_as(out, version, widen)?; + /// The body (without a length field) to a streaming [`Sink`], widening RLE count tables when + /// `widen` (see [`Self::write_unpadded_to`]). + pub(crate) fn write_body_to( + &self, + out: &mut Sink<'_, W>, + version: Version, + widen: bool, + ) -> std::io::Result<()> { + let start = out.pos(); + self.write_unpadded_to(out, version, widen)?; 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(()) } } diff --git a/crates/psd/src/tagged.rs b/crates/psd/src/tagged.rs index 6fce19bbe9..e54f4daf0b 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 @@ -508,6 +508,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 c725c7d3dc..9fadf9a00c 100644 --- a/crates/psd/src/tiff.rs +++ b/crates/psd/src/tiff.rs @@ -152,16 +152,54 @@ 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 signature, then the blocks in big-endian order. + fn body(&self) -> Result> { let version = self.version; + let signature = if version.is_psb() { SIGNATURE_PSB } else { SIGNATURE }; + let len_field = |key: &[u8; 4]| if uses_long_length(version, key) { 8u64 } else { 4 }; + // Reserved at its exact length, as the buffer holds all the layers' pixels: one that is a + // few bytes short doubles at its last append, copying them once more (#6607). + let mut len = signature.len() as u64; + let info_pad = match &self.layer_info { + Some(info) => { + let pad = info.pad_len(version, 4)?; + len = len.saturating_add(8 + len_field(&self.layer_info_key)).saturating_add(info.unpadded_len(version)?).saturating_add(pad as u64); + pad + } + None => 0, + }; + if let Some(m) = &self.global_layer_mask { + let pad = TaggedBlock::default_padding(m.data.len(), 4); + len = len.saturating_add(8 + len_field(b"LMsk")).saturating_add(m.data.len() as u64).saturating_add(pad as u64); + } + len = self.global_blocks.iter().fold(len, |n, b| n.saturating_add(b.encoded_len_aligned(version, 4) as u64)); + len = len.saturating_add(self.trailing.len() as u64); + let no_memory = || PsdError::OutOfMemory("not enough memory for the layer data"); let mut body = Vec::new(); + body.try_reserve_exact(usize::try_from(len).map_err(|_| no_memory())?).map_err(|_| no_memory())?; + body.put(signature); if let Some(info) = &self.layer_info { - // Pad to 4 without cloning the layers (and all their pixel data) just to set `padding`. - 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::OutOfMemory("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)?; + // 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 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() + info_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 +211,18 @@ 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` (signature included) converted to `order`. + fn finish(body: Vec, version: Version, order: ByteOrder) -> Result<(Vec, Vec)> { + if !order.is_little() { + return Ok((body, Vec::new())); + } + let signature = if version.is_psb() { SIGNATURE_PSB } else { SIGNATURE }; + let blocks = body.get(signature.len()..).ok_or_else(|| PsdError::invalid("image source data without its signature"))?; + // Converted behind the signature, into one buffer sized for both. + transcode::transcode_blocks_after(signature, blocks, version, ByteOrder::Big, ByteOrder::Little) } /// 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). @@ -223,6 +286,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]) } diff --git a/crates/psd/src/tiff/tests.rs b/crates/psd/src/tiff/tests.rs index 3836822bf4..533e534430 100644 --- a/crates/psd/src/tiff/tests.rs +++ b/crates/psd/src/tiff/tests.rs @@ -8,6 +8,32 @@ use crate::testgen; /// 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 a PSD writes the bytes copying them does, and leaves the +/// rest of the file (its merged image) as it was. The big-endian body is reserved at its exact +/// length, so the buffer is never grown (a copy of every layer's pixels). +#[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); + if !order.is_little() { + assert_eq!(b.0.capacity(), b.0.len(), "{}: the body grew", 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() && file.global_layer_mask.is_none(), "{}", case.name); + assert_eq!(file.image_data, case.file.image_data, "{}", case.name); + assert_eq!(file.header, case.file.header, "{}", 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 { @@ -973,6 +999,11 @@ fn global_blocks_written_without_copies_keep_their_bytes() { 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_blocks_after(signature, &body, version, ByteOrder::Big, ByteOrder::Little).unwrap(); + assert_eq!(after, [signature, &little[..]].concat()); + assert_eq!(after.capacity(), signature.len() + body.len()); } } diff --git a/crates/psd/src/tiff/transcode.rs b/crates/psd/src/tiff/transcode.rs index 31d12b702f..15c33d4a9d 100644 --- a/crates/psd/src/tiff/transcode.rs +++ b/crates/psd/src/tiff/transcode.rs @@ -7,6 +7,16 @@ pub fn transcode_blocks(data: &[u8], version: Version, from: ByteOrder, to: Byte 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::new(); + out.try_reserve_exact(prefix.len().saturating_add(data.len())).map_err(|_| PsdError::OutOfMemory("not enough memory for the layer data"))?; + 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); @@ -61,8 +71,13 @@ macro_rules! copy_int { 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) {