io: save layers past the gather size band by band, with their pixels, staged as they are encoded

This commit is contained in:
FredApps committed 2026-11-03 13:21:06 +01:00
1 parent afa0a86341
commit 52eed15281
4 files changed
+386 -8

No files matched your search

+5 -8
View File
@@ -15,6 +15,7 @@ use crate::blocks;
use crate::pixels::{deinterleave, encode_be, psd_depth};
use crate::psd_import::REGENERATED;
mod banded;
mod document;
mod estimate;
mod merged;
@@ -43,10 +44,6 @@ const PSD_MAX_FILE_SIZE: u64 = 2 * 1024 * 1024 * 1024;
/// Room kept under [`PSD_MAX_FILE_SIZE`] for what the save adds after the conversion (the image
/// preview resource, a few KB).
const PSD_SAVE_HEADROOM: u64 = 1024 * 1024;
/// Most bytes of one layer's interleaved samples the exporter gathers. The interleaved bytes and
/// the channel planes made from them (or the band parts and the joined buffer) are alive together,
/// so the peak is about twice this; it is also what fits in a file of at most [`PSD_MAX_FILE_SIZE`].
const MAX_LAYER_GATHER_BYTES: u64 = if cfg!(target_pointer_width = "64") { 1 << 30 } else { 256 << 20 };
/// Options for [`document_to_psd_with`].
#[derive(Debug, Clone)]
@@ -221,11 +218,11 @@ impl Ex {
return (PsdRect::default(), self.empty_channels(), warnings);
}
// A layer record is one dense rectangle, so a few pixels far apart make a box of mostly
// nothing, gathered and then copied again. Past the cap the layer is saved empty, said so.
// nothing, gathered and then copied again. Past `banded_from` the layer is gathered and
// encoded a band of rows at a time instead (#5333).
let dense = u64::from(r.width()).saturating_mul(u64::from(r.height())).saturating_mul(s.format().bytes_per_pixel() as u64);
if dense > MAX_LAYER_GATHER_BYTES {
warnings.push(format!("layer \"{name}\" spans {}×{} px, too large to write: saved without its pixels", r.width(), r.height()));
return (PsdRect::default(), self.empty_channels(), warnings);
if dense > banded::banded_from() {
return (to_psd_rect(r), self.banded_channels(&s, r), warnings);
}
// The interleaved gather is the sequential pass for full-canvas layers, so it runs
// in row bands on all cores and the band results concatenate in order.
+134
View File
@@ -0,0 +1,134 @@
//! Layers too large to gather at once, saved band by band (#5333).
//!
//! A layer record is one dense rectangle, gathered interleaved and split into channel planes,
//! so a layer's save held about twice its dense size; past [`BANDED_FROM`] that was refused and the
//! layer saved without its pixels. Now such a layer is gathered, split and encoded a band of
//! rows at a time. RLE rows pack independently (the row-count table is kept and written ahead of
//! the packed rows) and raw rows join, so those channels are the bytes the whole-layer encoder
//! writes. ZIP with prediction (32-bit) predicts per row and feeds one zlib stream: the same
//! pixels, but not always the same bytes, as zlib packs input it is given in parts differently.
//! With a stage each band's parts go to the scratch disk as they are made (see [`Parts`]).
use std::io::Write as _;
use photocraft_psd::compression::{PlaneLayout, encode_planes, predict};
use photocraft_psd::{ChannelData, Compression, PsdError};
use photocraft_raster::Surface;
use super::Ex;
use super::stage::Parts;
use crate::pixels::{deinterleave, psd_depth};
/// Dense bytes of one layer (as gathered) from which it is saved band by band. Below it a layer
/// is gathered whole, which is faster: the peak is about twice this.
pub(super) const BANDED_FROM: u64 = if cfg!(target_pointer_width = "64") { 1 << 30 } else { 256 << 20 };
/// Interleaved bytes gathered per band. A band's planes and encoded parts are alive with it, so a
/// banded layer's save holds about three times this.
const BAND_BYTES: usize = 64 << 20;
#[cfg(test)]
thread_local! {
/// `(BANDED_FROM, BAND_BYTES)` for this thread's exports, so tests band small layers.
pub(crate) static BANDS_FOR_TESTS: std::cell::Cell<Option<(u64, usize)>> = const { std::cell::Cell::new(None) };
}
pub(super) fn banded_from() -> u64 {
#[cfg(test)]
if let Some((from, _)) = BANDS_FOR_TESTS.get() {
return from;
}
BANDED_FROM
}
fn band_bytes() -> usize {
#[cfg(test)]
if let Some((_, bytes)) = BANDS_FOR_TESTS.get() {
return bytes;
}
BAND_BYTES
}
/// One channel's encoding state across bands.
struct Channel {
id: i16,
table: Vec<u8>,
zip: Option<flate2::write::ZlibEncoder<Vec<u8>>>,
parts: Parts,
}
impl Ex {
/// The channels of `s` over `r` (non-empty), alpha first, encoded band by band.
pub(super) fn banded_channels(&self, s: &Surface, r: photocraft_geom::Rect) -> Vec<ChannelData> {
// RLE fails only on a row too long for its count (not within PSD/PSB limits); then the
// layer is written raw, as a channel encoded whole falls back to.
self.banded_pass(s, r, self.compression()).or_else(|_| self.banded_pass(s, r, Compression::Raw)).unwrap_or_else(|_| self.empty_channels())
}
fn banded_pass(&self, s: &Surface, r: photocraft_geom::Rect, compression: Compression) -> photocraft_psd::Result<Vec<ChannelData>> {
let (w, h) = (r.width() as usize, r.height() as usize);
let bpp = s.format().bytes_per_pixel();
let band_rows = (band_bytes() / (w * bpp).max(1)).max(1);
let depth = psd_depth(self.fmt.sample);
let count = if self.version.is_psb() { 4 } else { 2 };
let head = if compression == Compression::Rle { h.checked_mul(count).ok_or(PsdError::LimitExceeded("row count overflow"))? } else { 0 };
let mut channels: Vec<Channel> = (0..=self.cc)
.map(|k| Channel {
id: k as i16 - 1,
table: Vec::with_capacity(head),
zip: (compression == Compression::ZipPrediction).then(|| flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default())),
parts: Parts::new(self.stage.clone(), head),
})
.collect();
let mut invert = vec![self.cmyk; self.cc];
invert.push(false);
for y in (0..h).step_by(band_rows) {
let rows = band_rows.min(h - y);
let top = r.y0 + y as i32;
let pieces = crate::pixels::par_map(crate::pixels::bands(rows), |b| {
s.to_interleaved(photocraft_geom::Rect::new(r.x0, top + b.start as i32, r.x1, top + b.end as i32))
});
let mut bytes = Vec::with_capacity(w * rows * bpp);
for piece in pieces {
bytes.extend_from_slice(&piece);
}
if self.fmt.mode == photocraft_color::ColorMode::Lab && self.fmt.sample == photocraft_color::SampleType::U16 {
crate::pixels::lab16_chroma(&mut bytes, self.cc + 1, false);
}
let mut planes: Vec<Option<Vec<u8>>> = deinterleave(&bytes, self.cc + 1, self.fmt.sample, &invert).into_iter().map(Some).collect();
drop(bytes);
let layout = PlaneLayout { planes: 1, width: w, height: rows, depth, version: self.version };
// Alpha (planes[cc]) is channel 0, then the colour channels; each on its own thread.
let work: Vec<(&mut Channel, Vec<u8>)> =
channels.iter_mut().enumerate().map(|(k, c)| (c, planes[if k == 0 { self.cc } else { k - 1 }].take().unwrap_or_default())).collect();
let done = crate::pixels::par_map(work, |(c, mut plane)| -> photocraft_psd::Result<()> {
match compression {
Compression::Rle => {
let mut packed = encode_planes(Compression::Rle, &plane, &layout)?;
let rest = packed.split_off(rows * count);
c.table.extend_from_slice(&packed);
c.parts.push(rest);
}
Compression::ZipPrediction => {
predict(&mut plane, &layout)?;
let zip = c.zip.as_mut().ok_or_else(|| PsdError::Invalid("banded ZIP channel without its stream".into()))?;
zip.write_all(&plane).map_err(|e| PsdError::Invalid(format!("zlib: {e}")))?;
let out = std::mem::take(zip.get_mut());
c.parts.push(out);
}
_ => c.parts.push(plane),
}
Ok(())
});
done.into_iter().collect::<photocraft_psd::Result<()>>()?;
}
channels
.into_iter()
.map(|mut c| {
if let Some(zip) = c.zip.take() {
c.parts.push(zip.finish().map_err(|e| PsdError::Invalid(format!("zlib: {e}")))?);
}
c.parts.finish(c.id, compression, &c.table)
})
.collect()
}
}
+120
View File
@@ -95,9 +95,129 @@ impl Stage {
image
}
/// Appends one part of a channel written band by band; `None` when the write fails.
fn append(&self, data: &[u8]) -> Option<u64> {
self.file.0.append(data).ok()
}
/// Bytes on the scratch disk.
#[cfg(test)]
pub(crate) fn len(&self) -> u64 {
self.file.0.len()
}
}
/// One channel of a layer encoded band by band (#5333): its head (an RLE row-count table, filled
/// in when the last band is encoded) and the bands' encoded parts in order. With a stage every
/// part goes to the scratch disk as it is made, so a layer of any size is saved holding about one
/// band; without one the parts are joined in memory, as a channel encoded whole would be.
pub(crate) struct Parts {
stage: Option<Arc<Stage>>,
head_len: usize,
/// Without a stage: the head's room and the parts so far.
joined: Vec<u8>,
/// With a stage: the parts, staged or (when a write failed) kept.
parts: Vec<Part>,
len: u64,
}
enum Part {
Kept(Vec<u8>),
Staged { offset: u64, len: u64 },
}
impl Part {
fn len(&self) -> u64 {
match self {
Part::Kept(v) => v.len() as u64,
Part::Staged { len, .. } => *len,
}
}
}
impl Parts {
pub(crate) fn new(stage: Option<Arc<Stage>>, head_len: usize) -> Self {
let joined = if stage.is_none() { vec![0; head_len] } else { Vec::new() };
Parts { stage, head_len, joined, parts: Vec::new(), len: head_len as u64 }
}
/// Adds the next encoded part.
pub(crate) fn push(&mut self, data: Vec<u8>) {
if data.is_empty() {
return;
}
self.len += data.len() as u64;
match &self.stage {
None => self.joined.extend_from_slice(&data),
Some(stage) => self.parts.push(match stage.append(&data) {
Some(offset) => Part::Staged { offset, len: data.len() as u64 },
None => Part::Kept(data),
}),
}
}
/// The channel: `head` (of the length given to [`Parts::new`]) and then the parts.
pub(crate) fn finish(mut self, id: i16, compression: photocraft_psd::Compression, head: &[u8]) -> photocraft_psd::Result<ChannelData> {
if head.len() != self.head_len {
return Err(PsdError::Invalid("banded channel head has the wrong length".into()));
}
let Some(stage) = self.stage else {
self.joined[..head.len()].copy_from_slice(head);
self.joined.shrink_to_fit();
return Ok(ChannelData::new(id, Some(compression), self.joined));
};
let mut parts = Vec::with_capacity(self.parts.len() + 1);
if !head.is_empty() {
parts.push(Part::Kept(head.to_vec()));
}
parts.append(&mut self.parts);
let mut starts = Vec::with_capacity(parts.len());
let mut at = 0;
for p in &parts {
starts.push(at);
at += p.len();
}
let joined = Joined { file: stage.file.clone(), parts, starts, len: self.len };
let stored = Stored { source: Source::from_arc(Arc::new(joined)), offset: 0, len: self.len };
Ok(ChannelData { id, compression: Some(compression), data: Vec::new(), stored: Some(stored) })
}
}
/// A banded channel's bytes, in memory and in its staged parts. A read is split at the parts, so
/// the writer's consecutive pass reads each staged append from its start to its end, and the stage
/// file checks it.
struct Joined {
file: Arc<Backing>,
parts: Vec<Part>,
starts: Vec<u64>,
len: u64,
}
impl ReadAt for Joined {
fn len(&self) -> u64 {
self.len
}
fn read_at(&self, offset: u64, buf: &mut [u8]) -> photocraft_psd::Result<()> {
if offset.checked_add(buf.len() as u64).is_none_or(|end| end > self.len) {
return Err(PsdError::Read(format!("staged export data, {} bytes at offset {offset} past its {} bytes", buf.len(), self.len)));
}
let mut pos = offset;
let mut buf = buf;
let mut i = self.starts.partition_point(|&s| s <= pos).saturating_sub(1);
while !buf.is_empty() {
let (part, start) = (&self.parts[i], self.starts[i]);
let within = pos - start;
let n = usize::try_from((part.len() - within).min(buf.len() as u64)).unwrap_or(buf.len());
let (now, rest) = std::mem::take(&mut buf).split_at_mut(n);
match part {
Part::Kept(v) => now.copy_from_slice(&v[within as usize..within as usize + n]),
Part::Staged { offset, .. } => self.file.read_at(offset + within, now)?,
}
buf = rest;
pos += n as u64;
i += 1;
}
Ok(())
}
}
+127
View File
@@ -672,3 +672,130 @@ fn staging_keeps_short_or_unwritable_data_in_memory() {
assert!(stage::Stage::for_document(10, None).is_none(), "not asked for");
let _ = std::fs::remove_dir(&dir);
}
/// The first layer's channels, decoded.
fn decoded_channels(file: &PsdFile) -> Vec<Vec<u8>> {
let layer = &file.layers()[0];
let (w, h) = (layer.rect.width() as usize, layer.rect.height() as usize);
layer.channels.iter().map(|c| c.decode(w, h, file.header.depth, file.header.version).unwrap()).collect()
}
/// A noisy, translucent layer inset from the canvas: `w`×`h` px in `mode`/`depth`.
fn banding_document(mode: ColorMode, depth: SampleType, w: u32, h: u32) -> Document {
let mut doc = Document::new("banded", photocraft_geom::Size::new(w, h), mode, depth);
let mut layer = Layer::raster("Layer 1", doc.pixel_format());
let rect = photocraft_geom::Rect::new(5, 3, w as i32 - 7, h as i32 - 2);
let surface = layer.surface_mut().unwrap();
let ch = surface.channels();
let mut state = 0x2545_f491_u32;
let n = rect.width() as usize * rect.height() as usize * ch;
let data: Vec<f32> = (0..n)
.map(|i| {
state ^= state << 13;
state ^= state >> 17;
state ^= state << 5;
// Runs as well as noise, so RLE packs both kinds of row.
let v = if (i / (ch * 40)).is_multiple_of(3) { 0.5 } else { (state >> 20) as f32 / 4095.0 };
if i % ch == ch - 1 { v.max(0.25) } else { v }
})
.collect();
surface.write_region(rect, &data);
doc.layers.push(layer);
doc
}
/// Exports `doc` with layers past `banded` bytes saved in bands of `rows` rows.
fn export_banded(doc: &Document, options: &PsdExportOptions, banded: Option<usize>) -> (PsdFile, Vec<String>) {
let row_bytes = doc.size.width as usize * doc.pixel_format().bytes_per_pixel();
banded::BANDS_FOR_TESTS.set(banded.map(|rows| (0, rows * row_bytes + 3)));
let out = document_to_psd_sized(doc, options, 0, &Interrupt::NONE, PSD_MAX_FILE_SIZE);
banded::BANDS_FOR_TESTS.set(None);
out
}
/// #5333: a layer saved band by band (here every layer, in bands of a few rows) writes the bytes
/// of one gathered whole (ZIP with prediction, 32-bit, the same pixels); RGB, CMYK and Lab; PSD, PSB and a PSD
/// promoted to PSB; in memory and staged on the scratch disk (then also streamed).
#[test]
fn banded_layers_write_the_bytes_of_whole_ones() {
let dir = std::env::temp_dir().join(format!("pc-psd-banded-{}", std::process::id()));
let cases = [
(ColorMode::Rgb, SampleType::U8),
(ColorMode::Rgb, SampleType::U16),
(ColorMode::Rgb, SampleType::F32),
(ColorMode::Cmyk, SampleType::U8),
(ColorMode::Lab, SampleType::U16),
];
for (mode, depth) in cases {
let doc = banding_document(mode, depth, 203, 157);
for force_psb in [false, true] {
for staged in [false, true] {
stage::DIR_FOR_TESTS.with(|d| *d.borrow_mut() = staged.then(|| dir.clone()));
let options = PsdExportOptions { force_psb, stage_on_scratch_from: staged.then_some(0), ..Default::default() };
let (want, want_warnings) = export_banded(&doc, &options, None);
for rows in [1, 7, 1000] {
let what = format!("{mode:?} {depth:?}, psb {force_psb}, staged {staged}, {rows} rows a band");
let (file, warnings) = export_banded(&doc, &options, Some(rows));
assert_eq!(warnings, want_warnings, "{what}");
let layer = &file.layers()[0];
assert_eq!(layer.rect, want.layers()[0].rect, "{what}");
if staged {
assert!(layer.channels.iter().all(|c| c.stored.is_some() && c.data.is_empty()), "{what}: banded channels are staged");
}
if depth == SampleType::F32 {
// One zlib stream fed band by band packs differently from one fed whole
// (the encoder sees a different amount of input ahead), so the ZIP
// channels are compared decoded, here and as the streamed file reads back.
let mut w = std::io::Cursor::new(Vec::new());
file.write_to(&mut w).unwrap();
let back = PsdFile::from_bytes(&w.into_inner()).unwrap();
assert_eq!(decoded_channels(&back), decoded_channels(&want), "{what}: banded ZIP channels differ");
assert!(back.image_data.encoded().unwrap() == want.image_data.encoded().unwrap(), "{what}");
continue;
}
let bytes = want.to_bytes().unwrap();
assert!(file.to_bytes().unwrap() == bytes, "{what}: banded bytes differ");
let mut w = std::io::Cursor::new(Vec::new());
file.write_to(&mut w).unwrap();
assert!(w.into_inner() == bytes, "{what}: streamed banded bytes differ");
if !force_psb {
let (mut promoted, mut whole) = (file.clone(), want.clone());
promoted.promote_to_psb().unwrap();
whole.promote_to_psb().unwrap();
let mut w = std::io::Cursor::new(Vec::new());
promoted.write_to(&mut w).unwrap();
assert!(w.into_inner() == whole.to_bytes().unwrap(), "{what}: promoted banded bytes differ");
}
}
}
}
}
stage::DIR_FOR_TESTS.with(|d| *d.borrow_mut() = None);
let _ = std::fs::remove_dir_all(&dir);
}
/// #5333: a layer past the gather size is saved with its pixels (it used to be saved empty, with a
/// warning), and they come back on import.
#[test]
fn banded_layers_round_trip() {
let dir = std::env::temp_dir().join(format!("pc-psd-banded-rt-{}", std::process::id()));
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
let doc = banding_document(ColorMode::Rgb, depth, 181, 133);
for staged in [false, true] {
stage::DIR_FOR_TESTS.with(|d| *d.borrow_mut() = staged.then(|| dir.clone()));
let options = PsdExportOptions { stage_on_scratch_from: staged.then_some(0), ..Default::default() };
let (file, warnings) = export_banded(&doc, &options, Some(5));
assert!(warnings.is_empty(), "{warnings:?}");
let mut w = std::io::Cursor::new(Vec::new());
file.write_to(&mut w).unwrap();
let back = PsdFile::from_bytes(&w.into_inner()).unwrap();
let (read, _) = crate::psd_import::psd_to_document(&back);
let full = photocraft_geom::Rect::new(0, 0, doc.size.width as i32, doc.size.height as i32);
let want = doc.layers[0].surface().unwrap().read_region(full);
let got = read.layers[0].surface().unwrap().read_region(full);
assert!(got == want, "{depth:?}, staged {staged}: pixels differ after the round trip");
}
}
stage::DIR_FOR_TESTS.with(|d| *d.borrow_mut() = None);
let _ = std::fs::remove_dir_all(&dir);
}