Merge branch 'main' into refactor/interchange-shared-preflight

This commit is contained in:
Dylan M. Taylor
2026-11-16 13:15:45 -05:00
committed by GitHub
11 changed files with 727 additions and 532 deletions
Generated
+19 -19
View File
@@ -1519,7 +1519,7 @@ dependencies = [
[[package]]
name = "craft-psd"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87"
source = "git+https://github.com/storytold/craft-libs?rev=ce2ec507c2e6a6a078a5f450f641487f8931816d#ce2ec507c2e6a6a078a5f450f641487f8931816d"
dependencies = [
"encoding_rs",
"flate2",
@@ -1541,9 +1541,9 @@ dependencies = [
[[package]]
name = "craft-raw"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=402dfe46ad568a97f660bcbe30e3a80429b9e1fe#402dfe46ad568a97f660bcbe30e3a80429b9e1fe"
source = "git+https://github.com/storytold/craft-libs?rev=bea91b1861eea3889bec9d26338076f2ff31c4ac#bea91b1861eea3889bec9d26338076f2ff31c4ac"
dependencies = [
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=402dfe46ad568a97f660bcbe30e3a80429b9e1fe)",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bea91b1861eea3889bec9d26338076f2ff31c4ac)",
"miniz_oxide 0.9.1",
"rayon",
"serde",
@@ -1579,7 +1579,7 @@ dependencies = [
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=402dfe46ad568a97f660bcbe30e3a80429b9e1fe#402dfe46ad568a97f660bcbe30e3a80429b9e1fe"
source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -1588,7 +1588,7 @@ dependencies = [
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87"
source = "git+https://github.com/storytold/craft-libs?rev=bea91b1861eea3889bec9d26338076f2ff31c4ac#bea91b1861eea3889bec9d26338076f2ff31c4ac"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -3020,7 +3020,7 @@ dependencies = [
[[package]]
name = "filmcraft-bitstream"
version = "0.20.1"
source = "git+https://github.com/storytold/filmcraft?rev=6e561687f0efc9a674c4bfb1c8251da178d1fb55#6e561687f0efc9a674c4bfb1c8251da178d1fb55"
source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c"
dependencies = [
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)",
]
@@ -3028,7 +3028,7 @@ dependencies = [
[[package]]
name = "filmcraft-cfb"
version = "0.20.1"
source = "git+https://github.com/storytold/filmcraft?rev=6e561687f0efc9a674c4bfb1c8251da178d1fb55#6e561687f0efc9a674c4bfb1c8251da178d1fb55"
source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c"
dependencies = [
"craft-cfb 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7f3fdc0dfebd03f33a241f91f916e9a78d3e5c93)",
]
@@ -3036,7 +3036,7 @@ dependencies = [
[[package]]
name = "filmcraft-codecs"
version = "0.20.1"
source = "git+https://github.com/storytold/filmcraft?rev=6e561687f0efc9a674c4bfb1c8251da178d1fb55#6e561687f0efc9a674c4bfb1c8251da178d1fb55"
source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c"
dependencies = [
"craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)",
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=937ac93c5cf3cd4b6a81e195b078fe161eb081b9)",
@@ -3060,7 +3060,7 @@ dependencies = [
[[package]]
name = "filmcraft-color"
version = "0.20.1"
source = "git+https://github.com/storytold/filmcraft?rev=6e561687f0efc9a674c4bfb1c8251da178d1fb55#6e561687f0efc9a674c4bfb1c8251da178d1fb55"
source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c"
dependencies = [
"serde",
]
@@ -3068,10 +3068,10 @@ dependencies = [
[[package]]
name = "filmcraft-dng"
version = "0.20.1"
source = "git+https://github.com/storytold/filmcraft?rev=6e561687f0efc9a674c4bfb1c8251da178d1fb55#6e561687f0efc9a674c4bfb1c8251da178d1fb55"
source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c"
dependencies = [
"craft-raw",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=402dfe46ad568a97f660bcbe30e3a80429b9e1fe)",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bea91b1861eea3889bec9d26338076f2ff31c4ac)",
"image",
"rayon",
"thiserror 2.0.21",
@@ -3080,7 +3080,7 @@ dependencies = [
[[package]]
name = "filmcraft-frame"
version = "0.20.1"
source = "git+https://github.com/storytold/filmcraft?rev=6e561687f0efc9a674c4bfb1c8251da178d1fb55#6e561687f0efc9a674c4bfb1c8251da178d1fb55"
source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c"
dependencies = [
"filmcraft-color",
"filmcraft-time",
@@ -3091,7 +3091,7 @@ dependencies = [
[[package]]
name = "filmcraft-geom"
version = "0.20.1"
source = "git+https://github.com/storytold/filmcraft?rev=6e561687f0efc9a674c4bfb1c8251da178d1fb55#6e561687f0efc9a674c4bfb1c8251da178d1fb55"
source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c"
dependencies = [
"serde",
]
@@ -3099,7 +3099,7 @@ dependencies = [
[[package]]
name = "filmcraft-interchange"
version = "0.20.1"
source = "git+https://github.com/storytold/filmcraft?rev=6e561687f0efc9a674c4bfb1c8251da178d1fb55#6e561687f0efc9a674c4bfb1c8251da178d1fb55"
source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c"
dependencies = [
"craft-aaf",
"craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)",
@@ -3118,7 +3118,7 @@ dependencies = [
[[package]]
name = "filmcraft-isobmff"
version = "0.20.1"
source = "git+https://github.com/storytold/filmcraft?rev=6e561687f0efc9a674c4bfb1c8251da178d1fb55#6e561687f0efc9a674c4bfb1c8251da178d1fb55"
source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c"
dependencies = [
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)",
]
@@ -3126,7 +3126,7 @@ dependencies = [
[[package]]
name = "filmcraft-matroska"
version = "0.20.1"
source = "git+https://github.com/storytold/filmcraft?rev=6e561687f0efc9a674c4bfb1c8251da178d1fb55#6e561687f0efc9a674c4bfb1c8251da178d1fb55"
source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c"
dependencies = [
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)",
]
@@ -3134,7 +3134,7 @@ dependencies = [
[[package]]
name = "filmcraft-media"
version = "0.20.1"
source = "git+https://github.com/storytold/filmcraft?rev=6e561687f0efc9a674c4bfb1c8251da178d1fb55#6e561687f0efc9a674c4bfb1c8251da178d1fb55"
source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c"
dependencies = [
"craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)",
"craft-dpx 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)",
@@ -3153,7 +3153,7 @@ dependencies = [
[[package]]
name = "filmcraft-project"
version = "0.20.1"
source = "git+https://github.com/storytold/filmcraft?rev=6e561687f0efc9a674c4bfb1c8251da178d1fb55#6e561687f0efc9a674c4bfb1c8251da178d1fb55"
source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c"
dependencies = [
"filmcraft-color",
"filmcraft-geom",
@@ -3168,7 +3168,7 @@ dependencies = [
[[package]]
name = "filmcraft-time"
version = "0.20.1"
source = "git+https://github.com/storytold/filmcraft?rev=6e561687f0efc9a674c4bfb1c8251da178d1fb55#6e561687f0efc9a674c4bfb1c8251da178d1fb55"
source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c"
dependencies = [
"craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=57288edafdc45552e30481cc649021de446abfa0)",
]
+9 -9
View File
@@ -21,7 +21,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 = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ce2ec507c2e6a6a078a5f450f641487f8931816d" }
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" }
@@ -99,15 +99,15 @@ craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-lib
# footage decoding: FilmCraft's pure-Rust crates, pinned to a revision (plan/adr/0001).
# Only `crates/media`, `crates/export` and `crates/interchange` may depend on these.
filmcraft-codecs = { git = "https://github.com/storytold/filmcraft", rev = "6e561687f0efc9a674c4bfb1c8251da178d1fb55" }
filmcraft-media = { git = "https://github.com/storytold/filmcraft", rev = "6e561687f0efc9a674c4bfb1c8251da178d1fb55" }
filmcraft-frame = { git = "https://github.com/storytold/filmcraft", rev = "6e561687f0efc9a674c4bfb1c8251da178d1fb55" }
filmcraft-color = { git = "https://github.com/storytold/filmcraft", rev = "6e561687f0efc9a674c4bfb1c8251da178d1fb55" }
filmcraft-time = { git = "https://github.com/storytold/filmcraft", rev = "6e561687f0efc9a674c4bfb1c8251da178d1fb55" }
filmcraft-codecs = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" }
filmcraft-media = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" }
filmcraft-frame = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" }
filmcraft-color = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" }
filmcraft-time = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" }
# timeline interchange (EDL, FCP7 XML, FCPXML, OTIO) for Premiere Pro interop (crates/interchange only)
filmcraft-interchange = { git = "https://github.com/storytold/filmcraft", rev = "6e561687f0efc9a674c4bfb1c8251da178d1fb55" }
filmcraft-project = { git = "https://github.com/storytold/filmcraft", rev = "6e561687f0efc9a674c4bfb1c8251da178d1fb55" }
filmcraft-geom = { git = "https://github.com/storytold/filmcraft", rev = "6e561687f0efc9a674c4bfb1c8251da178d1fb55" }
filmcraft-interchange = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" }
filmcraft-project = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" }
filmcraft-geom = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" }
# gpu (the same wgpu eframe / egui-wgpu use)
wgpu = { version = "30.0.1", features = ["fragile-send-sync-non-atomic-wasm"] }
+3
View File
@@ -12,3 +12,6 @@ workspace = true
[dependencies]
craft-psd = { workspace = true }
miniz_oxide = "0.9"
[dev-dependencies]
craft-psd = { workspace = true, features = ["testgen"] }
+2 -3
View File
@@ -1,8 +1,8 @@
//! Photoshop document (PSD / PSB) reader, implemented from Adobe's public *Photoshop File Formats
//! Specification* (see README.md), and a minimal writer ([`mod@write`]) for fixtures.
//!
//! [`Psd::parse`] reads the structure (header, layer records and their additional information,
//! the layer tree) without decoding pixels; [`Psd::composite`] decodes the merged image and
//! [`Psd::parse`] reads the structure with `craft_psd` (header, layer records and their
//! additional information, the layer tree) without decoding pixels; [`Psd::composite`] decodes the merged image and
//! [`Psd::layer_pixels`] one layer (with its layer mask applied to alpha) on demand. Pixels come
//! out as straight (unpremultiplied) RGBA `f32` in 0..1, display-encoded (32-bit documents,
//! which are linear, are encoded to sRGB).
@@ -32,7 +32,6 @@ pub use model::{
Adjustment, ChannelInfo, ColorMode, Layer, LayerMask, LinkedFile, MAX_GROUP_DEPTH, Node, Pixels, Rect, Section, SmartObject, SubPath, TextInfo, VectorMask,
};
pub use parse::is_psd;
pub(crate) use pixels::pack_bits;
#[cfg(test)]
use pixels::{lab_to_rgb, srgb_encode, unpack_bits};
+249 -229
View File
@@ -11,102 +11,114 @@ pub fn is_psd(bytes: &[u8]) -> bool {
}
impl Psd {
/// Reads the structure with [`craft_psd::PsdFile::from_source`]: header, colour mode data,
/// layer records with their additional information and the global blocks. Channel data and
/// the merged image stay in `data` (as ranges), decoded on demand.
pub fn parse(data: impl Into<Arc<[u8]>>) -> Result<Psd> {
let data: Arc<[u8]> = data.into();
let mut r = Reader::new(&data);
if r.bytes(4).ok() != Some(b"8BPS") {
if !is_psd(&data) {
return Err(Error::NotPsd);
}
let version = r.u16()?;
let psb = match version {
1 => false,
2 => true,
_ => return Err(Error::NotPsd),
let (read, splice) = read_file(&data);
let (head, file, warnings) = match read {
Ok(file) => {
// The compression field before the merged image's data.
let merged = file.image_data.stored.as_ref().map_or(data.len(), |s| (splice.map(s.offset) as usize).saturating_sub(2));
((file.header.clone(), file.color_mode_data.clone(), merged), Some(file), vec![])
}
// A damaged layer section must not discard the document: keep the header and the
// merged image, drop the layers and say so. Without a merged image there is nothing to
// fall back to, so the original error stands.
Err(e) => match flattened(&data) {
Some(head) => (head, None, vec![format!("Layers could not be read ({}); only the flattened image is available", error(&e))]),
None => return Err(error(&e)),
},
};
r.skip(6)?;
let channels = r.u16()?;
let height = r.u32()?;
let width = r.u32()?;
let depth = r.u16()?;
let mode_v = r.u16()?;
let (h, palette, merged_offset) = head;
let mode_v = h.color_mode.as_u16();
let mode = ColorMode::from_u16(mode_v).ok_or_else(|| Error::Unsupported(format!("colour mode {mode_v}")))?;
if !matches!(depth, 1 | 8 | 16 | 32) {
return Err(Error::Unsupported(format!("{depth}-bit")));
if !matches!(h.depth, 1 | 8 | 16 | 32) {
return Err(Error::Unsupported(format!("{}-bit", h.depth)));
}
if width == 0 || height == 0 || width > 300_000 || height > 300_000 {
return Err(Error::Invalid(format!("size {width}x{height}")));
if h.width == 0 || h.height == 0 || h.width > 300_000 || h.height > 300_000 {
return Err(Error::Invalid(format!("size {}x{}", h.width, h.height)));
}
// Colour mode data.
let n = r.u32()? as usize;
let palette = r.bytes(n)?.to_vec();
// Image resources.
let n = r.u32()? as usize;
r.skip(n)?;
// Layer and mask information.
let mut psd = Psd {
psb,
width,
height,
channels,
depth,
psb: h.version.is_psb(),
width: h.width,
height: h.height,
channels: h.channels,
depth: h.depth,
mode,
layers: vec![],
merged_alpha: false,
palette,
linked: vec![],
warnings: vec![],
warnings,
data: data.clone(),
merged_offset: 0,
merged_offset,
};
let lm_len = r.length(psb)?;
let lm_end = r.pos.checked_add(lm_len).filter(|&e| e <= data.len()).ok_or(Error::Truncated)?;
if lm_len > 0 {
let li_len = r.length(psb)?;
let li_end = r.pos.checked_add(li_len).filter(|&e| e <= lm_end).ok_or(Error::Truncated)?;
if li_len > 0
&& let Err(e) = psd.layer_info(&data, r.pos, li_end)
{
// A damaged layer section must not discard the document: keep the header and the
// merged image, drop the layers and say so. Without a merged image there is
// nothing to fall back to, so the original error stands.
if lm_end.checked_add(2).is_none_or(|n| n > data.len()) {
return Err(e);
}
psd.layers.clear();
psd.warnings.push(format!("Layers could not be read ({e}); only the flattened image is available"));
}
r.pos = li_end;
if r.pos + 4 <= lm_end {
let g = r.u32()? as usize;
r.pos = (r.pos + g).min(lm_end);
}
// Global additional layer information (16/32-bit layer info lives here).
while let Some((key, start, end)) = next_block(&data, &mut r.pos, lm_end, psb) {
if matches!(&key, b"lnk2" | b"lnkD" | b"lnk3" | b"lnkE") {
psd.linked_files(&data, start, end);
}
if matches!(&key, b"Lr16" | b"Lr32" | b"Layr") && psd.layers.is_empty() && end > start {
// The block holds the layer info, normally without its length field; accept
// both layouts.
if psd.layer_info(&data, start, end).is_err() || psd.layers.is_empty() {
psd.layers.clear();
let skip = if psb { 8 } else { 4 };
if start + skip < end && psd.layer_info(&data, start + skip, end).is_err() {
psd.layers.clear();
}
}
}
r.pos = end;
let Some(file) = file else {
psd.merged_alpha = section_merged_alpha(&data);
return Ok(psd);
};
if let Some((block, e)) = file.unreadable_layer_block() {
// A 16/32-bit file's layers live in a global block; when it is damaged the file reads
// as flattened. Its layer count still says whether the merged image has alpha.
psd.merged_alpha = block.data.get(..2).is_some_and(|c| i16::from_be_bytes([c[0], c[1]]) < 0);
psd.warnings.push(format!("Layers could not be read ({}); only the flattened image is available", error(&e)));
}
if let Some(info) = &file.layer_info {
psd.merged_alpha = info.merged_alpha;
psd.layers = info.layers.iter().enumerate().map(|(i, rec)| psd.layer(rec, i, splice)).collect();
}
for b in &file.global_blocks {
if let Some(stored) = b.stored.as_ref().filter(|_| linked(&b.key, 0)) {
let start = splice.map(stored.offset) as usize;
psd.linked_files(&data, start, start.saturating_add(stored.len as usize).min(data.len()));
}
}
if !psd.layers.is_empty() {
// A 16/32-bit layer block recovered the layers.
psd.warnings.clear();
}
psd.merged_offset = lm_end;
Ok(psd)
}
/// One layer record of the model, its additional information read into [`Layer`].
/// `splice` maps craft-psd's offsets back into `self.data` (see [`read_file`]).
fn layer(&self, rec: &craft_psd::LayerRecord, index: usize, splice: Splice) -> Layer {
let channels = rec
.channels
.iter()
.map(|c| match &c.stored {
// `ChannelInfo` covers the compression field and the data after it.
Some(s) => ChannelInfo { id: c.id, offset: (splice.map(s.offset) as usize).saturating_sub(2), len: s.len as usize + 2 },
None => ChannelInfo { id: c.id, offset: 0, len: 0 },
})
.collect();
let r = rec.rect;
let mut l = Layer {
index,
rect: Rect { top: r.top, left: r.left, bottom: r.bottom, right: r.right },
blend: rec.blend_mode.key(),
opacity: rec.opacity,
fill_opacity: 255,
clipping: rec.clipping != 0,
hidden: rec.flags.hidden(),
protect_transparency: rec.flags.transparency_protected(),
channels,
name: mac_roman_string(&rec.name),
..Default::default()
};
if let craft_psd::MaskData::Mask(m) = &rec.mask {
let rect = Rect { top: m.rect.top, left: m.rect.left, bottom: m.rect.bottom, right: m.rect.right };
l.mask = Some(LayerMask { rect, default_color: m.default_color, disabled: m.flags & 2 != 0, inverted: m.flags & 4 != 0 });
}
for b in &rec.blocks {
l.keys.push(b.key);
// A malformed block only loses that block's information.
let _ = self.layer_block(&mut l, &b.key, &b.data);
}
l
}
/// The embedded bytes of linked file `uuid`.
pub fn linked_data(&self, uuid: &str) -> Option<&[u8]> {
let f = self.linked.iter().find(|f| f.uuid == uuid)?;
@@ -116,140 +128,15 @@ impl Psd {
/// Linked layer data records (spec: "Linked Layer"): length, kind (`liFD` embedded data,
/// `liFE` external file, `liFA` alias), version, unique id, original file name, type,
/// creator, data length, optional descriptors, then the data. A damaged record ends the list.
/// Ranges in [`LinkedFile::data`] are in the document bytes (`self.data`); craft-psd reports
/// them relative to the block, so the block's start is added back.
fn linked_files(&mut self, data: &[u8], start: usize, end: usize) {
let mut pos = start;
while pos + 8 <= end {
let mut r = Reader::at(&data[..end], pos);
let Ok(len) = r.u64() else { break };
let body = r.pos;
let Some(rec_end) = body.checked_add(len as usize).filter(|e| *e <= end) else { break };
let mut r = Reader::at(&data[..rec_end], body);
let rec = (|| -> Result<LinkedFile> {
let kind = r.tag()?;
let version = r.u32()?;
let n = r.u8()? as usize;
let uuid = String::from_utf8_lossy(r.bytes(n)?).into_owned();
let name = descriptor::read_unicode(&mut r)?;
let file_type = String::from_utf8_lossy(&r.tag()?).trim().to_string();
let _creator = r.tag()?;
let dlen = r.u64()? as usize;
if r.u8()? != 0 {
let _v = r.u32()?;
descriptor::read_descriptor(&mut r)?;
}
let mut out = LinkedFile { uuid, name, file_type, data: None };
match &kind {
b"liFD" => {
let s = r.pos;
r.skip(dlen)?;
out.data = Some(s..s + dlen);
}
b"liFE" => {
let _v = r.u32()?;
descriptor::read_descriptor(&mut r)?;
if version > 3 {
r.skip(4 + 4 + 8)?;
}
let _size = r.u64()?;
if version > 2 && r.remaining() >= dlen && dlen > 0 {
let s = r.pos;
out.data = Some(s..s + dlen);
}
}
_ => {}
}
Ok(out)
})();
match rec {
Ok(f) => self.linked.push(f),
Err(_) => break,
}
pos = rec_end.div_ceil(4) * 4;
let Some(block) = data.get(start..end) else { return };
for f in craft_psd::smart::linked_files(block) {
self.linked.push(LinkedFile { uuid: f.uuid, name: f.name, file_type: f.file_type, data: f.data.map(|r| (start + r.start)..(start + r.end)) });
}
}
fn layer_info(&mut self, data: &[u8], start: usize, end: usize) -> Result<()> {
let mut r = Reader::at(&data[..end], start);
let count = r.i16()?;
self.merged_alpha = count < 0;
let n = count.unsigned_abs() as usize;
let mut layers = Vec::with_capacity(n);
for i in 0..n {
layers.push(self.layer_record(&mut r, i)?);
}
// Channel image data follows in record order.
for l in &mut layers {
for c in &mut l.channels {
c.offset = r.pos;
r.skip(c.len)?;
}
}
self.layers = layers;
Ok(())
}
fn layer_record(&self, r: &mut Reader, index: usize) -> Result<Layer> {
let psb = self.psb;
let (top, left, bottom, right) = (r.i32()?, r.i32()?, r.i32()?, r.i32()?);
let nch = r.u16()? as usize;
if nch > 64 {
return Err(Error::Invalid("channel count".into()));
}
let mut channels = Vec::with_capacity(nch);
for _ in 0..nch {
let id = r.i16()?;
let len = r.length(psb)?;
channels.push(ChannelInfo { id, offset: 0, len });
}
if r.bytes(4)? != b"8BIM" {
return Err(Error::Invalid("layer record signature".into()));
}
let blend = r.tag()?;
let opacity = r.u8()?;
let clipping = r.u8()? != 0;
let flags = r.u8()?;
r.skip(1)?;
let extra = r.u32()? as usize;
let extra_end = r.pos.checked_add(extra).filter(|&e| e <= r.data.len()).ok_or(Error::Truncated)?;
let mut l = Layer {
index,
rect: Rect { top, left, bottom, right },
blend,
opacity,
fill_opacity: 255,
clipping,
hidden: flags & 2 != 0,
protect_transparency: flags & 1 != 0,
channels,
..Default::default()
};
// Layer mask data.
let mlen = r.u32()? as usize;
let mstart = r.pos;
if mlen >= 18 {
let rect = Rect { top: r.i32()?, left: r.i32()?, bottom: r.i32()?, right: r.i32()? };
let default_color = r.u8()?;
let mflags = r.u8()?;
l.mask = Some(LayerMask { rect, default_color, disabled: mflags & 2 != 0, inverted: mflags & 4 != 0 });
}
r.pos = mstart + mlen;
// Blending ranges.
let blen = r.u32()? as usize;
r.skip(blen)?;
l.name = r.pascal(4)?;
let mut pos = r.pos;
let data = r.data;
while let Some((key, start, end)) = next_block(data, &mut pos, extra_end, psb) {
l.keys.push(key);
let block = &data[start..end];
// A malformed block only loses that block's information.
let _ = self.layer_block(&mut l, &key, block);
pos = end;
}
r.pos = extra_end;
Ok(l)
}
fn layer_block(&self, l: &mut Layer, key: &[u8; 4], b: &[u8]) -> Result<()> {
let mut r = Reader::new(b);
match key {
@@ -482,33 +369,166 @@ impl Psd {
}
}
/// The next additional-information block at `*pos` (signature `8BIM`/`8B64`, key, length):
/// returns (key, data start, data end). Skips up to 3 padding bytes before a signature.
fn next_block(data: &[u8], pos: &mut usize, end: usize, psb: bool) -> Option<([u8; 4], usize, usize)> {
let mut p = *pos;
for _ in 0..4 {
if p + 12 > end {
return None;
/// The header, colour mode data and merged image offset of a document whose layer and mask
/// section cannot be read: `None` when the merged image cannot be reached either.
fn flattened(data: &[u8]) -> Option<(craft_psd::Header, Vec<u8>, usize)> {
let head = craft_psd::head::HeadView::from_bytes(data).ok()?;
let at = usize::try_from(head.layer_section_offset).ok()?;
let len = if head.header.version.is_psb() {
u64::from_be_bytes(data.get(at..at + 8)?.try_into().ok()?)
} else {
u64::from(u32::from_be_bytes(data.get(at..at + 4)?.try_into().ok()?))
};
let field = if head.header.version.is_psb() { 8 } else { 4 };
let merged = at.checked_add(field)?.checked_add(usize::try_from(len).ok()?)?;
(merged.checked_add(2)? <= data.len()).then(|| (head.header.clone(), head.color_mode_data.to_vec(), merged))
}
/// Linked-file blocks can be most of a file: leave them in the source, read in place.
fn linked(key: &[u8; 4], _len: u64) -> bool {
craft_psd::smart::is_linked_layer_key(key)
}
/// Reads `data` with craft-psd. Where that loses what the old reader kept, it reads a copy with
/// the obstacle taken out, and the [`Splice`] maps the copy's offsets back into `data`:
/// - a damaged image resource (resources are not part of the model): no resources;
/// - damaged layer records in the section: none there, so a global `Lr16`/`Lr32`/`Layr` block
/// can still give the layers;
/// - a global layer block that starts with its own length (both layouts are accepted), or
/// that follows up to three stray bytes: the block without them.
fn read_file(data: &Arc<[u8]>) -> (std::result::Result<craft_psd::PsdFile, craft_psd::PsdError>, Splice) {
let read = |d: Arc<[u8]>| craft_psd::PsdFile::from_source_deferring(craft_psd::source::Source::new(d), linked, |_| Ok(false), |_| false).map(|(f, _)| f);
let layered = |f: &craft_psd::PsdFile| f.layer_info.as_ref().is_some_and(|i| !i.layers.is_empty());
let retry = |copy: Option<(Vec<u8>, Splice)>, accept: &dyn Fn(&craft_psd::PsdFile) -> bool| {
let (copy, splice) = copy?;
read(copy.into()).ok().filter(|f| accept(f)).map(|f| (f, splice))
};
let first = read(data.clone());
let got = match &first {
Ok(f) if layered(f) => None,
Ok(_) => retry(prefixed_layer_block(data), &layered),
Err(_) => retry(without_resources(data), &|_| true).or_else(|| retry(without_section_layers(data), &layered)),
};
match got {
Some((file, splice)) => (Ok(file), splice),
None => (first, Splice::default()),
}
}
/// A big-endian unsigned field of `width` bytes at `at`.
fn be(data: &[u8], at: usize, width: usize) -> Option<usize> {
let b = data.get(at..at.checked_add(width)?)?;
usize::try_from(b.iter().fold(0u64, |v, &b| v << 8 | u64::from(b))).ok()
}
/// The length-field width of the layer section and its long blocks.
fn field(data: &[u8]) -> usize {
if data.get(4..6) == Some(&[0, 2]) { 8 } else { 4 }
}
fn without_resources(data: &[u8]) -> Option<(Vec<u8>, Splice)> {
let res_at = be(data, 26, 4)?.checked_add(30)?;
let res_len = be(data, res_at, 4).filter(|&n| n > 0)?;
Splice::apply(data, res_at + 4, res_len, &[(res_at, 4)])
}
fn without_section_layers(data: &[u8]) -> Option<(Vec<u8>, Splice)> {
let head = craft_psd::head::HeadView::from_bytes(data).ok()?;
let ls = usize::try_from(head.layer_section_offset).ok()?;
let w = field(data);
let li_at = ls.checked_add(w)?;
let li_len = be(data, li_at, w).filter(|&n| n > 0)?;
Splice::apply(data, li_at + w, li_len, &[(li_at, w), (ls, w)])
}
/// The global layer block's repair, found by walking the top-level global blocks by their
/// declared lengths (so a linked file's payload is never searched): up to three stray bytes
/// before the first block, or the block's payload starting with its own length.
fn prefixed_layer_block(data: &[u8]) -> Option<(Vec<u8>, Splice)> {
let head = craft_psd::head::HeadView::from_bytes(data).ok()?;
let ls = usize::try_from(head.layer_section_offset).ok()?;
let w = field(data);
let end = be(data, ls, w)?.checked_add(ls + w)?.min(data.len());
let li_at = ls + w;
let gm_at = be(data, li_at, w)?.checked_add(li_at + w)?;
let blocks = be(data, gm_at, 4)?.checked_add(gm_at + 4)?;
let mut pos = blocks;
let is_sig = |i: usize| matches!(data.get(i..i + 4), Some(b"8BIM" | b"8B64"));
// Stray bytes before the first block hide every block from craft-psd.
let mut lead = None;
while pos < end {
let skip = (0..=3).find(|&k| is_sig(pos + k))?;
let at = pos + skip;
// Leading bytes before the first block are recorded before its key is looked at.
if lead.is_none() && pos == blocks && skip > 0 {
lead = Some((pos, skip));
}
if &data[p..p + 4] == b"8BIM" || &data[p..p + 4] == b"8B64" {
break;
let key: [u8; 4] = data.get(at + 4..at + 8)?.try_into().ok()?;
let width = if craft_psd::tagged::uses_long_length(head.header.version, &key) { 8 } else { 4 };
let len = be(data, at + 8, width)?;
let body = at + 8 + width;
if matches!(&key, b"Lr16" | b"Lr32" | b"Layr") {
if let Some((at, n)) = lead {
return Splice::apply(data, at, n, &[(ls, w)]);
}
// The payload's first field reads as a length that fits in it.
be(data, body, w).filter(|&n| n > 0 && n.checked_add(w).is_some_and(|e| e <= len))?;
return Splice::apply(data, body, w, &[(at + 8, width), (ls, w)]);
}
p += 1;
pos = body.checked_add(len)?;
}
None
}
/// A copy of the file with one range taken out, and the way from the copy's offsets back to the
/// original's.
#[derive(Debug, Clone, Copy, Default)]
struct Splice {
at: u64,
removed: u64,
}
impl Splice {
fn map(self, offset: u64) -> u64 {
if offset >= self.at { offset + self.removed } else { offset }
}
if p + 12 > end || !(&data[p..p + 4] == b"8BIM" || &data[p..p + 4] == b"8B64") {
return None;
/// `data` without the `removed` bytes at `at`, the length fields at `fixes` (offset, width;
/// all before `at`) shortened to match.
fn apply(data: &[u8], at: usize, removed: usize, fixes: &[(usize, usize)]) -> Option<(Vec<u8>, Splice)> {
let tail = data.get(at.checked_add(removed)?..)?;
let mut copy = Vec::with_capacity(at + tail.len());
copy.extend_from_slice(data.get(..at)?);
copy.extend_from_slice(tail);
for &(f, width) in fixes {
let v = (be(&copy, f, width)?.checked_sub(removed)? as u64).to_be_bytes();
copy.get_mut(f..f + width)?.copy_from_slice(&v[8 - width..]);
}
Some((copy, Splice { at: at as u64, removed: removed as u64 }))
}
let mut key = [0u8; 4];
key.copy_from_slice(&data[p + 4..p + 8]);
let wide =
psb && matches!(&key, b"LMsk" | b"Lr16" | b"Lr32" | b"Layr" | b"Mt16" | b"Mt32" | b"Mtrn" | b"Alph" | b"FMsk" | b"lnk2" | b"FEid" | b"FXid" | b"PxSD");
let mut r = Reader::at(&data[..end], p + 8);
let len = r.length(wide).ok()?;
let start = r.pos;
let stop = start.checked_add(len)?;
if stop > end {
return None;
}
/// Whether the layer section's (unreadable) layer count is negative, which marks the merged
/// image's first extra channel as its transparency.
fn section_merged_alpha(data: &[u8]) -> bool {
let Ok(head) = craft_psd::head::HeadView::from_bytes(data) else { return false };
let field = if head.header.version.is_psb() { 8 } else { 4 };
let Some(at) = usize::try_from(head.layer_section_offset).ok().and_then(|a| a.checked_add(2 * field)) else { return false };
let has_info = data.get(at - field..at).is_some_and(|l| l.iter().any(|&b| b != 0));
has_info && data.get(at..at + 2).is_some_and(|c| i16::from_be_bytes([c[0], c[1]]) < 0)
}
/// This crate's error for one from craft-psd.
fn error(e: &craft_psd::PsdError) -> Error {
match e {
craft_psd::PsdError::UnexpectedEof { .. } => Error::Truncated,
craft_psd::PsdError::InvalidSignature { .. } | craft_psd::PsdError::UnsupportedVersion(_) => Error::NotPsd,
craft_psd::PsdError::Unsupported(s) => Error::Unsupported(s.clone()),
other => Error::Invalid(other.to_string()),
}
*pos = stop;
Some((key, start, stop))
}
/// A Pascal string's bytes in the system (Mac Roman) encoding; ASCII covers the common case.
fn mac_roman_string(b: &[u8]) -> String {
b.iter().map(|&b| if b < 0x80 { b as char } else { super::read::mac_roman(b) }).collect()
}
+29 -75
View File
@@ -134,46 +134,36 @@ impl Psd {
/// Undo ZIP prediction in place; the 32-bit scratch row is charged to `budget`.
pub(crate) fn unpredict(&self, v: &mut [u8], w: usize, h: usize, budget: &mut Budget) -> Result<()> {
match self.depth {
16 => {
for row in v.chunks_exact_mut(w * 2).take(h) {
let mut prev = 0u16;
for c in row.as_chunks_mut::<2>().0 {
let x = u16::from_be_bytes([c[0], c[1]]).wrapping_add(prev);
c.copy_from_slice(&x.to_be_bytes());
prev = x;
}
}
}
32 => {
// One scratch row for the whole plane, charged: a wide, short layer passes the
// decode's peak check and would otherwise allocate it on top.
let mut planar = budget.filled(w.checked_mul(4).ok_or_else(|| too_large(w, h))?, 0u8)?;
#[cfg(test)]
counters::bump(&counters::SCRATCH);
for row in v.chunks_exact_mut(w * 4).take(h) {
for i in 1..row.len() {
row[i] = row[i].wrapping_add(row[i - 1]);
}
// Bytes are stored plane by plane (all first bytes, then all second bytes…).
planar.copy_from_slice(row);
for x in 0..w {
for b in 0..4 {
row[x * 4 + b] = planar[b * w + x];
}
}
}
budget.release(planar.len() as u64);
}
_ => {
for row in v.chunks_exact_mut(w).take(h) {
for i in 1..row.len() {
row[i] = row[i].wrapping_add(row[i - 1]);
}
}
}
// Preserve the reader's recovery behavior: decode only complete rows, at most h.
// The fallback depths historically used byte-wise prediction rather than packed bits.
let depth = match self.depth {
16 => 16,
32 => 32,
_ => 8,
};
let rowb = w.checked_mul(usize::from(depth / 8)).ok_or_else(|| too_large(w, h))?;
if rowb == 0 {
return Ok(());
}
Ok(())
let rows = (v.len() / rowb).min(h);
let layout = craft_psd::compression::PlaneLayout {
planes: 1,
width: w,
height: rows,
depth,
version: if self.psb { craft_psd::Version::Psb } else { craft_psd::Version::Psd },
};
let mut scratch = if depth == 32 {
let scratch = budget.filled(rowb, 0u8)?;
#[cfg(test)]
counters::bump(&counters::SCRATCH);
scratch
} else {
Vec::new()
};
let result = craft_psd::compression::unpredict_with_scratch(&mut v[..rows * rowb], &layout, &mut scratch);
budget.release(scratch.len() as u64);
result.map_err(|e| Error::Invalid(e.to_string()))
}
/// Hand every sample of `raw` (`w`×`h`, row-major, in order) to `f` as a float. Samples a short
@@ -505,42 +495,6 @@ pub(crate) fn unpack_bits(src: &[u8], row: usize, out: &mut Vec<u8>) -> Result<(
Ok(())
}
/// PackBits encoding of one row.
pub(crate) fn pack_bits(src: &[u8]) -> Vec<u8> {
let mut out = vec![];
let mut i = 0;
while i < src.len() {
// run of identical bytes
let mut run = 1;
while i + run < src.len() && src[i + run] == src[i] && run < 128 {
run += 1;
}
if run >= 2 {
out.push((1 - run as isize) as i8 as u8);
out.push(src[i]);
i += run;
continue;
}
// literal run
let start = i;
let mut n = 0;
while i < src.len() && n < 128 {
if i + 1 < src.len() && src[i + 1] == src[i] {
break;
}
i += 1;
n += 1;
}
if n == 0 {
i += 1;
n = 1;
}
out.push((n - 1) as u8);
out.extend_from_slice(&src[start..start + n]);
}
out
}
pub(crate) fn srgb_encode(v: f32) -> f32 {
if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }
}
+1 -1
View File
@@ -85,7 +85,7 @@ impl<'a> Reader<'a> {
}
/// Mac OS Roman upper half (0x80..=0xFF), as published by the Unicode Consortium mapping table.
fn mac_roman(b: u8) -> char {
pub(crate) fn mac_roman(b: u8) -> char {
const T: &str = "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ\u{F8FF}ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ";
T.chars().nth((b - 0x80) as usize).unwrap_or('?')
}
+77 -1
View File
@@ -1,8 +1,10 @@
use super::write::*;
use super::*;
use crate::pixels::srgb_encode;
mod integration;
mod opt;
mod shared_corpus;
fn gradient(w: u32, h: u32) -> Vec<[f32; 4]> {
(0..w * h).map(|i| [(i % w) as f32 / (w - 1).max(1) as f32, (i / w) as f32 / (h - 1).max(1) as f32, 0.25, 1.0]).collect()
@@ -171,7 +173,7 @@ fn text_effects_fill_and_adjustments() {
#[test]
fn packbits_round_trip() {
for src in [vec![], vec![1u8], vec![5; 300], (0..=255).collect::<Vec<u8>>(), vec![1, 1, 2, 3, 3, 3, 4, 5, 5]] {
let enc = pack_bits(&src);
let enc = craft_psd::compression::packbits::encode_vec(&src);
let mut out = vec![];
unpack_bits(&enc, src.len(), &mut out).unwrap();
assert_eq!(out, src);
@@ -519,3 +521,77 @@ fn a_failed_inflate_reports_its_status_not_its_output() {
let Err(Error::Invalid(msg)) = crate::limits::inflate(&z, 1 << 21) else { panic!("the checksum fails") };
assert!(msg.len() < 100, "{} bytes", msg.len());
}
#[test]
fn written_32_bit_documents_decode() {
// 32-bit samples are written as floats, raw or RLE, so both read back whole.
for rle in [true, false] {
let p = Psd::parse(write(&doc_with_layers(32, ColorMode::Rgb, rle))).expect("parse");
assert_eq!(p.depth, 32);
assert!(p.composite().is_ok(), "rle={rle}");
for i in 0..p.layers.len() {
assert!(p.layer_pixels(i, false).is_ok(), "rle={rle} layer {i}");
}
}
}
#[test]
fn deep_layers_go_in_their_global_block() {
for (depth, key) in [(16, b"Lr16"), (32, b"Lr32")] {
let bytes = write(&doc_with_layers(depth, ColorMode::Rgb, true));
let file = craft_psd::PsdFile::from_bytes(&bytes).expect("parse");
assert!(
matches!(file.layer_info_placement, craft_psd::LayerInfoPlacement::GlobalBlock { key: k, .. } if &k == key),
"{depth}-bit: {:?}",
file.layer_info_placement
);
assert_eq!(Psd::parse(bytes).expect("parse").layers.len(), doc_with_layers(depth, ColorMode::Rgb, true).layers.len());
}
}
#[test]
fn rows_too_wide_for_rle_are_written_raw() {
// 20000 32-bit samples are 80000 bytes per row, past the 65535 an RLE row count holds.
let doc = |w: u32| {
let mut d = WDoc::new(w, 1);
d.depth = 32;
d.composite = Some(vec![[0.5, 0.25, 0.75, 1.0]; w as usize]);
d.layers.push(WLayer::solid("Wide", Rect::new(0, 0, w as i32, 1), [0.5, 0.25, 0.75, 1.0]));
d
};
let want = Psd::parse(write(&doc(100))).expect("narrow").composite().expect("composite").data[0];
let p = Psd::parse(write(&doc(20_000))).expect("parse");
let c = p.composite().expect("composite");
assert_eq!(c.data.len(), 20_000);
assert!(c.data.iter().all(|px| *px == want), "{:?} vs {want:?}", c.data[0]);
assert!(p.layer_pixels(0, false).is_ok());
}
#[test]
fn written_32_bit_color_samples_keep_their_range() {
// The reader keeps finite 32-bit samples outside 0..1; the writer must be able to
// produce those fixtures. Integer depths stay clamped. A layer is present so the
// merged transparency flag is set and alpha is read back.
let want = [2.0, -0.5, 0.25, 1.5];
let mut d = WDoc::new(1, 1);
d.depth = 32;
d.rle = false;
d.composite = Some(vec![want]);
d.layers.push(WLayer::solid("HDR", Rect::new(0, 0, 1, 1), want));
let bytes = write(&d);
for v in want {
assert!(bytes.windows(4).any(|w| w == v.to_be_bytes()), "missing the {v} sample");
}
let p = Psd::parse(bytes).expect("parse");
assert!(p.merged_alpha);
let c = p.composite().expect("composite");
assert_eq!(c.data[0], [srgb_encode(2.0), srgb_encode(-0.5), srgb_encode(0.25), 1.5]);
assert_eq!(p.layer_pixels(0, false).expect("layer").data[0], c.data[0]);
let mut d8 = WDoc::new(1, 1);
d8.composite = Some(vec![want]);
d8.layers.push(WLayer::solid("HDR", Rect::new(0, 0, 1, 1), want));
let p8 = Psd::parse(write(&d8)).expect("parse 8-bit");
let q = |x: f32| (x.clamp(0.0, 1.0) * 255.0).round() / 255.0;
assert_eq!(p8.composite().expect("composite").data[0], [q(2.0), q(-0.5), q(0.25), q(1.5)]);
}
+19 -1
View File
@@ -385,7 +385,7 @@ fn stream(planes: &[Vec<u8>], w: usize, h: usize, depth: u16, comp: u16) -> Vec<
match comp {
0 => planes.iter().for_each(|p| out.extend(p)),
1 => {
let rows: Vec<Vec<u8>> = planes.iter().flat_map(|p| p.chunks(rowb.max(1)).map(pack_bits)).collect();
let rows: Vec<Vec<u8>> = planes.iter().flat_map(|p| p.chunks(rowb.max(1)).map(craft_psd::compression::packbits::encode_vec)).collect();
rows.iter().for_each(|r| out.extend((r.len() as u16).to_be_bytes()));
rows.iter().for_each(|r| out.extend(r));
}
@@ -650,3 +650,21 @@ fn placed_bake_solves_the_quad_once() {
so.map([1.0, 1.0], 20.0, 10.0);
assert_eq!(counters::take(&QUAD), 1);
}
#[test]
fn shared_unpredict_keeps_tail_bytes_and_refuses_unbudgeted_scratch() {
for depth in [8u16, 16, 32] {
let p = Psd { depth, ..base() };
let (w, h) = (3, 2);
let row = w * usize::from(depth / 8);
let mut actual: Vec<u8> = (0..row * 3 + 1).map(|i| (i * 31 % 251) as u8).collect();
let mut expected = actual.clone();
ref_unpredict(depth, &mut expected, w, h);
p.unpredict(&mut actual, w, h, &mut Budget::new(u64::MAX)).unwrap();
assert_eq!(actual, expected, "complete extra rows and partial tails stay untouched");
}
let p = Psd { depth: 32, ..base() };
let mut bytes = vec![0x31; 24];
assert!(p.unpredict(&mut bytes, 3, 2, &mut Budget::new(11)).is_err());
assert_eq!(bytes, vec![0x31; 24], "budget refusal precedes mutation");
}
+192
View File
@@ -0,0 +1,192 @@
//! The reader over craft-psd's generated corpus (every colour mode, depth, compression and PSB):
//! the model matches the shared reader's records and its channel ranges hold the stored bytes.
use crate::*;
#[test]
fn every_generated_case_reads_like_craft_psd() {
let mut decoded = 0;
for (i, case) in craft_psd::testgen::all_cases().into_iter().enumerate() {
let bytes = case.file.to_bytes().expect("write");
let shared = craft_psd::PsdFile::from_bytes(&bytes).expect("shared parse");
let p = match Psd::parse(bytes.clone()) {
Ok(p) => p,
// Modes this reader does not show are refused cleanly, never half-read.
Err(Error::Unsupported(_)) => continue,
Err(e) => panic!("case {i}: {e}"),
};
assert_eq!(
(p.width, p.height, p.depth, p.psb),
(shared.header.width, shared.header.height, shared.header.depth, shared.header.version.is_psb()),
"case {i}"
);
let records = shared.layer_info.as_ref().map_or(&[][..], |l| &l.layers[..]);
assert_eq!(p.layers.len(), records.len(), "case {i}");
for (l, rec) in p.layers.iter().zip(records) {
assert_eq!(l.blend, rec.blend_mode.key(), "case {i}");
assert_eq!(l.channels.len(), rec.channels.len(), "case {i}");
for (c, rc) in l.channels.iter().zip(&rec.channels) {
assert_eq!(c.id, rc.id, "case {i}");
// The range covers the compression field and the stored bytes after it.
assert!(c.len == 0 || c.len == rc.data.len() + 2, "case {i}");
assert!(c.len == 0 || bytes[c.offset + 2..c.offset + c.len] == rc.data[..], "case {i}");
}
}
// Decoding reads those ranges: it ends in pixels or a clean error, as before the cutover.
if p.composite().is_ok() {
decoded += 1;
}
for li in 0..p.layers.len() {
let _ = p.layer_pixels(li, false);
}
}
assert!(decoded > 100, "{decoded} composites decoded");
}
#[test]
fn a_damaged_layer_section_keeps_the_merged_image() {
let case = craft_psd::testgen::all_cases().into_iter().find(|c| c.file.layer_info.as_ref().is_some_and(|l| !l.layers.is_empty())).expect("a layered case");
let mut bytes = case.file.to_bytes().expect("write");
let head = craft_psd::head::HeadView::from_bytes(&bytes).expect("head");
// Overwrite the first layer record's signature.
let at = head.layer_section_offset as usize + if head.header.version.is_psb() { 16 } else { 8 } + 2 + 16;
let channels = usize::from(u16::from_be_bytes([bytes[at], bytes[at + 1]]));
let sig = at + 2 + channels * if head.header.version.is_psb() { 10 } else { 6 };
assert_eq!(&bytes[sig..sig + 4], b"8BIM");
bytes[sig..sig + 4].copy_from_slice(b"XXXX");
let p = Psd::parse(bytes).expect("flattened");
assert!(p.layers.is_empty());
assert!(p.warnings.iter().any(|w| w.contains("Layers could not be read")), "{:?}", p.warnings);
assert!(p.composite().is_ok());
}
/// The first generated case that is layered and passes `keep`, with its bytes.
fn layered(keep: impl Fn(&craft_psd::PsdFile) -> bool) -> Vec<u8> {
let case = craft_psd::testgen::all_cases()
.into_iter()
.find(|c| c.file.layer_info.as_ref().is_some_and(|l| !l.layers.is_empty()) && keep(&c.file))
.expect("a layered case");
case.file.to_bytes().expect("write")
}
#[test]
fn a_damaged_resource_keeps_the_layers() {
let intact = layered(|f| f.header.depth == 8 && !f.resources.is_empty());
let want = Psd::parse(intact.clone()).expect("intact");
let mut bytes = intact;
// The first resource: signature, id, padded Pascal name, then its length, made to run off the end.
let res_at = 30 + u32::from_be_bytes(bytes[26..30].try_into().unwrap()) as usize;
let name = 1 + usize::from(bytes[res_at + 4 + 6]);
let len_at = res_at + 4 + 6 + name + name % 2;
bytes[len_at..len_at + 4].copy_from_slice(&0x7fff_fff0u32.to_be_bytes());
let p = Psd::parse(bytes).expect("parse");
assert!(p.warnings.is_empty(), "{:?}", p.warnings);
assert_eq!(p.layers.len(), want.layers.len());
assert_eq!(p.merged_alpha, want.merged_alpha);
assert_eq!(p.composite().expect("composite").data, want.composite().expect("composite").data);
for i in 0..p.layers.len() {
assert_eq!(p.layers[i].name, want.layers[i].name);
assert_eq!(p.layer_pixels(i, false).map(|l| l.data).ok(), want.layer_pixels(i, false).map(|l| l.data).ok(), "layer {i}");
}
}
#[test]
fn a_damaged_16_bit_layer_block_is_reported() {
let intact = layered(|f| f.header.depth == 16 && matches!(f.layer_info_placement, craft_psd::LayerInfoPlacement::GlobalBlock { .. }));
let want = Psd::parse(intact.clone()).expect("intact");
assert!(want.merged_alpha, "the generated 16-bit cases carry merged alpha");
let mut bytes = intact;
let at = bytes.windows(8).position(|w| w == b"8BIMLr16").expect("Lr16 block");
let psb = want.psb;
// Block header, then the layer count and the first record's rect: its channel count follows.
let channels = at + 8 + if psb { 8 } else { 4 } + 2 + 16;
bytes[channels..channels + 2].copy_from_slice(&u16::MAX.to_be_bytes());
let p = Psd::parse(bytes).expect("flattened");
assert!(p.layers.is_empty());
assert!(p.warnings.iter().any(|w| w.contains("Layers could not be read")), "{:?}", p.warnings);
assert_eq!(p.merged_alpha, want.merged_alpha);
assert_eq!(p.composite().expect("composite").data, want.composite().expect("composite").data);
}
/// `bytes` with `insert` put at `at`, the length fields at `fixes` (offset, width) grown to match.
fn insert(bytes: &[u8], at: usize, insert: &[u8], fixes: &[(usize, usize)]) -> Vec<u8> {
let mut out = [&bytes[..at], insert, &bytes[at..]].concat();
for &(f, w) in fixes {
let v = out[f..f + w].iter().fold(0u64, |v, &b| v << 8 | u64::from(b)) + insert.len() as u64;
out[f..f + w].copy_from_slice(&v.to_be_bytes()[8 - w..]);
}
out
}
/// A 16-bit layered case (layers in `Lr16`), its parse, the layer section offset, the length
/// field width and the `Lr16` block's offset.
fn deep() -> (Vec<u8>, Psd, usize, usize, usize) {
let bytes = layered(|f| f.header.depth == 16 && matches!(f.layer_info_placement, craft_psd::LayerInfoPlacement::GlobalBlock { .. }));
let want = Psd::parse(bytes.clone()).expect("intact");
let ls = craft_psd::head::HeadView::from_bytes(&bytes).expect("head").layer_section_offset as usize;
let w = if want.psb { 8 } else { 4 };
let at = bytes.windows(8).position(|x| x[4..] == *b"Lr16" && matches!(&x[..4], b"8BIM" | b"8B64")).expect("Lr16");
(bytes, want, ls, w, at)
}
fn same_layers(p: &Psd, want: &Psd) {
assert!(p.warnings.is_empty(), "{:?}", p.warnings);
assert_eq!(p.layers.len(), want.layers.len());
assert_eq!(p.merged_alpha, want.merged_alpha);
assert_eq!(p.composite().expect("composite").data, want.composite().expect("composite").data);
for i in 0..p.layers.len() {
assert_eq!(p.layers[i].name, want.layers[i].name);
assert_eq!(p.layer_pixels(i, false).map(|l| l.data).ok(), want.layer_pixels(i, false).map(|l| l.data).ok(), "layer {i}");
}
}
#[test]
fn a_length_prefixed_16_bit_layer_block_reads() {
let (bytes, want, ls, w, at) = deep();
let body = at + 8 + w;
let len = u64::try_from(bytes.len()).unwrap().min(u64::from(u32::MAX));
let block_len = bytes[at + 8..body].iter().fold(0u64, |v, &b| v << 8 | u64::from(b));
assert!(block_len < len);
let prefix = &block_len.to_be_bytes()[8 - w..];
let p = Psd::parse(insert(&bytes, body, prefix, &[(at + 8, w), (ls, w)])).expect("parse");
same_layers(&p, &want);
}
#[test]
fn damaged_section_records_fall_back_to_the_16_bit_block() {
let (bytes, want, ls, w, _) = deep();
// A section layer info claiming one record that is cut short.
let li_at = ls + w;
assert!(bytes[li_at..li_at + w].iter().all(|&b| b == 0), "the generated file keeps its layers only in Lr16");
let p = Psd::parse(insert(&bytes, li_at + w, &[0, 1, 0, 0, 0, 0], &[(li_at, w), (ls, w)])).expect("parse");
same_layers(&p, &want);
}
#[test]
fn a_stray_byte_before_the_global_blocks_is_skipped() {
let (bytes, want, ls, w, _) = deep();
// Section layer info (empty) and global mask, then the first global block.
let li_at = ls + w;
let gm_at = li_at + w + bytes[li_at..li_at + w].iter().fold(0usize, |v, &b| v << 8 | usize::from(b));
let first = gm_at + 4 + u32::from_be_bytes(bytes[gm_at..gm_at + 4].try_into().unwrap()) as usize;
assert_eq!(&bytes[first..first + 4], b"8BIM");
let p = Psd::parse(insert(&bytes, first, &[0], &[(ls, w)])).expect("parse");
same_layers(&p, &want);
}
#[test]
fn stray_bytes_before_a_leading_16_bit_block_are_skipped() {
let (bytes, want, ls, w, at) = deep();
let li_at = ls + w;
let gm_at = li_at + w + bytes[li_at..li_at + w].iter().fold(0usize, |v, &b| v << 8 | usize::from(b));
let first = gm_at + 4 + u32::from_be_bytes(bytes[gm_at..gm_at + 4].try_into().unwrap()) as usize;
// Drop the blocks before `Lr16` so it comes first, then put 1 to 3 stray bytes before it.
let mut lead = [&bytes[..first], &bytes[at..]].concat();
let lm = lead[ls..ls + w].iter().fold(0u64, |v, &b| v << 8 | u64::from(b)) - (at - first) as u64;
lead[ls..ls + w].copy_from_slice(&lm.to_be_bytes()[8 - w..]);
assert_eq!(&lead[first + 4..first + 8], b"Lr16");
for n in 1..=3 {
let p = Psd::parse(insert(&lead, first, &vec![0; n], &[(ls, w)])).expect("parse");
same_layers(&p, &want);
}
}
+127 -194
View File
@@ -1,10 +1,18 @@
//! A minimal Photoshop document writer, per the same specification as the reader: RGB, CMYK or
//! Grayscale, 8 or 16 bits, raw or RLE channels, pixel layers with layer masks, groups and any
//! additional-information blocks (helpers below build text, effects, fill and adjustment
//! blocks). Used to generate test fixtures; not a full exporter.
//! blocks). Used to generate test fixtures; not a full exporter. The file itself is laid out and
//! encoded by craft-psd ([`craft_psd::PsdFile::to_bytes`]).
use craft_psd::layer::{LayerInfo, LayerRecord};
use craft_psd::tagged::{SectionType, TaggedBlock};
use craft_psd::{
BlendMode, BlendingRanges, ChannelData, Compression, GlobalLayerMask, Header, ImageData, LayerFlags, LayerInfoPlacement, MaskData, PsdFile, Version,
};
use crate::descriptor::{self, DValue, Descriptor, put_u16, put_u32, put_utf16};
use crate::{ColorMode, Rect, Section, engine_data, pack_bits};
use crate::limits::finite_sample;
use crate::{ColorMode, Rect, Section, engine_data};
/// A layer mask for [`WLayer`].
#[derive(Clone, Debug)]
@@ -93,7 +101,7 @@ impl WLayer {
pub struct WDoc {
pub width: u32,
pub height: u32,
/// 8 or 16.
/// 8, 16 or 32 (32-bit samples are written as floats).
pub depth: u16,
/// Rgb, Cmyk or Grayscale.
pub mode: ColorMode,
@@ -128,10 +136,14 @@ fn mode_channels(mode: ColorMode, p: [f32; 4]) -> Vec<f32> {
}
fn encode_samples(v: &[f32], depth: u16) -> Vec<u8> {
let mut out = Vec::with_capacity(v.len() * if depth == 16 { 2 } else { 1 });
let mut out = Vec::with_capacity(v.len() * usize::from(depth.div_ceil(8)));
for &x in v {
let x = x.clamp(0.0, 1.0);
if depth == 16 {
// Integer depths are stored in 0..1. 32-bit documents keep finite samples
// outside that range (HDR); NaN and infinities use the reader's mapping.
let x = if depth == 32 { finite_sample(x) } else { x.clamp(0.0, 1.0) };
if depth == 32 {
out.extend_from_slice(&x.to_be_bytes());
} else if depth == 16 {
put_u16(&mut out, (x * 65535.0).round() as u16);
} else {
out.push((x * 255.0).round() as u8);
@@ -140,139 +152,81 @@ fn encode_samples(v: &[f32], depth: u16) -> Vec<u8> {
out
}
/// One channel's data (compression field + data) for a `w`×`h` plane.
fn channel_data(v: &[f32], w: usize, h: usize, depth: u16, rle: bool) -> Vec<u8> {
let raw = encode_samples(v, depth);
let mut out = vec![];
let rowb = raw.len() / h.max(1);
if !rle || w == 0 || h == 0 {
put_u16(&mut out, 0);
out.extend_from_slice(&raw);
return out;
}
put_u16(&mut out, 1);
let rows: Vec<Vec<u8>> = raw.chunks(rowb.max(1)).map(pack_bits).collect();
for r in &rows {
put_u16(&mut out, r.len() as u16);
}
for r in rows {
out.extend_from_slice(&r);
}
out
/// The layer and merged-image compression of `doc`.
fn compression(doc: &WDoc) -> Compression {
if doc.rle { Compression::Rle } else { Compression::Raw }
}
fn pascal4(out: &mut Vec<u8>, s: &str) {
let b: Vec<u8> = s.bytes().map(|c| if c < 0x80 { c } else { b'?' }).take(255).collect();
out.push(b.len() as u8);
out.extend_from_slice(&b);
let total = 1 + b.len();
out.resize(out.len() + total.div_ceil(4) * 4 - total, 0);
/// One channel of a `w`×`h` plane, encoded by craft-psd. An empty plane is written raw.
fn channel(id: i16, v: &[f32], w: usize, h: usize, doc: &WDoc) -> craft_psd::Result<ChannelData> {
let c = if w == 0 || h == 0 { Compression::Raw } else { compression(doc) };
let samples = encode_samples(v, doc.depth);
// A PSD RLE row holds at most 65535 bytes; a wider plane is written raw.
ChannelData::encode(id, c, &samples, w, h, doc.depth, Version::Psd)
.or_else(|_| ChannelData::encode(id, Compression::Raw, &samples, w, h, doc.depth, Version::Psd))
}
fn block(out: &mut Vec<u8>, key: &[u8; 4], data: &[u8]) {
out.extend_from_slice(b"8BIM");
out.extend_from_slice(key);
let padded = data.len().div_ceil(2) * 2;
put_u32(out, padded as u32);
out.extend_from_slice(data);
out.resize(out.len() + padded - data.len(), 0);
/// The `luni` block: the UTF-16 length and code units, unpadded, as this writer has always
/// written it (`TaggedBlock::unicode_name` adds a terminator, which would change exported files).
fn unicode_name(name: &str) -> TaggedBlock {
let units: Vec<u16> = name.encode_utf16().collect();
let mut data = (units.len() as u32).to_be_bytes().to_vec();
data.extend(units.iter().flat_map(|u| u.to_be_bytes()));
TaggedBlock::new(*b"luni", data)
}
fn layer_info(doc: &WDoc) -> Vec<u8> {
let mut out = vec![];
out.extend_from_slice(&(-(doc.layers.len() as i16)).to_be_bytes());
let mut chan_data: Vec<Vec<(i16, Vec<u8>)>> = vec![];
for l in &doc.layers {
let (w, h) = (l.rect.width() as usize, l.rect.height() as usize);
let mut chans: Vec<(i16, Vec<u8>)> = vec![];
let n = w * h;
let alpha: Vec<f32> = l.pixels.iter().take(n).map(|p| p[3]).collect();
chans.push((-1, channel_data(&alpha, w, h, doc.depth, doc.rle)));
let cc = doc.mode.color_channels();
let planes: Vec<Vec<f32>> = l.pixels.iter().take(n).map(|p| mode_channels(doc.mode, *p)).collect();
for c in 0..cc {
let plane: Vec<f32> = planes.iter().map(|v| v[c]).collect();
chans.push((c as i16, channel_data(&plane, w, h, doc.depth, doc.rle)));
}
if let Some(m) = &l.mask {
chans.push((-2, channel_data(&m.data, m.rect.width() as usize, m.rect.height() as usize, doc.depth, doc.rle)));
}
// record
for v in [l.rect.top, l.rect.left, l.rect.bottom, l.rect.right] {
out.extend_from_slice(&v.to_be_bytes());
}
put_u16(&mut out, chans.len() as u16);
for (id, d) in &chans {
out.extend_from_slice(&id.to_be_bytes());
put_u32(&mut out, d.len() as u32);
}
out.extend_from_slice(b"8BIM");
out.extend_from_slice(&l.blend);
out.push(l.opacity);
out.push(l.clipping as u8);
let mut flags = 8u8;
if l.hidden {
flags |= 2;
}
out.push(flags);
out.push(0);
let mut extra = vec![];
match &l.mask {
Some(m) => {
put_u32(&mut extra, 20);
for v in [m.rect.top, m.rect.left, m.rect.bottom, m.rect.right] {
extra.extend_from_slice(&v.to_be_bytes());
}
extra.push(m.default_color);
extra.push(if m.disabled { 2 } else { 0 });
extra.extend_from_slice(&[0, 0]);
}
None => put_u32(&mut extra, 0),
}
put_u32(&mut extra, 0); // blending ranges
pascal4(&mut extra, &l.name);
let luni = unicode_plain(&l.name);
block(&mut extra, b"luni", &luni);
match l.section {
Section::Layer => {}
s => {
let mut d = vec![];
put_u32(
&mut d,
match s {
Section::OpenFolder => 1,
Section::ClosedFolder => 2,
_ => 3,
},
);
d.extend_from_slice(b"8BIM");
d.extend_from_slice(&l.blend);
block(&mut extra, b"lsct", &d);
}
}
for (k, d) in &l.blocks {
block(&mut extra, k, d);
}
put_u32(&mut out, extra.len() as u32);
out.extend_from_slice(&extra);
chan_data.push(chans);
}
for chans in chan_data {
for (_, d) in chans {
out.extend_from_slice(&d);
}
}
if out.len() % 2 == 1 {
out.push(0);
}
out
/// A legacy Pascal name: ASCII, anything else as `?`, at most 255 bytes.
fn legacy_name(s: &str) -> Vec<u8> {
s.bytes().map(|c| if c < 0x80 { c } else { b'?' }).take(255).collect()
}
/// A Unicode string without the terminating NUL (the layer-name `luni` form).
fn unicode_plain(s: &str) -> Vec<u8> {
let mut out = vec![];
put_utf16(&mut out, s, false);
out
fn psd_rect(r: Rect) -> craft_psd::Rect {
craft_psd::Rect { top: r.top, left: r.left, bottom: r.bottom, right: r.right }
}
/// The layer record of `l`: pixels, mask, name, section and blocks.
fn record(l: &WLayer, doc: &WDoc) -> craft_psd::Result<LayerRecord> {
let (w, h) = (l.rect.width() as usize, l.rect.height() as usize);
let n = w * h;
let alpha: Vec<f32> = l.pixels.iter().take(n).map(|p| p[3]).collect();
let mut channels = vec![channel(-1, &alpha, w, h, doc)?];
let planes: Vec<Vec<f32>> = l.pixels.iter().take(n).map(|p| mode_channels(doc.mode, *p)).collect();
for c in 0..doc.mode.color_channels() {
let plane: Vec<f32> = planes.iter().map(|v| v[c]).collect();
channels.push(channel(c as i16, &plane, w, h, doc)?);
}
let mut mask = MaskData::None;
if let Some(m) = &l.mask {
channels.push(channel(-2, &m.data, m.rect.width() as usize, m.rect.height() as usize, doc)?);
mask = MaskData::Mask(craft_psd::LayerMask::new(psd_rect(m.rect), m.default_color, if m.disabled { 2 } else { 0 }));
}
let mut flags = LayerFlags(8);
flags.set_hidden(l.hidden);
let mut blocks = vec![unicode_name(&l.name)];
let kind = match l.section {
Section::Layer => None,
Section::OpenFolder => Some(SectionType::OpenFolder),
Section::ClosedFolder => Some(SectionType::ClosedFolder),
Section::Divider => Some(SectionType::BoundingDivider),
};
if let Some(kind) = kind {
blocks.push(TaggedBlock::section_divider(kind, Some(BlendMode::from_key(l.blend)), None));
}
blocks.extend(l.blocks.iter().map(|(k, d)| TaggedBlock::new(*k, d.clone())));
Ok(LayerRecord {
rect: psd_rect(l.rect),
channels,
blend_mode: BlendMode::from_key(l.blend),
opacity: l.opacity,
clipping: u8::from(l.clipping),
flags,
filler: 0,
mask,
blending_ranges: BlendingRanges::default(),
name: legacy_name(&l.name),
blocks,
extra_trailing: vec![],
})
}
/// Normal "over" of the visible pixel layers (groups ignored), straight alpha.
@@ -298,76 +252,55 @@ fn flatten(doc: &WDoc) -> Vec<[f32; 4]> {
acc
}
/// Serialise a document.
/// Serialise a document with craft-psd.
pub fn write(doc: &WDoc) -> Vec<u8> {
// Every input `WDoc` describes is in range for the writer; a failure is a bug in the caller.
#[allow(clippy::expect_used)]
build(doc).and_then(|f| f.to_bytes()).expect("a WDoc is always writable")
}
fn build(doc: &WDoc) -> craft_psd::Result<PsdFile> {
let cc = doc.mode.color_channels();
let mut out = vec![];
out.extend_from_slice(b"8BPS");
put_u16(&mut out, 1);
out.extend_from_slice(&[0; 6]);
put_u16(&mut out, (cc + 1) as u16);
put_u32(&mut out, doc.height);
put_u32(&mut out, doc.width);
put_u16(&mut out, doc.depth);
put_u16(&mut out, doc.mode.to_u16());
put_u32(&mut out, 0); // colour mode data
put_u32(&mut out, 0); // image resources
// Layer and mask information.
let mut lm = vec![];
if !doc.layers.is_empty() {
let li = layer_info(doc);
if doc.depth == 16 {
put_u32(&mut lm, 0);
put_u32(&mut lm, 0); // global layer mask info
let mut padded = li;
while !padded.len().is_multiple_of(4) {
padded.push(0);
}
lm.extend_from_slice(b"8BIM");
lm.extend_from_slice(b"Lr16");
put_u32(&mut lm, padded.len() as u32);
lm.extend_from_slice(&padded);
} else {
put_u32(&mut lm, li.len() as u32);
lm.extend_from_slice(&li);
put_u32(&mut lm, 0);
}
if !doc.linked.is_empty() {
let d = linked_block(&doc.linked);
lm.extend_from_slice(b"8BIM");
lm.extend_from_slice(b"lnk2");
put_u32(&mut lm, d.len() as u32);
lm.extend_from_slice(&d);
}
let header = Header::new(Version::Psd, doc.width, doc.height, (cc + 1) as u16, doc.depth, craft_psd::ColorMode::from_u16(doc.mode.to_u16()));
let layers = doc.layers.iter().map(|l| record(l, doc)).collect::<craft_psd::Result<Vec<_>>>()?;
let has_layers = !layers.is_empty();
let mut global_blocks = vec![];
if has_layers && !doc.linked.is_empty() {
global_blocks.push(TaggedBlock::new(*b"lnk2", linked_block(&doc.linked)));
}
put_u32(&mut out, lm.len() as u32);
out.extend_from_slice(&lm);
// Merged image.
let comp = doc.composite.clone().unwrap_or_else(|| flatten(doc));
let w = doc.width as usize;
let planes: Vec<Vec<f32>> = comp.iter().map(|p| mode_channels(doc.mode, *p)).collect();
let mut chans: Vec<Vec<f32>> = (0..cc).map(|c| planes.iter().map(|v| v[c]).collect()).collect();
chans.push(comp.iter().map(|p| p[3]).collect());
if doc.rle {
put_u16(&mut out, 1);
let rows: Vec<Vec<Vec<u8>>> =
chans.iter().map(|c| encode_samples(c, doc.depth).chunks((w * if doc.depth == 16 { 2 } else { 1 }).max(1)).map(pack_bits).collect()).collect();
for c in &rows {
for r in c {
put_u16(&mut out, r.len() as u16);
}
}
for c in rows {
for r in c {
out.extend_from_slice(&r);
}
}
} else {
put_u16(&mut out, 0);
for c in &chans {
out.extend_from_slice(&encode_samples(c, doc.depth));
}
let mut merged = vec![];
for c in 0..cc {
merged.extend(encode_samples(&planes.iter().map(|v| v[c]).collect::<Vec<_>>(), doc.depth));
}
merged.extend(encode_samples(&comp.iter().map(|p| p[3]).collect::<Vec<_>>(), doc.depth));
let image_data = ImageData::encode(compression(doc), &merged, &header).or_else(|_| ImageData::encode(Compression::Raw, &merged, &header))?;
Ok(PsdFile {
header,
color_mode_data: vec![],
resources: vec![],
layer_info: has_layers.then_some(LayerInfo { merged_alpha: true, layers, padding: None }),
// 16- and 32-bit layers go in an `Lr16` / `Lr32` block, as Photoshop writes them.
layer_info_placement: match doc.depth {
16 | 32 if has_layers => {
LayerInfoPlacement::GlobalBlock { index: 0, signature: *b"8BIM", key: craft_psd::tiff::layer_info_key(doc.depth), padding: None }
}
_ => LayerInfoPlacement::Section,
},
global_layer_mask: has_layers.then(GlobalLayerMask::default),
global_blocks,
layer_mask_trailing: vec![],
image_data,
write_as_psb: false,
})
}
/// A Unicode string without the terminating NUL (the layer-name `luni` form).
fn unicode_plain(s: &str) -> Vec<u8> {
let mut out = vec![];
put_utf16(&mut out, s, false);
out
}