From c732a21c681e23e498f32b4f67f686fb098ba723 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 15:57:13 +0000 Subject: [PATCH 1/4] Use shared PSD builder for flat exports --- crates/codecs/src/psd.rs | 134 ++++++++++----------------------------- 1 file changed, 35 insertions(+), 99 deletions(-) diff --git a/crates/codecs/src/psd.rs b/crates/codecs/src/psd.rs index f0422edc13..284dae09ec 100644 --- a/crates/codecs/src/psd.rs +++ b/crates/codecs/src/psd.rs @@ -237,114 +237,50 @@ pub(crate) fn encode(img: &EncodeImage, meta: &EncodeMeta) -> Result> { if w > MAX_SIDE || h > MAX_SIDE { return Err(Error::Encode(format!("{w} × {h} is larger than a PSD can hold ({MAX_SIDE} px a side): use TIFF"))); } - let ch = usize::from(img.channels); - let color = if ch <= 2 { 1 } else { 3 }; - let (depth, bpc) = match img.samples { - Samples::U8(_) => (8u16, 1usize), - Samples::U16(_) => (16, 2), + let gray = img.channels <= 2; + let input_channels = usize::from(img.channels); + let output_channels = if gray { 2 } else { 4 }; + let pixels = (w as usize).checked_mul(h as usize).ok_or_else(|| Error::Encode("image too large".into()))?; + let size = pixels.checked_mul(output_channels).ok_or_else(|| Error::Encode("image too large".into()))?; + let (depth, data) = match img.samples { + Samples::U8(src) => { + let mut values = Vec::new(); + values.try_reserve_exact(size).map_err(|_| Error::Encode("image too large".into()))?; + for pixel in src.chunks_exact(input_channels).take(pixels) { + values.extend_from_slice(&pixel[..output_channels - 1]); + values.push(u8::MAX); + } + (8, if gray { craft_psd::PixelData::GrayA8(values) } else { craft_psd::PixelData::Rgba8(values) }) + } + Samples::U16(src) => { + let mut values = Vec::new(); + values.try_reserve_exact(size).map_err(|_| Error::Encode("image too large".into()))?; + for pixel in src.chunks_exact(input_channels).take(pixels) { + values.extend_from_slice(&pixel[..output_channels - 1]); + values.push(u16::MAX); + } + (16, if gray { craft_psd::PixelData::GrayA16(values) } else { craft_psd::PixelData::Rgba16(values) }) + } Samples::F32(_) => return Err(Error::Encode("32-bit float PSD is not supported: use TIFF".into())), }; - let (wu, hu) = (w as usize, h as usize); - let mut b = Vec::new(); - b.extend_from_slice(b"8BPS"); - b.extend_from_slice(&1u16.to_be_bytes()); - b.extend_from_slice(&[0; 6]); - b.extend_from_slice(&(color as u16).to_be_bytes()); - b.extend_from_slice(&h.to_be_bytes()); - b.extend_from_slice(&w.to_be_bytes()); - b.extend_from_slice(&depth.to_be_bytes()); - b.extend_from_slice(&(if color == 1 { 1u16 } else { 3 }).to_be_bytes()); - b.extend_from_slice(&0u32.to_be_bytes()); // colour mode data - let res = resource_section(meta); - b.extend_from_slice(&u32::try_from(res.len()).map_err(|_| Error::Encode("metadata too large for PSD".into()))?.to_be_bytes()); - b.extend_from_slice(&res); - b.extend_from_slice(&0u32.to_be_bytes()); // layer and mask information: none - // planar samples, one plane per colour channel (big-endian) - let plane = |c: usize| -> Vec { - let mut p = Vec::with_capacity(wu * hu * bpc); - match img.samples { - Samples::U8(s) => p.extend(s.iter().skip(c).step_by(ch).take(wu * hu)), - Samples::U16(s) => s.iter().skip(c).step_by(ch).take(wu * hu).for_each(|v| p.extend_from_slice(&v.to_be_bytes())), - Samples::F32(_) => {} - } - p - }; - if bpc == 1 { - b.extend_from_slice(&1u16.to_be_bytes()); - let mut counts = Vec::with_capacity(color * hu * 2); - let mut data = Vec::new(); - for c in 0..color { - for row in plane(c).chunks_exact(wu) { - let start = data.len(); - packbits(row, &mut data); - let n = u16::try_from(data.len() - start).map_err(|_| Error::Encode("PSD row too long".into()))?; - counts.extend_from_slice(&n.to_be_bytes()); - } - } - b.extend_from_slice(&counts); - b.extend_from_slice(&data); - } else { - b.extend_from_slice(&0u16.to_be_bytes()); - for c in 0..color { - b.extend_from_slice(&plane(c)); - } - } - Ok(b) -} - -/// The image resources section for `meta`. -fn resource_section(meta: &EncodeMeta) -> Vec { - let mut out = Vec::new(); - let mut add = |id: u16, data: &[u8]| { - out.extend_from_slice(b"8BIM"); - out.extend_from_slice(&id.to_be_bytes()); - out.extend_from_slice(&[0, 0]); // empty Pascal name, padded to even - out.extend_from_slice(&(data.len() as u32).to_be_bytes()); - out.extend_from_slice(data); - if data.len() % 2 == 1 { - out.push(0); - } - }; + let mut builder = craft_psd::PsdBuilder::new(w, h) + .color_mode(if gray { craft_psd::ColorMode::Grayscale } else { craft_psd::ColorMode::Rgb }) + .depth(depth) + .compression(if depth == 8 { craft_psd::Compression::Rle } else { craft_psd::Compression::Raw }); if let Some(ppi) = meta.ppi.filter(|p| *p > 0) { - // ResolutionInfo: 16.16 fixed pixels per inch, unit 1 (ppi), display unit 1 (inches), twice - let fixed = (u32::from(ppi) << 16).to_be_bytes(); - let one = 1u16.to_be_bytes(); - add(1005, &[&fixed[..], &one, &one, &fixed, &one, &one].concat()); + builder = builder.resolution(f64::from(ppi)); } if let Some(icc) = meta.icc { - add(1039, icc); + builder = builder.icc_profile(icc.to_vec()); } if let Some(exif) = meta.exif { - add(1058, exif); + builder = builder.resource(craft_psd::ImageResource::new(1058, exif.to_vec())); } if let Some(xmp) = meta.xmp { - add(1060, xmp.as_bytes()); - } - out -} - -/// PackBits: append one encoded row of `src` to `out` (runs of 2+ equal bytes as repeats, the -/// rest as literals of at most 128 bytes). -fn packbits(src: &[u8], out: &mut Vec) { - let mut rest = src; - while let Some(&b) = rest.first() { - // a run of 2 to 128 equal bytes - let run = rest.iter().take(128).take_while(|&&x| x == b).count(); - if run >= 2 { - // 1 - run in 2..=128: -1..=-127, as a signed byte - out.push((1 - run as i16) as i8 as u8); - out.push(b); - rest = rest.get(run..).unwrap_or_default(); - continue; - } - // a literal of 1 to 128 bytes: up to the next pair of equal bytes, or the end of the row - let unpaired = rest.windows(2).take(128).take_while(|w| w.first() != w.get(1)).count(); - let len = if unpaired.saturating_add(1) == rest.len() { rest.len() } else { unpaired }; - let (lit, tail) = rest.split_at_checked(len.clamp(1, 128)).unwrap_or((rest, &[][..])); - out.push(lit.len().saturating_sub(1) as u8); - out.extend_from_slice(lit); - rest = tail; + builder = builder.resource(craft_psd::ImageResource::new(1060, xmp.as_bytes().to_vec())); } + builder.composite(data); + builder.to_bytes().map_err(|e| Error::Encode(e.to_string())) } /// Stored dimensions and EXIF orientation (resource 1058) from the header and image resources, @@ -550,7 +486,7 @@ mod tests { let rows: [&[u8]; 6] = [&[], &[7], &[1, 1], &[1, 2, 3, 3, 3, 4, 5, 5], &[9; 300], &(0..=255u8).cycle().take(700).collect::>()]; for row in rows { let mut enc = Vec::new(); - super::packbits(row, &mut enc); + craft_psd::compression::packbits::encode(row, &mut enc); let mut out = vec![0u8; row.len()]; unpackbits(&enc, &mut out).unwrap(); assert_eq!(out, row); From 926b80087ea8ba9da0f589e72b5d58c80188bc84 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 16:01:26 +0000 Subject: [PATCH 2/4] Use borrowed shared PSD writer --- Cargo.lock | 2 +- Cargo.toml | 2 +- crates/codecs/src/psd.rs | 47 +++++----------------------------------- 3 files changed, 7 insertions(+), 44 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 04c07b04f1..9651d0c2b9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1319,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=9dcbd90c7d16e1a668b3afa057e940e2db328b93#9dcbd90c7d16e1a668b3afa057e940e2db328b93" +source = "git+https://github.com/storytold/craft-libs?rev=c94ab7a3f00588f1654afe18d981939c95b6d14c#c94ab7a3f00588f1654afe18d981939c95b6d14c" dependencies = [ "encoding_rs", "flate2", diff --git a/Cargo.toml b/Cargo.toml index 2346d9cd48..cf38fa86a0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,7 +27,7 @@ craft-window = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbf # HDR gain maps: ISO 21496-1 and hdrgm metadata, compute and apply (moved from crates/codecs; craft-libs#904). craft-gainmap = { git = "https://github.com/storytold/craft-libs", rev = "9dcbd90c7d16e1a668b3afa057e940e2db328b93" } # PSD/PSB: the header, colour mode data and image resources (craft-libs#885). -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "9dcbd90c7d16e1a668b3afa057e940e2db328b93" } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "c94ab7a3f00588f1654afe18d981939c95b6d14c" } # internal lightcraft-denoise-core = { path = "crates/denoise-core" } lightcraft-denoise = { path = "crates/denoise", default-features = false } diff --git a/crates/codecs/src/psd.rs b/crates/codecs/src/psd.rs index 284dae09ec..f39b37d780 100644 --- a/crates/codecs/src/psd.rs +++ b/crates/codecs/src/psd.rs @@ -237,50 +237,13 @@ pub(crate) fn encode(img: &EncodeImage, meta: &EncodeMeta) -> Result> { if w > MAX_SIDE || h > MAX_SIDE { return Err(Error::Encode(format!("{w} × {h} is larger than a PSD can hold ({MAX_SIDE} px a side): use TIFF"))); } - let gray = img.channels <= 2; - let input_channels = usize::from(img.channels); - let output_channels = if gray { 2 } else { 4 }; - let pixels = (w as usize).checked_mul(h as usize).ok_or_else(|| Error::Encode("image too large".into()))?; - let size = pixels.checked_mul(output_channels).ok_or_else(|| Error::Encode("image too large".into()))?; - let (depth, data) = match img.samples { - Samples::U8(src) => { - let mut values = Vec::new(); - values.try_reserve_exact(size).map_err(|_| Error::Encode("image too large".into()))?; - for pixel in src.chunks_exact(input_channels).take(pixels) { - values.extend_from_slice(&pixel[..output_channels - 1]); - values.push(u8::MAX); - } - (8, if gray { craft_psd::PixelData::GrayA8(values) } else { craft_psd::PixelData::Rgba8(values) }) - } - Samples::U16(src) => { - let mut values = Vec::new(); - values.try_reserve_exact(size).map_err(|_| Error::Encode("image too large".into()))?; - for pixel in src.chunks_exact(input_channels).take(pixels) { - values.extend_from_slice(&pixel[..output_channels - 1]); - values.push(u16::MAX); - } - (16, if gray { craft_psd::PixelData::GrayA16(values) } else { craft_psd::PixelData::Rgba16(values) }) - } + let samples = match img.samples { + Samples::U8(s) => craft_psd::flat::Samples::U8(s), + Samples::U16(s) => craft_psd::flat::Samples::U16(s), Samples::F32(_) => return Err(Error::Encode("32-bit float PSD is not supported: use TIFF".into())), }; - let mut builder = craft_psd::PsdBuilder::new(w, h) - .color_mode(if gray { craft_psd::ColorMode::Grayscale } else { craft_psd::ColorMode::Rgb }) - .depth(depth) - .compression(if depth == 8 { craft_psd::Compression::Rle } else { craft_psd::Compression::Raw }); - if let Some(ppi) = meta.ppi.filter(|p| *p > 0) { - builder = builder.resolution(f64::from(ppi)); - } - if let Some(icc) = meta.icc { - builder = builder.icc_profile(icc.to_vec()); - } - if let Some(exif) = meta.exif { - builder = builder.resource(craft_psd::ImageResource::new(1058, exif.to_vec())); - } - if let Some(xmp) = meta.xmp { - builder = builder.resource(craft_psd::ImageResource::new(1060, xmp.as_bytes().to_vec())); - } - builder.composite(data); - builder.to_bytes().map_err(|e| Error::Encode(e.to_string())) + let metadata = craft_psd::flat::Metadata { icc: meta.icc, exif: meta.exif, xmp: meta.xmp, ppi: meta.ppi }; + craft_psd::flat::write(w, h, img.channels, samples, metadata).map_err(|error| Error::Encode(error.to_string())) } /// Stored dimensions and EXIF orientation (resource 1058) from the header and image resources, From e44713b84d27a13231349f309d047bd38119e706 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 16:03:18 +0000 Subject: [PATCH 3/4] Refresh shared PSD test revision --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9651d0c2b9..55e3493a59 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1319,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c94ab7a3f00588f1654afe18d981939c95b6d14c#c94ab7a3f00588f1654afe18d981939c95b6d14c" +source = "git+https://github.com/storytold/craft-libs?rev=fcc7f4076df47bbee454256dfc99994782eb4c21#fcc7f4076df47bbee454256dfc99994782eb4c21" dependencies = [ "encoding_rs", "flate2", diff --git a/Cargo.toml b/Cargo.toml index cf38fa86a0..556a31c102 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,7 +27,7 @@ craft-window = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbf # HDR gain maps: ISO 21496-1 and hdrgm metadata, compute and apply (moved from crates/codecs; craft-libs#904). craft-gainmap = { git = "https://github.com/storytold/craft-libs", rev = "9dcbd90c7d16e1a668b3afa057e940e2db328b93" } # PSD/PSB: the header, colour mode data and image resources (craft-libs#885). -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "c94ab7a3f00588f1654afe18d981939c95b6d14c" } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "fcc7f4076df47bbee454256dfc99994782eb4c21" } # internal lightcraft-denoise-core = { path = "crates/denoise-core" } lightcraft-denoise = { path = "crates/denoise", default-features = false } From 860a261dc688d3dffe06821ecba4504b238f6392 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 17:59:26 +0000 Subject: [PATCH 4/4] Pin merged shared PSD writer --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 55e3493a59..c7591b3124 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1319,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=fcc7f4076df47bbee454256dfc99994782eb4c21#fcc7f4076df47bbee454256dfc99994782eb4c21" +source = "git+https://github.com/storytold/craft-libs?rev=16d838105b07965832bb43132880176f299634d5#16d838105b07965832bb43132880176f299634d5" dependencies = [ "encoding_rs", "flate2", diff --git a/Cargo.toml b/Cargo.toml index 556a31c102..8e664a864c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,7 +27,7 @@ craft-window = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbf # HDR gain maps: ISO 21496-1 and hdrgm metadata, compute and apply (moved from crates/codecs; craft-libs#904). craft-gainmap = { git = "https://github.com/storytold/craft-libs", rev = "9dcbd90c7d16e1a668b3afa057e940e2db328b93" } # PSD/PSB: the header, colour mode data and image resources (craft-libs#885). -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "fcc7f4076df47bbee454256dfc99994782eb4c21" } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "16d838105b07965832bb43132880176f299634d5" } # internal lightcraft-denoise-core = { path = "crates/denoise-core" } lightcraft-denoise = { path = "crates/denoise", default-features = false }