PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Tests: generated large-file fixtures and a P20 number (#5107)
David Mann8eef90bf7ede
diff --git a/crates/io/examples/big_psb_check.rs b/crates/io/examples/big_psb_check.rsindex 9b1eb80d4..3d0f40758 100644--- a/crates/io/examples/big_psb_check.rs+++ b/crates/io/examples/big_psb_check.rs@@ -1,14 +1,10 @@//! Opens the files written by `photocraft-psd`'s `big_psb` example and checks their pixels.//!//! `cargo run --release -p photocraft-io --example big_psb_check -- <file.psb>...`+//!+//! The opt-in tests in `tests/large_files.rs` generate and check the same files.-fn sample(x: u32, y: u32, c: u32, rle: bool) -> u8 {- if c == 3 {- return 255;- }- let x = if rle { 0 } else { x };- (x.wrapping_mul(7).wrapping_add(y.wrapping_mul(13)).wrapping_add(c.wrapping_mul(101)) & 0xff) as u8-}+use photocraft_psd::fixtures::sample;fn main() {for path in std::env::args().skip(1) {diff --git a/crates/io/tests/large_files.rs b/crates/io/tests/large_files.rsnew file mode 100644index 000000000..f492dd2d6--- /dev/null+++ b/crates/io/tests/large_files.rs@@ -0,0 +1,166 @@+//! Large-file fixtures (#216, #5107), generated at test time by `photocraft_psd::fixtures`: a 20 MP+//! layered PSD, a 150-layer layout, a PSD just under Photoshop's 2 GB cap and a 4.4 GB PSB. Each+//! is opened through `photocraft_io`, checked (size, layers, masks, effects, merged pixels), saved+//! again and re-opened.+//!+//! The two layered documents run in memory; the streamed files are written to+//! `$PHOTOCRAFT_FIXTURE_DIR` (default: the system temp dir), removed afterwards, and are opt-in:+//! `cargo test --release -p photocraft-io --test large_files -- --ignored`.++use std::path::PathBuf;++use photocraft_doc::{Document, LayerContent};+use photocraft_geom::Rect;+use photocraft_psd::Version;+use photocraft_psd::fixtures::{Grid, LAYERED_20MP, LAYOUT_150, PSB_4GB, PSD_2GB, Streamed};++/// Raster layers, groups, masked layers, layers with effects and hidden layers in `doc`.+fn census(doc: &Document) -> [usize; 5] {+ let mut n = [0; 5];+ for (_, _, l) in doc.walk() {+ match l.content {+ LayerContent::Raster(_) => n[0] += 1,+ LayerContent::Group(_) => n[1] += 1,+ _ => {}+ }+ n[2] += usize::from(l.mask.is_some());+ n[3] += usize::from(!l.effects.items.is_empty());+ n[4] += usize::from(!l.visible);+ }+ n+}++fn check_grid(g: &Grid, doc: &Document, what: &str) {+ assert_eq!((doc.size.width, doc.size.height), (g.width, g.height), "{what}");+ let layers: Vec<_> = (0..g.layers).filter_map(|i| g.layer(i)).collect();+ let want = [+ g.layers as usize + 1,+ g.rows() as usize,+ layers.iter().filter(|l| l.masked).count(),+ layers.iter().filter(|l| l.shadow).count(),+ layers.iter().filter(|l| l.hidden).count(),+ ];+ assert_eq!(census(doc), want, "{what}: [raster, groups, masked, with effects, hidden]");+ for (x, y) in g.sample_points() {+ let px = photocraft_compose::render(doc, Rect::from_xywh(x as i32, y as i32, 1, 1)).px;+ let got = px.first().copied().unwrap_or_default();+ let want = g.expected(x, y);+ for c in 0..3 {+ let v = (got[c] * 255.0).round() as i32;+ assert!((v - i32::from(want[c])).abs() <= 1, "{what}: ({x}, {y}) channel {c}: got {v}, want {}", want[c]);+ }+ assert!(got[3] > 0.999, "{what}: ({x}, {y}) is not opaque");+ }+}++/// Builds `g`, opens it, checks it, saves it as PSD and checks the re-opened file.+fn grid_roundtrip(g: Grid, what: &str) {+ let t = std::time::Instant::now();+ let bytes = g.build(Version::Psd).and_then(|f| f.to_bytes()).unwrap();+ let gen_s = t.elapsed().as_secs_f64();+ let t = std::time::Instant::now();+ let res = photocraft_io::import("fixture.psd", &bytes).unwrap();+ let open_s = t.elapsed().as_secs_f64();+ check_grid(&g, &res.document, what);+ let out = photocraft_io::export(&res.document, "fixture.psd", &Default::default()).unwrap();+ let again = photocraft_io::import("fixture.psd", &out.bytes).unwrap();+ check_grid(&g, &again.document, &format!("{what}, saved and re-opened"));+ eprintln!(+ "{what}: {:.1} MB, generated in {gen_s:.2} s, opened in {open_s:.2} s, saved as {:.1} MB",+ bytes.len() as f64 / 1e6,+ out.bytes.len() as f64 / 1e6+ );+}++/// 150 layers in 15 groups on A4 at 300 ppi, with masks, hidden layers, closed groups and drop+/// shadows.+#[test]+fn layout_with_150_layers_opens_and_saves() {+ grid_roundtrip(LAYOUT_150, "150-layer layout");+}++/// A 20 MP layered photo: background, five layers in two groups, a mask and a drop shadow.+#[test]+fn layered_20_mp_psd_opens_and_saves() {+ grid_roundtrip(LAYERED_20MP, "20 MP layered");+}++fn fixture_dir() -> PathBuf {+ let dir = std::env::var_os("PHOTOCRAFT_FIXTURE_DIR").map_or_else(std::env::temp_dir, PathBuf::from).join("photocraft-large-files");+ std::fs::create_dir_all(&dir).unwrap();+ dir+}++/// Removes the file when the test ends, passed or not.+struct Remove(PathBuf);++impl Drop for Remove {+ fn drop(&mut self) {+ let _ = std::fs::remove_file(&self.0);+ }+}++fn check_streamed(case: &Streamed, doc: &Document, what: &str) {+ assert_eq!((doc.size.width, doc.size.height), (case.width, case.height), "{what}");+ assert_eq!(doc.layers.len(), 1, "{what}");+ let s = doc.layers[0].surface().unwrap();+ let (w, h) = (case.width, case.height);+ for (x, y) in [(0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1), (w / 2, h / 2), (w / 3, h * 2 / 3), (12_345 % w, h - 7)] {+ let got = s.pixel(x as i32, y as i32);+ assert_eq!(got.len(), 4, "{what}");+ for (c, v) in got.iter().enumerate() {+ let want = f32::from(case.sample(x, y, c as u32)) / 255.0;+ assert!((v - want).abs() <= 1.0 / 510.0, "{what}: ({x}, {y}) channel {c}: got {v}, want {want}");+ }+ }+}++/// Writes `case`, opens it, checks it, saves it again (the writer picks PSD or PSB) and checks the+/// re-opened file.+fn streamed_roundtrip(case: &Streamed) {+ let path = fixture_dir().join(case.file_name());+ let _cleanup = Remove(path.clone());+ let t = std::time::Instant::now();+ let len = case.write_file(&path).unwrap();+ assert_eq!(std::fs::metadata(&path).unwrap().len(), len);+ eprintln!("{}: {:.2} GB written in {:.1} s", case.name, len as f64 / 1e9, t.elapsed().as_secs_f64());++ let t = std::time::Instant::now();+ let bytes = std::fs::read(&path).unwrap();+ let res = photocraft_io::import(&case.file_name(), &bytes).unwrap();+ drop(bytes);+ eprintln!("{}: read and opened in {:.1} s, warnings {:?}", case.name, t.elapsed().as_secs_f64(), res.warnings);+ check_streamed(case, &res.document, case.name);++ let t = std::time::Instant::now();+ let out = photocraft_io::export(&res.document, &case.file_name(), &Default::default()).unwrap();+ drop(res);+ // Version 2 = PSB: a re-save past 2 GB must switch to PSB; a smaller one stays PSD.+ let psb = out.bytes.get(4..6) == Some(&[0, 2]);+ assert!(psb || (case.version == Version::Psd && (out.bytes.len() as u64) < photocraft_psd::fixtures::PSD_MAX_FILE_BYTES), "{}", case.name);+ eprintln!(+ "{}: saved {:.2} GB ({}) in {:.1} s, warnings {:?}",+ case.name,+ out.bytes.len() as f64 / 1e9,+ if psb { "PSB" } else { "PSD" },+ t.elapsed().as_secs_f64(),+ out.warnings+ );+ let again = photocraft_io::import(if psb { "again.psb" } else { "again.psd" }, &out.bytes).unwrap();+ drop(out);+ check_streamed(case, &again.document, &format!("{}, saved and re-opened", case.name));+}++/// A 17,000² layered PSD of 2.02 GB, just under Photoshop's 2 GB PSD cap.+#[test]+#[ignore = "writes a 2 GB file and needs ~12 GB of memory; run in release"]+fn psd_just_under_2_gb_opens_and_saves() {+ streamed_roundtrip(&PSD_2GB);+}++/// A 25,000² layered PSB of 4.38 GB: layer channels of 625 MB, data past 4 GiB (#375).+#[test]+#[ignore = "writes a 4.4 GB file and needs ~25 GB of memory; run in release"]+fn psb_of_4_gb_opens_and_saves() {+ streamed_roundtrip(&PSB_4GB);+}diff --git a/crates/psd/examples/big_psb.rs b/crates/psd/examples/big_psb.rsindex 332936c1e..23bf4de77 100644--- a/crates/psd/examples/big_psb.rs+++ b/crates/psd/examples/big_psb.rs@@ -1,186 +1,24 @@-//! Writes multi-gigabyte PSB files for large-file tests (#375, #216), straight from the Adobe-//! PSD spec and independent of this crate's writer, so the fixtures don't inherit its limits.+//! Writes multi-gigabyte PSB files (and the 2 GB PSD) for large-file tests (#375, #216), straight+//! from the Adobe PSD spec and independent of this crate's writer, so the fixtures don't inherit+//! its limits. The generator is `photocraft_psd::fixtures` (feature `testgen`).//!//! `cargo run --release -p photocraft-psd --example big_psb -- <out dir> [case...]`//!-//! Every sample follows [`sample`], so a reader can check any pixel without the file. RLE cases-//! keep each row constant (tiny files, full decoded size); raw cases vary along x too.+//! Every sample follows `fixtures::sample`, so a reader can check any pixel without the file. RLE+//! cases keep each row constant (tiny files, full decoded size); raw cases vary along x too.-use std::fs::File;-use std::io::{self, BufWriter, Write};-use std::path::Path;+use photocraft_psd::fixtures::{PSB_CASES, PSD_2GB};-/// One generated file.-struct Case {- name: &'static str,- width: u32,- height: u32,- depth: u16,- /// Raw (0) or RLE (1).- rle: bool,- /// One full-canvas RGBA layer, or a flattened file (composite only).- layered: bool,-}--const CASES: &[Case] = &[- // Composite of 2.52 GB in one decode.- Case { name: "flat8-29k-rle", width: 29_000, height: 29_000, depth: 8, rle: true, layered: false },- // A 4.8 GB file: offsets past 4 GiB, composite of 4.8 GB.- Case { name: "flat8-40k-raw", width: 40_000, height: 40_000, depth: 8, rle: false, layered: false },- // 4.38 GB file: layer channels of 625 MB, composite of 1.9 GB, data past 4 GiB.- Case { name: "layer8-25k-raw", width: 25_000, height: 25_000, depth: 8, rle: false, layered: true },- // Layer channels of 900 MB, composite of 2.7 GB.- Case { name: "layer8-30k-rle", width: 30_000, height: 30_000, depth: 8, rle: true, layered: true },- // Layer channels of 2.18 GB each.- Case { name: "layer16-33k-rle", width: 33_000, height: 33_000, depth: 16, rle: true, layered: true },-];--/// The 8-bit sample of channel `c` (0..3 colour, 3 = alpha) at (`x`, `y`). RLE files ignore `x`.-/// 16-bit files store `v * 257`.-pub fn sample(x: u32, y: u32, c: u32, rle: bool) -> u8 {- if c == 3 {- return 255;- }- let x = if rle { 0 } else { x };- (x.wrapping_mul(7).wrapping_add(y.wrapping_mul(13)).wrapping_add(c.wrapping_mul(101)) & 0xff) as u8-}--fn main() -> io::Result<()> {+fn main() -> std::io::Result<()> {let args: Vec<String> = std::env::args().skip(1).collect();let out = args.first().map_or_else(|| std::env::temp_dir().join("photocraft-big-psb"), std::path::PathBuf::from);std::fs::create_dir_all(&out)?;let wanted = args.get(1..).unwrap_or(&[]);- for case in CASES.iter().filter(|c| wanted.is_empty() || wanted.iter().any(|w| w == c.name)) {- let path = out.join(format!("{}.psb", case.name));+ for case in PSB_CASES.iter().chain([&PSD_2GB]).filter(|c| wanted.is_empty() || wanted.iter().any(|w| w == c.name)) {+ let path = out.join(case.file_name());let t = std::time::Instant::now();- write_case(case, &path)?;- let len = std::fs::metadata(&path)?.len();+ let len = case.write_file(&path)?;println!("{}: {:.2} GB in {:.1} s", path.display(), len as f64 / 1e9, t.elapsed().as_secs_f64());}Ok(())}--fn row_bytes(c: &Case) -> u64 {- u64::from(c.width) * u64::from(c.depth / 8)-}--/// PackBits for a row of `n` equal bytes: runs of 128, then the remainder.-fn rle_row(n: u64, b: u8) -> Vec<u8> {- let mut v = Vec::new();- let mut left = n;- while left > 0 {- let run = left.min(128);- if run == 1 {- v.extend_from_slice(&[0, b]);- } else {- v.extend_from_slice(&[(257 - run) as u8, b]);- }- left -= run;- }- v-}--/// The bytes of one row of channel `ch`.-fn row(c: &Case, y: u32, ch: u32, buf: &mut Vec<u8>) {- buf.clear();- if c.rle {- buf.extend(rle_row(row_bytes(c), sample(0, y, ch, true)));- return;- }- for x in 0..c.width {- let s = sample(x, y, ch, false);- buf.push(s);- if c.depth == 16 {- buf.push(s);- }- }-}--/// Size of a channel block (compression word, RLE counts, rows) of `planes` planes.-fn channel_len(c: &Case, planes: u64) -> u64 {- let rows = planes * u64::from(c.height);- if c.rle { 2 + rows * 4 + rows * rle_row(row_bytes(c), 0).len() as u64 } else { 2 + rows * row_bytes(c) }-}--/// Writes the compression word, the counts and the rows of `chans`.-fn write_planes(w: &mut impl Write, c: &Case, chans: &[u32]) -> io::Result<()> {- w.write_all(&u16::from(c.rle).to_be_bytes())?;- if c.rle {- let n = rle_row(row_bytes(c), 0).len() as u32;- for _ in 0..chans.len() as u64 * u64::from(c.height) {- w.write_all(&n.to_be_bytes())?;- }- }- let mut buf = Vec::new();- for &ch in chans {- for y in 0..c.height {- row(c, y, ch, &mut buf);- w.write_all(&buf)?;- }- }- Ok(())-}--fn write_case(c: &Case, path: &Path) -> io::Result<()> {- let mut w = BufWriter::with_capacity(8 << 20, File::create(path)?);- // Header: PSB (version 2), 3 channels, RGB.- w.write_all(b"8BPS")?;- w.write_all(&2u16.to_be_bytes())?;- w.write_all(&[0; 6])?;- w.write_all(&3u16.to_be_bytes())?;- w.write_all(&c.height.to_be_bytes())?;- w.write_all(&c.width.to_be_bytes())?;- w.write_all(&c.depth.to_be_bytes())?;- w.write_all(&3u16.to_be_bytes())?;- // Colour mode data and image resources: empty.- w.write_all(&0u32.to_be_bytes())?;- w.write_all(&0u32.to_be_bytes())?;-- if c.layered {- // Transparency (-1), then R, G, B: one block per channel.- let ids: [(i16, u32); 4] = [(-1, 3), (0, 0), (1, 1), (2, 2)];- let ch_len = channel_len(c, 1);- let name = b"Layer 1";- let mut rec = Vec::new();- for v in [0i32, 0, c.height as i32, c.width as i32] {- rec.extend_from_slice(&v.to_be_bytes());- }- rec.extend_from_slice(&4u16.to_be_bytes());- for (id, _) in ids {- rec.extend_from_slice(&id.to_be_bytes());- rec.extend_from_slice(&ch_len.to_be_bytes());- }- rec.extend_from_slice(b"8BIMnorm");- rec.extend_from_slice(&[255, 0, 0, 0]);- // Extra data: no mask, no blending ranges, the Pascal name padded to 4.- let mut extra = Vec::new();- extra.extend_from_slice(&0u32.to_be_bytes());- extra.extend_from_slice(&0u32.to_be_bytes());- extra.push(name.len() as u8);- extra.extend_from_slice(name);- while extra.len() % 4 != 0 {- extra.push(0);- }- rec.extend_from_slice(&(extra.len() as u32).to_be_bytes());- rec.extend_from_slice(&extra);-- let mut layer_info = 2 + rec.len() as u64 + 4 * ch_len;- let pad = layer_info % 2;- layer_info += pad;- // Layer and mask information: layer info (8-byte length) + empty global mask (4 bytes).- w.write_all(&(8 + layer_info + 4).to_be_bytes())?;- w.write_all(&layer_info.to_be_bytes())?;- w.write_all(&1i16.to_be_bytes())?;- w.write_all(&rec)?;- for (_, ch) in ids {- write_planes(&mut w, c, &[ch])?;- }- w.write_all(&vec![0; pad as usize])?;- w.write_all(&0u32.to_be_bytes())?;- } else {- w.write_all(&0u64.to_be_bytes())?;- }- // The merged image.- write_planes(&mut w, c, &[0, 1, 2])?;- w.flush()-}diff --git a/crates/psd/src/fixtures.rs b/crates/psd/src/fixtures.rsnew file mode 100644index 000000000..a8bd3d43c--- /dev/null+++ b/crates/psd/src/fixtures.rs@@ -0,0 +1,566 @@+//! Large-file stress fixtures (#216, #375, #5107), generated at test time and never committed.+//!+//! Two kinds:+//!+//! * [`Streamed`]: multi-gigabyte PSD/PSB files written straight from the Adobe PSD spec, row by+//! row, independent of [`PsdBuilder`] (so they don't inherit its limits, and the generator needs+//! a few megabytes of memory however large the file). One full-canvas layer (or none) plus the+//! merged image; every sample follows [`sample`], so a reader can check any pixel without the+//! file. [`PSD_2GB`] is the largest file Photoshop saves as PSD; [`PSB_CASES`] are 2.5–5 GB.+//! * [`Grid`]: layered documents built with [`PsdBuilder`]: a background and a grid of layers in+//! groups, with masks, a hidden layer, a closed group and drop shadows. [`LAYERED_20MP`] is the+//! 20 MP photo-sized document, [`LAYOUT_150`] the 150-layer A4 layout. [`Grid::expected`] is+//! the merged colour at any point away from the shadows ([`Grid::sample_points`] lists some).+//!+//! Photoshop's limits, which the presets respect: a PSD is at most 30,000 px a side and 2 GB; a+//! PSB at most 300,000 px a side.++use std::io::{self, Write};++use crate::builder::{GroupSpec, LayerSpec, MaskSpec, PixelData, PsdBuilder};+use crate::descriptor::{Descriptor, Id, Value, VersionedDescriptor};+use crate::error::Result;+use crate::file::PsdFile;+use crate::header::Version;+use crate::layer::Rect;+use crate::tagged::TaggedBlock;++/// Photoshop's PSD size cap: files of 2 GB or more must be PSB.+pub const PSD_MAX_FILE_BYTES: u64 = 2 * 1024 * 1024 * 1024;+/// Photoshop's PSD side cap (px).+pub const PSD_MAX_SIDE: u32 = 30_000;++/// The 8-bit sample of channel `c` (0..3 colour, 3 = alpha) at (`x`, `y`) in a [`Streamed`] file.+/// RLE files ignore `x` (constant rows compress to almost nothing). 16-bit files store `v * 257`.+pub fn sample(x: u32, y: u32, c: u32, rle: bool) -> u8 {+ if c == 3 {+ return 255;+ }+ let x = if rle { 0 } else { x };+ (x.wrapping_mul(7).wrapping_add(y.wrapping_mul(13)).wrapping_add(c.wrapping_mul(101)) & 0xff) as u8+}++/// A large RGB file written row by row.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct Streamed {+ /// File stem, e.g. `layer8-25k-raw`.+ pub name: &'static str,+ /// PSD (v1) or PSB (v2).+ pub version: Version,+ /// Width (px).+ pub width: u32,+ /// Height (px).+ pub height: u32,+ /// 8 or 16.+ pub depth: u16,+ /// RLE (PackBits) or raw.+ pub rle: bool,+ /// One full-canvas RGBA layer, or a flattened file (merged image only).+ pub layered: bool,+}++const fn psb(name: &'static str, side: u32, depth: u16, rle: bool, layered: bool) -> Streamed {+ Streamed { name, version: Version::Psb, width: side, height: side, depth, rle, layered }+}++/// A 2.02 GB layered PSD just under Photoshop's 2 GB cap: 17,000² px, one raw full-canvas layer+/// (289 MB per channel) and the raw merged image.+pub const PSD_2GB: Streamed =+ Streamed { name: "psd-layer8-17k-raw", version: Version::Psd, width: 17_000, height: 17_000, depth: 8, rle: false, layered: true };++/// The 4–5 GB PSB generated for #375 and #216.+pub const PSB_CASES: [Streamed; 5] = [+ // Composite of 2.52 GB in one decode.+ psb("flat8-29k-rle", 29_000, 8, true, false),+ // A 4.8 GB file: offsets past 4 GiB, composite of 4.8 GB.+ psb("flat8-40k-raw", 40_000, 8, false, false),+ // 4.38 GB file: layer channels of 625 MB, composite of 1.9 GB, data past 4 GiB.+ PSB_4GB,+ // Layer channels of 900 MB, composite of 2.7 GB.+ psb("layer8-30k-rle", 30_000, 8, true, true),+ // Layer channels of 2.18 GB each.+ psb("layer16-33k-rle", 33_000, 16, true, true),+];++/// The layered 4.38 GB PSB (25,000² px, raw): layer data and the merged image past 4 GiB.+pub const PSB_4GB: Streamed = psb("layer8-25k-raw", 25_000, 8, false, true);++/// PackBits for a row of `n` equal bytes: runs of 128, then the remainder.+fn rle_row(n: u64, b: u8) -> Vec<u8> {+ let mut v = Vec::new();+ let mut left = n;+ while left > 0 {+ let run = left.min(128);+ // `run` is 1..=128, so 257 - run is 129..=256 and only 256 (run 1) needs the literal form.+ if run == 1 {+ v.extend_from_slice(&[0, b]);+ } else {+ v.extend_from_slice(&[(257 - run) as u8, b]);+ }+ left -= run;+ }+ v+}++fn too_big(what: &str) -> io::Error {+ io::Error::new(io::ErrorKind::InvalidInput, format!("{what} does not fit a PSD (v1) length field"))+}++impl Streamed {+ /// File name with the right extension.+ pub fn file_name(&self) -> String {+ format!("{}.{}", self.name, if self.version == Version::Psb { "psb" } else { "psd" })+ }++ fn psb(&self) -> bool {+ self.version == Version::Psb+ }++ fn row_bytes(&self) -> u64 {+ u64::from(self.width) * u64::from(self.depth / 8)+ }++ /// Bytes of one RLE row (all rows have the same length).+ fn rle_len(&self) -> u64 {+ rle_row(self.row_bytes(), 0).len() as u64+ }++ /// Size of a channel block (compression word, RLE counts, rows) of `planes` planes.+ fn channel_len(&self, planes: u64) -> u64 {+ let rows = planes * u64::from(self.height);+ let count = if self.psb() { 4 } else { 2 };+ if self.rle { 2 + rows * count + rows * self.rle_len() } else { 2 + rows * self.row_bytes() }+ }++ /// Writes a length field: 8 bytes in PSB, 4 in PSD.+ fn put_len(&self, out: &mut Vec<u8>, v: u64, what: &str) -> io::Result<()> {+ if self.psb() {+ out.extend_from_slice(&v.to_be_bytes());+ } else {+ out.extend_from_slice(&u32::try_from(v).map_err(|_| too_big(what))?.to_be_bytes());+ }+ Ok(())+ }++ /// The layer record of the one layer: transparency (-1), then R, G, B.+ fn layer_record(&self) -> io::Result<Vec<u8>> {+ let ch_len = self.channel_len(1);+ let name = b"Layer 1";+ let mut rec = Vec::new();+ for v in [0, 0, self.height, self.width] {+ rec.extend_from_slice(&v.to_be_bytes());+ }+ rec.extend_from_slice(&4u16.to_be_bytes());+ for id in [-1i16, 0, 1, 2] {+ rec.extend_from_slice(&id.to_be_bytes());+ self.put_len(&mut rec, ch_len, "a layer channel")?;+ }+ rec.extend_from_slice(b"8BIMnorm");+ rec.extend_from_slice(&[255, 0, 0, 0]);+ // Extra data: no mask, no blending ranges, the Pascal name padded to 4.+ let mut extra = Vec::new();+ extra.extend_from_slice(&0u32.to_be_bytes());+ extra.extend_from_slice(&0u32.to_be_bytes());+ extra.push(name.len() as u8);+ extra.extend_from_slice(name);+ while extra.len() % 4 != 0 {+ extra.push(0);+ }+ rec.extend_from_slice(&(extra.len() as u32).to_be_bytes());+ rec.extend_from_slice(&extra);+ Ok(rec)+ }++ /// The header, the empty colour-mode and resource sections and the layer section's head+ /// (everything before the first channel's data), plus the padding after the layer channels.+ fn head(&self) -> io::Result<(Vec<u8>, u64)> {+ let mut h = Vec::new();+ h.extend_from_slice(b"8BPS");+ h.extend_from_slice(&(if self.psb() { 2u16 } else { 1 }).to_be_bytes());+ h.extend_from_slice(&[0; 6]);+ h.extend_from_slice(&3u16.to_be_bytes());+ h.extend_from_slice(&self.height.to_be_bytes());+ h.extend_from_slice(&self.width.to_be_bytes());+ h.extend_from_slice(&self.depth.to_be_bytes());+ h.extend_from_slice(&3u16.to_be_bytes());+ // Colour mode data and image resources: empty.+ h.extend_from_slice(&0u32.to_be_bytes());+ h.extend_from_slice(&0u32.to_be_bytes());+ if !self.layered {+ self.put_len(&mut h, 0, "the layer section")?;+ return Ok((h, 0));+ }+ let rec = self.layer_record()?;+ let mut layer_info = 2 + rec.len() as u64 + 4 * self.channel_len(1);+ let pad = layer_info % 2;+ layer_info += pad;+ let len_field = if self.psb() { 8 } else { 4 };+ // Layer and mask information: layer info (with its length) + empty global mask (4 bytes).+ self.put_len(&mut h, len_field + layer_info + 4, "the layer section")?;+ self.put_len(&mut h, layer_info, "the layer info")?;+ h.extend_from_slice(&1i16.to_be_bytes());+ h.extend_from_slice(&rec);+ Ok((h, pad))+ }++ /// The exact size of the file [`write_to`](Self::write_to) writes, without writing it.+ pub fn file_len(&self) -> io::Result<u64> {+ let (head, pad) = self.head()?;+ let layers = if self.layered { 4 * self.channel_len(1) + pad + 4 } else { 0 };+ Ok(head.len() as u64 + layers + self.channel_len(3))+ }++ /// The bytes of one row of channel `ch`.+ fn row(&self, y: u32, ch: u32, buf: &mut Vec<u8>) {+ buf.clear();+ if self.rle {+ buf.extend(rle_row(self.row_bytes(), sample(0, y, ch, true)));+ return;+ }+ for x in 0..self.width {+ let s = sample(x, y, ch, false);+ buf.push(s);+ if self.depth == 16 {+ buf.push(s);+ }+ }+ }++ /// Writes the compression word, the counts and the rows of `chans`.+ fn write_planes(&self, w: &mut impl Write, chans: &[u32]) -> io::Result<()> {+ w.write_all(&u16::from(self.rle).to_be_bytes())?;+ if self.rle {+ let n = self.rle_len();+ let one = if self.psb() {+ u32::try_from(n).map_err(|_| too_big("an RLE row"))?.to_be_bytes().to_vec()+ } else {+ u16::try_from(n).map_err(|_| too_big("an RLE row"))?.to_be_bytes().to_vec()+ };+ for _ in 0..chans.len() as u64 * u64::from(self.height) {+ w.write_all(&one)?;+ }+ }+ let mut buf = Vec::new();+ for &ch in chans {+ for y in 0..self.height {+ self.row(y, ch, &mut buf);+ w.write_all(&buf)?;+ }+ }+ Ok(())+ }++ /// Streams the file into `w` (buffer it). Returns the bytes written. A PSD whose lengths+ /// don't fit its 32-bit fields is refused before anything is written.+ pub fn write_to(&self, w: &mut impl Write) -> io::Result<u64> {+ let len = self.file_len()?;+ let (head, pad) = self.head()?;+ w.write_all(&head)?;+ if self.layered {+ // Transparency, then R, G, B.+ for ch in [3, 0, 1, 2] {+ self.write_planes(w, &[ch])?;+ }+ w.write_all(&vec![0; pad as usize])?;+ w.write_all(&0u32.to_be_bytes())?;+ }+ self.write_planes(w, &[0, 1, 2])?;+ w.flush()?;+ Ok(len)+ }++ /// Writes the file to `path` (created or truncated). Returns its size.+ #[cfg(not(target_arch = "wasm32"))]+ pub fn write_file(&self, path: &std::path::Path) -> io::Result<u64> {+ let mut w = io::BufWriter::with_capacity(8 << 20, std::fs::File::create(path)?);+ self.write_to(&mut w)+ }++ /// The 8-bit value of channel `c` (3 = alpha) at (`x`, `y`): the layer's and the merged+ /// image's (they are the same).+ pub fn sample(&self, x: u32, y: u32, c: u32) -> u8 {+ sample(x, y, c, self.rle)+ }+}++/// A layered document: a background and a grid of layers, one group per grid row.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct Grid {+ /// Canvas width (px).+ pub width: u32,+ /// Canvas height (px).+ pub height: u32,+ /// Layers in the grid (the background is extra).+ pub layers: u32,+ /// Grid columns; a group per row of `cols` layers.+ pub cols: u32,+}++/// A 20 MP (5472 × 3648) layered photo: background, 5 layers in 2 groups (one closed), a+/// mask and a drop shadow.+pub const LAYERED_20MP: Grid = Grid { width: 5472, height: 3648, layers: 5, cols: 3 };++/// A 150-layer A4 layout at 300 ppi (2480 × 3508): background + 149 layers in 15 groups, with+/// masks, hidden layers, closed groups and drop shadows.+pub const LAYOUT_150: Grid = Grid { width: 2480, height: 3508, layers: 149, cols: 10 };++/// What a grid layer carries.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct GridLayer {+ /// Bounds in document coordinates.+ pub rect: Rect,+ /// Base colour; the layer adds its local x to it (a horizontal ramp).+ pub base: [u8; 3],+ /// Has a mask showing only the left half.+ pub masked: bool,+ /// Hidden.+ pub hidden: bool,+ /// Has a drop shadow (`lfx2`).+ pub shadow: bool,+}++/// The `lfx2` descriptor of a drop shadow: multiply, black, 75 %, 120°, distance 5, size 5.+fn drop_shadow() -> Vec<u8> {+ let px = |v: f64| Value::UnitFloat { unit: *b"#Pxl", value: v };+ let color = Descriptor::new("RGBC").with("Rd ", Value::Double(0.0)).with("Grn ", Value::Double(0.0)).with("Bl ", Value::Double(0.0));+ let shadow = Descriptor::new("DrSh")+ .with("enab", Value::Boolean(true))+ .with("Md ", Value::Enumerated { type_id: Id::new("BlnM"), value: Id::new("Mltp") })+ .with("Clr ", Value::Descriptor(color))+ .with("Opct", Value::UnitFloat { unit: *b"#Prc", value: 75.0 })+ .with("uglg", Value::Boolean(false))+ .with("lagl", Value::UnitFloat { unit: *b"#Ang", value: 120.0 })+ .with("Dstn", px(5.0))+ .with("Ckmt", px(0.0))+ .with("blur", px(5.0));+ let root = Descriptor::new("null")+ .with("Scl ", Value::UnitFloat { unit: *b"#Prc", value: 100.0 })+ .with("masterFXSwitch", Value::Boolean(true))+ .with("DrSh", Value::Descriptor(shadow));+ let mut data = 0u32.to_be_bytes().to_vec();+ data.extend(VersionedDescriptor::new(root).to_bytes());+ data+}++impl Grid {+ /// Grid rows (= groups).+ pub fn rows(&self) -> u32 {+ self.layers.div_ceil(self.cols.max(1))+ }++ fn cell(&self) -> (u32, u32) {+ (self.width / self.cols.max(1), self.height / self.rows().max(1))+ }++ /// Gap between a layer and its cell's edge (larger than any shadow's reach).+ fn inset(&self) -> u32 {+ let (cw, ch) = self.cell();+ (cw.min(ch) / 8).max(1)+ }++ /// Layer `i` of the grid (0-based, bottom to top), or `None` past the end.+ pub fn layer(&self, i: u32) -> Option<GridLayer> {+ if i >= self.layers {+ return None;+ }+ let (cw, ch) = self.cell();+ let inset = self.inset();+ let (col, row) = (i % self.cols.max(1), i / self.cols.max(1));+ let rect =+ Rect::from_xywh((col * cw + inset) as i32, (row * ch + inset) as i32, cw.saturating_sub(2 * inset).max(1), ch.saturating_sub(2 * inset).max(1));+ let masked = i % 5 == 1;+ let hidden = i % 13 == 12;+ Some(GridLayer {+ rect,+ base: [(i * 37 + 20) as u8, (i * 91 + 50) as u8, (i * 53 + 90) as u8],+ masked,+ hidden,+ shadow: i % 7 == 3 && !masked && !hidden,+ })+ }++ /// Name of grid layer `i`.+ pub fn layer_name(i: u32) -> String {+ format!("Layer {}", i + 1)+ }++ /// Name of the group of grid row `r`.+ pub fn group_name(r: u32) -> String {+ format!("Row {}", r + 1)+ }++ /// Groups of rows `r % 4 == 3` are closed in the layers panel.+ pub fn group_open(r: u32) -> bool {+ r % 4 != 3+ }++ /// The background's colour at (`x`, `y`): [`sample`] in runs of 16 px (RLE has runs to find).+ pub fn background(x: u32, y: u32) -> [u8; 3] {+ [0, 1, 2].map(|c| sample(x / 16, y, c, false))+ }++ /// Grid layer `i`'s pixel colour at document (`x`, `y`), ignoring visibility and mask.+ fn layer_color(l: &GridLayer, x: u32) -> [u8; 3] {+ let lx = x.wrapping_sub(l.rect.left as u32);+ l.base.map(|b| (u32::from(b) + lx) as u8)+ }++ /// The merged colour at (`x`, `y`). Exact except within a few pixels of a shadowed layer's+ /// edges (the merged image this generator stores leaves shadows out).+ pub fn expected(&self, x: u32, y: u32) -> [u8; 3] {+ let (cw, ch) = self.cell();+ let (col, row) = (x / cw.max(1), y / ch.max(1));+ if col < self.cols+ && let Some(l) = self.layer(row * self.cols + col)+ {+ let (xi, yi) = (x as i32, y as i32);+ let inside = xi >= l.rect.left && xi < l.rect.right && yi >= l.rect.top && yi < l.rect.bottom;+ let shown = !l.masked || i64::from(xi) < i64::from(l.rect.left) + l.rect.width() / 2;+ if inside && shown && !l.hidden {+ return Self::layer_color(&l, x);+ }+ }+ Self::background(x, y)+ }++ /// Points to check, away from every shadow: in each of a few layers, its shown half, its+ /// masked-out half, and the gap at its cell's corner.+ pub fn sample_points(&self) -> Vec<(u32, u32)> {+ let step = (self.layers / 12).max(1);+ let mut v = vec![(0, 0), (self.width - 1, self.height - 1)];+ for i in (0..self.layers).step_by(step as usize) {+ let Some(l) = self.layer(i) else { continue };+ let (w, h) = (l.rect.width() as u32, l.rect.height() as u32);+ let (x0, y0) = (l.rect.left as u32, l.rect.top as u32);+ v.push((x0 + w / 4, y0 + h / 2));+ v.push((x0 + w * 3 / 4, y0 + h / 2));+ v.push((x0 - self.inset() / 2, y0 - self.inset() / 2));+ }+ v+ }++ /// Builds the file (8-bit RGB, RLE): layers bottom to top, the merged image from+ /// [`expected`](Self::expected).+ pub fn build(&self, version: Version) -> Result<PsdFile> {+ let (w, h) = (self.width, self.height);+ let mut b = PsdBuilder::new(w, h).version(version);+ let mut bg = Vec::with_capacity(w as usize * h as usize * 4);+ for y in 0..h {+ for x in 0..w {+ bg.extend(Self::background(x, y));+ bg.push(255);+ }+ }+ b.push_layer(LayerSpec::new("Background", 0, 0, w, h, PixelData::Rgba8(bg)));+ for row in 0..self.rows() {+ b.begin_group(GroupSpec { open: Self::group_open(row), ..GroupSpec::new(Self::group_name(row)) });+ for i in row * self.cols..((row + 1) * self.cols).min(self.layers) {+ let Some(l) = self.layer(i) else { continue };+ let (lw, lh) = (l.rect.width() as u32, l.rect.height() as u32);+ let mut px = Vec::with_capacity(lw as usize * lh as usize * 4);+ for _ in 0..lh {+ for lx in 0..lw {+ px.extend(Self::layer_color(&l, l.rect.left as u32 + lx));+ px.push(255);+ }+ }+ let mut spec = LayerSpec::new(Self::layer_name(i), l.rect.left, l.rect.top, lw, lh, PixelData::Rgba8(px));+ spec.visible = !l.hidden;+ if l.masked {+ let data = (0..lh).flat_map(|_| (0..lw).map(move |x| if x < lw / 2 { 255 } else { 0 })).collect();+ spec.mask = Some(MaskSpec { rect: l.rect, data, default_color: 0, disabled: false });+ }+ if l.shadow {+ spec.extra_blocks.push(TaggedBlock::new(*b"lfx2", drop_shadow()));+ }+ b.push_layer(spec);+ }+ b.end_group()?;+ }+ let mut merged = Vec::with_capacity(w as usize * h as usize * 4);+ for y in 0..h {+ for x in 0..w {+ merged.extend(self.expected(x, y));+ merged.push(255);+ }+ }+ b.composite(PixelData::Rgba8(merged));+ b.build()+ }+}++#[cfg(test)]+#[allow(clippy::unwrap_used, clippy::indexing_slicing)]+mod tests {+ use super::*;++ #[test]+ fn presets_respect_photoshop_limits() {+ let psd = PSD_2GB.file_len().unwrap();+ assert!(psd < PSD_MAX_FILE_BYTES && psd > 2_000_000_000, "{psd}");+ const { assert!(PSD_2GB.width <= PSD_MAX_SIDE && PSD_2GB.height <= PSD_MAX_SIDE) };+ for c in PSB_CASES {+ assert!(c.file_len().is_ok() && c.width <= 300_000, "{}", c.name);+ }+ assert!(PSB_4GB.file_len().unwrap() > 4 << 30);+ // A PSD too big for its 32-bit lengths is refused, not wrapped.+ let huge = Streamed { width: 33_000, height: 33_000, ..PSD_2GB };+ assert!(huge.file_len().is_err());+ assert!(huge.write_to(&mut io::sink()).is_err());+ }++ /// Small streamed files parse, and their pixels are [`sample`]'s.+ #[test]+ fn small_streamed_files_parse() {+ for version in [Version::Psd, Version::Psb] {+ for (rle, layered, depth) in [(false, true, 8), (true, true, 8), (true, false, 16), (false, false, 8)] {+ let c = Streamed { name: "t", version, width: 300, height: 7, depth, rle, layered };+ let mut out = Vec::new();+ let n = c.write_to(&mut out).unwrap();+ assert_eq!(n, out.len() as u64, "{c:?}");+ let file = PsdFile::from_bytes(&out).unwrap();+ let merged = file.image_data.decode(&file.header).unwrap();+ let bps = usize::from(depth / 8);+ let plane = 300 * 7 * bps;+ for (x, y, ch) in [(0u32, 0u32, 0u32), (299, 6, 2), (150, 3, 1)] {+ let i = ch as usize * plane + (y as usize * 300 + x as usize) * bps;+ assert_eq!(merged[i], c.sample(x, y, ch), "{c:?} ({x}, {y}) {ch}");+ }+ assert_eq!(file.layers().len(), usize::from(layered), "{c:?}");+ }+ }+ }++ #[test]+ fn grid_layout_is_consistent() {+ for g in [LAYERED_20MP, LAYOUT_150] {+ let last = g.layer(g.layers - 1).unwrap();+ assert!(last.rect.right <= g.width as i32 && last.rect.bottom <= g.height as i32);+ assert!(g.layer(g.layers).is_none());+ let all: Vec<_> = (0..g.layers).filter_map(|i| g.layer(i)).collect();+ assert!(all.iter().any(|l| l.masked) && all.iter().any(|l| l.shadow));+ for (x, y) in g.sample_points() {+ assert!(x < g.width && y < g.height);+ }+ }+ assert!((0..LAYOUT_150.layers).filter_map(|i| LAYOUT_150.layer(i)).any(|l| l.hidden));+ }++ /// A small grid builds, parses, and its merged image is [`Grid::expected`].+ #[test]+ fn small_grid_builds() {+ let g = Grid { width: 120, height: 90, layers: 14, cols: 4 };+ let file = g.build(Version::Psd).unwrap();+ let bytes = file.to_bytes().unwrap();+ let file = PsdFile::from_bytes(&bytes).unwrap();+ // Background + 14 layers + 4 groups (two records each).+ assert_eq!(file.layers().len(), 1 + 14 + 8);+ let merged = file.image_data.decode(&file.header).unwrap();+ for (x, y) in g.sample_points() {+ let want = g.expected(x, y);+ for c in 0..3 {+ assert_eq!(merged[c * 120 * 90 + (y * 120 + x) as usize], want[c], "({x}, {y}) {c}");+ }+ }+ }+}diff --git a/crates/psd/src/lib.rs b/crates/psd/src/lib.rsindex 00d73c400..1950e48dd 100644--- a/crates/psd/src/lib.rs+++ b/crates/psd/src/lib.rs@@ -51,6 +51,8 @@ pub mod descriptor;pub mod error;pub mod file;pub mod filter_effects;+#[cfg(any(test, feature = "testgen"))]+pub mod fixtures;pub mod grd;pub mod hdr;pub mod header;diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.tomlindex d6a49c003..b9a3870ca 100644--- a/crates/ui-egui/Cargo.toml+++ b/crates/ui-egui/Cargo.toml@@ -57,8 +57,9 @@ photocraft-raw = { workspace = true, features = ["testgen"] }egui_kittest = { workspace = true, features = ["wgpu", "snapshot", "eframe"] }# Benchmark helpers for the `--json` benches `cargo xtask perf` runs (in-process RSS, percentiles).photocraft-testkit = { workspace = true }-# Only for examples/perf_scenarios.rs (a 500-brush .abr for the #210 import row).-photocraft-psd = { workspace = true }+# examples/perf_scenarios.rs (a 500-brush .abr for the #210 import row) and large_file_bench.rs+# (the generated 2 GB PSD and 4.4 GB PSB of P20, `fixtures`).+photocraft-psd = { workspace = true, features = ["testgen"] }[build-dependencies]# Deflates the translation catalogs and egui's default fonts (build.rs); already linked at run time to inflate them.diff --git a/crates/ui-egui/examples/large_file_bench.rs b/crates/ui-egui/examples/large_file_bench.rsnew file mode 100644index 000000000..fcf1228b2--- /dev/null+++ b/crates/ui-egui/examples/large_file_bench.rs@@ -0,0 +1,125 @@+//! Large-file open benchmark (P20, #210, #216, #5107): open the generated 2 GB PSD (17,000² px, a+//! raw full-canvas layer and merged image, just under Photoshop's PSD cap) and the 4.4 GB PSB+//! (25,000² px, data past 4 GiB) until the document is editable: read the file, decode it into a+//! document and open it in a session (the colour policy runs there), the way File › Open does+//! before the first canvas refresh. The canvas refresh is left out (large_image_bench and+//! huge_doc_bench time it).+//!+//! ```sh+//! cargo run --release -p photocraft-ui-egui --example large_file_bench -- [--reps 3] [--only psd|psb] [--cache DIR] [--clean] [--json out.json]+//! ```+//!+//! The fixtures (`photocraft_psd::fixtures`, about 6.4 GB together) are generated once into+//! `--cache` (default: `$PHOTOCRAFT_FIXTURE_DIR`, else `fixtures/` in the target directory next+//! to this binary) and kept for the next run; `--clean` removes them afterwards. Each row also+//! records the peak resident memory of its opens. Needs about 30 GB of memory for the PSB.++use std::path::PathBuf;+use std::time::{Duration, Instant};++use photocraft_engine::Session;+use photocraft_psd::fixtures::{PSB_4GB, PSD_2GB, Streamed};+use photocraft_testkit::perf::{RssSampler, row};+use serde_json::json;++fn arg(args: &[String], name: &str) -> Option<String> {+ args.iter().position(|a| a == name).and_then(|i| args.get(i + 1).cloned())+}++/// `<target>/fixtures`: the binary lives in `<target>/release/examples/`.+fn default_cache() -> PathBuf {+ if let Some(d) = std::env::var_os("PHOTOCRAFT_FIXTURE_DIR") {+ return PathBuf::from(d);+ }+ std::env::current_exe().ok().and_then(|e| e.ancestors().nth(3).map(|t| t.join("fixtures"))).unwrap_or_else(std::env::temp_dir)+}++/// Opens `path` like File › Open: read, decode, open in a session. Returns the session (the+/// caller drops it outside the timing) and whether a sampled pixel came back right.+fn open(case: &Streamed, path: &std::path::Path) -> Result<(Session, bool), String> {+ let bytes = std::fs::read(path).map_err(|e| format!("read {}: {e}", path.display()))?;+ let doc = photocraft_io::import(&case.file_name(), &bytes).map_err(|e| e.to_string())?.document;+ drop(bytes);+ let mut s = Session::new();+ s.open_document(doc, Some(path.display().to_string()));+ let (x, y) = (case.width / 3, case.height * 2 / 3);+ let ok = s.active().and_then(|st| st.doc.layers.first()).and_then(|l| l.surface()).is_some_and(|surf| {+ let got = surf.pixel(x as i32, y as i32);+ got.len() == 4 && got.iter().enumerate().all(|(c, v)| (v - f32::from(case.sample(x, y, c as u32)) / 255.0).abs() <= 1.0 / 510.0)+ });+ Ok((s, ok))+}++fn main() {+ let args: Vec<String> = std::env::args().collect();+ let reps: usize = arg(&args, "--reps").and_then(|v| v.parse().ok()).unwrap_or(3).max(1);+ let only = arg(&args, "--only");+ let dir = arg(&args, "--cache").map_or_else(default_cache, PathBuf::from);+ let clean = args.iter().any(|a| a == "--clean");+ if let Err(e) = std::fs::create_dir_all(&dir) {+ eprintln!("create {}: {e}", dir.display());+ std::process::exit(1);+ }+ let sampler = RssSampler::start(Duration::from_millis(5));+ let cases = [("psd", "open 2 GB PSD (read + decode + document)", PSD_2GB), ("psb", "open 4.4 GB PSB (read + decode + document)", PSB_4GB)];+ let mut rows = Vec::new();+ let mut errors = Vec::new();+ for (key, name, case) in &cases {+ if only.as_deref().is_some_and(|o| o != *key) {+ continue;+ }+ let path = dir.join(case.file_name());+ let want = case.file_len().unwrap_or(0);+ if std::fs::metadata(&path).map(|m| m.len()).ok() != Some(want) {+ let t = Instant::now();+ match case.write_file(&path) {+ Ok(len) => println!("generated {} ({:.2} GB) in {:.1} s", path.display(), len as f64 / 1e9, t.elapsed().as_secs_f64()),+ Err(e) => {+ errors.push(json!({"name": name, "error": format!("generate {}: {e}", path.display())}));+ continue;+ }+ }+ }+ let mut samples = Vec::new();+ let mut peak = None;+ for _ in 0..reps {+ sampler.reset();+ let t = Instant::now();+ match open(case, &path) {+ Ok((s, ok)) => {+ let ms = t.elapsed().as_secs_f64() * 1000.0;+ peak = peak.max(sampler.peak());+ println!("{name:<44} {ms:>9.0} ms peak RSS {:>6} MB{}", sampler.peak().unwrap_or(0) >> 20, if ok { "" } else { " WRONG PIXELS" });+ if !ok {+ errors.push(json!({"name": name, "error": "the opened document's pixels don't match the fixture"}));+ break;+ }+ samples.push(ms);+ drop(s);+ }+ Err(e) => {+ println!("{name}: {e}");+ errors.push(json!({"name": name, "error": e}));+ break;+ }+ }+ }+ if !samples.is_empty() {+ rows.push(row(name, &samples, peak, None));+ }+ if clean {+ let _ = std::fs::remove_file(&path);+ }+ }+ if let Some(out) = arg(&args, "--json") {+ let context =+ json!({"reps": reps, "cache": dir.display().to_string(), "errors": errors, "threads": std::thread::available_parallelism().map(|n| n.get()).ok()});+ let report = photocraft_testkit::perf::report("large_file_bench", context, rows, Some(&sampler));+ if let Err(e) = photocraft_testkit::perf::write_report(&out, &report) {+ eprintln!("{e}");+ }+ }+ if !errors.is_empty() {+ std::process::exit(1);+ }+}diff --git a/docs/file-format-parity.md b/docs/file-format-parity.mdindex d2c9d8ccd..bc32ff306 100644--- a/docs/file-format-parity.md+++ b/docs/file-format-parity.md@@ -1,6 +1,6 @@# File-format parity-> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-12 · **Change:** minor (CMYK Invert, Posterize and Threshold on the inks; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026+> **Last reviewed:** 2026-10-13 · **Last updated:** 2026-10-13 · **Change:** minor (large-file fixtures: a 20 MP layered PSD, a 150-layer layout, a 2 GB PSD and a 4.4 GB PSB generated at test time and round-tripped, FILE-216-2 done, #5107; earlier: CMYK Invert, Posterize and Threshold on the inks; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026Every format Photoshop 2026 (27.11.0) reads or writes, with PhotoCraft's support, fidelity andtests. Photoshop's list comes from its `Info.plist` `CFBundleDocumentTypes`, the PiPL read/write@@ -22,7 +22,7 @@ XL are missing (gap G10). Remaining: 300–500 h including PSD fidelity.| Format | Photoshop | PhotoCraft read | PhotoCraft write | Fidelity and tests ||---|---|---|---|---|| PSD | R/W | yes | yes | 1/8/16/32-bit; Bitmap, Gray, Indexed, RGB, CMYK, Multichannel, Lab, Duotone; layers, groups, masks, vector masks, adjustment and fill layers, effects, text, shapes, smart objects (SoLd/lnk2; CS2 PlLd/lnkD read with their warp, kept as is or re-saved as SoLd once edited), smart filters (14 mapped, rest verbatim), slices, comps, Advanced Blending. Oracle floors: Photoshop-authored 145/258, io 146/170, psd-tools 236/309; round trip ≥ 169/170, 308/309, 258/256. Known failures: #1281, #2469 (#2374, text layers, closed 2026-10-10; #2465, CS2 `PlLd`-only smart objects, fixed 2026-10-12) |-| PSB | R/W | yes | yes | Auto-switches above 2 GB (REL-212-2); 4–5 GB fixtures generated (FILE-216-2); > 4 GB fails on Windows (#375) |+| PSB | R/W | yes | yes | Auto-switches above 2 GB (REL-212-2); generated 20 MP, 150-layer, 2 GB PSD and 4.4 GB PSB fixtures opened, saved and re-opened by io tests/large_files.rs (FILE-216-2, 2026-10-13; the 4.4 GB PSB opens on Windows); > 4 GB from the app's File › Open on Windows: #375 || Cloud PSD (.psdc) | R/W | no | no | Out of scope (Adobe cloud) || TIFF | R/W | yes | yes | 8/16/32f, Gray/RGB/CMYK, BigTIFF, every IFD, banded parallel decode; layered TIFF both byte orders (FILE-215-7: extra alpha channels not written) || JPEG | R/W | yes | yes | 8-bit Gray/RGB/CMYK, ICC/EXIF/XMP; Save keeps the opened file's quality (estimated from its quantisation tables, #2399); no JPEG Options dialog (quality 0–12, baseline/progressive) (FILE-215-19) |@@ -142,6 +142,7 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings.| Date | Change | Summary ||---|---|---|+| 2026-10-13 | minor | Large-file fixtures generated at test time (20 MP layered, 150-layer layout, 2.02 GB PSD, 4.38 GB PSB), opened, saved and re-opened by io tests/large_files.rs; FILE-216-2 done; P20/P60 open times measurable (#5107) || 2026-10-12 | minor | `.atn`: 112 events mapped (Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, points, Bitmap) || 2026-10-12 | minor | DDS textures open, read-only (#1327) || 2026-10-12 | minor | #2465 fixed: Photoshop CS2 placed layers (`PlLd` only, file in `lnkD`) open as editable smart objects and save their edits |diff --git a/docs/gaps.md b/docs/gaps.mdindex f7929c276..0a7d95525 100644--- a/docs/gaps.md+++ b/docs/gaps.md@@ -1,6 +1,6 @@# Where PhotoCraft falls short of Photoshop-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed) · **Target:** Adobe Photoshop 2026+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed) · **Target:** Adobe Photoshop 2026Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impacton the way to beta. This is the work list agents pick from: take the highest-ranked entry that@@ -47,7 +47,8 @@ what an agent can't finish alone.within the corpus. Smart-filter re-render matches 5/30. User reports: a PSD with text layersre-saved unmodified would not reopen (#2374, closed 2026-10-10), Photoshop 26.6 cannot reopen our files (#1281), "PSD notopening in Photoshop" (#2469), a CS2-era smart object unavailable (#2465, fixed 2026-10-12), PSB smart object- blank (#1764), perspective placed layers flattened (#579, fixed by #426), PSB > 4 GB fails on Windows (#375).+ blank (#1764), perspective placed layers flattened (#579, fixed by #426), PSB > 4 GB fails on Windows (#375; a generated 4.38 GB PSB opens, saves and re-opens+ through io on Windows, io tests/large_files.rs, 2026-10-13).No test opens our exports in a third-party editor (FILE-216-4).- **Impact:** PSD is the format professionals exchange. Beta requires it to be reliable.- **Estimate:** 150–250 h. **Human:** opening exports in Photoshop on the owner's Mac (or a@@ -255,6 +256,7 @@ what an agent can't finish alone.| Date | Change | Summary ||---|---|---|+| 2026-10-13 | minor | G1: generated large-file fixtures (20 MP, 150 layers, 2 GB PSD, 4.38 GB PSB) round-trip in io tests/large_files.rs; the 4.38 GB PSB opens on Windows through io (#375 evidence); FILE-216-2 done (#5107) || 2026-10-13 | minor | G4: minimum inputs in Shape Dynamics and Transfer follow their Control (#3825, partial); no readiness percentage or estimate changed || 2026-10-12 | minor | G5: Free Transform options bar H/V skew fields done || 2026-10-12 | minor | G11: `.atn` import maps 112 events (Select and Mask, Spatter, Ripple, Crystallize, Pattern Fill, mask targeting, Step Backward, points, Bitmap) |diff --git a/docs/scorecard.md b/docs/scorecard.mdindex af13a3f26..52f7a1d1f 100644--- a/docs/scorecard.md+++ b/docs/scorecard.md@@ -6,8 +6,8 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js| Area | Done | Partial | Missing | Key numbers ||---|---:|---:|---:|---|-| [Performance](#performance) | 3 | 22 | 22 | 56 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 17 not run, 5 not measurable yet (baseline 2026-10-05) |-| [File compatibility](#file-compatibility) | 7 | 13 | 7 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 236/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 145/256, round trip ≥ 258/256 |+| [Performance](#performance) | 3 | 22 | 23 | 57 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 19 not run, 4 not measurable yet (baseline 2026-10-05) |+| [File compatibility](#file-compatibility) | 8 | 12 | 7 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 236/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 145/256, round trip ≥ 258/256 || [Tools](#tools) | 28 | 14 | 1 | || [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 156 (target 0) || [Type](#type) | 4 | 3 | 2 | |@@ -43,6 +43,8 @@ Baseline: 2026-10-05, commit `f5d2bcb54a`, Apple M4 Pro (48 GB), GPU Apple M4 Pr| P17 | Move a layer on a 32-bit document with 20 layers | ≤ 100 ms p95 | 386 | 681 | 681 | 1.2 GB | 1.6 GB | over budget (target not met yet) | [#209](https://github.com/storytold/photocraft/issues/209) || P18 | Open a 20 MP layered PSD: first pixels (today: fully opened) | ≤ 1000 ms p95 | 1753 | 2794 | 2794 | 2.2 GB | 1.9 GB | over budget (target not met yet) | [#210](https://github.com/storytold/photocraft/issues/210) || P19 | Open a 20 MP layered PSD: editable | ≤ 3000 ms p95 | 1753 | 2794 | 2794 | 2.2 GB | 1.9 GB | pass | [#210](https://github.com/storytold/photocraft/issues/210) |+| P20 | Open a 2 GB PSD: editable | opens with progress, editable, never blank | – | – | – | – | – | not run | [#210](https://github.com/storytold/photocraft/issues/210) |+| P60 | Open a 4–5 GB PSB: editable | opens with progress, editable, never blank | – | – | – | – | – | not run | [#210](https://github.com/storytold/photocraft/issues/210) || P21 | Content-Aware Fill on 10 MP | ≤ 1500 ms p95 | 218 | 256 | 256 | 1.8 GB | 1.8 GB | pass | [#210](https://github.com/storytold/photocraft/issues/210) || P22 | Spot Healing stroke on 10 MP | ≤ 500 ms p95 | 157 | 247 | 247 | 1.8 GB | 1.9 GB | pass | [#210](https://github.com/storytold/photocraft/issues/210) || P24 | Import 500 brushes (longest UI-thread step) | ≤ 100 ms max | – | – | – | – | – | not run | [#210](https://github.com/storytold/photocraft/issues/210) |@@ -81,7 +83,6 @@ Baseline: 2026-10-05, commit `f5d2bcb54a`, Apple M4 Pro (48 GB), GPU Apple M4 Pr| Id | Scenario | Target | Why | Issue ||---|---|---|---|---|| P15 | Zoom / pan frame time on a 15000×10000 16-bit document | ≤ 16 ms per frame | no headless canvas frame harness yet (zoom and pan sample the GPU texture in the egui paint callback) | [#209](https://github.com/storytold/photocraft/issues/209) |-| P20 | Open a 2 GB PSD / 4–5 GB PSB | opens with progress, editable, never blank | opens run in the background with progress (#210), but there are no generated large-file fixtures yet (#216) | [#210](https://github.com/storytold/photocraft/issues/210) || P23 | Warp / Puppet / Perspective preview at 4K | ≤ 16 ms per frame, commit in the background | the previews run inside the UI tools; no headless frame harness, no background commit | [#210](https://github.com/storytold/photocraft/issues/210) || P34 | Brush preview memory, small dab on an 8K viewport | ≤ 2 MiB | the live brush preview buffers are UI-side; no headless counter yet | [#211](https://github.com/storytold/photocraft/issues/211) || P35 | Marquee drag on 24 MP with Alt/Shift | ≤ 17 ms p95 | Shift/Alt marquee modifiers don't exist yet (#208) and the drag preview is UI-side | [#211](https://github.com/storytold/photocraft/issues/211) |@@ -120,7 +121,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t| FILE-215-20 | Artboard tool with handles and + buttons, Duplicate Artboard beside, vector PDF pages | partial | [#215](https://github.com/storytold/photocraft/issues/215) | artboard_tool.rs: Artboard tool draws, selects, moves and resizes boards by their handles (⇧ keeps proportions), its + buttons add a board or (⌥) a copy beside the selected one (#3033); Duplicate Artboard places the copy beside (#1584); raster PDF pages only || FILE-215-21 | Local libraries of colours, patterns, images and layers, as linked items or copies | missing | [#215](https://github.com/storytold/photocraft/issues/215) | Only preset libraries (preset_store.rs) || FILE-216-1 | Every corpus fetched and enforced in CI, cached by pin | done | [#216](https://github.com/storytold/photocraft/issues/216) | ci.yml has a corpus job (name: corpus tests) on every PR and on main: the corpora are pinned in xtask/src/corpus_pins.rs, sha256-verified after both a cache restore and a download, and a missing corpus fails the tests. The cache key follows the pins, so it is cached by pin as this row asks (#190) |-| FILE-216-2 | Large-file fixtures: 20 MP, 150-layer, generated 2 GB PSD and 4-5 GB PSB stress tests | partial | [#216](https://github.com/storytold/photocraft/issues/216) | 4-5 GB PSB fixtures: psd example big_psb writes them (raw and RLE, planes past 2 GiB), io example big_psb_check opens and checks them; opt-in io tests/large_psb.rs (2.5 GB merged image). No 2 GB PSD, 150-layer or 20 MP fixture, nothing in CI |+| FILE-216-2 | Large-file fixtures: 20 MP, 150-layer, generated 2 GB PSD and 4-5 GB PSB stress tests | done | [#216](https://github.com/storytold/photocraft/issues/216) | Generated at test time by psd fixtures.rs (feature testgen; never committed). io tests/large_files.rs: layered_20_mp_psd_opens_and_saves (5472x3648, 5 layers in 2 groups, mask, drop shadow) and layout_with_150_layers_opens_and_saves (A4 300 ppi, 150 layers in 15 groups, masks, hidden layers, closed groups, drop shadows) run in every cargo test (~2 s each); opt-in psd_just_under_2_gb_opens_and_saves (17,000 px, 2.02 GB PSD) and psb_of_4_gb_opens_and_saves (25,000 px, 4.38 GB PSB, data past 4 GiB), each opened, pixel-checked, saved and re-opened; plus large_psb.rs (2.5 GB merged image). Open times: ui-egui large_file_bench (P20, P60). The 2 GB and 4 GB files are not run in CI (6.4 GB on disk, ~16 GB of memory) (#5107) || FILE-216-3 | TIFF, RAW and EXR corpora read by tests; per-camera RAW coverage reported | partial | [#216](https://github.com/storytold/photocraft/issues/216) | EXR: corpus/exr (the OpenEXR deep test images, pinned) is read by codecs tests/deep_exr.rs in the CI corpus job, against the ID manifests of the upstream sidecars. corpus/tiff and corpus/raw are still copied in by hand and no test reads them; no per-camera RAW report || FILE-216-4 | Exports re-open in a third-party oracle editor | missing | [#216](https://github.com/storytold/photocraft/issues/216) | The round trip is our export -> our import || FILE-216-5 | Save-path tests: layered TIFF, PDF, SVG, ACO/ASE, .shc, Smart Filters, atomic-save failure | partial | [#216](https://github.com/storytold/photocraft/issues/216) | Every save path that exists is tested by saving and reading back: layered TIFF io tests/tiff_layers.rs (every_compression_keeps_the_layers, advanced_blending_survives_layered_tiff_in_both_byte_orders), print PDF engine print_cmds/tests.rs (print_dry_run_renders_a_pdf_and_reports_the_platform_backend decodes the image back), ACO/ASE engine swatch_cmds/tests.rs (aco_round_trip_keeps_16_bit_values_and_books, ase_round_trip_keeps_groups_floats_and_kinds), .shc psd shc.rs shc_round_trips_and_rejects_hostile_input and engine layer_style.rs contour_presets_and_custom_curves_apply_in_one_undo_step, Smart Filters engine tests/smart_psd.rs (smart_filters_survive_psd_in_every_colour_model), atomic-save failure format/src/atomic/tests.rs (BUG-203-6). There is no SVG writer (SVG opens only) and no Photoshop PDF save (FILE-215-10), so those have nothing to test yet; the row stays partial until they exist |diff --git a/perf/budgets.toml b/perf/budgets.tomlindex a95c1c83d..7feb202e3 100644--- a/perf/budgets.toml+++ b/perf/budgets.toml@@ -60,6 +60,12 @@ package = "photocraft-ui-egui"args = ["--size", "14000x14000", "--op", "refresh"]note = "196 MP: open and full refresh"+[[bench]]+name = "large_file_bench"+package = "photocraft-ui-egui"+args = ["--reps", "3"]+note = "generated 2 GB PSD and 4.4 GB PSB (6.4 GB cached in <target>/fixtures): read + decode + open; needs ~16 GB of memory"+# Hook: the layout-document bench lands with perf/layout-documents (#125/#128). It runs (and its# rows are kept in results.json) as soon as the example exists; add scenarios for its rows then.[[bench]]@@ -250,12 +256,23 @@ bench = "perf_scenarios"row = "open 20 MP layered PSD (decode + first composite)"budget_ms = 3000+# P20/P60: generated fixtures (`photocraft_psd::fixtures`, #5107); the row checks a pixel, so a+# blank document fails it. No time budget yet: the target is the behaviour (progress, editable).[[scenario]]id = "P20"-title = "Open a 2 GB PSD / 4–5 GB PSB"+title = "Open a 2 GB PSD: editable"+issue = 210+bench = "large_file_bench"+row = "open 2 GB PSD (read + decode + document)"+target = "opens with progress, editable, never blank"++[[scenario]]+id = "P60"+title = "Open a 4–5 GB PSB: editable"issue = 210+bench = "large_file_bench"+row = "open 4.4 GB PSB (read + decode + document)"target = "opens with progress, editable, never blank"-not_measurable = "opens run in the background with progress (#210), but there are no generated large-file fixtures yet (#216)"[[scenario]]id = "P21"diff --git a/scorecard/file_compat.toml b/scorecard/file_compat.tomlindex 40b242ea5..4b1fd7163 100644--- a/scorecard/file_compat.toml+++ b/scorecard/file_compat.toml@@ -162,9 +162,9 @@ note = "ci.yml has a corpus job (name: corpus tests) on every PR and on main: th[[item]]id = "FILE-216-2"target = "Large-file fixtures: 20 MP, 150-layer, generated 2 GB PSD and 4-5 GB PSB stress tests"-status = "partial"+status = "done"issue = 216-note = "4-5 GB PSB fixtures: psd example big_psb writes them (raw and RLE, planes past 2 GiB), io example big_psb_check opens and checks them; opt-in io tests/large_psb.rs (2.5 GB merged image). No 2 GB PSD, 150-layer or 20 MP fixture, nothing in CI"+note = "Generated at test time by psd fixtures.rs (feature testgen; never committed). io tests/large_files.rs: layered_20_mp_psd_opens_and_saves (5472x3648, 5 layers in 2 groups, mask, drop shadow) and layout_with_150_layers_opens_and_saves (A4 300 ppi, 150 layers in 15 groups, masks, hidden layers, closed groups, drop shadows) run in every cargo test (~2 s each); opt-in psd_just_under_2_gb_opens_and_saves (17,000 px, 2.02 GB PSD) and psb_of_4_gb_opens_and_saves (25,000 px, 4.38 GB PSB, data past 4 GiB), each opened, pixel-checked, saved and re-opened; plus large_psb.rs (2.5 GB merged image). Open times: ui-egui large_file_bench (P20, P60). The 2 GB and 4 GB files are not run in CI (6.4 GB on disk, ~16 GB of memory) (#5107)"[[item]]id = "FILE-216-3"