Commit Graph
21 Commits
Author SHA1 Message Date
FredApps 07ae59b628 Merge pull request #9745 from vangel76/perf/9741-psd-zip-predict
perf(psd): single-pass 16/32-bit ZIP prediction encode and decode
2026-11-07 15:39:45 +01:00
FredApps afa0a86341 psd: widen staged RLE data to PSB in short reads, never reading it back whole 2026-11-03 13:06:09 +01:00
FredApps 05fc07b538 Merge main into fix/save-memory-6607
Resolve against main's save restructure (Services::save_file/SaveCtl, scratch-integrity checks,
ZipWriter::with_entries, exact encoded_len):
- PSD/PSB saves stream the file model through atomic_write_stream_progress; the length used for
  progress and reservations is main's exact encoded_len (the PR's size_bound under-counted lazy
  data); export_with/encode_with share checked_stages, so main's scratch checks (previews
  included) still refuse unreadable scratch.
- Drop ZipWriter::for_entries in favour of main's with_entries.
- TIFF: take_from_psd moves layer data out of the export's own model (never the document);
  body() reserves its exact length, failures are OutOfMemory (not LimitExceeded, which would
  trigger the PSB retry).
- Streaming writer: AlreadyExists from the writer is a failed save, not a name collision.
- Remove dead Vec put_widened_rle; channel_data_len is test-only.
2026-11-03 09:23:16 +01:00
Khawar Zamman Wani 97a83f074f Bound PSD layer and mask import memory before decoding (#10503)
* Bound PSD import pixel storage before decoding

* Include ZIP inflater workspace in PSD preflight

* PSD import: budget unknown-mode layers, stop after a fatal layer error, keep best-effort for non-allocation limits (#8593 review)
2026-11-01 12:33:09 +01:00
vangel76 a3f9d7e8d8 Merge upstream/main into perf/9741-psd-zip-predict 2026-10-29 20:40:22 +01:00
David MannandClaude Opus 5.5 f428433ccb Merge main into fix/psd-size-encoded
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 02:59:27 +01:00
aiongg 363a5797f8 refactor(psd): move compression.rs tests to compression/tests.rs 2026-10-26 22:30:11 +00:00
vangel76andClaude Sonnet 5.5 41904c30cc perf(psd): single-pass 16/32-bit ZIP prediction encode and decode
Carry the running sample in a register and walk each row once instead of
re-reading the value just written. 32-bit paths now write four byte
planes (or the interleaved samples) in one sequential pass.

Adds a randomised test that compares predict/unpredict with the old
index-based versions for depths 8/16/32, odd widths and 1-3 row planes.

Fixes #9741

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 21:54:49 +01:00
zuujiscomandClaude Opus 5.5 ec6a4c1a50 Save: stop doubling the encoded file in memory (#6607)
Saving needed about 4x the file's size in extra RAM: the whole encoded
file was buffered in memory before it hit the disk. Now PSD/PSB and
layered TIFF stream into the destination as they are encoded.

- format: atomic_write_stream_progress hands the encoder a writer that
  goes through the temp file, so bytes are freed as they are written;
  ZipWriter reserves the estimate only where output can exceed it, and
  gives back the unused part of a reserved buffer after compressing.
- psd: PsdFile::save streams layer by layer (ImageSourceData::take_from_psd
  moves rather than copies), and the TIFF encoder writes rows out as they
  are compressed instead of holding the uncompressed plane.
- io/codecs: layered TIFF export streams the interleaved composite, the
  app's save and export paths pass a progress callback through the stream.

A 24 MB PSD/PSB or layered TIFF now saves with a few MB of working set
instead of a second copy of the file; on wasm32 the memory is returned,
on Windows it is no longer counted as committed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 08:09:59 +05:30
David Mann 80078cb7b0 Merge main into fix/psd-size-encoded 2026-10-20 17:23:09 +02:00
FinnNkandClaude Opus 5.5 e3224000ca fix(psd): make packbits::decode_into crate-private and overflow-safe (#6950)
decode_into computed out.len() + expected unchecked. With a non-empty
buffer and an expected length near usize::MAX it panicked in debug builds
and, in release, wrapped and returned Ok having decoded nothing. Compute
the target with checked_add and report LimitExceeded, and test each packet
as len > target - out.len() so the bound checks cannot overflow either.

The only callers are decode and decode_rle in this module, and the crate
README documents packbits::{encode, decode} as the public API, so
decode_into becomes pub(crate).

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-19 14:19:48 -04:00
David MannandClaude Opus 5.5 99a416a019 Merge main into fix/psd-size-encoded
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-15 16:38:06 +02:00
4446ec6d65 PSD: write tiff blocks without copies, inflate merged ZIP once (#5221)
* Raw: measure the Nikon D90 image area (4288x2848 at (10, 10))

Aligning the decoded D90 sensor plane with the camera's own JPEG puts the
image at (10, 10) in the 4352x2868 sensor plane, giving the camera's
4288x2848 frame (10-pixel margins; the right border reads the camera's flat
255 from column 4310). Add the measured ImageArea so a D90 NEF opens on the
camera's frame instead of the uncropped plane, and make a measured profile
leave a file that carries its own colour calibration (a DNG) untouched.

* Codecs: open Cineon (.cin) film frames read-only

Cineon is the 10-bit logarithmic film-scan format DPX grew from. Read it from
the same Kodak header family: the generic header (big-endian, orientation at
192, channel count at 193, the channel-1 bits/dimensions), one or three
channels, three 10-bit samples packed into each 32-bit word on a word
boundary. The 10-bit code values open as U16 (round(c x 65535 / 1023)); the
file's log black/white points are a display choice and are not applied. A
depth other than 10 bits or a channel count other than 1/3 is Unsupported;
truncation errors rather than panicking. Read-only (no Cineon writer), so
.cin joins the open filters and Cineon read closes part of #1049's G10 gap.

* PSD: write tiff blocks without copies, inflate merged ZIP once

- ImageSourceData::to_bytes writes the global mask and global blocks
  straight from the model with 4-byte alignment instead of cloning each
  block (data included) to set its padding. Same bytes.
- The tiff transcoder's nested regions and blocks write into the parent's
  buffer (taken and handed back, error or not) instead of building their
  own output and copying it up per nesting level. Bodies that fail or are
  not transcoded are truncated before being copied as stored or dropped.
  Same bytes.
- PsdFile::from_bytes_and_merged decodes the merged image with the parse
  when asked: a ZIP stream is inflated once (the decode's stream check is
  the parse's); the parse-only check runs only when the decode fails, to
  keep from_bytes' errors. PSD import uses it with merged_needed.
- PsdBuilder::composite documents that Gray/CMYK composites stay straight.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Keyboard shortcut sets: Set menu, New Set, Save, Delete, .kys Export and Summarize (K2)

Edit › Keyboard Shortcuts gets Photoshop's set management. A set is a saved copy of the
bindings (Preferences.shortcutSets, the one in use in shortcutSet; "" is PhotoCraft Defaults),
and the Set menu shows "(modified)" when the bindings differ from it. New Set…, Save and
Delete wait for OK like the rest of the dialog. Export… writes the dialog's bindings as a .kys
file (commands then tools, Photoshop's macOS key spelling), each row carrying our id as pc-id
so PhotoCraft imports its own sets back exactly, whatever the label; Summarize… writes
Photoshop's HTML list of every bound command by menu.

edit.keyboardShortcuts takes useSet (before the call's edits), saveSet, deleteSet, sets and
activeSet (after them), exportKys and summarize; every reply reports the sets, the set in use
and whether it is modified. Bad names, keys or counts are errors that change nothing.

* .kys import: tool keys and sets saved on Windows (K3)

Photoshop's <tool> rows now import: each matches our tool by name (our tool names are
Photoshop's) or by pc-id in sets PhotoCraft exported, and a letter other than the tool's own
becomes its override, while its own letter keeps the tool cycling with the others (#5036).

A set saved on Windows spells the primary modifier Ctrl where a Mac set writes Cmd and keeps
Control for the Control key. A set with no Cmd or Opt anywhere but some Ctrl is read as a
Windows set, its Ctrl as our Cmd: Ctrl+L is the Cmd+L default, not a Control-key override that
would also mean Control on a Mac. The import reports `windows`.

* cargo fmt the extension lists

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Vikram Bhaskaran <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Tanish Manku <[email protected]>
2026-10-15 00:32:55 -04:00
David MannandClaude Opus 5.5 e6238ad399 PSD save: widen RLE row counts while writing a promoted PSB (#5285)
promote_to_psb used to rewrite every RLE stream in place (grow the
Vec, move the packed rows, widen the count table): a reallocation and
a full extra pass over the channel data of a file that is already over
2 GB, right before to_bytes copies it all once more.

Now promotion only marks the model: PsdFile gains `write_as_psb`. The
model stays a consistent PSD (header version 1, two-byte row counts),
so every reader that decodes it with header.version is unaffected.
to_bytes and encoded_len write version 2, long length fields and
four-byte row counts, widening each table while the stream is copied
out (the packed rows are the same in both versions). written_version()
reports what will be written; pad_layer_info_to() pads the written
body. Promotion checks every count table first, so an error leaves the
model unmarked and the write cannot fail on a table later.

Tests: a promoted PSD writes exactly the PSB written directly and reads
back as it, for every generated case; the promoted model is unchanged
apart from the flag and decodes as before; damaged tables fail with an
error before and after promotion.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-14 01:34:23 +02:00
David MannandClaude Opus 5.5 1e076433dc PSD save: choose PSB by the encoded size, not the raw estimate (#5285)
Root cause: the auto-PSB switch (#212) decided before encoding, from
estimate_psd_size: the uncompressed size of every layer, mask and merged
plane plus fixed overheads. Channels are then RLE-packed, so documents
whose PSD would be far under the 2 GB limit (a 2.02 GB "raw" document
written as a 1.75 GB file, or a 35 MB file from 2.2 GB of flat layers)
were saved as PSB. The Multichannel writer used the same estimate.

Change: the document is encoded as PSD (PSB only when forced or past
30000 px) and the decision is made on the exact length of the file that
will be written. PsdFile::encoded_len computes what to_bytes writes
without serializing the pixel data. When it is over the limit,
PsdFile::promote_to_psb turns the model into the equivalent PSB in place:
the packed RLE rows are the same in both versions, so only the row-count
tables widen from 2 to 4 bytes (length fields widen on write). Nothing is
re-encoded and the result is byte-identical to a PSB written directly
(tested). The promotion is atomic: every stream is checked and its room
reserved before the first changes. The layer info is re-padded for PSB
and kept 8B64 block signatures are resolved after the version is final.
A 1 MB headroom covers the image preview the save adds afterwards.

The raw-size estimate is removed: the exact length is cheap (only the
layer records are serialized to measure them), so it no longer needs a
fast path.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-14 00:21:58 +02:00
Elvis33LE fc0a579a4a PSD: parallel RLE for the merged image; layer channels decode and gather on all cores (#2754)
Saving a 36 MP document spent most of its time packing the merged image's
RLE rows one after another on one thread (packbits over ~144 MB), and
importing it decoded each layer's channels sequentially. The merged-image
row packer now runs in parallel chunks that concatenate in order (rows are
independent; errors surface like the sequential path's), the layer gather
runs in row bands on all cores before the per-channel RLE, the layer's
channels decode side by side, and the full-surface clone per layer is
gone.

Measured on a 6000×4000 8-bit document with a photo, a paint layer and a
Levels adjustment: save 2.86 s -> 2.55-2.64 s, open's import stage
1.12 s -> 1.07 s (psd_to_document 745 -> 564 ms). The remaining save time
is dominated by the merged composite render itself (~0.7 s).
2026-10-13 13:23:44 -04:00
Valentin KleinandClaude Opus 5.5 0fb4bbf1db PSD: don't inflate an over-budget ZIP merged image at parse time (#2926) (#2967)
validate_planes bounded its zlib loop by the uncapped declared size, so a
PSD/PSB declaring more than MAX_DECODED_BYTES of merged image could make
PsdFile::from_bytes decompress far past the decode budget before any
error. decode_planes refuses such a layout with LimitExceeded anyway, so
the stream is now kept verbatim without inflating it, like an unknown
compression method. A layered file whose merged composite is too large
still opens (the importer only warns when the composite can't be decoded).

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 10:40:31 -04:00
cf83e05821 fix(psd): Improve interoperability and decoding (#1955)
* fix(psd): Align global tagged blocks to four bytes

Use four-byte defaults for global blocks and streamed layer information.
Read global payloads without full copies while preserving block order,
explicit padding and the first layer candidate. Keep two-byte layer
alignment; test canonical padding and lossless PSD/PSB parsing.

* fix(psd): Preserve transparent composite colours and precision

* fix(psd): Check ZIP integrity and bound layer previews

* fix(io): Use document CMYK profiles for PSD fill pixels

Generated fill pixels used the default CMYK separation even when the PSD
embedded a different profile. Scope layer export to the document colour
space so cached pixels and the composite use the same profile.

Check native cached samples against an explicit ICC transform at 8 and
16 bits.

* io: refuse an empty RGB composite before splitting it into planes

chunks_exact(0) panics; an empty decoded composite now returns an error.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 03:46:52 -04:00
8948511eeb Large PSBs open with their pixels: decode planes past 2 GiB, plus 4-5 GB PSB fixtures (#375) (#782)
* PSD: decode planes up to 8 GiB, so large PSBs keep their pixels (#375)

MAX_DECODED_BYTES capped a single decode at 2 GiB. Real PSBs go past
that in one plane set: the merged image of a 30000x30000 RGB file is
2.7 GB, a 33000x33000 16-bit layer channel 2.2 GB. Opening such a file
gave a document with no layers (flattened files) or layers whose
channels were "treated as empty" (layered files). Saving hit the same
cap on the encode side and silently fell back to uncompressed data.

The cap is now 8 GiB on 64-bit targets and 2 GiB elsewhere, the budget
photocraft-codecs already uses for Limits::max_alloc. It stays a
backstop: the decoders bound their output by their input on their own
(RLE expands at most 64x, Raw needs every byte present). The Raw and
RLE output buffers are reserved with try_reserve_exact, so a machine
without that much memory gets an error instead of an abort.

generated with Claude Code

* PSD import: a channel that can't be decoded leaves its layer empty (#375)

The warning says the channel is "treated as empty", but the importer
filled a missing transparency channel with opaque alpha, so a layer
whose channels all failed became an opaque black rectangle over the
document. A channel that is present but undecodable now leaves the
whole layer empty (transparent), as the warning says.

tests/large_psb.rs: the damaged-channel case (PSD and PSB), and an
opt-in release test that opens a flattened 29000x29000 PSB whose
merged image decodes to 2.52 GB (16 s, 11.6 GB peak here).

generated with Claude Code

* Large-file fixtures: generate and check 4-5 GB PSBs (#375, #216)

photocraft-psd example big_psb writes five PSBs straight from the spec,
independent of this crate's writer and its limits: flattened and
layered, raw (4.4 and 4.8 GB files, data past 4 GiB) and RLE (small
files whose planes decode past 2 GiB, up to a 33000x33000 16-bit
layer). Every sample follows one formula, so photocraft-io example
big_psb_check opens a file through photocraft_io::import and checks
pixels without a reference; with SAVE set it saves as PSB and checks
the re-opened file.

Release build, this machine: all five open with correct pixels and
survive a PSB save and re-open (5-14 s per import). Before the 8 GiB
cap, three of the five opened empty or black.

Scorecard FILE-216-2 missing -> partial: no 2 GB PSD, 150-layer or
20 MP fixture yet, and nothing runs in CI.

generated with Claude Code

* psd: ZIP channels reserve fallibly and read in bounded chunks

A small ZIP channel declaring a huge decoded size could make
zip_decompress try a multi-GiB with_capacity/read_to_end and abort on
allocation failure. Reserve with try_reserve_exact/try_reserve, read
through take(expected) in 1 MiB chunks, and report LimitExceeded
instead. Tests: absurd declared sizes, past MAX_DECODED_BYTES, garbage.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-07 18:59:39 -04:00
Brandon ThomasandClaude Opus 5.5 f7eb6ea9e7 Format: adopt the craft-family rustfmt.toml and format the workspace
CI's `cargo fmt --all -- --check` has failed on every run because the
repo had no rustfmt config and was never formatted. Use the same settings
as EffectCraft/FilmCraft (max_width 160, use_small_heuristics Max), which
also keeps the churn small. Formatting only; no code changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-04 11:31:17 -04:00
Brandon Thomas 16941f7198 one-shot 2026-09-30 05:02:08 -04:00