Skip to content

LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust

Merge branch 'fix-psd-rle-alloc' into integ-b9

Clauded316d97d800c
diff --cc crates/codecs/src/psd.rs
index 86cb2008a,d49a38854..66dec826b
--- a/crates/codecs/src/psd.rs
+++ b/crates/codecs/src/psd.rs
@@@ -182,98 -211,38 +211,111 @@@ pub(crate) fn decode(bytes: &[u8], opts
finish(F, raw, Meta { icc, exif, xmp, ..Default::default() }, (width as u32, height as u32), opts)
}
+/// Stored dimensions and EXIF orientation (resource 1058) from the header and image resources,
+/// without reading the merged image data. Refused, as a decode would refuse it: an unsupported
+/// depth, colour mode or compression, or merged image data that runs past the end of the file
+/// (truncated). The run-length data itself is not unpacked.
+pub(crate) fn header(bytes: &[u8]) -> Result<(u32, u32, u16)> {
+ let mut r = Rd { b: bytes, p: 0 };
+ if r.take(4)? != b"8BPS" {
+ return Err(err("bad signature"));
+ }
+ let psb = match r.u16()? {
+ 1 => false,
+ 2 => true,
+ _ => return Err(err("bad version")),
+ };
+ r.take(6)?;
+ let channels = r.u16()? as usize;
+ let height = r.u32()? as usize;
+ let width = r.u32()? as usize;
+ let depth = r.u16()?;
+ let mode = r.u16()?;
+ check_size(F, width as u64, height as u64, &DecodeOptions::default())?;
+ if channels == 0 || channels > 56 {
+ return Err(err("bad channel count"));
+ }
+ let cm_len = r.u32()? as usize;
+ let color_mode_data = r.take(cm_len)?;
+ let res_len = r.u32()? as usize;
+ let (_, exif, _) = resources(r.take(res_len)?);
+ let lm_len = if psb { r.u64()? as usize } else { r.u32()? as usize };
+ r.take(lm_len)?;
+ let compression = r.u16()?;
+ let bpc = match depth {
+ 8 => 1usize,
+ 16 => 2,
+ 32 => 4,
+ 1 => return Err(Error::Unsupported(F, "1-bit bitmap PSD")),
+ _ => return Err(err("bad depth")),
+ };
+ let n_color = match mode {
+ 1 | 8 | 7 | 2 => 1,
+ 3 => 3,
+ 4 => 4,
+ 9 => return Err(Error::Unsupported(F, "Lab PSD")),
+ _ => return Err(err("unknown colour mode")),
+ };
+ if channels < n_color {
+ return Err(err("too few channels"));
+ }
+ if mode == 2 && (color_mode_data.len() < 768 || depth != 8) {
+ return Err(err("bad indexed palette"));
+ }
+ let rest = bytes.len().saturating_sub(r.p);
+ let need = match compression {
+ 0 => width.checked_mul(height).and_then(|n| n.checked_mul(bpc)).and_then(|n| n.checked_mul(channels)),
+ 1 => {
+ // the row byte counts, then the rows they count
+ let rows = channels.checked_mul(height).ok_or_else(|| err("truncated"))?;
+ let table = rows.checked_mul(if psb { 4 } else { 2 }).filter(|&t| t <= rest).ok_or_else(|| err("truncated"))?;
+ let mut total = table;
+ for _ in 0..rows {
+ total = total.saturating_add(if psb { r.u32()? as usize } else { r.u16()? as usize });
+ }
+ Some(total)
+ }
+ _ => return Err(Error::Unsupported(F, "ZIP-compressed merged image data")),
+ };
+ if need.is_none_or(|n| n > rest) {
+ return Err(err("truncated"));
+ }
+ let orientation = exif.as_deref().map(crate::exif::summarize).unwrap_or_default().orientation.unwrap_or(1);
+ Ok((width as u32, height as u32, orientation))
+}
+
- /// PackBits: append exactly `row_bytes` bytes (zero-padded if the run data is short).
- fn unpackbits(mut src: &[u8], row_bytes: usize, out: &mut Vec<u8>) {
- let target = out.len() + row_bytes;
- while out.len() < target && !src.is_empty() {
- let h = src[0] as i8;
- src = &src[1..];
+ /// A zero-filled buffer whose allocation failure is an error, not an abort.
+ fn zeroed<T: Clone + Default>(len: usize, too_large: impl Fn() -> Error) -> Result<Vec<T>> {
+ let mut v = Vec::new();
+ v.try_reserve_exact(len).map_err(|_| too_large())?;
+ v.resize(len, T::default());
+ Ok(v)
+ }
+
+ /// PackBits: decode one row into `row` (pre-zeroed, so short run data leaves zero padding).
+ /// A run that would write past the end of the row is an error; trailing bytes are ignored.
+ fn unpackbits(mut src: &[u8], row: &mut [u8]) -> Result<()> {
+ let mut at = 0;
+ while at < row.len() {
+ let Some((&h, rest)) = src.split_first() else { break };
+ src = rest;
+ let h = h as i8;
if h >= 0 {
- let n = (h as usize + 1).min(src.len()).min(target - out.len());
- out.extend_from_slice(&src[..n]);
- src = &src[(h as usize + 1).min(src.len())..];
+ let n = h as usize + 1;
+ let lit = src.get(..n).unwrap_or(src);
+ let dst = row.get_mut(at..at + lit.len()).ok_or_else(|| err("RLE row overruns its width"))?;
+ dst.copy_from_slice(lit);
+ at += lit.len();
+ src = src.get(n..).unwrap_or(&[]);
} else if h != -128 {
- let n = ((1 - h as isize) as usize).min(target - out.len());
- if let Some(&b) = src.first() {
- out.extend(std::iter::repeat_n(b, n));
- src = &src[1..];
- }
+ let n = (1 - h as isize) as usize;
+ let Some((&b, rest)) = src.split_first() else { break };
+ src = rest;
+ row.get_mut(at..at + n).ok_or_else(|| err("RLE row overruns its width"))?.fill(b);
+ at += n;
}
}
- out.resize(target, 0);
+ Ok(())
}
fn resources(mut b: &[u8]) -> (Option<Vec<u8>>, Option<Vec<u8>>, Option<String>) {