psd: parse descriptors and placed layers with craft-psd

Pin only craft-psd to craft-libs main 9fc471fc (includes #1887
parse_prefix and #1885 PackBits recovery). Mid-stream descriptor
reads use Descriptor::parse_prefix, mapped back to the public
effectcraft Descriptor/DValue types. SoLd/SoLE/PlLd placements come
from craft_psd::smart::SmartObject, including quiltWarp, and
render_placed bakes through craft_psd::FloatImage.

Pixel decode stays local until a follow-up can check unmatte parity
on composite_f32.
This commit is contained in:
FredApps committed 2026-11-16 16:15:25 +01:00
1 parent 91f9e9b1ef
commit 3bc3adb4e0
6 files changed
+107 -261

No files matched your search

Generated
+1 -1
View File
@@ -1359,7 +1359,7 @@ dependencies = [
[[package]]
name = "craft-psd"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e836b6fd893eca3fbe5880f000dbf446c3a32fcc#e836b6fd893eca3fbe5880f000dbf446c3a32fcc"
source = "git+https://github.com/storytold/craft-libs?rev=9fc471fc5c18f467394a043adf17f021c2b27cae#9fc471fc5c18f467394a043adf17f021c2b27cae"
dependencies = [
"encoding_rs",
"flate2",
+1 -1
View File
@@ -20,7 +20,7 @@ craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs"
craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] }
craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e836b6fd893eca3fbe5880f000dbf446c3a32fcc" }
craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9fc471fc5c18f467394a043adf17f021c2b27cae" }
craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
+62 -117
View File
@@ -108,14 +108,6 @@ impl Descriptor {
}
}
/// A key or class id: length-prefixed string, or a 4-character code when the length is 0.
pub(crate) fn read_id(r: &mut Reader) -> Result<String> {
let n = r.u32()? as usize;
let n = if n == 0 { 4 } else { n };
let b = r.bytes(n)?;
Ok(String::from_utf8_lossy(b).into_owned())
}
pub(crate) fn read_unicode(r: &mut Reader) -> Result<String> {
let n = r.u32()? as usize;
let mut v = Vec::with_capacity(n.min(r.remaining() / 2));
@@ -128,122 +120,70 @@ pub(crate) fn read_unicode(r: &mut Reader) -> Result<String> {
Ok(String::from_utf16_lossy(&v))
}
/// Read a descriptor (after its version field).
/// Read a descriptor (after its version field) with [`craft_psd::descriptor::Descriptor::parse_prefix`].
/// The public [`Descriptor`] / [`DValue`] types stay this crate's (engine interchange uses them).
pub fn read_descriptor(r: &mut Reader) -> Result<Descriptor> {
read_descriptor_at(r, 0)
let rest = r.data.get(r.pos..).unwrap_or(&[]);
let (d, used) = craft_psd::descriptor::Descriptor::parse_prefix(rest).map_err(desc_err)?;
r.skip(used)?;
Ok(from_craft_descriptor(d))
}
/// [`read_descriptor`] nested `depth` values deep: the limit in [`read_value`] counts nested
/// descriptors too, so a file can't recurse until the stack overflows.
fn read_descriptor_at(r: &mut Reader, depth: usize) -> Result<Descriptor> {
let class_name = read_unicode(r)?;
let class_id = read_id(r)?;
let n = r.u32()? as usize;
if n > 100_000 {
return Err(Error::Invalid("descriptor item count".into()));
fn desc_err(e: craft_psd::PsdError) -> Error {
match e {
craft_psd::PsdError::UnexpectedEof { .. } => Error::Truncated,
craft_psd::PsdError::Unsupported(s) => Error::Unsupported(s),
other => Error::Invalid(other.to_string()),
}
let mut items = Vec::with_capacity(n.min(64));
for _ in 0..n {
let key = read_id(r)?;
let ty = r.tag()?;
let v = read_value(r, &ty, depth)?;
items.push((key, v));
}
Ok(Descriptor { class_name, class_id, items })
}
fn read_value(r: &mut Reader, ty: &[u8; 4], depth: usize) -> Result<DValue> {
if depth > 64 {
return Err(Error::Invalid("descriptor nesting".into()));
fn id_str(id: &craft_psd::descriptor::Id) -> String {
String::from_utf8_lossy(id.as_bytes()).into_owned()
}
fn unit_str(u: &[u8; 4]) -> String {
String::from_utf8_lossy(u).into_owned()
}
fn from_craft_descriptor(d: craft_psd::descriptor::Descriptor) -> Descriptor {
Descriptor {
class_name: d.name.to_string_lossy(),
class_id: id_str(&d.class_id),
items: d.items.into_iter().map(|(k, v)| (id_str(&k), from_craft_value(v))).collect(),
}
}
fn from_craft_value(v: craft_psd::descriptor::Value) -> DValue {
use craft_psd::descriptor::Value;
match v {
Value::Descriptor(d) | Value::GlobalObject(d) => DValue::Descriptor(from_craft_descriptor(d)),
Value::List(l) => DValue::List(l.into_iter().map(from_craft_value).collect()),
Value::Double(x) => DValue::Double(if x.is_finite() { x } else { 0.0 }),
Value::UnitFloat { unit, value } => DValue::UnitFloat(unit_str(&unit), if value.is_finite() { value } else { 0.0 }),
Value::UnitFloats { unit, values } => DValue::UnitFloats(unit_str(&unit), values.into_iter().map(|x| if x.is_finite() { x } else { 0.0 }).collect()),
Value::Text(s) => DValue::Text(s.to_string_lossy()),
Value::Enumerated { type_id, value } => DValue::Enum(id_str(&type_id), id_str(&value)),
Value::Integer(i) => DValue::Integer(i),
Value::LargeInteger(i) => DValue::LargeInteger(i),
Value::Boolean(b) => DValue::Bool(b),
Value::Class(c) | Value::GlobalClass(c) => DValue::Class(c.name.to_string_lossy(), id_str(&c.class_id)),
Value::Alias(b) | Value::Path(b) | Value::RawData(b) => DValue::Raw(b),
Value::ObjectArray(o) => DValue::ObjectArray(o.prefix, from_craft_descriptor(o.body)),
Value::Reference(items) => DValue::Reference(items.into_iter().map(from_craft_ref).collect()),
}
}
fn from_craft_ref(it: craft_psd::descriptor::ReferenceItem) -> RefItem {
use craft_psd::descriptor::ReferenceItem;
match it {
ReferenceItem::Property { class, key } => RefItem::Property(id_str(&class.class_id), id_str(&key)),
ReferenceItem::Class(c) => RefItem::Class(id_str(&c.class_id)),
ReferenceItem::Enumerated { class, type_id, value } => RefItem::Enum(id_str(&class.class_id), id_str(&type_id), id_str(&value)),
ReferenceItem::Offset { class, offset } => RefItem::Offset(id_str(&class.class_id), offset),
ReferenceItem::Identifier { id, .. } => RefItem::Identifier(id as i32),
ReferenceItem::Index { index, .. } => RefItem::Index(index as i32),
ReferenceItem::Name { class, name } => RefItem::Name(id_str(&class.class_id), name.to_string_lossy()),
}
Ok(match ty {
b"Objc" | b"GlbO" => DValue::Descriptor(read_descriptor_at(r, depth + 1)?),
b"VlLs" => {
let n = r.u32()? as usize;
if n > 1_000_000 {
return Err(Error::Invalid("descriptor list length".into()));
}
let mut v = Vec::with_capacity(n.min(256));
for _ in 0..n {
let t = r.tag()?;
v.push(read_value(r, &t, depth + 1)?);
}
DValue::List(v)
}
b"ObAr" => {
let n = r.u32()?;
DValue::ObjectArray(n, read_descriptor_at(r, depth + 1)?)
}
b"doub" => DValue::Double(r.f64_finite()?),
b"UntF" => {
let unit = String::from_utf8_lossy(&r.tag()?).into_owned();
DValue::UnitFloat(unit, r.f64_finite()?)
}
b"UnFl" => {
let unit = String::from_utf8_lossy(&r.tag()?).into_owned();
let n = r.u32()? as usize;
let mut v = Vec::with_capacity(n.min(1024));
for _ in 0..n {
v.push(r.f64_finite()?);
}
DValue::UnitFloats(unit, v)
}
b"TEXT" => DValue::Text(read_unicode(r)?),
b"enum" => {
let t = read_id(r)?;
DValue::Enum(t, read_id(r)?)
}
b"long" => DValue::Integer(r.u32()? as i32),
b"comp" => DValue::LargeInteger(r.u64()? as i64),
b"bool" => DValue::Bool(r.u8()? != 0),
b"type" | b"GlbC" => {
let name = read_unicode(r)?;
DValue::Class(name, read_id(r)?)
}
b"alis" | b"tdta" | b"Pth " => {
let n = r.u32()? as usize;
DValue::Raw(r.bytes(n)?.to_vec())
}
b"obj " => {
let n = r.u32()? as usize;
let mut items = Vec::with_capacity(n.min(16));
for _ in 0..n {
let t = r.tag()?;
items.push(match &t {
b"prop" => {
let _name = read_unicode(r)?;
let class = read_id(r)?;
RefItem::Property(class, read_id(r)?)
}
b"Clss" => {
let _name = read_unicode(r)?;
RefItem::Class(read_id(r)?)
}
b"Enmr" => {
let _name = read_unicode(r)?;
let class = read_id(r)?;
let ty = read_id(r)?;
RefItem::Enum(class, ty, read_id(r)?)
}
b"rele" => {
let _name = read_unicode(r)?;
let class = read_id(r)?;
RefItem::Offset(class, r.u32()? as i32)
}
b"Idnt" => RefItem::Identifier(r.u32()? as i32),
b"indx" => RefItem::Index(r.u32()? as i32),
b"name" => {
let _name = read_unicode(r)?;
let class = read_id(r)?;
RefItem::Name(class, read_unicode(r)?)
}
other => return Err(Error::Invalid(format!("reference item `{}`", String::from_utf8_lossy(other)))),
});
}
DValue::Reference(items)
}
other => return Err(Error::Invalid(format!("descriptor type `{}`", String::from_utf8_lossy(other)))),
})
}
// ---------------------------------------------------------------- writing
@@ -387,11 +327,16 @@ fn write_value(out: &mut Vec<u8>, v: &DValue) {
out.extend_from_slice(&o.to_be_bytes());
}
RefItem::Identifier(i) => {
// Photoshop stores a class before the id; craft-psd reads it that way.
out.extend_from_slice(b"Idnt");
put_unicode(out, "");
put_id(out, "null");
out.extend_from_slice(&i.to_be_bytes());
}
RefItem::Index(i) => {
out.extend_from_slice(b"indx");
put_unicode(out, "");
put_id(out, "null");
out.extend_from_slice(&i.to_be_bytes());
}
RefItem::Name(c, n) => {
+3 -27
View File
@@ -1,7 +1,5 @@
use super::limits::{Error, Result};
use super::model::{
Adjustment, ChannelInfo, ColorMode, Layer, LayerMask, LinkedFile, MAX_GROUP_DEPTH, Node, Rect, Section, SmartObject, SubPath, TextInfo, VectorMask,
};
use super::model::{Adjustment, ChannelInfo, ColorMode, Layer, LayerMask, LinkedFile, MAX_GROUP_DEPTH, Node, Rect, Section, SubPath, TextInfo, VectorMask};
use super::{Psd, Reader, descriptor, engine_data, placed};
use std::sync::Arc;
@@ -236,32 +234,10 @@ impl Psd {
l.adjustment = Some(Adjustment::Other(String::from_utf8_lossy(key).into_owned()));
}
b"SoLd" | b"SoLE" => {
let _id = r.tag()?;
let _ver = r.u32()?;
let _dver = r.u32()?;
let d = descriptor::read_descriptor(&mut r)?;
let uuid = d.text("Idnt").unwrap_or_default().to_string();
let t = placed::eight(&d, "Trnf").unwrap_or([0.0; 8]);
// The non-affine transform when present (perspective), else the transform.
let t = placed::eight(&d, "nonAffineTransform").unwrap_or(t);
let size = d.obj("Sz ").and_then(|s| Some([s.num("Wdth")?, s.num("Hght")?]));
let warp = d.obj("warp").and_then(placed::Warp::read);
l.smart_object = Some(SmartObject { uuid, quad: placed::quad_from(t), size, warp });
l.smart_object = Some(placed::from_craft_smart(craft_psd::smart::SmartObject::from_placed_layer_data(b).map_err(|e| error(&e))?));
}
b"PlLd" if l.smart_object.is_none() => {
let _id = r.tag()?;
let _ver = r.u32()?;
let n = r.u8()? as usize;
let uuid = String::from_utf8_lossy(r.bytes(n)?).into_owned();
let _page = r.u32()?;
let _pages = r.u32()?;
let _aa = r.u32()?;
let _ty = r.u32()?;
let mut t = [0.0; 8];
for v in &mut t {
*v = r.f64_finite()?;
}
l.smart_object = Some(SmartObject { uuid, quad: placed::quad_from(t), size: None, warp: None });
l.smart_object = Some(placed::from_craft_smart(craft_psd::smart::SmartObject::from_placed_layer(b).map_err(|e| error(&e))?));
}
b"vmsk" | b"vsms" => {
let _ver = r.u32()?;
+37 -112
View File
@@ -14,14 +14,7 @@ use crate::{Pixels, SmartObject};
/// The most pixels a baked smart object may have: 2^24 (256 MiB as float RGBA). The size comes
/// from the file's transform, which is untrusted.
pub const MAX_BAKE_PIXELS: u64 = 1 << 24;
/// The bake's rasterising budget, in bounding-box pixels visited over all mesh triangles, as a
/// multiple of the output pixel count. A sane warp visits about 2× the output; a hostile mesh
/// that makes every triangle cover the whole output would visit thousands of times more.
const BAKE_WORK_FACTOR: u64 = 8;
/// The smallest budget, so tiny outputs are never refused for rounding at the triangle edges.
const MIN_BAKE_WORK: u64 = 1 << 20;
pub const MAX_BAKE_PIXELS: u64 = craft_psd::smart::MAX_BAKE_PIXELS;
/// A placed layer's warp.
#[derive(Clone, Debug, Default, PartialEq)]
@@ -61,14 +54,40 @@ pub(crate) fn floats(v: Option<&DValue>) -> Vec<f64> {
}
}
/// The eight numbers of a transform entry (`Trnf`, `nonAffineTransform`), when it has exactly eight.
pub(crate) fn eight(d: &Descriptor, key: &str) -> Option<[f64; 8]> {
floats(d.get(key)).try_into().ok()
pub(crate) fn from_craft_smart(s: craft_psd::smart::SmartObject) -> SmartObject {
SmartObject { uuid: s.uuid, quad: s.quad, size: s.size, warp: s.warp.map(from_craft_warp) }
}
/// The corner quad (top-left, top-right, bottom-right, bottom-left) from x0 y0 … x3 y3.
pub(crate) fn quad_from(t: [f64; 8]) -> [[f64; 2]; 4] {
[[t[0], t[1]], [t[2], t[3]], [t[4], t[5]], [t[6], t[7]]]
fn from_craft_warp(w: craft_psd::smart::Warp) -> Warp {
Warp {
style: w.style,
bend: w.bend,
horizontal: w.horizontal,
vertical: w.vertical,
rotate_vertical: w.rotate_vertical,
bounds: w.bounds,
cols: w.cols,
rows: w.rows,
mesh: w.mesh,
}
}
fn to_craft_smart(s: &SmartObject) -> craft_psd::smart::SmartObject {
craft_psd::smart::SmartObject { uuid: s.uuid.clone(), quad: s.quad, size: s.size, warp: s.warp.as_ref().map(to_craft_warp) }
}
fn to_craft_warp(w: &Warp) -> craft_psd::smart::Warp {
craft_psd::smart::Warp {
style: w.style.clone(),
bend: w.bend,
horizontal: w.horizontal,
vertical: w.vertical,
rotate_vertical: w.rotate_vertical,
bounds: w.bounds,
cols: w.cols,
rows: w.rows,
mesh: w.mesh.clone(),
}
}
impl Warp {
@@ -313,105 +332,11 @@ impl SmartObject {
/// `k` pixels per document pixel (into `size` pixels when given; see [`Self::placed_size`]).
/// Returns the pixels and their document-space origin. `None` when the content is empty or
/// the baked image would exceed [`MAX_BAKE_PIXELS`] or the mesh needs more rasterising work than
/// the budget allows (see [`BAKE_WORK_FACTOR`]).
/// the budget allows.
pub fn render_placed(&self, content: &Pixels, k: f64, size: Option<(u32, u32)>) -> Option<(Pixels, [f64; 2])> {
let (cw, ch) = (content.width as f64, content.height as f64);
if content.width == 0 || content.height == 0 {
return None;
}
// The quad is solved once for the bounds, the size and the whole grid.
let m = square_to_quad(self.quad);
let bb = self.bounds_with(&m, cw, ch);
let (ow, oh) = match size {
Some((w, h)) => (w.max(1), h.max(1)),
None => size_for(bb, k),
};
let (ow, oh) = (ow as usize, oh as usize);
let count = ow.checked_mul(oh).filter(|&c| c as u64 <= MAX_BAKE_PIXELS)?;
// A forward grid, filled triangle by triangle with inverse barycentric sampling.
let n = 48usize;
let mut dst = Vec::with_capacity((n + 1) * (n + 1));
let mut src = Vec::with_capacity((n + 1) * (n + 1));
for j in 0..=n {
for i in 0..=n {
let s = [i as f64 / n as f64 * cw, j as f64 / n as f64 * ch];
let d = self.map_with(&m, s, cw, ch);
dst.push([(d[0] - bb[0]) * k, (d[1] - bb[1]) * k]);
src.push(s);
}
}
let mut out: Vec<[f32; 4]> = Vec::new();
out.try_reserve_exact(count).ok()?;
out.resize(count, [0.0; 4]);
let sample = |x: f64, y: f64| -> [f32; 4] {
let (fx, fy) = ((x - 0.5).clamp(0.0, cw - 1.0), (y - 0.5).clamp(0.0, ch - 1.0));
let (x0, y0) = (fx.floor() as usize, fy.floor() as usize);
let (x1, y1) = ((x0 + 1).min(content.width as usize - 1), (y0 + 1).min(content.height as usize - 1));
let (a, b) = ((fx - x0 as f64) as f32, (fy - y0 as f64) as f32);
let at = |x: usize, y: usize| {
let p = content.data[y * content.width as usize + x];
[p[0] * p[3], p[1] * p[3], p[2] * p[3], p[3]]
};
let (p00, p10, p01, p11) = (at(x0, y0), at(x1, y0), at(x0, y1), at(x1, y1));
let mut o = [0.0; 4];
for c in 0..4 {
o[c] = (p00[c] * (1.0 - a) + p10[c] * a) * (1.0 - b) + (p01[c] * (1.0 - a) + p11[c] * a) * b;
}
o
};
let idx = |i: usize, j: usize| j * (n + 1) + i;
// A sane mesh's triangles each span about one grid cell (ow/n by oh/n), rounded out to
// whole pixels. A thin output (16384×1) stacks every grid row onto the same pixel row, so
// allow each of the 2n² triangles about two cells' extent along each axis, with margin.
let rounding = (4 * n as u64).saturating_mul((ow as u64).saturating_add(oh as u64).saturating_add(n as u64));
let budget = (count as u64).saturating_mul(BAKE_WORK_FACTOR).max(MIN_BAKE_WORK).saturating_add(rounding);
let mut work = 0u64;
for j in 0..n {
for i in 0..n {
for tri in [[idx(i, j), idx(i + 1, j), idx(i + 1, j + 1)], [idx(i, j), idx(i + 1, j + 1), idx(i, j + 1)]] {
let [a, b, c] = tri.map(|t| dst[t]);
let den = (b[1] - c[1]) * (a[0] - c[0]) + (c[0] - b[0]) * (a[1] - c[1]);
if den.abs() < 1e-12 {
continue;
}
// Loop-invariant per triangle: the source corners and the barycentric coefficients.
let [sa, sb, sc] = tri.map(|t| src[t]);
let (l1y, l1x) = (b[1] - c[1], c[0] - b[0]);
let (l2y, l2x) = (c[1] - a[1], a[0] - c[0]);
let x0 = a[0].min(b[0]).min(c[0]).floor().max(0.0) as usize;
let x1 = (a[0].max(b[0]).max(c[0]).ceil() as usize).min(ow);
let y0 = a[1].min(b[1]).min(c[1]).floor().max(0.0) as usize;
let y1 = (a[1].max(b[1]).max(c[1]).ceil() as usize).min(oh);
work = work.saturating_add((x1.saturating_sub(x0) as u64).saturating_mul(y1.saturating_sub(y0) as u64));
if work > budget {
return None;
}
for y in y0..y1 {
for x in x0..x1 {
let (px, py) = (x as f64 + 0.5, y as f64 + 0.5);
let l1 = (l1y * (px - c[0]) + l1x * (py - c[1])) / den;
let l2 = (l2y * (px - c[0]) + l2x * (py - c[1])) / den;
let l3 = 1.0 - l1 - l2;
if l1 < -1e-9 || l2 < -1e-9 || l3 < -1e-9 {
continue;
}
let sx = sa[0] * l1 + sb[0] * l2 + sc[0] * l3;
let sy = sa[1] * l1 + sb[1] * l2 + sc[1] * l3;
out[y * ow + x] = sample(sx, sy);
}
}
}
}
}
// Back to straight alpha.
for p in &mut out {
if p[3] > 0.0 {
for c in 0..3 {
p[c] /= p[3];
}
}
}
Some((Pixels { width: ow as u32, height: oh as u32, data: out }, [bb[0], bb[1]]))
let img = craft_psd::FloatImage { width: content.width, height: content.height, data: content.data.clone() };
let (out, origin) = to_craft_smart(self).render_placed(&img, k, size)?;
Some((Pixels { width: out.width, height: out.height, data: out.data }, origin))
}
}
+3 -3
View File
@@ -641,11 +641,11 @@ fn placed_bake_solves_the_quad_once() {
assert_eq!(counters::take(&QUAD), 1, "33×33 mapped points, one solve (was 1089)");
so.placed_size(20.0, 10.0, 1.0);
assert_eq!(counters::take(&QUAD), 1);
// The bounds, the size and the 49×49 grid of one bake share a single solve (was 1089 × 2 + 2401).
// The bake itself runs in craft-psd, so it no longer bumps this crate's quad counter.
so.render_placed(&content(20, 10), 1.0, None).unwrap();
assert_eq!(counters::take(&QUAD), 1);
assert_eq!(counters::take(&QUAD), 0);
so.render_placed(&content(20, 10), 1.0, Some((40, 40))).unwrap();
assert_eq!(counters::take(&QUAD), 1);
assert_eq!(counters::take(&QUAD), 0);
// A single `map` still solves for itself.
so.map([1.0, 1.0], 20.0, 10.0);
assert_eq!(counters::take(&QUAD), 1);