Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

fix(psd): Improve interoperability and decoding (#1955)

Rene Leonhardtcf83e0582121
diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs
index 2379edb55..0d240239e 100644
--- a/crates/io/src/lib.rs
+++ b/crates/io/src/lib.rs
@@ -307,8 +307,45 @@ pub fn export(doc: &Document, name_or_ext: &str, opts: &ExportOptions) -> Result
/// with the document pixel model and un-matted from white (Photoshop mattes
/// the merged image of transparent documents). Used as the compositing oracle.
pub fn merged_composite(file: &PsdFile) -> Result<Vec<[f32; 4]>, IoError> {
- let img = file.composite_rgba8().ok();
let h = &file.header;
+ h.validate()?;
+ if h.color_mode == photocraft_psd::ColorMode::Rgb && file.merged_has_alpha() {
+ // Preserve native sample precision before removing the white matte.
+ let raw = file.decode_merged()?;
+ let plane = raw.len() / usize::from(h.channels);
+ if plane == 0 {
+ return Err(PsdError::Invalid("empty RGB composite".into()).into());
+ }
+ let planes = raw
+ .chunks_exact(plane)
+ .take(4)
+ .map(|bytes| match h.depth {
+ 32 => Ok(photocraft_psd::pixels::samples_f32(bytes)),
+ 16 => Ok(photocraft_psd::pixels::samples_u16(bytes).into_iter().map(|v| f32::from(v) / 65535.0).collect()),
+ _ => photocraft_psd::pixels::plane_to_u8(bytes, h.depth, h.width as usize, h.height as usize)
+ .map(|values| values.into_iter().map(|v| f32::from(v) / 255.0).collect()),
+ })
+ .collect::<Result<Vec<_>, _>>()?;
+ let [r, g, b, a] = planes.as_slice() else { return Err(PsdError::Invalid("missing RGB composite channels".into()).into()) };
+ return Ok(r
+ .iter()
+ .zip(g)
+ .zip(b)
+ .zip(a)
+ .map(|(((&r, &g), &b), &a)| {
+ let mut pixel = [r, g, b, a];
+ let alpha = pixel[3];
+ for c in pixel.iter_mut().take(3) {
+ *c = pixels::unmatte(*c, alpha, 1.0);
+ if h.depth != 32 {
+ *c = c.clamp(0.0, 1.0);
+ }
+ }
+ pixel
+ })
+ .collect());
+ }
+ let img = file.composite_rgba8().ok();
// CMYK goes through the colour-managed model conversion (the PSD crate's RGBA preview is a
// naive, profile-free conversion).
if let (Some(img), false) = (img, matches!(h.color_mode, photocraft_psd::ColorMode::Lab | photocraft_psd::ColorMode::Cmyk)) {
diff --git a/crates/io/tests/common/mod.rs b/crates/io/tests/common/mod.rs
index 882fa4246..710763cda 100644
--- a/crates/io/tests/common/mod.rs
+++ b/crates/io/tests/common/mod.rs
@@ -368,7 +368,7 @@ pub fn strict_block_errors(bytes: &[u8]) -> Vec<String> {
}
}
for b in &file.global_blocks {
- let pad = b.padding.as_ref().map_or(b.data.len() % 2, Vec::len);
+ let pad = b.padding.as_ref().map_or((4 - b.data.len() % 4) % 4, Vec::len);
if (b.data.len() + pad) % 4 != 0 {
errs.push(format!("global {}: {} data bytes + {pad} padding is not a multiple of 4", b.key_str(), b.data.len()));
}
diff --git a/crates/io/tests/psd_structure.rs b/crates/io/tests/psd_structure.rs
index 5321153fc..e893adaf9 100644
--- a/crates/io/tests/psd_structure.rs
+++ b/crates/io/tests/psd_structure.rs
@@ -497,6 +497,11 @@ fn merged_composite_unmattes_photoshop_white() {
hdr.header.channels = 4;
hdr.image_data =
photocraft_psd::ImageData { compression: Compression::Raw, data: [1.5_f32, 0.25, 0.5, 0.5].into_iter().flat_map(f32::to_be_bytes).collect() };
+ assert_eq!(merged_composite(&hdr).unwrap(), vec![[2.0, -0.5, 0.0, 0.5]]);
+ let mut deep = testgen::merged_only(Version::Psd, ColorMode::Rgb, 16, Compression::Raw, 1, 1);
+ deep.header.channels = 4;
+ deep.image_data.data = [65535_u16, 65535, 65535, 65500].into_iter().flat_map(u16::to_be_bytes).collect();
+ assert_eq!(merged_composite(&deep).unwrap()[0][3], 65500.0 / 65535.0);
let imported = import("hdr.psd", &hdr.to_bytes().unwrap()).unwrap().document;
assert_eq!(imported.depth, photocraft_color::SampleType::F32);
assert_eq!(imported.layers[0].surface().unwrap().pixel(0, 0), vec![2.0, -0.5, 0.0, 0.5]);
diff --git a/crates/psd/src/builder.rs b/crates/psd/src/builder.rs
index 7343bcf47..04737337e 100644
--- a/crates/psd/src/builder.rs
+++ b/crates/psd/src/builder.rs
@@ -82,6 +82,34 @@ impl PixelData {
PixelData::Rgba16(v) | PixelData::GrayA16(v) | PixelData::Cmyka16(v) => (0..n).all(|i| v[i * spp + spp - 1] == 65535),
}
}
+
+ fn composite_plane(&self, c: usize, n: usize) -> Vec<u8> {
+ // Photoshop stores transparent RGB composites against white; layer channels stay straight.
+ match self {
+ Self::Rgba8(v) if c < 3 => v
+ .as_chunks::<4>()
+ .0
+ .iter()
+ .take(n)
+ .map(|p| {
+ let (color, alpha) = (u32::from(p[c]), u32::from(p[3]));
+ if alpha == 0 { p[c] } else { ((color * alpha + 127) / 255 + 255 - alpha) as u8 }
+ })
+ .collect(),
+ Self::Rgba16(v) if c < 3 => v
+ .as_chunks::<4>()
+ .0
+ .iter()
+ .take(n)
+ .flat_map(|p| {
+ let (color, alpha) = (u32::from(p[c]), u32::from(p[3]));
+ let value = if alpha == 0 { p[c] } else { ((color * alpha + 32767) / 65535 + 65535 - alpha) as u16 };
+ value.to_be_bytes()
+ })
+ .collect(),
+ _ => self.plane(c, n),
+ }
+ }
}
/// A layer mask given as 8-bit samples.
@@ -261,7 +289,8 @@ impl PsdBuilder {
self.entries.push(Entry::GroupEnd(g));
Ok(self)
}
- /// Supplies the merged composite (same pixel format as layers, full canvas).
+ /// Supplies the merged composite (straight samples, same format as layers, full canvas).
+ /// Transparent RGB is stored against white, quantized at the document depth.
pub fn composite(&mut self, pixels: PixelData) -> &mut Self {
self.composite = Some(pixels);
self
@@ -394,7 +423,7 @@ impl PsdBuilder {
let with_alpha = !p.alpha_is_opaque(n);
let mut planes = Vec::new();
for c in 0..cc + usize::from(with_alpha) {
- planes.extend(p.plane(c, n));
+ planes.extend(if with_alpha { p.composite_plane(c, n) } else { p.plane(c, n) });
}
(true, planes, with_alpha)
}
diff --git a/crates/psd/src/compression.rs b/crates/psd/src/compression.rs
index a8fa0f426..7a50b3cec 100644
--- a/crates/psd/src/compression.rs
+++ b/crates/psd/src/compression.rs
@@ -214,9 +214,9 @@ pub fn decode_planes(compression: Compression, data: &[u8], layout: &PlaneLayout
Ok(out)
}
Compression::Rle => decode_rle(data, layout, total),
- Compression::Zip => zip_decompress(data, total),
+ Compression::Zip => inflate_checked(data, total as u64, true),
Compression::ZipPrediction => {
- let mut v = zip_decompress(data, total)?;
+ let mut v = inflate_checked(data, total as u64, true)?;
unpredict(&mut v, layout)?;
Ok(v)
}
@@ -243,10 +243,7 @@ pub fn encode_planes(compression: Compression, decoded: &[u8], layout: &PlaneLay
}
}
-/// Returns the number of leading bytes of `data` that a decoder would consume
-/// (validating structure). For RLE this is the count table plus the counted
-/// bytes; for Raw it is the decoded size; for ZIP the zlib stream is
-/// decompressed (without keeping output) and the whole input is consumed.
+/// Validates encoded sizes and, for ZIP, the complete stream and checksum.
pub(crate) fn validate_planes(compression: Compression, data: &[u8], layout: &PlaneLayout) -> Result<()> {
let total = layout.total_bytes()?;
match compression {
@@ -269,29 +266,43 @@ pub(crate) fn validate_planes(compression: Compression, data: &[u8], layout: &Pl
}
Ok(())
}
- Compression::Zip | Compression::ZipPrediction => {
- // Decompress without keeping the output, through the end of the
- // stream so the Adler-32 checksum is verified too.
- let mut dec = flate2::read::ZlibDecoder::new(data);
- let mut buf = [0u8; 8192];
- let mut got: u64 = 0;
- loop {
- let n = dec.read(&mut buf).map_err(|e| PsdError::Decompress(e.to_string()))?;
- if n == 0 {
- break;
- }
- got += n as u64;
- if got > total.saturating_add(1 << 20) {
- // Far more output than needed; stop (bomb guard).
- break;
- }
- }
- if got < total {
- return Err(PsdError::Decompress(format!("zlib stream produced {got} of {total} bytes")));
+ Compression::Zip | Compression::ZipPrediction => inflate_checked(data, total, false).map(|_| ()),
+ Compression::Unknown(_) => Ok(()),
+ }
+}
+
+// Keep only the requested pixels, but consume the trailer to verify Adler-32.
+// A bounded surplus tolerates padding without unbounded decompression work.
+fn inflate_checked(data: &[u8], expected: u64, keep: bool) -> Result<Vec<u8>> {
+ const OOM: PsdError = PsdError::LimitExceeded("not enough memory for the decoded channel data");
+ let mut decoder = flate2::Decompress::new(true);
+ let mut out = Vec::new();
+ if keep {
+ out.try_reserve_exact(expected.min(data.len().saturating_mul(1032) as u64) as usize).map_err(|_| OOM)?;
+ }
+ let mut buf = vec![0; expected.saturating_add(1).clamp(8192, 1 << 20) as usize];
+ loop {
+ let before = (decoder.total_in(), decoder.total_out());
+ let input = data.get(before.0 as usize..).ok_or_else(|| PsdError::Decompress("zlib input overflow".into()))?;
+ let status = decoder.decompress(input, &mut buf, flate2::FlushDecompress::None).map_err(|e| PsdError::Decompress(e.to_string()))?;
+ let got = decoder.total_out();
+ if got > expected.saturating_add(1 << 20) {
+ return Err(PsdError::LimitExceeded("zlib output exceeds the declared size and padding allowance"));
+ }
+ if keep {
+ let n = (got - before.1).min(expected.saturating_sub(out.len() as u64)) as usize;
+ out.try_reserve(n).map_err(|_| OOM)?;
+ out.extend_from_slice(buf.get(..n).ok_or_else(|| PsdError::Decompress("zlib output overflow".into()))?);
+ }
+ if status == flate2::Status::StreamEnd {
+ if got < expected {
+ return Err(PsdError::Decompress(format!("zlib stream produced {got} of {expected} bytes")));
}
- Ok(())
+ return Ok(out);
+ }
+ if before == (decoder.total_in(), got) {
+ return Err(PsdError::Decompress("incomplete zlib stream".into()));
}
- Compression::Unknown(_) => Ok(()),
}
}
@@ -473,6 +484,27 @@ pub fn unpredict(buf: &mut [u8], layout: &PlaneLayout) -> Result<()> {
mod tests {
use super::*;
+ #[test]
+ fn checked_zip_validates_trailer_size_and_padding_budget() {
+ let layout = PlaneLayout { planes: 1, width: 3, height: 1, depth: 8, version: Version::Psd };
+ for compression in [Compression::Zip, Compression::ZipPrediction] {
+ let data = encode_planes(compression, &[1, 2, 3], &layout).unwrap();
+ for cut in 0..data.len() {
+ assert!(decode_planes(compression, &data[..cut], &layout).is_err(), "cut {cut}");
+ assert!(validate_planes(compression, &data[..cut], &layout).is_err());
+ }
+ let mut corrupt = data;
+ *corrupt.last_mut().unwrap() ^= 1;
+ assert!(decode_planes(compression, &corrupt, &layout).is_err());
+ assert!(validate_planes(compression, &corrupt, &layout).is_err());
+ }
+ let padded = zip_compress(&[1, 2, 3, 0]);
+ assert_eq!(decode_planes(Compression::Zip, &padded, &layout).unwrap(), [1, 2, 3]);
+ let bomb = zip_compress(&vec![0; (1 << 20) + 4]);
+ assert!(decode_planes(Compression::Zip, &bomb, &layout).is_err());
+ assert!(validate_planes(Compression::Zip, &bomb, &layout).is_err());
+ }
+
fn layout(planes: usize, width: usize, height: usize, depth: u16, version: Version) -> PlaneLayout {
PlaneLayout { planes, width, height, depth, version }
}
diff --git a/crates/psd/src/file.rs b/crates/psd/src/file.rs
index 7425dc8a9..e493eddc1 100644
--- a/crates/psd/src/file.rs
+++ b/crates/psd/src/file.rs
@@ -6,7 +6,7 @@ use crate::image_data::ImageData;
use crate::io::{Reader, WriteExt};
use crate::layer::{LayerInfo, LayerRecord};
use crate::resources::{self, ImageResource, ResourceData, ids};
-use crate::tagged::{TaggedBlock, read_blocks, uses_long_length, write_blocks};
+use crate::tagged::{TaggedBlock, read_blocks_with, uses_long_length, write_blocks};
/// Where the layer info was stored in the file.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
@@ -112,22 +112,23 @@ impl PsdFile {
if s.remaining() >= 4 {
let n = s.u32()?;
global_layer_mask = Some(GlobalLayerMask { data: s.bytes_u64(u64::from(n))?.to_vec() });
- let (blocks, trailing) = read_blocks(&mut s, header.version)?;
+ let mut candidate_seen = layer_info.is_some();
+ let (blocks, trailing) = read_blocks_with(&mut s, header.version, 4, |index, signature, key, data, padding| {
+ if candidate_seen || !matches!(&key, b"Lr16" | b"Lr32" | b"Layr") {
+ return false;
+ }
+ candidate_seen = true;
+ let Ok(info) = LayerInfo::read_body(data, header.version) else { return false };
+ layer_info = Some(info);
+ layer_info_placement = LayerInfoPlacement::GlobalBlock { index, signature, key, padding: padding.clone() };
+ true
+ })?;
global_blocks = blocks;
layer_mask_trailing = trailing;
} else {
layer_mask_trailing = s.peek_rest().to_vec();
}
}
- // 16/32-bit files keep their layers in a global Lr16/Lr32 block.
- if layer_info.is_none()
- && let Some(i) = global_blocks.iter().position(|b| matches!(&b.key, b"Lr16" | b"Lr32" | b"Layr"))
- && let Ok(info) = LayerInfo::read_body(&global_blocks[i].data, header.version)
- {
- let b = global_blocks.remove(i);
- layer_info = Some(info);
- layer_info_placement = LayerInfoPlacement::GlobalBlock { index: i, signature: b.signature, key: b.key, padding: b.padding };
- }
let image_data = ImageData::read(&mut r, &header)?;
Ok(PsdFile { header, color_mode_data, resources, layer_info, layer_info_placement, global_layer_mask, global_blocks, layer_mask_trailing, image_data })
}
@@ -164,7 +165,7 @@ impl PsdFile {
match (&self.layer_info, &self.layer_info_placement) {
(Some(info), LayerInfoPlacement::GlobalBlock { index, signature, key, padding }) => {
let (before, after) = self.global_blocks.split_at((*index).min(self.global_blocks.len()));
- write_blocks(&mut out, before, v)?;
+ write_blocks(&mut out, before, v, 4)?;
// Write into the final buffer: a temporary LayerInfo payload and a clone
// of all neighboring opaque blocks otherwise double the save's memory.
out.put(signature);
@@ -177,11 +178,11 @@ impl PsdFile {
out.end_len(at, long)?;
match padding {
Some(bytes) => out.put(bytes),
- None => out.extend(std::iter::repeat_n(0u8, len % 2)),
+ None => out.extend(std::iter::repeat_n(0u8, (4 - len % 4) % 4)),
}
- write_blocks(&mut out, after, v)?;
+ write_blocks(&mut out, after, v, 4)?;
}
- _ => write_blocks(&mut out, &self.global_blocks, v)?,
+ _ => write_blocks(&mut out, &self.global_blocks, v, 4)?,
}
out.put(&self.layer_mask_trailing);
}
@@ -295,6 +296,24 @@ mod write_tests {
use super::*;
use crate::{Compression, testgen};
+ #[test]
+ fn global_blocks_default_to_four_byte_padding() {
+ for version in [Version::Psd, Version::Psb] {
+ for len in 1usize..8 {
+ let mut file = testgen::small(version, Compression::Raw);
+ file.global_blocks = vec![TaggedBlock::new(*b"TEST", vec![7; len]), TaggedBlock::new(*b"NEXT", vec![8; 4])];
+ let bytes = file.to_bytes().unwrap();
+ let start = bytes.windows(8).position(|b| b == b"8BIMTEST").unwrap() + 12;
+ let next = bytes.windows(8).position(|b| b == b"8BIMNEXT").unwrap();
+ assert_eq!(next - start, len.next_multiple_of(4));
+ let mut expected = vec![7; len];
+ expected.resize(len.next_multiple_of(4), 0);
+ assert_eq!(&bytes[start..start + expected.len()], expected);
+ assert_eq!(PsdFile::from_bytes(&bytes).unwrap(), file);
+ }
+ }
+ }
+
#[test]
fn streamed_layer_info_equals_a_materialized_tagged_block() {
for version in [Version::Psd, Version::Psb] {
@@ -326,4 +345,31 @@ mod write_tests {
file.layer_info_placement = LayerInfoPlacement::GlobalBlock { index: usize::MAX, signature: *b"8BIM", key: *b"Lr16", padding: None };
assert!(matches!(file.to_bytes(), Err(PsdError::LimitExceeded(_))));
}
+
+ #[test]
+ fn global_layers_preserve_order_padding_and_first_candidate() {
+ for version in [Version::Psd, Version::Psb] {
+ for depth in [16, 32] {
+ let mut file = testgen::layered(version, ColorMode::Rgb, depth, Compression::Raw);
+ let key = if depth == 16 { *b"Lr16" } else { *b"Lr32" };
+ file.global_blocks = vec![TaggedBlock::new(*b"BEFR", vec![1]), TaggedBlock::new(*b"AFTR", vec![2, 3])];
+ file.layer_info_placement = LayerInfoPlacement::GlobalBlock { index: 1, signature: *b"8B64", key, padding: Some(vec![7, 8]) };
+ file.layer_mask_trailing = vec![9; 4];
+ let bytes = file.to_bytes().unwrap();
+ let parsed = PsdFile::from_bytes(&bytes).unwrap();
+ assert_eq!(parsed, file);
+ assert_eq!(parsed.to_bytes().unwrap(), bytes);
+ let mut duplicate = Vec::new();
+ file.layer_info.as_ref().unwrap().write_body(&mut duplicate, version).unwrap();
+ file.global_blocks.push(TaggedBlock::new(key, duplicate));
+ assert_eq!(PsdFile::from_bytes(&file.to_bytes().unwrap()).unwrap(), file);
+ file.global_blocks.insert(0, TaggedBlock::new(key, vec![255]));
+ let bytes = file.to_bytes().unwrap();
+ let parsed = PsdFile::from_bytes(&bytes).unwrap();
+ assert!(parsed.layer_info.is_none());
+ assert_eq!(parsed.global_blocks.len(), 5);
+ assert_eq!(parsed.to_bytes().unwrap(), bytes);
+ }
+ }
+ }
}
diff --git a/crates/psd/src/layer.rs b/crates/psd/src/layer.rs
index 2ecf0df6f..cee675826 100644
--- a/crates/psd/src/layer.rs
+++ b/crates/psd/src/layer.rs
@@ -611,7 +611,7 @@ impl LayerRecord {
out.put_len(self.blending_ranges.data.len() as u64, false)?;
out.put(&self.blending_ranges.data);
write_pascal(out, &self.name, 4);
- write_blocks(out, &self.blocks, version)?;
+ write_blocks(out, &self.blocks, version, 2)?;
out.put(&self.extra_trailing);
out.end_len(at, false)
}
diff --git a/crates/psd/src/pixels.rs b/crates/psd/src/pixels.rs
index 0f019741d..013d82176 100644
--- a/crates/psd/src/pixels.rs
+++ b/crates/psd/src/pixels.rs
@@ -9,6 +9,7 @@ use crate::error::{PsdError, Result};
use crate::file::PsdFile;
use crate::header::{ColorMode, Header, Version};
use crate::layer::{CHANNEL_REAL_USER_MASK, CHANNEL_TRANSPARENCY, CHANNEL_USER_MASK, LayerRecord, Rect};
+use std::borrow::Cow;
/// Interprets planar big-endian bytes as u16 samples.
pub fn samples_u16(bytes: &[u8]) -> Vec<u16> {
@@ -49,8 +50,16 @@ pub fn plane_to_u8(bytes: &[u8], depth: u16, width: usize, height: usize) -> Res
Ok(match depth {
1 => unpack_bits(bytes, width, height).into_iter().map(|b| if b == 1 { 0 } else { 255 }).collect(),
8 => bytes.to_vec(),
- 16 => samples_u16(bytes).into_iter().map(|v| ((u32::from(v) * 255 + 32767) / 65535) as u8).collect(),
- 32 => samples_f32(bytes).into_iter().map(|v| if v.is_nan() { 0 } else { (v.clamp(0.0, 1.0) * 255.0).round() as u8 }).collect(),
+ 16 => bytes.as_chunks::<2>().0.iter().map(|b| ((u32::from(u16::from_be_bytes(*b)) * 255 + 32767) / 65535) as u8).collect(),
+ 32 => bytes
+ .as_chunks::<4>()
+ .0
+ .iter()
+ .map(|b| {
+ let v = f32::from_be_bytes(*b);
+ if v.is_nan() { 0 } else { (v.clamp(0.0, 1.0) * 255.0).round() as u8 }
+ })
+ .collect(),
d => return Err(PsdError::Unsupported(format!("depth {d}"))),
})
}
@@ -87,8 +96,34 @@ pub struct GrayImage {
pub default_value: u8,
}
-fn interleave(mode: ColorMode, color: &[Vec<u8>], alpha: Option<&[u8]>, palette: &[u8], n: usize) -> Result<Vec<u8>> {
- let mut out = vec![0u8; n * 4];
+fn interleave(mode: ColorMode, color: &[Cow<'_, [u8]>], alpha: Option<&[u8]>, palette: &[u8], n: usize) -> Result<Vec<u8>> {
+ if color.len() != color_channel_count(mode)? || color.iter().any(|p| p.len() != n) || alpha.is_some_and(|p| p.len() != n) {
+ return Err(PsdError::invalid("channel size mismatch"));
+ }
+ let len = n
+ .checked_mul(4)
+ .filter(|&len| len as u64 <= crate::compression::MAX_DECODED_BYTES)
+ .ok_or(PsdError::LimitExceeded("RGBA output exceeds MAX_DECODED_BYTES"))?;
+ let mut out = Vec::new();
+ out.try_reserve_exact(len).map_err(|_| PsdError::LimitExceeded("not enough memory for RGBA output"))?;
+ out.resize(len, 255);
+ if mode == ColorMode::Rgb {
+ let [r, g, b] = color else { return Err(PsdError::invalid("RGB requires three channels")) };
+ let rgb = r.iter().zip(g.iter()).zip(b.iter());
+ match alpha {
+ Some(alpha) => {
+ for (rgba, (((r, g), b), a)) in out.as_chunks_mut::<4>().0.iter_mut().zip(rgb.zip(alpha)) {
+ *rgba = [*r, *g, *b, *a];
+ }
+ }
+ None => {
+ for (rgba, ((r, g), b)) in out.as_chunks_mut::<4>().0.iter_mut().zip(rgb) {
+ *rgba = [*r, *g, *b, 255];
+ }
+ }
+ }
+ return Ok(out);
+ }
for i in 0..n {
let (r, g, b) = match mode {
ColorMode::Rgb => (color[0][i], color[1][i], color[2][i]),
@@ -122,6 +157,24 @@ fn color_channel_count(mode: ColorMode) -> Result<usize> {
}
}
+fn unmatte_to_u8(color: &[u8], alpha: &[u8], depth: u16) -> Result<Vec<u8>> {
+ let convert = |c: f32, a: f32| {
+ let straight = if a > 0.0 { (c + a - 1.0) / a } else { c };
+ (straight.clamp(0.0, 1.0) * 255.0).round() as u8
+ };
+ Ok(match depth {
+ 16 => color
+ .as_chunks::<2>()
+ .0
+ .iter()
+ .zip(alpha.as_chunks::<2>().0)
+ .map(|(c, a)| convert(f32::from(u16::from_be_bytes(*c)) / 65535.0, f32::from(u16::from_be_bytes(*a)) / 65535.0))
+ .collect(),
+ 32 => color.as_chunks::<4>().0.iter().zip(alpha.as_chunks::<4>().0).map(|(c, a)| convert(f32::from_be_bytes(*c), f32::from_be_bytes(*a))).collect(),
+ d => return Err(PsdError::Unsupported(format!("RGB composite depth {d}"))),
+ })
+}
+
/// A borrowed view of a layer with the file context needed to decode it.
#[derive(Debug, Clone, Copy)]
pub struct Layer<'a> {
@@ -154,24 +207,31 @@ impl<'a> Layer<'a> {
pub fn rgba8(&self) -> Result<RgbaImage> {
let rect = self.record.rect;
let (w, h) = rect.size()?;
- let n = w * h;
+ let n = w.checked_mul(h).ok_or(PsdError::LimitExceeded("layer size overflow"))?;
+ if n.checked_mul(4).is_none_or(|len| len as u64 > crate::compression::MAX_DECODED_BYTES) {
+ return Err(PsdError::LimitExceeded("RGBA output exceeds MAX_DECODED_BYTES"));
+ }
let depth = self.header.depth;
let mode = self.header.color_mode;
let cc = color_channel_count(mode)?;
let mut color = Vec::with_capacity(cc);
for id in 0..cc as i16 {
let plane = if self.record.channel(id).is_some() {
- plane_to_u8(&self.channel_bytes(id)?, depth, w, h)?
+ let bytes = self.channel_bytes(id)?;
+ if depth == 8 { bytes } else { plane_to_u8(&bytes, depth, w, h)? }
} else {
vec![if mode == ColorMode::Cmyk { 255 } else { 0 }; n]
};
if plane.len() != n {
return Err(PsdError::invalid("channel size mismatch"));
}
- color.push(plane);
+ color.push(Cow::Owned(plane));
}
let alpha = match self.record.channel(CHANNEL_TRANSPARENCY) {
- Some(_) => Some(plane_to_u8(&self.channel_bytes(CHANNEL_TRANSPARENCY)?, depth, w, h)?),
+ Some(_) => {
+ let bytes = self.channel_bytes(CHANNEL_TRANSPARENCY)?;
+ Some(if depth == 8 { bytes } else { plane_to_u8(&bytes, depth, w, h)? })
+ }
None => None,
};
let data = interleave(mode, &color, alpha.as_deref(), &[], n)?;
@@ -215,24 +275,54 @@ impl PsdFile {
/// The merged composite as RGBA8. Supports RGB, grayscale, CMYK, indexed,
/// duotone (as gray) and bitmap at all depths. Alpha comes from the first
- /// extra channel when [`PsdFile::merged_has_alpha`] is true.
+ /// extra channel when [`PsdFile::merged_has_alpha`] is true. Removes the
+ /// white matte from RGB composites before reducing precision.
pub fn composite_rgba8(&self) -> Result<RgbaImage> {
let h = &self.header;
+ h.validate()?;
let (w, hh) = (h.width as usize, h.height as usize);
- let n = w * hh;
+ let n = w.checked_mul(hh).ok_or(PsdError::LimitExceeded("composite size overflow"))?;
let cc = color_channel_count(h.color_mode)?;
if usize::from(h.channels) < cc {
return Err(PsdError::invalid("fewer channels than the color mode requires"));
}
let all = self.decode_merged()?;
- let plane = h.row_bytes() * hh;
- let get = |i: usize| -> Result<Vec<u8>> { plane_to_u8(&all[i * plane..(i + 1) * plane], h.depth, w, hh) };
+ let plane = h.row_bytes().checked_mul(hh).ok_or(PsdError::LimitExceeded("plane size overflow"))?;
+ let alpha_bytes = if self.merged_has_alpha() {
+ Some(all.get(cc * plane..(cc + 1) * plane).ok_or_else(|| PsdError::invalid("alpha channel size mismatch"))?)
+ } else {
+ None
+ };
+ let get = |i: usize| -> Result<Cow<'_, [u8]>> {
+ let bytes = all.get(i * plane..(i + 1) * plane).ok_or_else(|| PsdError::invalid("channel size mismatch"))?;
+ if h.depth == 8 { Ok(Cow::Borrowed(bytes)) } else { plane_to_u8(bytes, h.depth, w, hh).map(Cow::Owned) }
+ };
let mut color = Vec::with_capacity(cc);
for i in 0..cc {
- color.push(get(i)?);
+ color.push(
+ if h.color_mode == ColorMode::Rgb
+ && h.depth != 8
+ && let Some(alpha) = alpha_bytes
+ {
+ let bytes = all.get(i * plane..(i + 1) * plane).ok_or_else(|| PsdError::invalid("channel size mismatch"))?;
+ Cow::Owned(unmatte_to_u8(bytes, alpha, h.depth)?)
+ } else {
+ get(i)?
+ },
+ );
}
let alpha = if self.merged_has_alpha() { Some(get(cc)?) } else { None };
- let data = interleave(h.color_mode, &color, alpha.as_deref(), &self.color_mode_data, n)?;
+ let mut data = interleave(h.color_mode, &color, alpha.as_deref(), &self.color_mode_data, n)?;
+ if h.color_mode == ColorMode::Rgb && h.depth == 8 && alpha.is_some() {
+ for pixel in data.as_chunks_mut::<4>().0 {
+ let a = u32::from(pixel[3]);
+ for c in pixel.iter_mut().take(3) {
+ if let Some(straight) = ((u32::from(*c) + a).saturating_sub(255) * 255 + a / 2).checked_div(a) {
+ *c = straight.min(255) as u8;
+ }
+ }
+ }
+ }
Ok(RgbaImage { left: 0, top: 0, width: h.width, height: h.height, data })
}
}
@@ -241,6 +331,23 @@ impl PsdFile {
mod tests {
use super::*;
+ #[test]
+ fn float_composite_removes_white_matte_without_changing_native_data() {
+ let mut file = crate::testgen::merged_only(Version::Psd, ColorMode::Rgb, 32, crate::Compression::Raw, 1, 1);
+ file.header.channels = 4;
+ let native = f32_to_bytes(&[0.75, 0.875, 1.0, 0.25]);
+ file.image_data = crate::ImageData::encode(crate::Compression::Raw, &native, &file.header).unwrap();
+ assert_eq!(file.composite_rgba8().unwrap().data, [0, 128, 255, 64]);
+ assert_eq!(file.decode_merged().unwrap(), native);
+ }
+
+ #[test]
+ fn oversized_layer_preview_rejects_missing_channels_before_allocating() {
+ let mut file = crate::testgen::small(Version::Psb, crate::Compression::Raw);
+ file.layers_mut().push(LayerRecord { rect: Rect::from_xywh(0, 0, 300000, 300000), ..Default::default() });
+ assert!(matches!(file.iter_layers().last().unwrap().rgba8(), Err(PsdError::LimitExceeded(_))));
+ }
+
#[test]
fn sample_conversions() {
assert_eq!(samples_u16(&[0x12, 0x34, 0xff, 0xff]), vec![0x1234, 0xffff]);
@@ -261,4 +368,13 @@ mod tests {
assert_eq!(plane_to_u8(&[0b1000_0000], 1, 2, 1).unwrap(), vec![0, 255]);
assert!(plane_to_u8(&[], 12, 0, 0).is_err());
}
+
+ #[test]
+ fn rgb_interleave_checks_planes_and_preserves_alpha() {
+ let color = [Cow::Borrowed(&[1, 2][..]), Cow::Borrowed(&[3, 4][..]), Cow::Borrowed(&[5, 6][..])];
+ assert_eq!(interleave(ColorMode::Rgb, &color, Some(&[7, 8]), &[], 2).unwrap(), [1, 3, 5, 7, 2, 4, 6, 8]);
+ assert_eq!(interleave(ColorMode::Rgb, &color, None, &[], 2).unwrap(), [1, 3, 5, 255, 2, 4, 6, 255]);
+ assert!(interleave(ColorMode::Rgb, &color[..2], None, &[], 2).is_err());
+ assert!(interleave(ColorMode::Rgb, &color, Some(&[7]), &[], 2).is_err());
+ }
}
diff --git a/crates/psd/src/tagged.rs b/crates/psd/src/tagged.rs
index 97501e240..7d66eae92 100644
--- a/crates/psd/src/tagged.rs
+++ b/crates/psd/src/tagged.rs
@@ -38,7 +38,8 @@ pub struct TaggedBlock {
/// Block data exactly as covered by the length field.
pub data: Vec<u8>,
/// Bytes that followed the data before the next block. `None` means
- /// "default": zero-pad to an even length. Parsing yields `None` whenever
+ /// "default": zero-pad to a multiple of four for global blocks, two for
+ /// layer blocks. Parsing yields `None` whenever
/// the stored padding equals the default, so the model stays canonical.
pub padding: Option<Vec<u8>>,
}
@@ -159,8 +160,8 @@ impl TaggedBlock {
String::from_utf8_lossy(&self.key).into_owned()
}
- fn default_padding(len: usize) -> usize {
- len % 2
+ fn default_padding(len: usize, alignment: usize) -> usize {
+ (alignment - len % alignment) % alignment
}
/// Typed view for known keys. `None` for keys without a typed parser,
@@ -323,22 +324,22 @@ impl TaggedBlock {
Ok(())
}
- pub(crate) fn write(&self, out: &mut Vec<u8>, version: Version) -> Result<()> {
+ pub(crate) fn write(&self, out: &mut Vec<u8>, version: Version, alignment: usize) -> Result<()> {
out.put(&self.signature);
out.put(&self.key);
out.put_len(self.data.len() as u64, uses_long_length(version, &self.key))?;
out.put(&self.data);
match &self.padding {
Some(p) => out.put(p),
- None => out.extend(std::iter::repeat_n(0u8, Self::default_padding(self.data.len()))),
+ None => out.extend(std::iter::repeat_n(0u8, Self::default_padding(self.data.len(), alignment))),
}
Ok(())
}
- /// Serialized size in bytes.
+ /// Serialized size in bytes as a layer block (two-byte alignment).
pub fn encoded_len(&self, version: Version) -> usize {
let l = if uses_long_length(version, &self.key) { 8 } else { 4 };
- let p = self.padding.as_ref().map_or(Self::default_padding(self.data.len()), Vec::len);
+ let p = self.padding.as_ref().map_or(Self::default_padding(self.data.len(), 2), Vec::len);
8 + l + self.data.len() + p
}
}
@@ -429,6 +430,16 @@ fn is_sig(b: &[u8]) -> bool {
/// a block (fewer than 12 bytes or no valid signature) are returned as
/// trailing data.
pub(crate) fn read_blocks(r: &mut Reader<'_>, version: Version) -> Result<(Vec<TaggedBlock>, Vec<u8>)> {
+ read_blocks_with(r, version, 2, |_, _, _, _, _| false)
+}
+
+/// The callback consumes selected payloads before they are copied into owned blocks.
+pub(crate) fn read_blocks_with(
+ r: &mut Reader<'_>,
+ version: Version,
+ alignment: usize,
+ mut consume: impl FnMut(usize, [u8; 4], [u8; 4], &[u8], &Option<Vec<u8>>) -> bool,
+) -> Result<(Vec<TaggedBlock>, Vec<u8>)> {
let mut blocks = Vec::new();
loop {
let rest = r.peek_rest();
@@ -440,7 +451,7 @@ pub(crate) fn read_blocks(r: &mut Reader<'_>, version: Version) -> Result<(Vec<T
let signature = r.array::<4>()?;
let key = r.array::<4>()?;
let len = r.len_field(uses_long_length(version, &key))?;
- let data = r.bytes_u64(len)?.to_vec();
+ let data = r.bytes_u64(len)?;
// Detect padding: the smallest k in 0..=3 such that the next block
// signature (or the end of the region) follows k bytes later.
let rest = r.peek_rest();
@@ -451,16 +462,21 @@ pub(crate) fn read_blocks(r: &mut Reader<'_>, version: Version) -> Result<(Vec<T
break;
}
}
- let pad = pad.unwrap_or(0);
+ // Opaque trailing bytes can follow canonical zero padding without another signature.
+ let default = TaggedBlock::default_padding(data.len(), alignment);
+ let pad = pad.unwrap_or_else(|| if rest.get(..default).is_some_and(|p| p.iter().all(|&b| b == 0)) { default } else { 0 });
let pad_bytes = r.bytes(pad)?.to_vec();
- let padding = if pad_bytes.len() == TaggedBlock::default_padding(data.len()) && pad_bytes.iter().all(|&b| b == 0) { None } else { Some(pad_bytes) };
- blocks.push(TaggedBlock { signature, key, data, padding });
+ let padding =
+ if pad_bytes.len() == TaggedBlock::default_padding(data.len(), alignment) && pad_bytes.iter().all(|&b| b == 0) { None } else { Some(pad_bytes) };
+ if !consume(blocks.len(), signature, key, data, &padding) {
+ blocks.push(TaggedBlock { signature, key, data: data.to_vec(), padding });
+ }
}
}
-pub(crate) fn write_blocks(out: &mut Vec<u8>, blocks: &[TaggedBlock], version: Version) -> Result<()> {
+pub(crate) fn write_blocks(out: &mut Vec<u8>, blocks: &[TaggedBlock], version: Version, alignment: usize) -> Result<()> {
for b in blocks {
- b.write(out, version)?;
+ b.write(out, version, alignment)?;
}
Ok(())
}
@@ -471,7 +487,7 @@ mod tests {
fn rt(blocks: &[TaggedBlock], version: Version) -> Vec<u8> {
let mut out = Vec::new();
- write_blocks(&mut out, blocks, version).unwrap();
+ write_blocks(&mut out, blocks, version, 2).unwrap();
let (back, trailing) = read_blocks(&mut Reader::new(&out), version).unwrap();
assert_eq!(back, blocks);
assert!(trailing.is_empty());
@@ -585,7 +601,7 @@ mod tests {
#[test]
fn trailing_bytes_kept() {
let mut out = Vec::new();
- write_blocks(&mut out, &[TaggedBlock::layer_id(1)], Version::Psd).unwrap();
+ write_blocks(&mut out, &[TaggedBlock::layer_id(1)], Version::Psd, 2).unwrap();
out.extend_from_slice(&[0; 8]);
let (blocks, trailing) = read_blocks(&mut Reader::new(&out), Version::Psd).unwrap();
assert_eq!(blocks.len(), 1);
@@ -597,7 +613,7 @@ mod tests {
#[test]
fn short_trailing_pad_attributed_to_block() {
let mut out = Vec::new();
- write_blocks(&mut out, &[TaggedBlock::layer_id(1)], Version::Psd).unwrap();
+ write_blocks(&mut out, &[TaggedBlock::layer_id(1)], Version::Psd, 2).unwrap();
out.extend_from_slice(&[0; 2]);
let (blocks, trailing) = read_blocks(&mut Reader::new(&out), Version::Psd).unwrap();
assert_eq!(blocks[0].padding, Some(vec![0, 0]));
diff --git a/crates/psd/src/tiff.rs b/crates/psd/src/tiff.rs
index 1cd2057cf..0d8f36888 100644
--- a/crates/psd/src/tiff.rs
+++ b/crates/psd/src/tiff.rs
@@ -173,7 +173,7 @@ impl ImageSourceData {
blocks.push(b);
}
let mut body = Vec::new();
- write_blocks(&mut body, &blocks, version)?;
+ write_blocks(&mut body, &blocks, version, 2)?;
body.put(&self.trailing);
let (body, warnings) =
if order.is_little() { transcode::transcode_blocks(&body, version, ByteOrder::Big, ByteOrder::Little)? } else { (body, Vec::new()) };
diff --git a/crates/psd/tests/builder.rs b/crates/psd/tests/builder.rs
index 87e3b8dc9..e5c6c0935 100644
--- a/crates/psd/tests/builder.rs
+++ b/crates/psd/tests/builder.rs
@@ -195,15 +195,16 @@ fn empty_layer() {
#[test]
fn composite_supplied_with_alpha() {
- let px = rgba_pattern(3, 2, 0);
- let mut b = PsdBuilder::new(3, 2);
- b.push_layer(LayerSpec::new("x", 0, 0, 3, 2, PixelData::Rgba8(px.clone())));
+ let px = vec![255, 0, 0, 128, 17, 89, 203, 0];
+ let mut b = PsdBuilder::new(2, 1);
+ b.push_layer(LayerSpec::new("x", 0, 0, 2, 1, PixelData::Rgba8(px.clone())));
b.composite(PixelData::Rgba8(px.clone()));
let f = built(&b);
assert_eq!(f.header.channels, 4);
assert!(f.layer_info.as_ref().unwrap().merged_alpha);
assert!(f.merged_has_alpha());
assert_eq!(f.has_real_merged_data(), Some(true));
+ assert_eq!(f.decode_merged().unwrap(), [255, 17, 127, 89, 127, 203, 128, 0]);
assert_eq!(f.composite_rgba8().unwrap().data, px);
}
diff --git a/crates/psd/tests/proptests.rs b/crates/psd/tests/proptests.rs
index 264633980..ba12d22f2 100644
--- a/crates/psd/tests/proptests.rs
+++ b/crates/psd/tests/proptests.rs
@@ -137,7 +137,7 @@ proptest! {
// Only padding patterns the detector can recover are modeled:
// zeros up to 3 bytes.
tb.padding = match pad { 0 => None, n => Some(vec![0; n - 1]) };
- if tb.padding.as_ref().is_some_and(|p| p.len() == tb.data.len() % 2) {
+ if tb.padding.as_ref().is_some_and(|p| p.len() == (4 - tb.data.len() % 4) % 4) {
tb.padding = None;
}
f.global_blocks.push(tb);