Skip to content

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

PSD: read smart-filter masks (FEid) with one section per smart object (#396)

EthanSuquetfbe5f80ba485
diff --git a/crates/psd/src/filter_effects.rs b/crates/psd/src/filter_effects.rs
index a50213749..8ccb95fe2 100644
--- a/crates/psd/src/filter_effects.rs
+++ b/crates/psd/src/filter_effects.rs
@@ -3,14 +3,19 @@
//! Layout (Adobe PSD spec, "Filter Effects", checked against Photoshop-authored files):
//!
//! ```text
-//! u32 version (1..=3), u64 length of what follows, then until that length is used up:
-//! Pascal identifier (the smart object's `placed` id in its `SoLd` descriptor, unpadded)
-//! u32 item version (1), u64 item length, then inside the item:
-//! rect (top, left, bottom, right), u32 depth, u32 max channels,
-//! max channels + 2 slots: u32 written flag; if set u64 length, u16 compression, data
-//! after the item: u8 flag; if set rect, u64 length, u16 compression, data
+//! u32 version (1..=3), then one section per smart object, each padded with zeros to a multiple
+//! of 4 bytes (the padding is not counted in its length):
+//! u64 length, then until that length is used up:
+//! Pascal identifier (the smart object's `placed` id in its `SoLd` descriptor, unpadded)
+//! u32 item version (1), u64 item length, then inside the item:
+//! rect (top, left, bottom, right), u32 depth, u32 max channels,
+//! max channels + 2 slots: u32 written flag; if set u64 length, u16 compression, data
+//! after the item: u8 flag; if set rect, u64 length, u16 compression, data
//! ```
//!
+//! Photoshop puts one item in each section. Files written by earlier PhotoCraft versions put
+//! every item in one section; both read.
+//!
//! The slots hold the unfiltered placed pixels (colour channels from slot 0, transparency in the
//! last slot) and the trailing image is the filter mask, in document coordinates. RLE row counts
//! are four bytes wide (PSB style) in every file version.
@@ -117,6 +122,29 @@ fn read_plane(r: &mut Reader<'_>) -> Result<EffectsPlane> {
Ok(EffectsPlane { compression, data: sub.peek_rest().to_vec() })
}
+/// One item: identifier, the cached planes and the filter mask after them.
+fn read_item(body: &mut Reader<'_>) -> Result<FilterEffectsItem> {
+ let id = String::from_utf8_lossy(&read_pascal(body, 1)?).into_owned();
+ let version = body.u32()?;
+ let item_len = body.u64()?;
+ let mut it = body.sub(item_len)?;
+ let rect = read_rect(&mut it)?;
+ let depth = it.u32()?;
+ let max_channels = it.u32()?;
+ if max_channels > MAX_SLOTS {
+ return Err(PsdError::LimitExceeded("filter effects: too many channels"));
+ }
+ let mut slots = Vec::with_capacity(max_channels as usize + 2);
+ for _ in 0..max_channels + 2 {
+ slots.push(if it.u32()? != 0 { Some(read_plane(&mut it)?) } else { None });
+ }
+ if !it.is_empty() {
+ return Err(PsdError::invalid(format!("filter effects item {id}: {} unexpected bytes", it.remaining())));
+ }
+ let mask = if body.is_empty() || body.u8()? == 0 { None } else { Some((read_rect(body)?, read_plane(body)?)) };
+ Ok(FilterEffectsItem { id, version, rect, depth, max_channels, slots, mask })
+}
+
fn write_plane(out: &mut Vec<u8>, p: &EffectsPlane) {
out.put_u64(p.data.len() as u64 + 2);
out.put_u16(p.compression.as_u16());
@@ -124,48 +152,40 @@ fn write_plane(out: &mut Vec<u8>, p: &EffectsPlane) {
}
impl FilterEffects {
- /// Parses block data. Trailing zero padding (up to 3 bytes) is allowed.
+ /// Parses block data. Trailing zero padding is allowed.
pub fn parse(data: &[u8]) -> Result<Self> {
let mut r = Reader::new(data);
let version = r.u32()?;
if !(1..=3).contains(&version) {
return Err(PsdError::invalid(format!("filter effects version {version}")));
}
- let len = r.u64()?;
- let mut body = r.sub(len)?;
- let rest = r.peek_rest();
- if rest.len() > 3 || rest.iter().any(|&b| b != 0) {
- return Err(PsdError::invalid(format!("filter effects: {} unexpected bytes after the data", rest.len())));
- }
let mut items = Vec::new();
- while !body.is_empty() {
- let id = String::from_utf8_lossy(&read_pascal(&mut body, 1)?).into_owned();
- let item_version = body.u32()?;
- let item_len = body.u64()?;
- let mut it = body.sub(item_len)?;
- let rect = read_rect(&mut it)?;
- let depth = it.u32()?;
- let max_channels = it.u32()?;
- if max_channels > MAX_SLOTS {
- return Err(PsdError::LimitExceeded("filter effects: too many channels"));
+ loop {
+ let len = r.u64()?;
+ let mut body = r.sub(len)?;
+ while !body.is_empty() {
+ items.push(read_item(&mut body)?);
}
- let mut slots = Vec::with_capacity(max_channels as usize + 2);
- for _ in 0..max_channels + 2 {
- slots.push(if it.u32()? != 0 { Some(read_plane(&mut it)?) } else { None });
+ // Sections are padded to 4 bytes; the last one's padding may be cut short.
+ let pad = ((4 - len % 4) % 4).min(r.remaining() as u64);
+ r.skip(pad as usize)?;
+ let rest = r.peek_rest();
+ if rest.iter().all(|&b| b == 0) && rest.len() <= 3 {
+ break;
}
- if !it.is_empty() {
- return Err(PsdError::invalid(format!("filter effects item {id}: {} unexpected bytes", it.remaining())));
+ if rest.len() < 8 {
+ return Err(PsdError::invalid(format!("filter effects: {} unexpected bytes after the data", rest.len())));
}
- let mask = if body.is_empty() || body.u8()? == 0 { None } else { Some((read_rect(&mut body)?, read_plane(&mut body)?)) };
- items.push(FilterEffectsItem { id, version: item_version, rect, depth, max_channels, slots, mask });
}
Ok(FilterEffects { version, items })
}
- /// Serializes block data (without padding).
+ /// Serializes block data as Photoshop writes it: one section per item, each padded to 4 bytes.
pub fn to_bytes(&self) -> Vec<u8> {
- let mut body = Vec::new();
+ let mut out = Vec::new();
+ out.put_u32(self.version);
for it in &self.items {
+ let mut body = Vec::new();
write_pascal(&mut body, it.id.as_bytes(), 1);
body.put_u32(it.version);
let at = body.begin_len(true);
@@ -191,11 +211,14 @@ impl FilterEffects {
}
None => body.put_u8(0),
}
+ out.put_u64(body.len() as u64);
+ out.put(&body);
+ out.resize(out.len().next_multiple_of(4), 0);
+ }
+ if self.items.is_empty() {
+ // One empty section, so the block still parses.
+ out.put_u64(0);
}
- let mut out = Vec::with_capacity(body.len() + 12);
- out.put_u32(self.version);
- out.put_u64(body.len() as u64);
- out.put(&body);
out
}
}
@@ -213,6 +236,13 @@ mod tests {
FilterEffectsItem { id: id.into(), version: 1, rect, depth: 8, max_channels: 24, slots, mask: mask.then(|| (rect, plane(128))) }
}
+ /// The unpadded body of `it`'s section.
+ fn section(it: &FilterEffectsItem) -> Vec<u8> {
+ let b = FilterEffects { version: 3, items: vec![it.clone()] }.to_bytes();
+ let len = u64::from_be_bytes(b[4..12].try_into().unwrap()) as usize;
+ b[12..12 + len].to_vec()
+ }
+
#[test]
fn round_trips() {
let fx = FilterEffects { version: 3, items: vec![item("a-1", true), item("b-2", false)] };
@@ -221,6 +251,9 @@ mod tests {
assert_eq!(back, fx);
assert_eq!(back.items[0].decoded_mask().unwrap().1, vec![128; 16]);
assert_eq!(back.items[0].slots[0].as_ref().unwrap().decode(4, 4, 8).unwrap(), vec![10; 16]);
+ // No items still writes a section, so the block reads back.
+ let empty = FilterEffects { version: 3, items: Vec::new() };
+ assert_eq!(FilterEffects::parse(&empty.to_bytes()).unwrap(), empty);
// Padding is allowed, garbage is not.
let mut padded = bytes.clone();
padded.extend([0, 0]);
@@ -229,6 +262,39 @@ mod tests {
assert!(FilterEffects::parse(&padded).is_err());
}
+ /// Photoshop writes one length-prefixed section per smart object, each padded to 4 bytes
+ /// outside its length. A document with two filtered smart objects has two sections.
+ #[test]
+ fn reads_one_section_per_item() {
+ let (a, b) = (item("a-1", true), item("b-2", false));
+ let (sa, sb) = (section(&a), section(&b));
+ assert_ne!(sa.len() % 4, 0, "the first section must need padding");
+ let mut bytes = 3u32.to_be_bytes().to_vec();
+ for s in [&sa, &sb] {
+ bytes.extend((s.len() as u64).to_be_bytes());
+ bytes.extend(s.iter());
+ bytes.resize(bytes.len().next_multiple_of(4), 0);
+ }
+ let fx = FilterEffects::parse(&bytes).unwrap();
+ assert_eq!(fx.items, vec![a, b]);
+ // Written back the same way, byte for byte.
+ assert_eq!(fx.to_bytes(), bytes);
+ }
+
+ /// Older PhotoCraft files hold every item in one section; they still read.
+ #[test]
+ fn reads_several_items_in_one_section() {
+ let items = vec![item("a-1", true), item("b-2", false)];
+ let mut body = Vec::new();
+ for it in &items {
+ body.extend(section(it));
+ }
+ let mut bytes = 3u32.to_be_bytes().to_vec();
+ bytes.extend((body.len() as u64).to_be_bytes());
+ bytes.extend(&body);
+ assert_eq!(FilterEffects::parse(&bytes).unwrap().items, items);
+ }
+
#[test]
fn mutations_never_panic() {
let bytes = FilterEffects { version: 3, items: vec![item("x", true), item("y", false)] }.to_bytes();
@@ -260,7 +326,8 @@ mod tests {
#[test]
fn malformed_data_is_an_error() {
let bytes = FilterEffects { version: 3, items: vec![item("x", true)] }.to_bytes();
- for n in 0..bytes.len() {
+ // Cut anywhere before the end of the section (only its padding may be missing).
+ for n in 0..12 + section(&item("x", true)).len() {
assert!(FilterEffects::parse(&bytes[..n]).is_err(), "truncated at {n}");
}
let mut bad = bytes.clone();