PhotoCraft: An open-source, photo editor written by scratch in pure Rust
PSD import: flat fallback respects the decode budget; checked sizes (#5200, #5202) (#5206)
Valentin Klein3b45e8baee71
diff --git a/crates/io/src/adjust_map.rs b/crates/io/src/adjust_map.rsindex 6e8247838..d4bc31269 100644--- a/crates/io/src/adjust_map.rs+++ b/crates/io/src/adjust_map.rs@@ -280,7 +280,8 @@ fn parse_gradient_map(d: &[u8]) -> Option<Adjustment> {3 => (Some(d.get(4..8)?), 8),_ => return None,};- at += 4 + be32(d, at)? as usize * 2;+ // The gradient's name (UTF-16 units); checked, as `len * 2` overflows a 32-bit `usize`.+ at = (be32(d, at)? as usize).checked_mul(2)?.checked_add(at + 4)?;let n = usize::from(be16(d, at)?);at += 2;let mut stops = Vec::with_capacity(n);diff --git a/crates/io/src/exr_parts.rs b/crates/io/src/exr_parts.rsindex 5474d0031..7e25feb98 100644--- a/crates/io/src/exr_parts.rs+++ b/crates/io/src/exr_parts.rs@@ -225,8 +225,8 @@ pub fn import(name: &str, bytes: &[u8], sel: &Selection) -> Result<ImportResult,return Err(IoError::Unsupported("no parts or groups selected".into()));}- // Decode each needed whole part once; groups come from their part's named channels.- let mut part_pixels: Vec<Option<Image>> = vec![None; info.len()];+ // Each chosen part (deduplicated above) decodes once; groups come from their part's named+ // channels.let mut layers: Vec<Layer> = Vec::new();let mut warnings: Vec<String> = Vec::new();let mut gray_only = true;@@ -234,14 +234,7 @@ pub fn import(name: &str, bytes: &[u8], sel: &Selection) -> Result<ImportResult,let mut f16_seen = false;for part in &chosen_parts {- let img = match &part_pixels[part.index] {- Some(img) => img.clone(),- None => {- let img = codecs::decode_exr_part(bytes, part.index, &opts)?;- part_pixels[part.index] = Some(img.clone());- img- }- };+ let img = codecs::decode_exr_part(bytes, part.index, &opts)?;if img.sample_type() == SampleType::F16 {f16_seen = true;}diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rsindex 5512a55c0..54fe96090 100644--- a/crates/io/src/flat.rs+++ b/crates/io/src/flat.rs@@ -16,13 +16,15 @@ const BAND_BYTES: usize = 32 << 20;/// Decodes a flat image into a single-layer document; a TIFF with Photoshop layer data opens/// layered (see [`crate::tiff_layers`]).pub fn import_flat(name: &str, bytes: &[u8]) -> Result<ImportResult, IoError> {- if codecs::detect(bytes) == Some(Format::Tiff) {+ // Detected once; every step below branches on it.+ let format = codecs::detect(bytes);+ if format == Some(Format::Tiff) {return import_tiff_page(name, bytes, None);}- let img = codecs::decode(bytes)?;+ let img = codecs::decode_as(format.ok_or(codecs::CodecError::UnknownFormat)?, bytes)?;// A palette BMP or PNG opens in Indexed Color mode with its colour table, as in Photoshop// (#3802, #4804).- let palette = match codecs::detect(bytes) {+ let palette = match format {Some(Format::Bmp) => codecs::bmp_palette(bytes).ok().flatten().map(|c| (c, None)),Some(Format::Png) => codecs::png_palette(bytes).ok().flatten().map(|p| (p.colors, p.transparent)),_ => None,@@ -34,15 +36,15 @@ pub fn import_flat(name: &str, bytes: &[u8]) -> Result<ImportResult, IoError> {r.document.mode = ColorMode::Indexed;r.document.color_table = Some(photocraft_doc::ColorTable { colors, transparent });}- r.document.file_encoding = file_encoding(bytes);- if codecs::detect(bytes) == Some(Format::Tga) && img.layout() == ChannelLayout::Rgba {+ r.document.file_encoding = file_encoding_as(format, bytes);+ if format == Some(Format::Tga) && img.layout() == ChannelLayout::Rgba {tga_alpha_to_channel(&mut r.document)?;}// OpenEXR and Radiance HDR hold linear, scene-referred values (Rec. 709 primaries unless// stated otherwise, and an OpenEXR `Y` is linear luminance): tag them linear sRGB or linear// gray so they display and convert correctly.let d = &mut r.document;- if d.icc_profile.is_none() && matches!(codecs::detect(bytes), Some(Format::OpenExr | Format::Hdr)) {+ if d.icc_profile.is_none() && matches!(format, Some(Format::OpenExr | Format::Hdr)) {d.icc_profile = match d.mode {ColorMode::Rgb => Some(photocraft_cms::Builtin::LinearSrgb.profile().to_bytes()),ColorMode::Grayscale => Some(photocraft_cms::builtin::linear_gray().to_bytes()),@@ -68,8 +70,13 @@ pub fn import_gif_frames(name: &str, bytes: &[u8], each: &mut dyn FnMut(Document/// (estimated from its quantisation tables) and a WebP's lossless or lossy encoding with its/// quality. A lossy WebP whose quality can't be read gets [`DEFAULT_LOSSY_WEBP_QUALITY`].pub fn file_encoding(bytes: &[u8]) -> photocraft_doc::FileEncoding {+ file_encoding_as(codecs::detect(bytes), bytes)+}++/// [`file_encoding`] for `bytes` already detected as `format`.+fn file_encoding_as(format: Option<Format>, bytes: &[u8]) -> photocraft_doc::FileEncoding {let mut e = photocraft_doc::FileEncoding::default();- match codecs::detect(bytes) {+ match format {Some(Format::Jpeg) => e.jpeg_quality = codecs::jpeg_quality(bytes),Some(Format::WebP) => match codecs::webp_encoding(bytes) {Some(codecs::WebpEncoding::Lossless) => e.webp_lossless = Some(true),diff --git a/crates/io/src/kra/tiles.rs b/crates/io/src/kra/tiles.rsindex b369341b9..8af6638aa 100644--- a/crates/io/src/kra/tiles.rs+++ b/crates/io/src/kra/tiles.rs@@ -231,9 +231,9 @@ impl<'a> TileFile<'a> {for &(x, y, data) in &self.tiles {ctl.check().map_err(|_| IoError::Cancelled)?;let (flag, payload) = data.split_first().ok_or_else(|| invalid("empty tile"))?;- let planar = match flag {- 1 => lzf_decompress(payload, expected)?,- 0 if payload.len() == expected => payload.to_vec(),+ let planar: std::borrow::Cow<'_, [u8]> = match flag {+ 1 => lzf_decompress(payload, expected)?.into(),+ 0 if payload.len() == expected => payload.into(),0 => return Err(invalid("raw tile has the wrong size")),f => return Err(invalid(format!("unknown tile compression flag {f}"))),};diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rsindex 211bba4da..94c4ea993 100644--- a/crates/io/src/psd_import.rs+++ b/crates/io/src/psd_import.rs@@ -595,14 +595,83 @@ fn unicode_names(data: &[u8]) -> Vec<String> {while at + 4 <= data.len() {let n = u32::from_be_bytes([data[at], data[at + 1], data[at + 2], data[at + 3]]) as usize;at += 4;- let Some(b) = data.get(at..at + n * 2) else { break };+ // Checked: `n * 2` overflows a 32-bit `usize` for a hostile length.+ let Some(end) = n.checked_mul(2).and_then(|len| at.checked_add(len)) else { break };+ let Some(b) = data.get(at..end) else { break };let units: Vec<u16> = b.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]])).collect();out.push(String::from_utf16_lossy(&units).trim_end_matches('\0').to_string());- at += n * 2;+ at = end;}out}+/// Plane `i` of a decoded merged image whose planes are `plane` bytes each, or `None` when it is+/// short or the offsets overflow.+fn merged_plane(all: &[u8], i: usize, plane: usize) -> Option<&[u8]> {+ all.get(i.checked_mul(plane)?..i.checked_add(1)?.checked_mul(plane)?)+}++/// The merged image of a file the layered path does not open (Bitmap, Indexed, Duotone; 1-bit+/// files) as RGBA8. What `composite_rgba8` can't read (Multichannel) shows its first channels as+/// RGB. An output over `cap` bytes is refused, never allocated (#5200).+fn flat_composite(+ file: &PsdFile,+ merged: Option<&Result<Vec<u8>, photocraft_psd::PsdError>>,+ cap: u64,+) -> Result<photocraft_psd::RgbaImage, photocraft_psd::PsdError> {+ use photocraft_psd::PsdError;+ match file.composite_rgba8() {+ Ok(img) => return Ok(img),+ // Over the output budget: the fallback below would make the same allocation.+ Err(e @ PsdError::LimitExceeded(_)) => return Err(e),+ Err(_) => {}+ }+ let all = match merged {+ Some(Ok(all)) => all,+ Some(Err(e)) => return Err(e.clone()),+ None => return Err(PsdError::Invalid("no merged image".into())),+ };+ let h = &file.header;+ let (w, hh) = (h.width as usize, h.height as usize);+ let len = w+ .checked_mul(hh)+ .and_then(|n| n.checked_mul(4))+ .filter(|&len| len as u64 <= cap)+ .ok_or(PsdError::LimitExceeded("RGBA output exceeds MAX_DECODED_BYTES"))?;+ let plane = h.row_bytes().checked_mul(hh).ok_or(PsdError::LimitExceeded("plane size overflow"))?;+ let mut data = Vec::new();+ data.try_reserve_exact(len).map_err(|_| PsdError::LimitExceeded("not enough memory for RGBA output"))?;+ data.resize(len, 255u8);+ for c in 0..3.min(usize::from(h.channels)) {+ let bytes = merged_plane(all, c, plane).ok_or_else(|| PsdError::Invalid("channel size mismatch".into()))?;+ let p = photocraft_psd::pixels::plane_to_u8(bytes, h.depth, w, hh)?;+ for (px, v) in data.as_chunks_mut::<4>().0.iter_mut().zip(&p) {+ px[c] = *v;+ }+ }+ Ok(photocraft_psd::RgbaImage { left: 0, top: 0, width: h.width, height: h.height, data })+}++/// Writes RGBA8 `data` covering `canvas` into `s`, a band of tile rows at a time (no full-size+/// float copy of the image).+fn write_rgba8(s: &mut Surface, canvas: Rect, data: &[u8]) {+ let fmt = s.format();+ let row = (canvas.width() as usize).saturating_mul(4);+ let mut vals = Vec::new();+ let mut y = canvas.y0;+ while y < canvas.y1 {+ let band = Rect::new(canvas.x0, y, canvas.x1, y.saturating_add(TILE_SIZE).min(canvas.y1));+ let start = ((y - canvas.y0) as usize).saturating_mul(row);+ let Some(rows) = data.get(start..start.saturating_add((band.height() as usize).saturating_mul(row))) else { break };+ vals.clear();+ for p in rows.as_chunks::<4>().0 {+ vals.extend(photocraft_raster::from_rgba(&fmt, p.map(|x| f32::from(x) / 255.0)));+ }+ s.write_region(band, &vals);+ y = band.y1;+ }+}+fn parse_guides(data: &[u8], doc: &mut Document) {let rd = |at: usize| data.get(at..at + 4).map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]));let Some(count) = rd(12) else { return };@@ -623,10 +692,21 @@ fn parse_guides(data: &[u8], doc: &mut Document) {/// Background (Photoshop 27.11 opens psd-tools' flat Bitmap and Indexed files that way), so it is/// written back as one.fn flat_background(s: Surface) -> Layer {+ // A band of tile rows at a time (no full-size float copy), stopping at the first+ // transparent pixel.let opaque = {let r = s.content_bounds();let n = s.channels();- !r.is_empty() && s.read_region(r).chunks_exact(n).all(|p| p.last().is_some_and(|a| *a >= 1.0))+ let mut vals = Vec::new();+ let mut y = r.y0;+ let mut opaque = !r.is_empty();+ while opaque && y < r.y1 {+ let band = Rect::new(r.x0, y, r.x1, y.saturating_add(TILE_SIZE).min(r.y1));+ s.read_region_into(band, &mut vals);+ opaque = vals.chunks_exact(n).all(|p| p.last().is_some_and(|a| *a >= 1.0));+ y = band.y1;+ }+ opaque};let mut l = Layer::new("Background", LayerContent::Raster(s));l.locks.transparency = opaque;@@ -771,7 +851,9 @@ pub fn psd_to_document_with(file: &PsdFile, ctl: &photocraft_raster::Interrupt)}let (w, hh) = (h.width as usize, h.height as usize);- let n = w * hh;+ // Pixels per plane and bytes per merged plane, checked: a 1-bit plane can decode within the+ // budget while `w * hh` does not fit a 32-bit `usize` (wasm32).+ let sizes = w.checked_mul(hh).zip(h.row_bytes().checked_mul(hh));let canvas = Rect::new(0, 0, h.width as i32, h.height as i32);// The merged composite is decoded only when something consumes it: a flattened or// multichannel file (it *is* the image), or extra alpha/spot channels behind the colour@@ -821,12 +903,13 @@ pub fn psd_to_document_with(file: &PsdFile, ctl: &photocraft_raster::Interrupt)}if doc.layers.is_empty()&& let Some(Ok(all)) = &merged+ // Always `Some` here: a decoded 8/16/32-bit plane holds at least `w * hh` bytes.+ && let Some((n, plane)) = sizes{// Flattened file: the merged image becomes the background layer.- let plane = h.row_bytes() * hh;let alpha_idx = if file.merged_has_alpha() { Some(cc) } else { None };- let mut planes: Vec<Option<&[u8]>> = (0..cc).map(|c| all.get(c * plane..(c + 1) * plane)).collect();- planes.push(alpha_idx.and_then(|a| all.get(a * plane..(a + 1) * plane)));+ let mut planes: Vec<Option<&[u8]>> = (0..cc).map(|c| merged_plane(all, c, plane)).collect();+ planes.push(alpha_idx.and_then(|a| merged_plane(all, a, plane)));let mut fill = vec![zero_sample(depth); cc];fill.push(max_sample(depth));let mut inv = vec![cx.cmyk; cc];@@ -882,47 +965,32 @@ pub fn psd_to_document_with(file: &PsdFile, ctl: &photocraft_raster::Interrupt)} else if !file.color_mode_data.is_empty() {cx.warn("color mode data is not preserved");}- let rgba = file.composite_rgba8().or_else(|_| {- // Multichannel: show the first channels as RGB.- let all = merged.clone().ok_or_else(|| photocraft_psd::PsdError::Invalid("no merged image".into()))??;- let plane = h.row_bytes() * hh;- let mut data = vec![255u8; n * 4];- for c in 0..3.min(usize::from(h.channels)) {- let p = photocraft_psd::pixels::plane_to_u8(&all[c * plane..(c + 1) * plane], h.depth, w, hh)?;- for i in 0..n {- data[i * 4 + c] = p[i];- }+ match flat_composite(file, merged.as_ref(), photocraft_psd::compression::MAX_DECODED_BYTES) {+ Ok(img) => {+ let mut s = Surface::new(fmt);+ write_rgba8(&mut s, canvas, &img.data);+ drop(img);+ s.prune();+ doc.layers.push(flat_background(s));}- Ok::<_, photocraft_psd::PsdError>(photocraft_psd::RgbaImage { left: 0, top: 0, width: h.width, height: h.height, data })- });- if let Ok(img) = rgba {- let mut s = Surface::new(fmt);- let vals: Vec<f32> = img- .data- .as_chunks::<4>()- .0- .iter()- .flat_map(|p| {- let v = photocraft_raster::from_rgba(&fmt, [p[0], p[1], p[2], p[3]].map(|x| f32::from(x) / 255.0));- v.into_iter()- })- .collect();- s.write_region(canvas, &vals);- s.prune();- doc.layers.push(flat_background(s));+ // A merged image that failed to decode was reported above.+ Err(_) if matches!(merged, Some(Err(_))) => {}+ Err(e) => cx.warn(format!("the image could not be read: {e}")),}}// Extra (alpha / spot) channels of the merged image.- if layered && let Some(Ok(all)) = &merged {+ if layered+ && let Some(Ok(all)) = &merged+ && let Some((n, plane)) = sizes+ {let first = cc + usize::from(file.merged_has_alpha());- let plane = h.row_bytes() * hh;let names = file.resource(1045).map(|r| unicode_names(&r.data)).unwrap_or_default();// Photoshop lists every extra channel, the merged transparency first when there is one.let skip = usize::from(file.merged_has_alpha() && names.len() == usize::from(h.channels).saturating_sub(cc));let names = names.get(skip..).unwrap_or_default();for (k, idx) in (first..usize::from(h.channels)).enumerate() {- let Some(p) = all.get(idx * plane..(idx + 1) * plane) else { break };+ let Some(p) = merged_plane(all, idx, plane) else { break };let mut s = Surface::new(cx.mask_fmt);s.write_interleaved(canvas, &be_to_ne_plane(p, depth, n));s.prune();@@ -962,3 +1030,54 @@ pub fn psd_to_document_with(file: &PsdFile, ctl: &photocraft_raster::Interrupt)ctl.progress(1.0);Some((doc, cx.warnings))}++#[cfg(test)]+mod tests {+ use super::*;+ use photocraft_psd::{Compression, PsdError, Version, testgen};++ /// #5200: the Multichannel fallback checks its RGBA output against the budget before+ /// allocating it (here a 2x2 image, 16 bytes, against caps of 15 and 16 bytes).+ #[test]+ fn flat_fallback_refuses_an_output_over_the_cap() {+ let file = testgen::merged_only(Version::Psd, PsdMode::Multichannel, 8, Compression::Raw, 2, 2);+ assert!(file.composite_rgba8().is_err(), "Multichannel goes through the fallback");+ let merged = file.decode_merged();+ assert!(matches!(flat_composite(&file, Some(&merged), 15), Err(PsdError::LimitExceeded(_))));+ let img = flat_composite(&file, Some(&merged), 16).unwrap();+ assert_eq!(img.data.len(), 16);+ }++ /// #5200: a composite over the budget is not retried by the fallback (which allocated the+ /// refused buffer: 14.4 GB for this 60000x60000 Bitmap header).+ #[test]+ fn flat_fallback_does_not_retry_an_over_budget_composite() {+ let mut file = testgen::small(Version::Psb, Compression::Raw);+ file.header.color_mode = PsdMode::Bitmap;+ file.header.depth = 1;+ file.header.channels = 1;+ file.header.width = 60_000;+ file.header.height = 60_000;+ let merged = Ok(vec![0u8; 16]);+ let cap = photocraft_psd::compression::MAX_DECODED_BYTES;+ assert!(matches!(flat_composite(&file, Some(&merged), cap), Err(PsdError::LimitExceeded(_))));+ }++ /// #5202: a hostile name length ends the list instead of overflowing.+ #[test]+ fn unicode_names_stop_at_a_hostile_length() {+ let mut data = 1u32.to_be_bytes().to_vec();+ data.extend([0, b'A']);+ data.extend(u32::MAX.to_be_bytes());+ data.extend([0, b'B']);+ assert_eq!(unicode_names(&data), ["A"]);+ }++ #[test]+ fn merged_plane_checks_offsets() {+ let all = [1u8, 2, 3, 4];+ assert_eq!(merged_plane(&all, 1, 2), Some(&[3u8, 4][..]));+ assert_eq!(merged_plane(&all, 2, 2), None);+ assert_eq!(merged_plane(&all, usize::MAX, 2), None);+ }+}