diff --git a/crates/codecs/src/exr_stream.rs b/crates/codecs/src/exr_stream.rs index a1d5818a16..1ed8ba1276 100644 --- a/crates/codecs/src/exr_stream.rs +++ b/crates/codecs/src/exr_stream.rs @@ -141,15 +141,17 @@ impl Decoder { if list.is_empty() || list.len() > 64 || list.iter().any(|c| c.sampling.0 != 1 || c.sampling.1 != 1) { return Err(unsupported("EXR channel count or subsampling")); } + // The same channels the whole-file decoder shows, so both routes open the same image. let names: Vec = list.iter().map(|c| c.name.to_string()).collect(); - let find = |name| names.iter().position(|n| n.rsplit('.').next() == Some(name)); - let (selected, gray) = if let (Some(r), Some(g), Some(b)) = (find("R"), find("G"), find("B")) { - (vec![Some(r), Some(g), Some(b), find("A")], false) - } else if let Some(y) = find("Y").or_else(|| (list.len() == 1).then_some(0)) { - (vec![Some(y), find("A")], true) - } else { - return Err(unsupported("no R/G/B or Y channels")); - }; + let (layout, picked) = crate::image::exr_color_channels(names.iter().map(String::as_str)).ok_or_else(|| unsupported("no R/G/B or Y channels"))?; + let gray = matches!(layout, crate::ChannelLayout::Gray | crate::ChannelLayout::GrayA); + let mut selected: Vec> = picked.into_iter().map(Some).collect(); + if !matches!(layout, crate::ChannelLayout::GrayA | crate::ChannelLayout::Rgba) { + selected.push(None); + } + if selected.len() != if gray { 2 } else { 4 } { + return Err(unsupported("EXR channel selection")); + } // The document path currently tags Rec. 709 linear samples. Keep custom // primaries on the existing decoder until their profiles can be mapped. if !gray && header.shared_attributes.chromaticities.is_some() { diff --git a/crates/codecs/tests/exr_stream.rs b/crates/codecs/tests/it/exr_stream.rs similarity index 98% rename from crates/codecs/tests/exr_stream.rs rename to crates/codecs/tests/it/exr_stream.rs index acf03e8ae1..65be2387b9 100644 --- a/crates/codecs/tests/exr_stream.rs +++ b/crates/codecs/tests/it/exr_stream.rs @@ -135,8 +135,8 @@ fn mixed_samples_and_offset_data_window_keep_coordinates_and_values() { while let Some(band) = decoder.next_band(&|| false).unwrap() { assert_eq!(band.y, rows); rows += band.height; - for p in band.data.chunks_exact(16) { - let v: Vec = p.chunks_exact(4).map(|s| f32::from_le_bytes(s.try_into().unwrap())).collect(); + for p in band.data.as_chunks::<16>().0 { + let v: Vec = p.as_chunks::<4>().0.iter().map(|s| f32::from_le_bytes(*s)).collect(); assert_eq!(v, [-0.25, 3.5, 42.0, 1.0]); } } diff --git a/crates/codecs/tests/it/main.rs b/crates/codecs/tests/it/main.rs index 4293fb4a48..72e878c44e 100644 --- a/crates/codecs/tests/it/main.rs +++ b/crates/codecs/tests/it/main.rs @@ -10,6 +10,7 @@ mod detect_caps; mod dpx; mod exr_cryptomatte; mod exr_multipart; +mod exr_stream; mod fidelity; mod gif_frames; mod heif; diff --git a/crates/engine/src/jobs/tests.rs b/crates/engine/src/jobs/tests.rs index 0974a5c17a..271162e3c6 100644 --- a/crates/engine/src/jobs/tests.rs +++ b/crates/engine/src/jobs/tests.rs @@ -543,6 +543,38 @@ fn open_runs_as_a_job_and_cancel_adds_nothing() { assert!(matches!(wait_event(&mut s, id).outcome, JobOutcome::Failed(_))); } +/// A flat scanline EXR opened from a path goes through the band decoder in the open job and +/// arrives as the same 32-bit document the whole-file decoder makes; cancelling adds nothing. +#[cfg(any(unix, windows))] +#[test] +fn an_exr_path_open_decodes_in_bands_and_cancels_cleanly() { + use photocraft_codecs::{ChannelLayout, EncodeOptions, ExrCompression, Format, Image, SampleType}; + let values: Vec = (0..64 * 48 * 3).map(|i| [0.25, 3.0, -0.5][i % 3]).collect(); + let image = Image::from_f32(64, 48, ChannelLayout::Rgb, &values).unwrap().convert(ChannelLayout::Rgb, SampleType::F16); + let bytes = photocraft_codecs::encode(&image, Format::OpenExr, &EncodeOptions { exr_compression: ExrCompression::Zip16, ..Default::default() }).unwrap(); + let path = std::env::temp_dir().join(format!("photocraft-open-job-{}.exr", std::process::id())); + std::fs::write(&path, &bytes).unwrap(); + let reference = photocraft_io::import("band.exr", &bytes).unwrap().document; + let mut s = Session::new(); + let id = job(s.start_open("band.exr", OpenSource::Path(path.to_string_lossy().into_owned())).unwrap()); + let e = wait_event(&mut s, id); + assert!(matches!(e.outcome, JobOutcome::Done(_)), "{e:?}"); + let doc = &s.documents()[0].doc; + assert_eq!((doc.size, doc.mode, doc.depth), (reference.size, reference.mode, reference.depth)); + use photocraft_doc::LayerContent; + let (LayerContent::Raster(a), LayerContent::Raster(r)) = (&doc.layers[0].content, &reference.layers[0].content) else { panic!("raster background") }; + assert_eq!(a.to_interleaved(reference.bounds()), r.to_interleaved(reference.bounds())); + + let id = job(s.start_open("again.exr", OpenSource::Path(path.to_string_lossy().into_owned())).unwrap()); + s.cancel_job(id); + let outcome = wait_event(&mut s, id).outcome; + assert!(matches!(outcome, JobOutcome::Cancelled | JobOutcome::Done(_)), "{outcome:?}"); + if outcome == JobOutcome::Cancelled { + assert_eq!(s.documents().len(), 1, "a cancelled open adds no document"); + } + std::fs::remove_file(path).unwrap(); +} + /// Ask When Opening: a file whose profile doesn't match is decoded but not added; the shell takes /// it once the prompt is answered. Without Ask it opens as usual. #[test] diff --git a/crates/io/src/exr_native.rs b/crates/io/src/exr_native.rs index 0d7555bd7b..af76690056 100644 --- a/crates/io/src/exr_native.rs +++ b/crates/io/src/exr_native.rs @@ -6,13 +6,37 @@ use photocraft_geom::{Rect, Size, TILE_SIZE}; use photocraft_raster::{Interrupt, Surface}; use std::io::{Read, Seek}; +/// Tiles the decoded image would add must fit the RAM tile budget when no scratch disk can +/// take cold tiles. +fn ram_tile_capacity(resident: u64, budget: u64, growth: u64) -> Result<(), IoError> { + if resident.checked_add(growth).is_none_or(|required| required > budget) { + return Err(IoError::OutOfMemory("decoded image tiles exceed the available RAM budget; enable a scratch disk or close other documents".into())); + } + Ok(()) +} + +/// A scratch disk that was on when the import started must still be on: its tiles may +/// already have moved there. +fn require_scratch(expected: bool) -> Result<(), IoError> { + if expected && !photocraft_raster::spill::enabled() { + return Err(IoError::Read( + photocraft_raster::spill::last_error().unwrap_or_else(|| "scratch storage was disabled while loading; retry the import".into()), + )); + } + Ok(()) +} + +/// Decode a single-part flat scanline EXR from `source` one compression block at a time. +/// `Ok(None)`: the header is not one the band decoder takes (multi-part, deep, tiled, custom +/// chromaticities, over its block limits or malformed by its stricter checks); the caller +/// falls back to the whole-file decoder. Once pixels are being decoded any failure fails the +/// open, so no partial document is published. pub(crate) fn import(source: R, ctl: &Interrupt<'_>) -> Result, IoError> { - let _metadata = photocraft_raster::memory::try_reserve(32 << 20).map_err(IoError::Unsupported)?; + let _metadata = photocraft_raster::memory::try_reserve(32 << 20).map_err(IoError::OutOfMemory)?; let mut decoder = match photocraft_codecs::exr_stream::Decoder::new(source, &|| ctl.cancelled()) { Ok(decoder) => decoder, Err(_) if ctl.cancelled() => return Err(IoError::Cancelled), - Err(photocraft_codecs::CodecError::Unsupported { .. }) => return Ok(None), - Err(e) => return Err(e.into()), + Err(_) => return Ok(None), }; let info = decoder.info(); let mode = if info.gray { ColorMode::Grayscale } else { ColorMode::Rgb }; @@ -22,19 +46,18 @@ pub(crate) fn import(source: R, ctl: &Interrupt<'_>) -> Result(source: R, ctl: &Interrupt<'_>) -> Result(source: R, ctl: &Interrupt<'_>) -> Result Vec { let values: Vec = (0..31 * 35 * layout.channels()).map(|i| [-0.25, 4.0, 0.0, 0.0001, 0.5][i % 5]).collect(); @@ -13,6 +9,10 @@ fn fixture(layout: ChannelLayout, sample: SampleType, compression: ExrCompressio photocraft_codecs::encode(&image, Format::OpenExr, &EncodeOptions { exr_compression: compression, ..Default::default() }).unwrap() } +fn open(path: &std::path::Path, ctl: &Interrupt) -> Result { + photocraft_io::import_file("HDR", path, &photocraft_io::ImportOptions::default(), ctl) +} + // One test keeps these imports from competing for the global working allowance. #[test] fn native_scanline_import_preserves_hdr_document_and_cancels_without_publication() { @@ -23,9 +23,8 @@ fn native_scanline_import_preserves_hdr_document_and_cancels_without_publication let bytes = fixture(layout, sample, compression); std::fs::write(&path, &bytes).unwrap(); let reference = photocraft_io::import("HDR", &bytes).unwrap(); - let native = photocraft_io::import_path_with("HDR", &path, &Interrupt::NONE).unwrap(); - let authorized = photocraft_io::import_seekable_with("HDR", &|| Ok(Cursor::new(&bytes)), &Interrupt::NONE).unwrap(); - for actual in [native, authorized] { + let actual = open(&path, &Interrupt::NONE).unwrap(); + { let a = &actual.document; let r = &reference.document; assert_eq!(actual.warnings, reference.warnings); @@ -56,9 +55,9 @@ fn native_scanline_import_preserves_hdr_document_and_cancels_without_publication cancelled.store(true, Ordering::Relaxed); } }; - assert!(matches!(photocraft_io::import_path_with("HDR", &path, &Interrupt::new(&cancel, &progress)), Err(photocraft_io::IoError::Cancelled))); + assert!(matches!(open(&path, &Interrupt::new(&cancel, &progress)), Err(photocraft_io::IoError::Cancelled))); std::fs::write(&path, &bytes[..bytes.len() / 2]).unwrap(); - assert!(photocraft_io::import_path_with("HDR", &path, &Interrupt::NONE).is_err()); + assert!(open(&path, &Interrupt::NONE).is_err()); // A syntactically complete huge header/table must be refused before reading // its pixel blocks when scratch is unavailable. No giant fixture is needed. assert!(!photocraft_raster::spill::enabled()); @@ -87,8 +86,7 @@ fn native_scanline_import_preserves_hdr_document_and_cancels_without_publication huge.extend_from_slice(&offset.to_le_bytes()); } huge.extend_from_slice(&[0; 8]); - assert!( - matches!(photocraft_io::import_seekable_with("huge", &|| Ok(Cursor::new(&huge)), &Interrupt::NONE), Err(photocraft_io::IoError::Unsupported(ref message)) if message.contains("decoded image tiles")) - ); + std::fs::write(&path, &huge).unwrap(); + assert!(matches!(open(&path, &Interrupt::NONE), Err(photocraft_io::IoError::OutOfMemory(ref message)) if message.contains("decoded image tiles"))); std::fs::remove_file(path).unwrap(); } diff --git a/crates/ui-egui/tests/exr_open.rs b/crates/ui-egui/tests/exr_open.rs deleted file mode 100644 index ae3b737bec..0000000000 --- a/crates/ui-egui/tests/exr_open.rs +++ /dev/null @@ -1,44 +0,0 @@ -#![cfg(not(target_arch = "wasm32"))] -use photocraft_codecs::{ChannelLayout, EncodeOptions, Format, Image}; -use photocraft_ui_egui::PhotocraftApp; - -#[test] -fn synchronous_native_exr_open_uses_tile_admission_before_huge_pixel_decode() { - let image = Image::from_f32(1, 1, ChannelLayout::Rgb, &[0.5, 2.0, -0.25]).unwrap(); - let bytes = photocraft_codecs::encode(&image, Format::OpenExr, &EncodeOptions::default()).unwrap(); - let mut header_end = 8; - loop { - if bytes[header_end] == 0 { - header_end += 1; - break; - } - for _ in 0..2 { - while bytes[header_end] != 0 { - header_end += 1; - } - header_end += 1; - } - let length = i32::from_le_bytes(bytes[header_end..header_end + 4].try_into().unwrap()) as usize; - header_end += 4 + length; - } - let mut huge = bytes[..header_end].to_vec(); - let needle = b"dataWindow\0box2i\0\x10\0\0\0"; - let at = huge.windows(needle.len()).position(|v| v == needle).unwrap() + needle.len(); - huge[at + 8..at + 12].copy_from_slice(&65535_i32.to_le_bytes()); - huge[at + 12..at + 16].copy_from_slice(&32767_i32.to_le_bytes()); - let offset = (header_end + 2048 * 8) as u64; - for _ in 0..2048 { - huge.extend_from_slice(&offset.to_le_bytes()); - } - huge.extend_from_slice(&[0; 8]); - let path = std::env::temp_dir().join(format!("photocraft-exr-ui-{}.exr", std::process::id())); - std::fs::write(&path, huge).unwrap(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.background_jobs = false; - photocraft_raster::spill::configure(None, 0).unwrap(); - photocraft_raster::memory::configure(photocraft_raster::memory::Policy { percent: None, absolute_bytes: 1 << 30 }); - let error = app.open_path(path.to_str().unwrap()).unwrap_err(); - assert!(error.contains("decoded image tiles"), "{error}"); - assert!(app.session.documents().is_empty()); - std::fs::remove_file(path).unwrap(); -} diff --git a/docs/roadmap.md b/docs/roadmap.md index 1710997e45..d2ca4a8435 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -125,4 +125,4 @@ Each milestone has a **definition of done (DoD)** and must leave `main` green on 2026-10-13: native scratch storage pages current and history tiles through compressed, CRC-checked files. Fresh RAM budgets default to 70%; engine-owned memory supervision stops with its last session. Scratch errors block edit/save commits and permit retry. Unix files are private and stale files swept at startup; Windows files use delete-on-close. See [scratch disks](scratch-disks.md). Streaming import and viewport rendering follow separately. -2026-10-13: seekable native PSD/PSB and supported scanline EXR imports decode bounded bands at the original resolution. Authorized opens retain read-only source protection. See [native streaming I/O](streaming-io.md). +2026-10-13: native path opens of single-part flat scanline EXR files decode one compression block at a time into tiles at the original resolution. See [EXR streaming](streaming-io.md). diff --git a/docs/scorecard.md b/docs/scorecard.md index 4733080bb1..db283ba4be 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -276,7 +276,7 @@ Never-crash attribute on 30 of 30 crate roots. | REL-2 | Every workspace crate carries the never-crash deny(clippy::unwrap_used, ...) attribute | done | | Counted automatically above (crate roots under crates/ and apps/); testkit gained it in #221 | | REL-3 | The app catches escaped panics around command dispatch and import/export | done | | a_panic_in_a_command_... runs the test-only `test.panic` spec through Session::execute and asserts Err plus an unchanged document (engine jobs_tests.rs); the worker guard is covered by a_panic_in_the_worker_...; crash_guard.rs guard_turns_a_panic_into_an_error covers import/export (apps/photocraft) | | REL-4 | Atomic save (temp, fsync, rename) for every document write | done | [#203](https://github.com/storytold/photocraft/issues/203) | photocraft_format::atomic_write (format/src/atomic.rs, #230): same-dir temp, sync_all, rename with Windows PermissionDenied retry, Unix dir fsync; every document write site routes through it and format/src/atomic/tests.rs failure-injects write, rename and read-only-dir errors | -| REL-212-1 | Fallible allocation for paste/erase/fill/transform/save/import, clear out-of-memory error | partial | [#212](https://github.com/storytold/photocraft/issues/212) | Raster region/tile buffers, paste/erase/fill/transform and warp output use fallible reservations; filter and lens working memory is admitted before edits, and current/history tiles spill to CRC-checked scratch. Native layered PSD/PSB and supported scanline EXR imports decode bounded bands; save/import boundaries preserve state; remaining encoder/decoder allocations still need broader audit. | +| REL-212-1 | Fallible allocation for paste/erase/fill/transform/save/import, clear out-of-memory error | partial | [#212](https://github.com/storytold/photocraft/issues/212) | Raster region/tile buffers, paste/erase/fill/transform and warp output use fallible reservations; filter and lens working memory is admitted before edits, and current/history tiles spill to CRC-checked scratch. Native path opens of flat scanline EXR decode bounded blocks into tiles; save/import boundaries preserve state; remaining encoder/decoder allocations still need broader audit. | | REL-212-2 | Export switches to PSB when the estimated file size exceeds 2 GB | done | [#212](https://github.com/storytold/photocraft/issues/212) | PSD export uses checked size estimates for raster, masks, channels, and retained metadata | | REL-212-3 | Tests: an allocation-limit injection makes each command Err with the document unchanged | partial | [#212](https://github.com/storytold/photocraft/issues/212) | Engine failpoint tests cover paste, erase, fill, transform, import and save transaction boundaries; codec-level allocator failure coverage remains open | diff --git a/docs/scratch-disks.md b/docs/scratch-disks.md index bf73af1948..bcc3103bce 100644 --- a/docs/scratch-disks.md +++ b/docs/scratch-disks.md @@ -57,5 +57,5 @@ read must never become saved pixels. Limitation: a tile that was already unreada read from outside the edited document (for example a clipboard copy) is not detected. Scratch storage alone does not make every format, filter or renderer streamable. See -[native PSD/EXR streaming](streaming-io.md) for the seekable import and output APIs. Viewport -rendering is a separate change built on these guards and memory reservations. +[EXR streaming](streaming-io.md) for the block-by-block EXR import. Viewport rendering is a +separate change built on these guards and memory reservations. diff --git a/docs/streaming-io.md b/docs/streaming-io.md index 3cc4d3a674..b7a84de6a2 100644 --- a/docs/streaming-io.md +++ b/docs/streaming-io.md @@ -1,36 +1,27 @@ -# Native PSD/EXR streaming +# EXR streaming -Native path opens inspect a seekable source before allocating decoded pixels. Supported layered -PSD/PSB files and flat scanline EXR files decode bounded bands directly into guarded raster -tiles. Their document dimensions and samples remain at the source resolution; scratch residency -can move cold tiles to disk. The byte decoder remains available for web and unsupported layouts, -subject to working-memory admission rather than a file-sized allocation without a budget. +Native path opens (`photocraft_io::import_file_for_open_with`, used by the background open job +and by automation file opens) decode single-part flat scanline EXR files one compression block +at a time straight into guarded raster tiles. The document keeps the source dimensions and +samples; HALF samples are stored as F32, with a warning. Tiles count against the RAM tile +budget, and scratch residency can move cold tiles to disk; without a scratch disk an image whose +tiles cannot fit the budget fails with a clear out-of-memory error before any pixels are +decoded. Layered PSD/PSB files use the existing streaming PSD reader on the same route. -PSD indexing retains bounded metadata and channel offsets without copying all channel data or -decoding the stored merged image. Independent seekable channel handles feed the existing document -mapping, preserving layers, masks, groups, metadata, colour models and depth. Unsupported nesting -and metadata limits produce errors. The native PSB writer uses the same metadata mapper with -deferred pixel sources and writes original-depth channel bands to a seekable output. +The block decoder (`photocraft_codecs::exr_stream`) treats the file as untrusted. Header metadata +is bounded (8 MiB, 4096 attributes); dimensions, channel count, chunk count, offsets, block +lengths and sample counts are checked against the file length and the header before anything is +allocated, and one decoded block is capped at 64 MiB. Duplicate, misaligned or truncated blocks +fail the open. It picks the same colour channels as the whole-file decoder. -EXR block decoding supports the flat scanline layouts accepted by the streaming decoder, including -the RGB HALF ZIP test image `65536 × 32768`. HALF samples are stored as F32, with a warning; this -does not reduce the document dimensions. Unsupported EXR layouts fall back to the normal codec -when its limits allow them. Chunk sizes, source bounds and transient buffers are checked before -allocation. Cancellation is checked between bands, and progress describes completed work. +Multi-part, deep, tiled, subsampled and custom-chromaticity files, and headers the block decoder +refuses, fall back to the whole-file decoder, under its own limits and working-memory admission. +Web and byte opens always use the whole-file decoder. -Control and CLI opens use the same importer. Authorized control opens create independent handles -under the held read-directory capability, including channel reopens. They do not gain ambient -filesystem access. Path opens check that file size and modification time remain unchanged. Read-only -and preview import flags survive the native and authorized routes, and templates keep an untitled -document without a source save path. +Cancellation is checked between reads and between scanlines, and progress reports completed +lines. A cancelled or failed open publishes no partial document. The open also fails if the +file's size or modification time changed while it was being read. -The seekable output API accepts a caller-owned writer; atomic path output encodes into a temporary -file beside the destination, syncs it using the shared platform helper, then renames it. Encoder -failure, cancellation or unwinding removes the temporary and preserves the old destination. Its -integration with the desktop background-save service is a separate change, using upstream's -`SaveCtl` and document-lock/saved-revision contract. - -Synthetic tests compare streamed import with the byte decoder across PSD/PSB versions, depths, -colour modes and compression, and verify masks, metadata, cancellation, EXR chunk handling, -source protection and capability bounds. Large-file runtime checks use the public fixtures at -[vistaero.es/photocraft](https://vistaero.es/photocraft/). +Tests compare the streamed document with the whole-file decoder across Gray/GrayA/RGB/RGBA, HALF +and FLOAT, and None/RLE/ZIP/ZIPS/PIZ compression, and cover cancellation, truncation, forged +offsets and lengths, hostile metadata and oversized headers. diff --git a/scorecard/reliability.toml b/scorecard/reliability.toml index 7bc708e548..2939a9152a 100644 --- a/scorecard/reliability.toml +++ b/scorecard/reliability.toml @@ -35,7 +35,7 @@ id = "REL-212-1" target = "Fallible allocation for paste/erase/fill/transform/save/import, clear out-of-memory error" status = "partial" issue = 212 -note = "Raster region/tile buffers, paste/erase/fill/transform and warp output use fallible reservations; filter and lens working memory is admitted before edits, and current/history tiles spill to CRC-checked scratch. Native layered PSD/PSB and supported scanline EXR imports decode bounded bands; save/import boundaries preserve state; remaining encoder/decoder allocations still need broader audit." +note = "Raster region/tile buffers, paste/erase/fill/transform and warp output use fallible reservations; filter and lens working memory is admitted before edits, and current/history tiles spill to CRC-checked scratch. Native path opens of flat scanline EXR decode bounded blocks into tiles; save/import boundaries preserve state; remaining encoder/decoder allocations still need broader audit." [[item]] id = "REL-212-2"