diff --git a/crates/codecs/src/codecs/tiff/bands.rs b/crates/codecs/src/codecs/tiff/bands.rs index debd624ff9..093f90efdf 100644 --- a/crates/codecs/src/codecs/tiff/bands.rs +++ b/crates/codecs/src/codecs/tiff/bands.rs @@ -221,7 +221,7 @@ fn decode_band( if lay.direct() && pref.len == band.len() && stride == out_row { match dec.read_chunk_bytes(chunk, band) { Ok(()) => tally.decoded += 1, - // The rows read before the end stay in `band`: a missing strip is zeros. + // Rows read before the end would survive: a missing strip is zeros. Err(e) if is_eof(&e) => { band.fill(0); tally.missing += 1; diff --git a/crates/codecs/src/codecs/tiff/decode.rs b/crates/codecs/src/codecs/tiff/decode.rs index c2d1dc7a0e..f698f04039 100644 --- a/crates/codecs/src/codecs/tiff/decode.rs +++ b/crates/codecs/src/codecs/tiff/decode.rs @@ -90,7 +90,10 @@ impl<'a> TiffBands<'a> { let mut icc = None; let meta = metadata(&file, &dir, &mut icc); let stored = ifd::orientation_of(&file, &dir); - Ok(TiffBands { b: bytes, p, stored, turn: 1, cap: limits.max_alloc, icc, meta, warnings: more.into_iter().collect() }) + // Extra samples are dropped here only on 32-bit targets, where the whole image counts. + let mut warnings = prepared_warnings(&p); + warnings.extend(more); + Ok(TiffBands { b: bytes, p, stored, turn: 1, cap: limits.max_alloc, icc, meta, warnings }) } /// The bands turned upright for the page's Orientation tag, as [`Image::oriented`] turns a @@ -203,8 +206,10 @@ impl<'a> TiffBands<'a> { return Err(err("the image data is missing (cut off or past the end of the file)").into()); } if tally.missing > 0 { - // Before `MorePages`, as the whole-image decode orders them. - self.warnings.insert(0, DecodeWarning::Truncated { format: F }); + // After the extra-sample warnings and before `MorePages`, as the whole-image decode + // orders them. + let at = self.warnings.iter().position(|w| matches!(w, DecodeWarning::MorePages { .. })).unwrap_or(self.warnings.len()); + self.warnings.insert(at, DecodeWarning::Truncated { format: F }); } Ok(()) } @@ -575,19 +580,27 @@ fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result 0 { - let count = u32::try_from(p.extras_over_limit).unwrap_or(u32::MAX); - img.warnings.push(DecodeWarning::ExtraSamplesOverLimit { format: F, count }); - } - if p.extras_dropped > 0 { - img.warnings.push(DecodeWarning::ExtraSamplesDropped { format: F, count: p.extras_dropped }); - } + img.warnings.extend(prepared_warnings(&p)); if tally.missing > 0 { img.warnings.push(DecodeWarning::Truncated { format: F }); } Ok(img) } +/// What [`prepare`] left out of the image: extra samples past the supported count, then extra +/// samples over the allocation budget. Both decoders report them, in this order. +fn prepared_warnings(p: &Prepared) -> Vec { + let mut warnings = Vec::new(); + if p.extras_over_limit > 0 { + let count = u32::try_from(p.extras_over_limit).unwrap_or(u32::MAX); + warnings.push(DecodeWarning::ExtraSamplesOverLimit { format: F, count }); + } + if p.extras_dropped > 0 { + warnings.push(DecodeWarning::ExtraSamplesDropped { format: F, count: p.extras_dropped }); + } + warnings +} + /// Checks one directory and lays it out for decoding. `whole`: the image is decoded into one /// buffer, which `limits.max_alloc` bounds; otherwise only its size is checked here. fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result { @@ -807,3 +820,29 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result) -> Result drop(bands); return import_tiff_whole(name, bytes, page); } - tiff_to_document(name, bands.upright()) + tiff_to_document(name, bands.upright(), crate::memory::available, BAND_BYTES) } /// A layered TIFF, or a flat one with extra samples, decoded whole: the layers are built from the @@ -262,22 +262,26 @@ fn import_tiff_whole(name: &str, bytes: &[u8], page: Option) -> Result) -> Result { +/// layer's tiles: only one group exists beside the document. `available`: the memory this +/// process can still use (see [`crate::memory::available`]); `budget`: the source bytes per core +/// converted at a time ([`BAND_BYTES`]). +fn tiff_to_document(name: &str, mut bands: codecs::TiffBands<'_>, available: impl FnOnce() -> Option, budget: usize) -> Result { let (w, h) = bands.dimensions(); let (layout, sample) = (bands.layout(), bands.sample_type()); let f = document_format(layout, sample); let fmt = PixelFormat::new(f.mode, f.depth, true); - // The layer's tiles, plus a group as decoded, turned upright, converted and read into a - // worker's scratch buffer. Linux overcommits, so the tiles below are allocated even when they - // can't be backed, and writing them would have the process killed: refuse first. let bpp = fmt.bytes_per_pixel() as u64; - let tiles = |n: u32| u64::from(n).div_ceil(TILE_SIZE as u64).saturating_mul(TILE_SIZE as u64); - let layer = tiles(w).saturating_mul(tiles(h)).saturating_mul(bpp); - let group = bands.group_bytes()? as u64; - let group_px = group / (layout.channels() as u64 * sample.bytes() as u64).max(1); - let needed = layer.saturating_add(group.saturating_mul(3)).saturating_add(group_px.saturating_mul(bpp)); - crate::memory::check_fits(w, h, needed, crate::memory::available())?; + if needs_memory_check(w, h, layout, sample) { + // The layer's tiles, plus a group as decoded, turned upright, converted and read into a + // worker's scratch buffer. Linux overcommits, so the tiles below are allocated even when + // they can't be backed, and writing them would have the process killed: refuse first. + let tiles = |n: u32| u64::from(n).div_ceil(TILE_SIZE as u64).saturating_mul(TILE_SIZE as u64); + let layer = tiles(w).saturating_mul(tiles(h)).saturating_mul(bpp); + let group = bands.group_bytes()? as u64; + let group_px = group / (layout.channels() as u64 * sample.bytes() as u64).max(1); + let needed = layer.saturating_add(group.saturating_mul(3)).saturating_add(group_px.saturating_mul(bpp)); + crate::memory::check_fits(w, h, needed, available())?; + } let mut s = Surface::new(fmt); let out_of_memory = |e: photocraft_raster::AllocationError| { let gb = (u64::from(w) * u64::from(h)).saturating_mul(bpp) as f64 / 1e9; @@ -290,15 +294,19 @@ fn tiff_to_document(name: &str, mut bands: codecs::TiffBands<'_>) -> Result) -> Result bool { + codecs::Limits::default().check(w, h, layout, sample).is_err() +} + +/// `0..rows` of `row` bytes each, split into rounds of about one piece per core, each piece at +/// most about `budget` bytes, in order. +fn conversion_rounds(rows: usize, row: usize, budget: usize) -> Vec>> { + let round = (budget / row.max(1)).max(1).saturating_mul(crate::pixels::bands(rows).len()).max(1); + (0..rows) + .step_by(round) + .map(|start| { + let end = start.saturating_add(round).min(rows); + crate::pixels::bands(end - start).into_iter().map(|r| start + r.start..start + r.end).collect() + }) + .collect() +} + /// How a decoded image's pixels are kept in a document. struct DocumentFormat { mode: ColorMode, @@ -1159,3 +1187,64 @@ mod cmyk_band_tests { assert_eq!(first[3], 255); } } + +#[cfg(test)] +mod tiff_banded_tests { + use super::*; + + #[test] + fn a_tiff_main_opened_opens_without_a_memory_check() { + // With no free memory reported, an ordinary small TIFF was refused ("not enough memory"): + // on a small machine or in a container whose page cache filled up. + let img = Image::from_raw(64, 64, ChannelLayout::Rgb, CSample::U8, vec![77; 64 * 64 * 3]).unwrap(); + let bytes = codecs::encode(&img, Format::Tiff, &codecs::EncodeOptions::default()).unwrap(); + let bands = codecs::TiffBands::open(&bytes, None, &codecs::Limits::banded()).unwrap(); + let r = tiff_to_document("small.tif", bands.upright(), || Some(0), BAND_BYTES).unwrap(); + assert_eq!((r.document.size.width, r.document.size.height), (64, 64)); + } + + #[test] + fn a_group_converted_in_many_rounds_is_the_whole_image_converted() { + // A budget of a few rows splits each group into many rounds: every row lands where the + // one-shot conversion put it, at every depth the convert branch takes. + for (layout, sample) in [(ChannelLayout::Rgb, CSample::U8), (ChannelLayout::Rgb, CSample::U16), (ChannelLayout::Gray, CSample::F32)] { + let (w, h) = (37u32, 101u32); + let n = (w * h) as usize * layout.channels(); + let px: Vec = (0..n).map(|i| ((i * 37 + i / 7) % 251) as f32 / 250.0).collect(); + let img = Image::from_normalized(w, h, layout, sample, &px).unwrap(); + let bytes = codecs::encode(&img, Format::Tiff, &codecs::EncodeOptions::default()).unwrap(); + let bands = codecs::TiffBands::open(&bytes, None, &codecs::Limits::banded()).unwrap(); + let row = w as usize * layout.channels() * sample.bytes(); + let r = tiff_to_document("rounds.tif", bands, || None, 3 * row).unwrap(); + let f = document_format(layout, sample); + let want = codecs::decode(&bytes).unwrap().convert(f.layout, f.sample); + let LayerContent::Raster(s) = &r.document.layers[0].content else { panic!("not a raster layer") }; + assert!(s.to_interleaved(r.document.bounds()) == want.data(), "{layout:?} {sample:?}"); + } + } + + #[test] + fn only_sizes_the_whole_image_decode_refused_are_checked() { + use {CSample as S, ChannelLayout as L}; + assert!(!needs_memory_check(6000, 4000, L::Rgb, S::U8)); + assert!(!needs_memory_check(20_000, 20_000, L::Rgba, S::U16)); + assert!(needs_memory_check(40_000, 30_000, L::Rgb, S::U8), "over 2^30 px"); + assert!(needs_memory_check(300_000, 300_000, L::Rgb, S::U8)); + } + + #[test] + fn conversion_rounds_cover_every_row_in_order_within_the_budget() { + let workers = crate::pixels::bands(usize::MAX >> 8).len(); + for (rows, row, budget) in [(0, 30, 100), (1, 30, 100), (1000, 30, 100), (997, 7, 50), (10, 1000, 1), (5000, 3, 1 << 20)] { + let rounds = conversion_rounds(rows, row, budget); + let pieces: Vec<_> = rounds.iter().flatten().cloned().collect(); + assert_eq!(pieces.iter().map(|r| r.len()).sum::(), rows, "{rows} rows"); + assert!(pieces.windows(2).all(|p| p[0].end == p[1].start), "contiguous and in order: {pieces:?}"); + assert!(pieces.first().is_none_or(|p| p.start == 0)); + let most = (budget / row).max(1); + assert!(pieces.iter().all(|p| p.len() <= most), "{rows} x {row} B, budget {budget}: {pieces:?}"); + assert!(rounds.iter().all(|r| r.len() <= workers)); + } + assert_eq!(conversion_rounds(5000, 3, 1 << 20).len(), 1, "a group under the budget is one round"); + } +} diff --git a/crates/io/src/memory.rs b/crates/io/src/memory.rs index 88fb78773b..94d34aa902 100644 --- a/crates/io/src/memory.rs +++ b/crates/io/src/memory.rs @@ -10,7 +10,7 @@ pub const RESERVE: u64 = 512 << 20; /// Bytes this process can still use without running out, or `None` where that isn't known. On /// Linux: the free RAM the kernel can hand out (`MemAvailable`, capped by the process's cgroup -/// v2 `memory.max` and those above it) plus free swap (capped by the cgroup's `memory.swap.max`). +/// v2 `memory.max` and those above it) plus free swap (capped by the cgroup's `memory.swap.max` and those above it). /// Elsewhere `None`: Windows refuses an allocation past its commit limit, which the importers /// already report as an error, and macOS pages to disk as it needs. pub fn available() -> Option { @@ -66,17 +66,25 @@ mod linux { } /// Memory and swap left under the limits of `dir` and every cgroup above it (`None`: no - /// limit). Both limits apply hierarchically. + /// limit). Both limits apply hierarchically. `memory.current` includes page cache, which the + /// kernel reclaims before a cgroup hits `memory.max`, so its inactive part counts as free. pub(super) fn cgroup_room(dir: &Path) -> (Option, Option) { - let room = |d: &Path, max: &str, current: &str| -> Option { - let max = std::fs::read_to_string(d.join(max)).ok()?.trim().parse::().ok()?; - let current = std::fs::read_to_string(d.join(current)).ok().and_then(|c| c.trim().parse::().ok()).unwrap_or(0); - Some(max.saturating_sub(current)) + let read = |d: &Path, f: &str| std::fs::read_to_string(d.join(f)).ok(); + let room = |d: &Path, max: &str, current: &str, reclaimable: u64| -> Option { + let max = read(d, max)?.trim().parse::().ok()?; + let current = read(d, current).and_then(|c| c.trim().parse::().ok()).unwrap_or(0); + Some(max.saturating_sub(current.saturating_sub(reclaimable))) }; - let swap = dir.ancestors().take(64).filter_map(|d| room(d, "memory.swap.max", "memory.swap.current")).min(); - let ram = dir.ancestors().take(64).filter_map(|d| room(d, "memory.max", "memory.current")).min(); + let inactive_file = |d: &Path| read(d, "memory.stat").and_then(|s| stat(&s, "inactive_file")).unwrap_or(0); + let swap = dir.ancestors().take(64).filter_map(|d| room(d, "memory.swap.max", "memory.swap.current", 0)).min(); + let ram = dir.ancestors().take(64).filter_map(|d| room(d, "memory.max", "memory.current", inactive_file(d))).min(); (ram, swap) } + + /// A `memory.stat` field (` ` per line). + fn stat(stat: &str, field: &str) -> Option { + stat.lines().find_map(|l| l.strip_prefix(field)?.strip_prefix(' '))?.trim().parse().ok() + } } #[cfg(test)] @@ -126,6 +134,12 @@ mod tests { assert_eq!(linux::cgroup_room(&leaf).1, Some(128 << 20), "the tighter leaf swap limit wins"); write(&leaf, "memory.max", "1610612736\n"); assert_eq!(linux::cgroup_room(&leaf).0, Some(512 << 20), "the tighter limit wins"); + write(&leaf, "memory.max", "2147483648\n"); + write(&leaf, "memory.current", "2147483648\n"); + write(&leaf, "memory.stat", "anon 268435456\nfile 1879048192\ninactive_file_x 1\ninactive_file 1610612736\n"); + assert_eq!(linux::cgroup_room(&leaf).0, Some(1610612736), "inactive page cache is reclaimed before the limit"); + write(&leaf, "memory.stat", "anon 268435456\n"); + assert_eq!(linux::cgroup_room(&leaf).0, Some(0), "no inactive_file: memory.current is all in use"); std::fs::remove_dir_all(&root).unwrap(); assert!(available().is_some()); } diff --git a/crates/io/tests/it/tiff_banded_import.rs b/crates/io/tests/it/tiff_banded_import.rs index 61cd7a9076..a7bc468205 100644 --- a/crates/io/tests/it/tiff_banded_import.rs +++ b/crates/io/tests/it/tiff_banded_import.rs @@ -61,6 +61,26 @@ fn every_layout_opens_as_the_whole_image_decode_does() { } } +/// A file stored as one strip is one group, the whole image, converted to the layer in rounds of +/// rows: the document is the one the whole-image decode gives (#8536 review). +#[test] +fn a_single_strip_tiff_opens_as_the_whole_image_decode_does() { + use flate2::{Compression, write::ZlibEncoder}; + use std::io::Write; + let (w, h) = (1531, 2049); + let img = pattern(w, h, ChannelLayout::Rgb, SampleType::U8); + let mut z = ZlibEncoder::new(Vec::new(), Compression::fast()); + z.write_all(img.data()).unwrap(); + let strip = z.finish().unwrap(); + let mut f = b"II*\0\0\0\0\0".to_vec(); + f.extend_from_slice(&strip); + let bytes = rgb_tiff_directory(f, w, h, h, &[8], &[strip.len() as u32]); + let r = photocraft_io::import("one-strip.tif", &bytes).unwrap(); + let decoded = codecs::decode(&bytes).unwrap(); + assert_eq!(decoded.data(), img.data()); + assert!(layer_bytes(&r) == decoded.convert(ChannelLayout::Rgba, SampleType::U8).data(), "pixels"); +} + /// Peak resident memory of this process so far (Linux), in bytes. fn peak_rss() -> Option { let status = std::fs::read_to_string("/proc/self/status").ok()?; @@ -133,10 +153,11 @@ fn rgb_tiff_directory(mut f: Vec, w: u32, h: u32, rows: u32, offsets: &[u32] (258, 3, 3, bits_at), (259, 3, 1, 8), (262, 3, 1, 2), - (273, 4, n, arrays_at), + // A single strip's offset and count fit in the entry itself. + (273, 4, n, if let [o] = offsets { *o } else { arrays_at }), (277, 3, 1, 3), (278, 4, 1, rows), - (279, 4, n, arrays_at + 4 * n), + (279, 4, n, if let [c] = counts { *c } else { arrays_at + 4 * n }), (284, 3, 1, 1), ]; f.extend_from_slice(&(entries.len() as u16).to_le_bytes()); diff --git a/crates/ui-egui/src/i18n/ar.tsv b/crates/ui-egui/src/i18n/ar.tsv index a0fb661609..2a5ef902fb 100644 --- a/crates/ui-egui/src/i18n/ar.tsv +++ b/crates/ui-egui/src/i18n/ar.tsv @@ -3550,7 +3550,3 @@ curves Smooth تنعيم Update and Restart التحديث وإعادة التشغيل X X Y Y - -# Select and Mask workspace closure reasons - Select and Mask was closed: its document is no longer the active one أُغلقت مساحة التحديد والقناع: لم يعد المستند الخاص بها نشطًا - Select and Mask was closed: another layer was selected أُغلقت مساحة التحديد والقناع: تم تحديد طبقة أخرى