Wire EXR band streaming into main's path open

- import_file_for_open_with decodes single-part flat scanline EXR block by block into
  tiles; headers the band decoder refuses fall back to the whole-file decoder, so files
  main opened still open. Band-time failures and cancellation publish no document.
- The RAM tile budget and scratch-disk checks live in exr_native (the PSD stream module
  they came from is dropped); over-budget opens fail with IoError::OutOfMemory.
- The band decoder picks colour channels with exr_color_channels, like the byte decoder.
- Tests move into the per-crate it binaries and use import_file; an engine open-job test
  covers the OpenSource::Path route. The ui-egui sync open test is dropped: main's
  synchronous open reads bytes, and the io test covers the oversized header.
- docs/streaming-io.md, roadmap, scratch-disks and REL-212-1 describe EXR only.
This commit is contained in:
FredApps committed 2026-11-03 09:23:15 +01:00
1 parent fdab6c0a33
commit 7e29a9999c
14 files changed
+139 -115

No files matched your search

+10 -8
View File
@@ -141,15 +141,17 @@ impl<R: Read + Seek> Decoder<R> {
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<String> = 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<Option<usize>> = 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() {
@@ -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<f32> = 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<f32> = 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]);
}
}
+1
View File
@@ -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;
+32
View File
@@ -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<f32> = (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]
+33 -11
View File
@@ -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<R: Read + Seek>(source: R, ctl: &Interrupt<'_>) -> Result<Option<ImportResult>, 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<R: Read + Seek>(source: R, ctl: &Interrupt<'_>) -> Result<O
let budget = photocraft_raster::memory::refresh();
let side = TILE_SIZE as u64;
let tiles = u64::from(info.width).div_ceil(side).saturating_mul(u64::from(info.height).div_ceil(side));
crate::psd_stream::ram_tile_capacity(
false,
ram_tile_capacity(
photocraft_raster::spill::stats().resident_bytes as u64,
budget.tile_bytes,
tiles.saturating_mul(side * side).saturating_mul(fmt.bytes_per_pixel() as u64),
)?;
}
let _working = photocraft_raster::memory::try_reserve(info.working_bytes).map_err(IoError::Unsupported)?;
let _working = photocraft_raster::memory::try_reserve(info.working_bytes).map_err(IoError::OutOfMemory)?;
let mut surface = Surface::new(fmt);
let mut done = 0;
loop {
ctl.check().map_err(|_| IoError::Cancelled)?;
crate::psd_stream::require_scratch(scratch_expected)?;
require_scratch(scratch_expected)?;
let band = decoder.next_band(&|| ctl.cancelled()).map_err(|e| if ctl.cancelled() { IoError::Cancelled } else { e.into() })?;
let Some(band) = band else {
break;
@@ -42,15 +65,14 @@ pub(crate) fn import<R: Read + Seek>(source: R, ctl: &Interrupt<'_>) -> Result<O
let rect = Rect::from_xywh(band.x as i32, band.y as i32, band.width, band.height);
if !photocraft_raster::spill::enabled() {
let missing = rect.tiles().filter(|c| surface.tile(*c).is_none()).count() as u64;
crate::psd_stream::ram_tile_capacity(
false,
ram_tile_capacity(
photocraft_raster::spill::stats().resident_bytes as u64,
photocraft_raster::memory::stats().1.tile_bytes,
missing.saturating_mul((TILE_SIZE as u64).pow(2)).saturating_mul(fmt.bytes_per_pixel() as u64),
)?;
}
surface.write_interleaved(rect, &band.data);
crate::psd_stream::require_scratch(scratch_expected)?;
require_scratch(scratch_expected)?;
done += 1;
ctl.progress(0.05 + 0.9 * done as f32 / info.blocks.max(1) as f32);
}
@@ -59,7 +81,7 @@ pub(crate) fn import<R: Read + Seek>(source: R, ctl: &Interrupt<'_>) -> Result<O
if info.has_alpha {
surface.prune();
}
crate::psd_stream::require_scratch(scratch_expected)?;
require_scratch(scratch_expected)?;
ctl.check().map_err(|_| IoError::Cancelled)?;
let mut document = Document::new("", Size::new(info.width, info.height), mode, SampleType::F32);
let mut layer = Layer::new("Background", LayerContent::Raster(surface));
+22 -1
View File
@@ -45,6 +45,8 @@ mod channel_map;
pub mod comps_map;
pub mod doc_path;
pub mod effects_map;
#[cfg(any(unix, windows))]
mod exr_native;
pub mod exr_parts;
mod flat;
mod gradient_bake;
@@ -462,7 +464,9 @@ fn import_psd(
/// ([`PsdFile::from_source`]) rather than read whole: its channel data is read layer by layer as
/// it is decoded, so opening it needs memory for the document, not for the document plus the
/// file. A read that fails meanwhile (the file is truncated or rewritten, its drive goes away)
/// fails the open. Other formats are read whole.
/// fails the open. A single-part flat scanline EXR is decoded one compression block at a time
/// into tiles, so its size is bounded by the tile budget (or the scratch disk), not by a
/// whole-file buffer and a decoded image. Other formats are read whole.
#[cfg(any(unix, windows))]
pub fn import_file_for_open_with(
name: &str,
@@ -477,6 +481,23 @@ pub fn import_file_for_open_with(
let psd = !has_extension(name, photocraft_format::EXTENSION) && photocraft_psd::ReadAt::read_at(&source, 0, &mut magic).is_ok() && is_psd(&magic);
if !psd {
drop(source);
// A flat scanline EXR is decoded block by block straight into tiles; other EXR
// layouts, and EXR headers the band decoder refuses, are read whole below.
if !has_extension(name, photocraft_format::EXTENSION) && photocraft_codecs::detect(&magic) == Some(photocraft_codecs::Format::OpenExr) {
let before = photocraft_raster::spill::read_error_generation();
let mut file = std::fs::File::open(path).map_err(read_failed)?;
let original = file.metadata().map_err(read_failed)?;
if let Some(mut result) = exr_native::import(&mut file, ctl)? {
let current = std::fs::metadata(path).map_err(read_failed)?;
if current.len() != original.len() || current.modified().ok() != original.modified().ok() {
return Err(IoError::Read(format!("{}: the file changed while it was being opened; open it again", path.display())));
}
photocraft_raster::spill::check_since(before).map_err(IoError::Read)?;
ctl.check().map_err(|_| IoError::Cancelled)?;
result.document.name = name.to_string();
return Ok((result, false));
}
}
let bytes = photocraft_format::read_file(path).map_err(read_failed)?;
return import_for_open_with(name, &bytes, opts, ctl);
}
+1
View File
@@ -73,6 +73,7 @@ mod resolution_axes;
mod roundtrip;
mod smart_contents_identity;
mod smart_corpus;
mod streaming_exr;
mod svg;
mod text_corpus;
mod text_styles;
@@ -1,11 +1,7 @@
#![cfg(not(target_arch = "wasm32"))]
use photocraft_codecs::{ChannelLayout, EncodeOptions, ExrCompression, Format, Image, SampleType};
use photocraft_doc::LayerContent;
use photocraft_raster::Interrupt;
use std::{
io::Cursor,
sync::atomic::{AtomicBool, Ordering},
};
use std::sync::atomic::{AtomicBool, Ordering};
fn fixture(layout: ChannelLayout, sample: SampleType, compression: ExrCompression) -> Vec<u8> {
let values: Vec<f32> = (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::ImportResult, photocraft_io::IoError> {
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();
}
-44
View File
@@ -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();
}
+1 -1
View File
@@ -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).
+1 -1
View File
@@ -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 |
+2 -2
View File
@@ -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.
+22 -31
View File
@@ -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.
+1 -1
View File
@@ -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"