From 4827d2b6f305a4dcfad59a3fce184b0222699694 Mon Sep 17 00:00:00 2001 From: Vincent Cloutier Date: Thu, 22 Oct 2026 11:55:37 -0400 Subject: [PATCH] feat(psd): parse legacy frame-animation metadata --- crates/psd/README.md | 29 ++- crates/psd/examples/animation_inspect.rs | 103 +++++++++ crates/psd/src/animation.rs | 228 ++++++++++++++++++++ crates/psd/src/lib.rs | 1 + crates/psd/src/metadata.rs | 12 ++ crates/psd/src/resources.rs | 8 + crates/psd/tests/animation.rs | 262 +++++++++++++++++++++++ crates/psd/tests/corpus.rs | 55 +++++ 8 files changed, 697 insertions(+), 1 deletion(-) create mode 100644 crates/psd/examples/animation_inspect.rs create mode 100644 crates/psd/src/animation.rs create mode 100644 crates/psd/tests/animation.rs diff --git a/crates/psd/README.md b/crates/psd/README.md index d745fd5bd8..eee9cec6fa 100644 --- a/crates/psd/README.md +++ b/crates/psd/README.md @@ -69,7 +69,14 @@ LayerInfo::unpadded_len(version), LayerInfo::pad_to(version, 4) // Photoshop p // Image resources ImageResource { signature, id, name, data }; ImageResource::parsed() -> Option> ResourceData::{ResolutionInfo, LayerState, LayerGroupInfo, Thumbnail, GlobalAngle, IccProfile, - GlobalAltitude, VersionInfo, Exif, Xmp} + GlobalAltitude, VersionInfo, Exif, Xmp, TimelineInfo, Animation} + +// Legacy animation syntax (no playback/document-model dependency) +animation::AnimationResource::from_bytes / to_bytes // maniIRFR; ordered raw records +animation::AnimationRecord::descriptor() // AnDs; version-16 descriptor +animation::{frame_info, frame_sets, layer_frame_states} // borrowed sparse views, opaque ids +animation::parse_descriptor // descriptor + up to 3 zero alignment bytes +metadata::MetadataItem::animation_descriptor() // mlst / tmln; leaves other metadata alone // Compression Compression::{Raw, Rle, Zip, ZipPrediction, Unknown(u16)} @@ -107,6 +114,7 @@ testgen::{all_cases, merged_only, layered, small, sample_descriptor, pattern_pla | Lr16 / Lr32 / Layr layer info | ✓ | ✓ | ✓ | lifted into `layer_info`; re-inserted at its original position | | luni lsct lsdk lyid lnsr clbl infx knko lspf lclr iOpa shmd | ✓ | ✓ | ✓ | `TaggedBlock::parsed()` | | ActionDescriptor (all OSTypes) | ✓ | ✓ | ✓ | including references, `ObAr` (best effort), `UnFl`, `Pth `, version-16 wrapper | +| Legacy frame animation syntax | ✓ | ✓ | partial | `mani` / `AnDs`, `mlst`, `tmln`, resource 1075; raw-preserving descriptor views, not playback or keyframe evaluation | | Layer tree (groups) | ✓ | ✓ | ✓ | open/closed folders plus bounding dividers; tolerant of malformed nesting | | RGBA8 extraction | ✓ | – | – | RGB / gray / CMYK layers; merged image also supports indexed / bitmap / duotone | | Builder | – | ✓ | – | RGB / gray / CMYK at 8/16 bit, masks, groups, blend modes, opacity, fill, visibility, clipping | @@ -130,6 +138,25 @@ allocations for padded channels return an error on failure. * Adjustment and fill layers: `curv`, `levl`, `hue2`, `SoCo`, `GdFl`, `PtFl`, …, plus `Patt`, `Txt2`, `FMsk`, 3D and video blocks. * Global layer mask info (raw, with accessors), thumbnails (raw), slices, guides, paths, and every other resource id. +## Legacy animation inspection + +```sh +cargo run -p photocraft-psd --example animation_inspect -- /path/to/input.psd +cargo test -p photocraft-psd --test animation +``` + +The inspection example accepts an explicit local PSD/PSB (up to 128 MiB), reports frame counts, +stored delays and descriptor counts, and checks byte-exact raw round-trips without modifying the +input. It does not print layer names, text or descriptor values. No personal file is bundled; +committed animation tests construct synthetic payloads and PSD/PSB containers. + +`mani` is detected by its payload signature within the plug-in resource range 4000–4999, not by +assuming that resource 4003 always belongs to animation. Unknown records and unsupported descriptor +versions stay raw. `FrIn` definitions and `FSts` playback order are separate; ids are opaque stored +`long` values. Missing frame delays remain absent, and sparse `mlst` properties are not filled with +guessed defaults. Timeline tracks, loops, inheritance and property evaluation are left to higher +layers. This parser alone does **not** make PSD animations play in PhotoCraft. + ## Testing `cargo test -p photocraft-psd --all-features` runs the unit tests, integration tests and proptests: diff --git a/crates/psd/examples/animation_inspect.rs b/crates/psd/examples/animation_inspect.rs new file mode 100644 index 0000000000..2b3f7391dc --- /dev/null +++ b/crates/psd/examples/animation_inspect.rs @@ -0,0 +1,103 @@ +//! Inspect a local PSD/PSB's animation structure without printing layer names, text, or metadata +//! values. No asset is bundled: pass a path explicitly. Does not decode pixels or modify the file. +//! `cargo run -p photocraft-psd --example animation_inspect -- /path/to/input.psd` + +#[cfg(not(target_arch = "wasm32"))] +fn inspect() -> Result<(), Box> { + use std::collections::BTreeMap; + use std::io::Read; + + use photocraft_psd::animation::{frame_info, frame_sets, layer_frame_states}; + use photocraft_psd::metadata::parse_shmd; + use photocraft_psd::{PsdFile, ResourceData}; + + let mut args = std::env::args_os().skip(1); + let path = args.next().ok_or("usage: animation_inspect ")?; + if args.next().is_some() { + return Err("expected exactly one input path".into()); + } + // Diagnostic tool, not the production large-file importer. Bound even a file growing while read. + const MAX_BYTES: u64 = 128 * 1024 * 1024; + let file = std::fs::File::open(path)?; + if !file.metadata()?.is_file() || file.metadata()?.len() > MAX_BYTES { + return Err("expected a regular PSD/PSB no larger than 128 MiB".into()); + } + let mut bytes = Vec::new(); + file.take(MAX_BYTES + 1).read_to_end(&mut bytes)?; + if bytes.len() as u64 > MAX_BYTES { + return Err("input exceeds the diagnostic tool's 128 MiB limit".into()); + } + let psd = PsdFile::from_bytes(&bytes)?; + println!("canvas={}x{} depth={} layers={}", psd.header.width, psd.header.height, psd.header.depth, psd.layers().len()); + let mut animations = 0; + for resource in &psd.resources { + match resource.parsed() { + Some(Ok(ResourceData::Animation(animation))) => { + animations += 1; + let back = animation.to_bytes()?; + if back != resource.data { + return Err("animation resource failed its byte-exact round trip".into()); + } + println!("animation resource: {} records; byte-exact round trip", animation.records.len()); + for record in &animation.records { + if let Some(d) = record.descriptor() { + let d = d?; + let frames = frame_info(&d.descriptor)?; + let sets = frame_sets(&d.descriptor)?; + let mut delays = BTreeMap::new(); + for frame in &frames { + *delays.entry(frame.delay_centiseconds).or_insert(0usize) += 1; + } + println!(" AnDs: {} definitions, {} frame sets", frames.len(), sets.len()); + println!(" stored delays (centiseconds -> frame count): {delays:?}"); + for set in sets { + let unresolved = set.frame_ids.iter().filter(|id| !frames.iter().any(|f| f.id == **id)).count(); + println!(" frame set: {} ordered references, {unresolved} unresolved", set.frame_ids.len()); + } + } + } + } + Some(Ok(ResourceData::TimelineInfo(d))) => println!("document timeline: {} descriptor fields", d.descriptor.items.len()), + Some(Err(e)) if resource.id == 1075 || (4000..=4999).contains(&resource.id) && resource.data.starts_with(b"mani") => return Err(e.into()), + _ => {} + } + } + let (mut states, mut tracks) = (0usize, 0usize); + for layer in psd.layers() { + for block in &layer.blocks { + if block.key != *b"shmd" { + continue; + } + let items = parse_shmd(&block.data)?; + for item in &items { + if let Some(d) = item.animation_descriptor() { + let d = d?; + if item.key == *b"mlst" { + layer_frame_states(&d.descriptor)?; + states += 1; + } else { + tracks += 1; + } + } + } + if photocraft_psd::metadata::write_shmd(&items) != block.data { + return Err("layer metadata failed its byte-exact round trip".into()); + } + } + } + if psd.to_bytes()? != bytes { + return Err("PSD/PSB failed its byte-exact round trip".into()); + } + println!("animation resources={animations}; layer frame-state descriptors={states}; layer timeline descriptors={tracks}"); + println!("whole PSD/PSB: byte-exact round trip; input unchanged"); + Ok(()) +} + +fn main() -> std::process::ExitCode { + #[cfg(not(target_arch = "wasm32"))] + if let Err(e) = inspect() { + eprintln!("animation inspection failed: {e}"); + return std::process::ExitCode::FAILURE; + } + std::process::ExitCode::SUCCESS +} diff --git a/crates/psd/src/animation.rs b/crates/psd/src/animation.rs new file mode 100644 index 0000000000..de29693f6c --- /dev/null +++ b/crates/psd/src/animation.rs @@ -0,0 +1,228 @@ +//! Legacy Photoshop frame-animation syntax, independent of playback or document semantics. +//! +//! Observed in a CS5-authored PSD: a plug-in image resource (id in 4000..=4999) starts with +//! `maniIRFR`, a big-endian u32 byte length, then `8BIM` / key / u32 length / data records. +//! `AnDs` holds a version-16 ActionDescriptor; other records (including `Roll`) stay opaque. +//! Layer `shmd` items `mlst` and `tmln`, and image resource 1075, also hold versioned descriptors. +//! These undocumented layouts were established by inspecting file structure, not proprietary code. +//! +//! Raw records remain the source of truth: typed accessors do not rewrite them, discard unknown +//! fields, interpret sparse layer-state inheritance, or assume a frame id is its sequence index. +//! This module does **not** import an animation into PhotoCraft or evaluate timeline tracks. + +use crate::descriptor::{Descriptor, Value, VersionedDescriptor}; +use crate::error::{PsdError, Result}; +use crate::io::{Reader, WriteExt}; + +/// A record in a `mani` resource. Data includes any padding counted in its stored length. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AnimationRecord<'a> { + /// Record key (`AnDs`, `Roll`, or an unknown key). + pub key: [u8; 4], + /// Borrowed, unmodified payload. + pub data: &'a [u8], +} + +impl AnimationRecord<'_> { + /// Typed view of `AnDs`; `None` for other records, including `Roll`. + pub fn descriptor(&self) -> Option> { + (self.key == *b"AnDs").then(|| parse_descriptor(self.data)) + } +} + +/// The records of a legacy frame-animation plug-in resource, in stored order. +/// +/// Unknown keys and duplicate records are preserved, not silently collapsed. The observed +/// envelope has no alignment bytes outside record lengths. Unsupported envelopes return an error; +/// callers should keep their original image resource unchanged in that case. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AnimationResource<'a> { + /// Ordered records, borrowing their payloads from the input. + pub records: Vec>, +} + +impl<'a> AnimationResource<'a> { + /// Parses a complete `maniIRFR` payload, checking the outer and every inner length. + /// Descriptor decoding is lazy, so unknown/future `AnDs` versions can still round-trip raw. + pub fn from_bytes(data: &'a [u8]) -> Result { + let mut r = Reader::new(data); + signature(&mut r, *b"mani", "mani")?; + signature(&mut r, *b"IRFR", "IRFR animation envelope")?; + let len = r.u32()?; + let mut body = r.sub(u64::from(len))?; + if !r.is_empty() { + return Err(PsdError::invalid("trailing bytes after animation envelope")); + } + let mut records = Vec::new(); + while !body.is_empty() { + signature(&mut body, *b"8BIM", "8BIM animation record")?; + let key = body.array()?; + let len = body.u32()?; + let data = body.bytes_u64(u64::from(len))?; + records.push(AnimationRecord { key, data }); + } + Ok(Self { records }) + } + + /// Writes the raw records, preserving their payloads exactly, including unknown fields, + /// unknown descriptor versions and noncanonical descriptor encodings. + pub fn to_bytes(&self) -> Result> { + // Check all lengths before constructing the output; no unchecked 32-bit length casts. + let mut len = 0u32; + for record in &self.records { + let n = u32::try_from(record.data.len()).map_err(|_| PsdError::LimitExceeded("animation record exceeds u32 length"))?; + len = len.checked_add(12).and_then(|v| v.checked_add(n)).ok_or(PsdError::LimitExceeded("animation envelope exceeds u32 length"))?; + } + let mut out = Vec::new(); + out.put(b"maniIRFR"); + out.put_u32(len); + for record in &self.records { + out.put(b"8BIM"); + out.put(&record.key); + out.put_len(record.data.len() as u64, false)?; + out.put(record.data); + } + Ok(out) + } +} + +fn signature(r: &mut Reader<'_>, expected: [u8; 4], name: &'static str) -> Result<()> { + let found = r.array()?; + if found != expected { + return Err(PsdError::InvalidSignature { expected: name, found }); + } + Ok(()) +} + +/// Parses a version-16 animation descriptor, allowing up to three zero alignment bytes. +/// +/// Raw payloads should be retained separately for byte-exact writing. This accessor is strict +/// about non-padding trailing bytes and does not guess how to read a future descriptor version. +/// It is shared by `AnDs`, layer `mlst` / `tmln`, and document timeline resource 1075. +pub fn parse_descriptor(data: &[u8]) -> Result { + let (value, consumed) = VersionedDescriptor::parse_prefix(data)?; + let tail = data.get(consumed..).ok_or_else(|| PsdError::invalid("animation descriptor length"))?; + if tail.len() > 3 || tail.iter().any(|&b| b != 0) { + return Err(PsdError::invalid("trailing bytes after animation descriptor")); + } + Ok(value) +} + +/// A frame-definition view. Its id is an opaque signed `long`, not a frame index. +#[derive(Debug, Clone, PartialEq)] +pub struct FrameInfo<'a> { + /// `FrID`, preserved without reinterpreting its bit pattern. + pub id: i32, + /// `FrDl` in centiseconds, or absent. No playback default or browser clamping is applied. + pub delay_centiseconds: Option, + /// All fields, including unknown ones, in their original order. + pub descriptor: &'a Descriptor, +} + +/// Reads the `FrIn` list from an `AnDs` descriptor. A missing list is not an empty animation. +/// Wrong types, missing frame ids and negative delays return errors. Duplicate ids are retained +/// for the document importer to diagnose rather than being silently overwritten here. +pub fn frame_info(descriptor: &Descriptor) -> Result>> { + let Some(Value::List(list)) = descriptor.get("FrIn") else { + return Err(PsdError::invalid("animation FrIn must be a list")); + }; + list.iter() + .map(|v| { + let Value::Descriptor(d) = v else { return Err(PsdError::invalid("animation frame must be a descriptor")) }; + let Some(Value::Integer(id)) = d.get("FrID") else { return Err(PsdError::invalid("animation frame FrID must be a long")) }; + let delay_centiseconds = match d.get("FrDl") { + None => None, + Some(Value::Integer(n)) => Some(u32::try_from(*n).map_err(|_| PsdError::invalid("negative animation frame delay"))?), + _ => return Err(PsdError::invalid("animation frame FrDl must be a long")), + }; + Ok(FrameInfo { id: *id, delay_centiseconds, descriptor: d }) + }) + .collect() +} + +/// A stored frame set: explicit playback order is separate from the `FrIn` definitions. +#[derive(Debug, Clone, PartialEq)] +pub struct FrameSet<'a> { + /// `FsID`, an opaque identifier. + pub id: i32, + /// `AFrm`, when present. Kept uninterpreted for the importer to validate. + pub active_frame: Option, + /// `FsFr` frame ids in stored order (including any duplicate or unresolved ids). + pub frame_ids: Vec, + /// Complete original descriptor, including fields not yet understood. + pub descriptor: &'a Descriptor, +} + +/// One sparse layer-state entry from `mlst` / `LaSt`. +#[derive(Debug, Clone, PartialEq)] +pub struct LayerFrameState<'a> { + /// `FrLs`: frame ids to which this entry refers. They are not frame indices. + pub frame_ids: Vec, + /// Complete sparse state, including visibility, blend options, offsets, masks, effects, + /// text settings and unknown fields. Omitted properties are deliberately not defaulted. + pub descriptor: &'a Descriptor, +} + +/// A layer's sparse animation states, without attempting to resolve their inheritance. +#[derive(Debug, Clone, PartialEq)] +pub struct LayerFrameStates<'a> { + /// `LaID`: PSD layer identifier, not the layer's record index. + pub layer_id: i32, + /// `LaSt` entries in stored order. + pub states: Vec>, +} + +/// Reads the identifiers and sparse entries of an `mlst` descriptor. This is a syntax view: +/// missing properties stay missing, and duplicate/unresolved references remain available for +/// the importer to validate. The original descriptor remains available to the caller. +pub fn layer_frame_states(descriptor: &Descriptor) -> Result> { + let Some(Value::Integer(layer_id)) = descriptor.get("LaID") else { + return Err(PsdError::invalid("animation layer LaID must be a long")); + }; + let Some(Value::List(list)) = descriptor.get("LaSt") else { + return Err(PsdError::invalid("animation layer LaSt must be a list")); + }; + let states = list + .iter() + .map(|v| { + let Value::Descriptor(d) = v else { return Err(PsdError::invalid("animation layer state must be a descriptor")) }; + let Some(Value::List(ids)) = d.get("FrLs") else { return Err(PsdError::invalid("animation layer FrLs must be a list")) }; + let frame_ids = ids + .iter() + .map(|v| match v { + Value::Integer(n) => Ok(*n), + _ => Err(PsdError::invalid("animation layer frame reference must be a long")), + }) + .collect::>>()?; + Ok(LayerFrameState { frame_ids, descriptor: d }) + }) + .collect::>>()?; + Ok(LayerFrameStates { layer_id: *layer_id, states }) +} + +/// Reads `FSts` without inferring order from frame ids or interpreting loop-related fields. +pub fn frame_sets(descriptor: &Descriptor) -> Result>> { + let Some(Value::List(list)) = descriptor.get("FSts") else { + return Err(PsdError::invalid("animation FSts must be a list")); + }; + list.iter() + .map(|v| { + let Value::Descriptor(d) = v else { return Err(PsdError::invalid("animation frame set must be a descriptor")) }; + let Some(Value::Integer(id)) = d.get("FsID") else { return Err(PsdError::invalid("animation frame set FsID must be a long")) }; + let active_frame = match d.get("AFrm") { + None => None, + Some(Value::Integer(n)) => Some(*n), + _ => return Err(PsdError::invalid("animation frame set AFrm must be a long")), + }; + let Some(Value::List(ids)) = d.get("FsFr") else { return Err(PsdError::invalid("animation frame set FsFr must be a list")) }; + let frame_ids = ids + .iter() + .map(|v| match v { + Value::Integer(n) => Ok(*n), + _ => Err(PsdError::invalid("animation frame reference must be a long")), + }) + .collect::>>()?; + Ok(FrameSet { id: *id, active_frame, frame_ids, descriptor: d }) + }) + .collect() +} diff --git a/crates/psd/src/lib.rs b/crates/psd/src/lib.rs index 6fb47cbdb9..4db9372938 100644 --- a/crates/psd/src/lib.rs +++ b/crates/psd/src/lib.rs @@ -43,6 +43,7 @@ pub mod abr; pub mod aco; pub mod act; +pub mod animation; pub mod ase; pub mod atn; pub mod blend; diff --git a/crates/psd/src/metadata.rs b/crates/psd/src/metadata.rs index 9e85d8cee7..0b8927adc1 100644 --- a/crates/psd/src/metadata.rs +++ b/crates/psd/src/metadata.rs @@ -26,6 +26,18 @@ pub struct MetadataItem { } impl MetadataItem { + /// Typed animation descriptor for `mlst` (sparse layer frame states) or `tmln` + /// (layer timeline tracks). Other metadata, including `cust` / XMP, is not interpreted. + /// The original item stays unchanged; inheritance and track evaluation belong to the importer. + pub fn animation_descriptor(&self) -> Option> { + matches!(&self.key, b"mlst" | b"tmln").then(|| { + if self.signature != *b"8BIM" { + return Err(PsdError::InvalidSignature { expected: "8BIM animation metadata", found: self.signature }); + } + crate::animation::parse_descriptor(&self.data) + }) + } + /// A new item; `data` is zero-padded to an even length as Photoshop writes it. pub fn new(key: [u8; 4], mut data: Vec) -> Self { if data.len() % 2 == 1 { diff --git a/crates/psd/src/resources.rs b/crates/psd/src/resources.rs index 4d78a062be..77213a9893 100644 --- a/crates/psd/src/resources.rs +++ b/crates/psd/src/resources.rs @@ -28,6 +28,8 @@ pub mod ids { pub const EXIF: u16 = 1058; /// XMP metadata. pub const XMP: u16 = 1060; + /// Document timeline settings (versioned descriptor). + pub const TIMELINE_INFO: u16 = 1075; } /// One image resource block. @@ -169,6 +171,10 @@ pub enum ResourceData<'a> { Exif(&'a [u8]), /// 1060: XMP packet (UTF-8). Xmp(&'a [u8]), + /// 1075: document timeline settings; tracks and rational times remain descriptor data. + TimelineInfo(crate::VersionedDescriptor), + /// A `mani` legacy animation resource in the plug-in resource id range (4000..=4999). + Animation(crate::animation::AnimationResource<'a>), } impl ImageResource { @@ -199,6 +205,8 @@ impl ImageResource { ids::VERSION_INFO => VersionInfo::from_bytes(d).map(ResourceData::VersionInfo), ids::EXIF => Ok(ResourceData::Exif(d)), ids::XMP => Ok(ResourceData::Xmp(d)), + ids::TIMELINE_INFO => crate::animation::parse_descriptor(d).map(ResourceData::TimelineInfo), + 4000..=4999 if d.starts_with(b"mani") => crate::animation::AnimationResource::from_bytes(d).map(ResourceData::Animation), _ => return None, }) } diff --git a/crates/psd/tests/animation.rs b/crates/psd/tests/animation.rs new file mode 100644 index 0000000000..ac96b6a0b9 --- /dev/null +++ b/crates/psd/tests/animation.rs @@ -0,0 +1,262 @@ +//! Synthetic only: no personal PSDs, paths, or copied descriptor payloads. + +use photocraft_psd::animation::{AnimationRecord, AnimationResource, frame_info, frame_sets, layer_frame_states, parse_descriptor}; +use photocraft_psd::descriptor::{Descriptor, Value, VersionedDescriptor}; +use photocraft_psd::metadata::{MetadataItem, parse_shmd, write_shmd}; +use photocraft_psd::{ImageResource, PsdBuilder, PsdFile, ResourceData, TaggedBlock, Version}; +use proptest::prelude::*; + +fn descriptor() -> VersionedDescriptor { + VersionedDescriptor::new( + Descriptor::default() + .with("AFSt", Value::Integer(7)) + .with( + "FrIn", + Value::List(vec![ + Value::Descriptor( + Descriptor::default().with("FrID", Value::Integer(-3)).with("FrDl", Value::Integer(3)).with("future", Value::Boolean(true)), + ), + Value::Descriptor(Descriptor::default().with("FrID", Value::Integer(21)).with("FrDl", Value::Integer(53))), + ]), + ) + .with( + "FSts", + Value::List(vec![Value::Descriptor( + Descriptor::default() + .with("FsID", Value::Integer(7)) + .with("AFrm", Value::Integer(0)) + .with("FsFr", Value::List(vec![Value::Integer(21), Value::Integer(-3)])) + .with("future", Value::RawData(vec![1, 2, 3])), + )]), + ), + ) +} + +fn resource(data: &[u8]) -> AnimationResource<'_> { + AnimationResource { + records: vec![ + AnimationRecord { key: *b"AnDs", data }, + AnimationRecord { key: *b"Roll", data: &[0; 8] }, + AnimationRecord { key: *b"next", data: &[9, 8, 7] }, + ], + } +} + +#[test] +fn raw_roundtrip_and_typed_views_preserve_order_and_unknown_data() { + let data = descriptor().to_bytes(); + let bytes = resource(&data).to_bytes().unwrap(); + let parsed = AnimationResource::from_bytes(&bytes).unwrap(); + assert_eq!(parsed, resource(&data)); + let d = parsed.records[0].descriptor().unwrap().unwrap(); + assert_eq!(d, descriptor()); + let frames = frame_info(&d.descriptor).unwrap(); + assert_eq!(frames.iter().map(|f| (f.id, f.delay_centiseconds)).collect::>(), [(-3, Some(3)), (21, Some(53))]); + assert_eq!(frames[0].descriptor.get("future"), Some(&Value::Boolean(true))); + let sets = frame_sets(&d.descriptor).unwrap(); + assert_eq!(sets[0].frame_ids, [21, -3], "playback order is not FrIn order or sorted id order"); + assert_eq!(sets[0].id, 7); + assert_eq!(sets[0].active_frame, Some(0)); + assert_eq!(sets[0].descriptor.get("future"), Some(&Value::RawData(vec![1, 2, 3]))); + assert!(parsed.records[1].descriptor().is_none()); + assert_eq!(parsed.to_bytes().unwrap(), bytes); +} + +#[test] +fn plugin_signature_not_a_single_resource_id_selects_the_parser() { + let data = descriptor().to_bytes(); + let bytes = resource(&data).to_bytes().unwrap(); + for id in [4000, 4003, 4999] { + let r = ImageResource::new(id, bytes.clone()); + assert!(matches!(r.parsed(), Some(Ok(ResourceData::Animation(_))))); + } + for id in [3999, 5000] { + assert!(ImageResource::new(id, bytes.clone()).parsed().is_none()); + } + assert!(ImageResource::new(4003, b"different plugin".to_vec()).parsed().is_none()); + assert!(matches!(ImageResource::new(4003, b"mani".to_vec()).parsed(), Some(Err(_)))); + assert!(matches!( + ImageResource::new(1075, VersionedDescriptor::new(Descriptor::default().with("Vrsn", Value::Integer(1))).to_bytes()).parsed(), + Some(Ok(ResourceData::TimelineInfo(_))) + )); +} + +#[test] +fn metadata_views_do_not_touch_xmp_or_other_items() { + let d = VersionedDescriptor::new(Descriptor::default().with("LaID", Value::Integer(42)).with( + "LaSt", + Value::List(vec![Value::Descriptor( + Descriptor::default() + .with("FrLs", Value::List(vec![Value::Integer(-3)])) + .with("blendOptions", Value::Descriptor(Descriptor::default().with("Opct", Value::Double(12.5)))), + )]), + )); + let items = vec![ + MetadataItem::new(*b"cust", vec![7, 9, 11]), + MetadataItem::new(*b"mlst", d.to_bytes()), + MetadataItem::new(*b"tmln", VersionedDescriptor::new(Descriptor::default().with("trackList", Value::List(vec![]))).to_bytes()), + MetadataItem::new(*b"next", vec![255; 4]), + ]; + let raw = write_shmd(&items); + let parsed = parse_shmd(&raw).unwrap(); + assert!(parsed[0].animation_descriptor().is_none()); + let layer_descriptor = parsed[1].animation_descriptor().unwrap().unwrap(); + assert_eq!(layer_descriptor, d); + let states = layer_frame_states(&layer_descriptor.descriptor).unwrap(); + assert_eq!(states.layer_id, 42); + assert_eq!(states.states[0].frame_ids, [-3]); + assert_eq!(states.states[0].descriptor.get("enab"), None, "missing visibility is not false"); + assert_eq!(states.states[0].descriptor.get("blendOptions"), Some(&Value::Descriptor(Descriptor::default().with("Opct", Value::Double(12.5))))); + assert!(parsed[2].animation_descriptor().unwrap().is_ok()); + assert!(parsed[3].animation_descriptor().is_none()); + assert_eq!(write_shmd(&parsed), raw); + let mut bad = parsed[1].clone(); + bad.signature = *b"nope"; + assert!(bad.animation_descriptor().unwrap().is_err()); +} + +#[test] +fn psd_and_psb_keep_animation_resources_and_metadata_byte_stable() { + let data = descriptor().to_bytes(); + let raw = resource(&data).to_bytes().unwrap(); + for version in [Version::Psd, Version::Psb] { + let mut file = PsdBuilder::new(1, 1).version(version).build().unwrap(); + file.resources.push(ImageResource::new(4003, raw.clone())); + file.global_blocks.push(TaggedBlock::new(*b"shmd", write_shmd(&[MetadataItem::new(*b"mlst", data.clone())]))); + let bytes = file.to_bytes().unwrap(); + let back = PsdFile::from_bytes(&bytes).unwrap(); + assert_eq!(back.to_bytes().unwrap(), bytes); + let animation = back.resource(4003).unwrap(); + assert!(matches!(animation.parsed(), Some(Ok(ResourceData::Animation(_))))); + } +} + +#[test] +fn every_truncation_and_hostile_envelope_length_is_rejected() { + let data = descriptor().to_bytes(); + let bytes = resource(&data).to_bytes().unwrap(); + for end in 0..bytes.len() { + assert!(AnimationResource::from_bytes(&bytes[..end]).is_err(), "prefix {end}"); + } + for at in [8, 20] { + for value in [0, 1, u32::MAX] { + let mut bad = bytes.clone(); + bad[at..at + 4].copy_from_slice(&value.to_be_bytes()); + assert!(AnimationResource::from_bytes(&bad).is_err(), "length {at} = {value}"); + } + } + for at in [0, 4, 12] { + let mut bad = bytes.clone(); + bad[at] = b'?'; + assert!(AnimationResource::from_bytes(&bad).is_err()); + } + let mut trailing = bytes.clone(); + trailing.push(0); + assert!(AnimationResource::from_bytes(&trailing).is_err()); +} + +#[test] +fn descriptor_padding_truncation_and_unknown_versions() { + let raw = descriptor().to_bytes(); + for end in 0..raw.len() { + assert!(parse_descriptor(&raw[..end]).is_err(), "descriptor prefix {end}"); + } + for padding in 0..=3 { + let mut padded = raw.clone(); + padded.extend(vec![0; padding]); + assert_eq!(parse_descriptor(&padded).unwrap(), descriptor()); + } + for tail in [vec![0; 4], vec![1], vec![0, 2]] { + let mut bad = raw.clone(); + bad.extend(tail); + assert!(parse_descriptor(&bad).is_err()); + } + let mut future = raw.clone(); + future[..4].copy_from_slice(&17u32.to_be_bytes()); + let bytes = resource(&future).to_bytes().unwrap(); + let r = AnimationResource::from_bytes(&bytes).unwrap(); + assert!(r.records[0].descriptor().unwrap().is_err()); + assert_eq!(r.to_bytes().unwrap(), bytes, "unsupported typed version must survive raw"); +} + +#[test] +fn absent_delays_and_duplicate_ids_are_not_silently_repaired() { + let d = Descriptor::default().with( + "FrIn", + Value::List(vec![ + Value::Descriptor(Descriptor::default().with("FrID", Value::Integer(4))), + Value::Descriptor(Descriptor::default().with("FrID", Value::Integer(4)).with("FrDl", Value::Integer(0))), + ]), + ); + let frames = frame_info(&d).unwrap(); + assert_eq!(frames.len(), 2); + assert_eq!(frames[0].delay_centiseconds, None); + assert_eq!(frames[1].delay_centiseconds, Some(0)); + let bytes = + AnimationResource { records: vec![AnimationRecord { key: *b"next", data: &[] }, AnimationRecord { key: *b"next", data: &[1] }] }.to_bytes().unwrap(); + assert_eq!(AnimationResource::from_bytes(&bytes).unwrap().to_bytes().unwrap(), bytes); +} + +#[test] +fn wrong_frame_and_set_types_return_errors() { + for value in [Value::Boolean(false), Value::List(vec![Value::Integer(1)]), Value::List(vec![Value::Descriptor(Descriptor::default())])] { + assert!(frame_info(&Descriptor::default().with("FrIn", value.clone())).is_err()); + assert!(frame_sets(&Descriptor::default().with("FSts", value)).is_err()); + } + for delay in [Value::Integer(-1), Value::Double(3.0)] { + let frame = Descriptor::default().with("FrID", Value::Integer(1)).with("FrDl", delay); + assert!(frame_info(&Descriptor::default().with("FrIn", Value::List(vec![Value::Descriptor(frame)]))).is_err()); + } + for (key, value) in [("FsID", Value::Boolean(false)), ("AFrm", Value::Double(0.0)), ("FsFr", Value::List(vec![Value::Boolean(true)]))] { + let mut set = Descriptor::default().with("FsID", Value::Integer(1)).with("FsFr", Value::List(vec![])); + set.items.retain(|(id, _)| !id.is(key)); + set = set.with(key, value); + assert!(frame_sets(&Descriptor::default().with("FSts", Value::List(vec![Value::Descriptor(set)]))).is_err()); + } +} + +#[test] +fn sparse_layer_states_retain_missing_properties_and_multiple_references() { + let first = Descriptor::default() + .with("FrLs", Value::List(vec![Value::Integer(21), Value::Integer(-3)])) + .with("enab", Value::Boolean(true)) + .with("Ofst", Value::Descriptor(Descriptor::default().with("Hrzn", Value::Integer(-7)).with("Vrtc", Value::Integer(12)))); + let second = Descriptor::default().with("FrLs", Value::List(vec![Value::Integer(99)])); + let d = Descriptor::default().with("LaID", Value::Integer(8)).with("LaSt", Value::List(vec![Value::Descriptor(first.clone()), Value::Descriptor(second)])); + let view = layer_frame_states(&d).unwrap(); + assert_eq!(view.states[0].frame_ids, [21, -3]); + assert_eq!(view.states[0].descriptor, &first); + assert_eq!(view.states[1].descriptor.get("Ofst"), None); + assert_eq!(view.states[1].descriptor.get("enab"), None); + for d in [ + Descriptor::default(), + Descriptor::default().with("LaID", Value::Boolean(true)), + Descriptor::default().with("LaID", Value::Integer(8)).with("LaSt", Value::Boolean(true)), + Descriptor::default().with("LaID", Value::Integer(8)).with("LaSt", Value::List(vec![Value::Integer(0)])), + ] { + assert!(layer_frame_states(&d).is_err()); + } + for state in [ + Descriptor::default(), + Descriptor::default().with("FrLs", Value::Integer(0)), + Descriptor::default().with("FrLs", Value::List(vec![Value::Boolean(true)])), + ] { + let d = Descriptor::default().with("LaID", Value::Integer(8)).with("LaSt", Value::List(vec![Value::Descriptor(state)])); + assert!(layer_frame_states(&d).is_err()); + } +} + +proptest! { + #[test] + fn arbitrary_animation_bytes_never_panic(data in proptest::collection::vec(any::(), 0..2048)) { + let _ = AnimationResource::from_bytes(&data); + let _ = parse_descriptor(&data); + } + + #[test] + fn opaque_record_roundtrip(data in proptest::collection::vec(any::(), 0..2048), key in any::<[u8; 4]>()) { + let r = AnimationResource { records: vec![AnimationRecord { key, data: &data }] }; + let bytes = r.to_bytes().unwrap(); + prop_assert_eq!(AnimationResource::from_bytes(&bytes).unwrap(), r); + } +} diff --git a/crates/psd/tests/corpus.rs b/crates/psd/tests/corpus.rs index 90abb4fefd..fad6305f64 100644 --- a/crates/psd/tests/corpus.rs +++ b/crates/psd/tests/corpus.rs @@ -19,6 +19,61 @@ fn collect(dir: &Path, out: &mut Vec) { } } +/// The existing pinned ag-psd corpus includes public animation cases. Exercise typed syntax +/// against those without adding personal files or new corpus pins. +#[test] +fn corpus_animation_syntax() { + use photocraft_psd::ResourceData; + use photocraft_psd::animation::{frame_info, frame_sets, layer_frame_states}; + use photocraft_psd::metadata::parse_shmd; + + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/psd/ag-psd/read-write"); + for (case, delay) in [("animation-frame", Some(30)), ("animation-offset", Some(50)), ("animation-effects", None)] { + for name in ["src.psd", "expected.psd"] { + let path = root.join(case).join(name); + let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}; run cargo xtask corpus --psd", path.display())); + let psd = PsdFile::from_bytes(&bytes).unwrap(); + let mut found = 0; + for resource in &psd.resources { + if let Some(Ok(ResourceData::Animation(animation))) = resource.parsed() { + found += 1; + assert_eq!(animation.to_bytes().unwrap(), resource.data); + for record in &animation.records { + if let Some(d) = record.descriptor() { + let d = d.unwrap(); + let frames = frame_info(&d.descriptor).unwrap(); + assert_eq!(frames.len(), 2, "{case}/{name}"); + assert!(frames.iter().all(|f| f.delay_centiseconds == delay), "{case}/{name}"); + let sets = frame_sets(&d.descriptor).unwrap(); + assert_eq!(sets.len(), 1); + assert_eq!(sets[0].frame_ids.len(), 2); + assert!(sets[0].frame_ids.iter().all(|id| frames.iter().any(|f| f.id == *id))); + } + } + } + } + assert_eq!(found, 1, "{case}/{name}"); + let mut state_layers = 0; + for layer in psd.layers() { + for block in &layer.blocks { + if block.key == *b"shmd" { + for item in parse_shmd(&block.data).unwrap() { + if item.key == *b"mlst" { + let d = item.animation_descriptor().unwrap().unwrap(); + let states = layer_frame_states(&d.descriptor).unwrap(); + assert!(!states.states.is_empty()); + state_layers += 1; + } + } + } + } + } + assert_eq!(state_layers, 2, "{case}/{name}"); + assert_eq!(psd.to_bytes().unwrap(), bytes); + } + } +} + /// Files known to be invalid upstream, with the reason. They are reported but /// do not fail the test. const KNOWN_BAD: &[(&str, &str)] =