Skip to content

EffectCraft: An open-source motion graphics and compositing tool written by scratch in pure Rust

Merge pull request #1139 from vangel76/fix-psd-decode-memory-budget

Brandon Thomasfc54b5debc18
diff --cc crates/psd/src/lib.rs
index a2bf5893a,a78165998..39dede6cd
--- a/crates/psd/src/lib.rs
+++ b/crates/psd/src/lib.rs
@@@ -57,6 -56,79 +57,101 @@@ fn decode_pixels(w: usize, h: usize) -
}
}
+ fn too_large(w: usize, h: usize) -> Error {
+ Error::Unsupported(format!("{w}×{h} pixels is too large to decode"))
+ }
+
+ /// What one decode (the composite, or one layer) may hold in memory at once: 4 GiB, 1 GiB where
+ /// pointers are 32 bits wide (WebAssembly). [`MAX_DECODE_PIXELS`] bounds one image; this bounds
+ /// the sum of the buffers a decode keeps alive together.
+ #[cfg(target_pointer_width = "32")]
+ const DECODE_BUDGET: u64 = 1 << 30;
+ #[cfg(not(target_pointer_width = "32"))]
+ const DECODE_BUDGET: u64 = 4 << 30;
+
+ /// The bytes the buffers of one decode hold right now, against a limit. A decode charges a buffer
+ /// before it allocates it (and releases it when it drops it), so a file that would need more
+ /// than the limit fails with an error instead of an out-of-memory abort.
+ struct Budget {
+ limit: u64,
+ live: u64,
+ }
+
+ impl Budget {
+ fn new(limit: u64) -> Budget {
+ Budget { limit, live: 0 }
+ }
+
+ fn charge(&mut self, bytes: u64) -> Result<()> {
+ self.check(bytes)?;
+ self.live += bytes;
+ Ok(())
+ }
+
+ /// Whether `bytes` more would still fit, without taking them. A decode checks its whole
+ /// expected peak first, so one that cannot fit fails before it has allocated anything.
+ fn check(&self, bytes: u64) -> Result<()> {
+ match self.live.checked_add(bytes) {
+ Some(total) if total <= self.limit => Ok(()),
+ _ => {
+ const MIB: u64 = 1 << 20;
+ Err(Error::Unsupported(format!(
+ "decoding needs {} MiB more with {} MiB in use, over the {} MiB memory budget",
+ bytes / MIB,
+ self.live / MIB,
+ self.limit / MIB
+ )))
+ }
+ }
+ }
+
+ fn release(&mut self, bytes: u64) {
+ self.live = self.live.saturating_sub(bytes);
+ }
+
+ /// An empty vector with room for `n` items, charged.
+ fn vec<T>(&mut self, n: usize) -> Result<Vec<T>> {
+ self.charge((n as u64).saturating_mul(std::mem::size_of::<T>() as u64))?;
+ let mut v = Vec::new();
+ v.try_reserve_exact(n).map_err(|_| Error::Unsupported(format!("out of memory for {n} items")))?;
+ Ok(v)
+ }
+
+ /// `n` copies of `value`, charged.
+ fn filled<T: Clone>(&mut self, n: usize, value: T) -> Result<Vec<T>> {
+ let mut v = self.vec::<T>(n)?;
+ v.resize(n, value);
+ Ok(v)
+ }
+ }
+
+ /// Inflate a zlib stream to at most `limit` bytes.
+ fn inflate(src: &[u8], limit: usize) -> Result<Vec<u8>> {
+ miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(src, limit).map_err(|e| Error::Invalid(format!("zip: {e:?}")))
+ }
+
++/// Give back what a channel buffer from `Psd::channel_bytes` / `Psd::decode_plane` was charged:
++/// a borrowed one (uncompressed data, or a plane of an inflated stream charged as a whole) was not.
++fn release_bytes(budget: &mut Budget, raw: &Cow<'_, [u8]>) {
++ if let Cow::Owned(v) = raw {
++ budget.release(v.len() as u64);
++ }
++}
++
++/// A 32-bit float sample made safe to use: NaN reads as 0, +inf as white (1.0, like the integer
++/// depths' maximum), -inf as 0.
++fn finite_sample(v: f32) -> f32 {
++ if v.is_nan() {
++ 0.0
++ } else if v == f32::INFINITY {
++ 1.0
++ } else if v == f32::NEG_INFINITY {
++ 0.0
++ } else {
++ v
++ }
++}
++
/// Whether `bytes` start like a Photoshop document.
pub fn is_psd(bytes: &[u8]) -> bool {
bytes.len() >= 6 && &bytes[..4] == b"8BPS" && matches!(u16::from_be_bytes([bytes[4], bytes[5]]), 1 | 2)
@@@ -830,88 -861,61 +925,121 @@@ impl Psd
}
}
- /// Decode one channel of `w`×`h` samples at `offset` (compression field first). Values 0..1.
- fn decode_channel(&self, offset: usize, len: usize, w: usize, h: usize) -> Result<Vec<f32>> {
+ /// The raw big-endian bytes of one channel of `w`×`h` samples at `offset` (compression field
- /// first): `row_bytes(w) × h` of them with the compression and the prediction undone. The
- /// buffer is charged to `budget`; the caller releases it once it is dropped.
- fn channel_bytes(&self, offset: usize, len: usize, w: usize, h: usize, budget: &mut Budget) -> Result<Vec<u8>> {
++ /// first): `row_bytes(w) × h` of them with the compression and the prediction undone.
++ /// Uncompressed data is borrowed from the file, not copied; any other buffer is charged to
++ /// `budget` and the caller releases it (see [`release_bytes`]) once it is dropped.
++ fn channel_bytes(&self, offset: usize, len: usize, w: usize, h: usize, budget: &mut Budget) -> Result<Cow<'_, [u8]>> {
let end = offset.checked_add(len).filter(|&e| e <= self.data.len()).ok_or(Error::Truncated)?;
- let mut r = Reader::at(&self.data[..end], offset);
+ let mut r = Reader::at(self.data.get(..end).ok_or(Error::Truncated)?, offset);
let comp = r.u16()?;
decode_pixels(w, h)?;
- let raw = self.plane_bytes(comp, &mut r, w, h)?;
- Ok(self.samples(&raw, w, h))
++ self.plane_bytes(comp, &mut r, w, h, budget)
+ }
+
+ /// The raw bytes (`row_bytes(w)` × `h`, ZIP prediction undone) of one channel whose pixel data
+ /// follows `r`'s position (after the compression field). Uncompressed data is borrowed, not
- /// copied.
- fn plane_bytes<'a>(&self, comp: u16, r: &mut Reader<'a>, w: usize, h: usize) -> Result<Cow<'a, [u8]>> {
++ /// copied; the other buffers are charged to `budget`.
++ fn plane_bytes<'a>(&self, comp: u16, r: &mut Reader<'a>, w: usize, h: usize, budget: &mut Budget) -> Result<Cow<'a, [u8]>> {
let rowb = self.row_bytes(w);
- Ok(match self.open_planes(comp, r, 1, 1, w, h)? {
- PlaneStream::Raw => Cow::Borrowed(r.bytes(rowb * h)?),
- PlaneStream::Rle(counts) => Cow::Owned(Self::unpack_plane(&counts, 0, r, rowb, h)?),
+ let size = rowb.checked_mul(h).ok_or_else(|| too_large(w, h))?;
- match comp {
- 0 => {
- let src = r.bytes(size)?;
- let mut v = budget.vec::<u8>(size)?;
- v.extend_from_slice(src);
- Ok(v)
++ Ok(match self.open_planes(comp, r, 1, 1, w, h, budget)? {
++ PlaneStream::Raw => Cow::Borrowed(r.bytes(size)?),
++ PlaneStream::Rle(counts) => Cow::Owned(Self::unpack_plane(&counts, 0, r, rowb, h, budget)?),
+ PlaneStream::Zip(mut v) => {
- v.resize(rowb * h, 0);
++ v.resize(size, 0);
+ self.zip_plane(comp, &mut v, 0, w, h)?;
+ Cow::Owned(v)
}
+ })
+ }
+
+ /// Prepare the pixel data at `r` (just after the compression field) of `total` planes of
+ /// `w`×`h` samples, of which the first `want` are decoded: the RLE row sizes of every plane,
- /// or the inflated ZIP data, which holds all planes one after another.
- fn open_planes(&self, comp: u16, r: &mut Reader, total: usize, want: usize, w: usize, h: usize) -> Result<PlaneStream> {
- let rowb = self.row_bytes(w);
++ /// or the inflated ZIP data, which holds all planes one after another (charged to `budget`
++ /// before it is inflated).
++ #[allow(clippy::too_many_arguments)]
++ fn open_planes(&self, comp: u16, r: &mut Reader, total: usize, want: usize, w: usize, h: usize, budget: &mut Budget) -> Result<PlaneStream> {
++ let size = self.row_bytes(w).checked_mul(h).ok_or_else(|| too_large(w, h))?;
+ Ok(match comp {
+ 0 => PlaneStream::Raw,
1 => {
- let mut counts = Vec::with_capacity(h.min(r.remaining() / 2));
- for _ in 0..h {
+ let n = total.saturating_mul(h);
+ let mut counts = Vec::with_capacity(n.min(r.remaining() / 2));
+ for _ in 0..n {
counts.push(if self.psb { r.u32()? as usize } else { r.u16()? as usize });
}
- let mut out = budget.vec::<u8>(size)?;
- for c in counts {
- unpack_bits(r.bytes(c)?, rowb, &mut out)?;
- }
- Ok(out)
+ PlaneStream::Rle(counts)
}
2 | 3 => {
let rest = r.bytes(r.remaining())?;
- let v = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(rest, want * rowb * h).map_err(|e| Error::Invalid(format!("zip: {e:?}")))?;
- PlaneStream::Zip(v)
- budget.charge(size as u64)?;
- let mut v = inflate(rest, size)?;
- v.resize(size, 0);
- if comp == 3 {
- self.unpredict(&mut v, w, h);
- }
- Ok(v)
++ // One stream holds every plane: what it may decode to is what they need.
++ let all = size.checked_mul(want).ok_or_else(|| too_large(w, h))?;
++ budget.charge(all as u64)?;
++ PlaneStream::Zip(inflate(rest, all)?)
}
- c => Err(Error::Unsupported(format!("compression {c}"))),
+ c => return Err(Error::Unsupported(format!("compression {c}"))),
+ })
+ }
+
+ /// The raw bytes (`row_bytes(w)` × `h`, ZIP prediction undone) of plane `c`: raw and RLE
+ /// planes are read from `r` in order, raw ones borrowed from the file data, ZIP ones from the
- /// inflated buffer, un-predicted in place.
- fn decode_plane<'x, 'a: 'x>(&self, comp: u16, planes: &'x mut PlaneStream, r: &mut Reader<'a>, c: usize, w: usize, h: usize) -> Result<Cow<'x, [u8]>> {
++ /// inflated buffer (un-predicted in place; already charged by `open_planes`), RLE ones charged
++ /// to `budget`.
++ #[allow(clippy::too_many_arguments)]
++ fn decode_plane<'x, 'a: 'x>(
++ &self,
++ comp: u16,
++ planes: &'x mut PlaneStream,
++ r: &mut Reader<'a>,
++ c: usize,
++ w: usize,
++ h: usize,
++ budget: &mut Budget,
++ ) -> Result<Cow<'x, [u8]>> {
+ let rowb = self.row_bytes(w);
++ let size = rowb.checked_mul(h).ok_or_else(|| too_large(w, h))?;
+ Ok(match planes {
- PlaneStream::Raw => Cow::Borrowed(r.bytes(rowb * h)?),
- PlaneStream::Rle(counts) => Cow::Owned(Self::unpack_plane(counts, c, r, rowb, h)?),
++ PlaneStream::Raw => Cow::Borrowed(r.bytes(size)?),
++ PlaneStream::Rle(counts) => Cow::Owned(Self::unpack_plane(counts, c, r, rowb, h, budget)?),
+ PlaneStream::Zip(v) => Cow::Borrowed(self.zip_plane(comp, v, c, w, h)?),
+ })
+ }
+
- /// Unpack the `h` RLE rows of plane `c` (row byte counts `counts`, plane after plane).
- fn unpack_plane(counts: &[usize], c: usize, r: &mut Reader, rowb: usize, h: usize) -> Result<Vec<u8>> {
- let mut out = Vec::with_capacity(rowb * h);
++ /// Unpack the `h` RLE rows of plane `c` (row byte counts `counts`, plane after plane) into a
++ /// buffer charged to `budget`.
++ fn unpack_plane(counts: &[usize], c: usize, r: &mut Reader, rowb: usize, h: usize, budget: &mut Budget) -> Result<Vec<u8>> {
++ let mut out = budget.vec::<u8>(rowb.checked_mul(h).ok_or(Error::Truncated)?)?;
+ for row in 0..h {
+ let n = *counts.get(c * h + row).ok_or(Error::Truncated)?;
+ unpack_bits(r.bytes(n)?, rowb, &mut out)?;
+ }
+ Ok(out)
+ }
+
+ /// Plane `c` of the inflated ZIP data of consecutive planes, un-predicted in place (`comp` 3).
+ fn zip_plane<'v>(&self, comp: u16, v: &'v mut [u8], c: usize, w: usize, h: usize) -> Result<&'v [u8]> {
+ let rowb = self.row_bytes(w);
+ let plane = v.get_mut(c * rowb * h..(c + 1) * rowb * h).ok_or(Error::Truncated)?;
+ if comp == 3 {
+ self.unpredict(plane, w, h);
}
+ Ok(plane)
}
+ /// One channel as `w * h` floats (0..1), charged to `budget` (the caller releases it).
+ fn channel_floats(&self, offset: usize, len: usize, w: usize, h: usize, budget: &mut Budget) -> Result<Vec<f32>> {
+ let raw = self.channel_bytes(offset, len, w, h, budget)?;
+ let mut out = budget.filled(decode_pixels(w, h)?, 0.0f32)?;
+ self.for_each_sample(&raw, w, h, |i, v| {
+ if let Some(o) = out.get_mut(i) {
+ *o = v;
+ }
+ });
- budget.release(raw.len() as u64);
++ release_bytes(budget, &raw);
+ Ok(out)
+ }
+
fn row_bytes(&self, w: usize) -> usize {
if self.depth == 1 { w.div_ceil(8) } else { w * self.bytes_per_sample() }
}
@@@ -965,32 -967,13 +1095,14 @@@
for x in 0..w {
let b = raw.get(y * rowb + x / 8).copied().unwrap_or(0);
// 1 = black.
- out.push(if b & (0x80 >> (x % 8)) != 0 { 0.0 } else { 1.0 });
+ f(y * w + x, if b & (0x80 >> (x % 8)) != 0 { 0.0 } else { 1.0 });
}
}
- out
}
- 16 => raw.as_chunks::<2>().0.iter().take(w * h).map(|c| u16::from_be_bytes([c[0], c[1]]) as f32 / 65535.0).collect(),
+ 16 => raw.as_chunks::<2>().0.iter().take(n).enumerate().for_each(|(i, c)| f(i, u16::from_be_bytes([c[0], c[1]]) as f32 / 65535.0)),
- 32 => raw.as_chunks::<4>().0.iter().take(n).enumerate().for_each(|(i, c)| f(i, f32::from_be_bytes([c[0], c[1], c[2], c[3]]))),
+ // NaN reads as 0, +inf as white (1.0, like the integer depths' maximum), -inf as 0.
- 32 => raw
- .as_chunks::<4>()
- .0
- .iter()
- .take(w * h)
- .map(|c| {
- let v = f32::from_be_bytes([c[0], c[1], c[2], c[3]]);
- if v.is_nan() {
- 0.0
- } else if v == f32::INFINITY {
- 1.0
- } else if v == f32::NEG_INFINITY {
- 0.0
- } else {
- v
- }
- })
- .collect(),
- _ => raw.iter().take(w * h).map(|&b| b as f32 / 255.0).collect(),
++ 32 => raw.as_chunks::<4>().0.iter().take(n).enumerate().for_each(|(i, c)| f(i, finite_sample(f32::from_be_bytes([c[0], c[1], c[2], c[3]])))),
+ _ => raw.iter().take(n).enumerate().for_each(|(i, &b)| f(i, b as f32 / 255.0)),
}
}
@@@ -1023,17 -1041,57 +1170,25 @@@
let nch = self.channels as usize;
let cc = self.mode.color_channels();
let want = (cc + usize::from(self.merged_alpha)).min(nch);
- let mut planes: Vec<Option<Vec<f32>>> = vec![None; nch];
- let mut stream = self.open_planes(comp, &mut r, nch, want, w, h)?;
- for (c, p) in planes.iter_mut().enumerate().take(want) {
- *p = Some(self.samples(&self.decode_plane(comp, &mut stream, &mut r, c, w, h)?, w, h));
+ let rowb = self.row_bytes(w);
+ let size = rowb.checked_mul(h).ok_or_else(|| too_large(w, h))?;
+ // The peak: the result, the CMYK black channel and what the channels decode through.
+ let black_bytes = if self.mode == ColorMode::Cmyk && want > 3 { 4 * n as u64 } else { 0 };
+ let transient = if matches!(comp, 2 | 3) { (size as u64).saturating_mul(want as u64) } else { size as u64 };
+ budget.check((16 * n as u64).saturating_add(black_bytes).saturating_add(transient))?;
+ // Opaque black until a channel says otherwise.
+ let mut data = budget.filled(n, [0.0f32, 0.0, 0.0, 1.0])?;
+ let mut black = if self.mode == ColorMode::Cmyk && want > 3 { Some(budget.filled(n, 0.0f32)?) } else { None };
- match comp {
- 0 => {
- for c in 0..want {
- self.store_merged_channel(c, r.bytes(size)?, &mut data, &mut black);
- }
- }
- 1 => {
- let total = nch.saturating_mul(h);
- let mut counts = Vec::with_capacity(total.min(r.remaining() / 2));
- for _ in 0..total {
- counts.push(if self.psb { r.u32()? as usize } else { r.u16()? as usize });
- }
- for c in 0..want {
- let mut out = budget.vec::<u8>(size)?;
- for row in 0..h {
- let count = *counts.get(c * h + row).ok_or(Error::Truncated)?;
- unpack_bits(r.bytes(count)?, rowb, &mut out)?;
- }
- self.store_merged_channel(c, &out, &mut data, &mut black);
- budget.release(size as u64);
- }
- }
- 2 | 3 => {
- let rest = r.bytes(r.remaining())?;
- // One stream holds every channel: what it may decode to is what they need.
- let total = size.checked_mul(want).ok_or_else(|| too_large(w, h))?;
- budget.charge(total as u64)?;
- let mut v = inflate(rest, total)?;
- for c in 0..want {
- let plane = v.get_mut(c * size..(c + 1) * size).ok_or(Error::Truncated)?;
- if comp == 3 {
- self.unpredict(plane, w, h);
- }
- self.store_merged_channel(c, plane, &mut data, &mut black);
- }
- }
- c => return Err(Error::Unsupported(format!("compression {c}"))),
++ let mut stream = self.open_planes(comp, &mut r, nch, want, w, h, &mut budget)?;
++ for c in 0..want {
++ let raw = self.decode_plane(comp, &mut stream, &mut r, c, w, h, &mut budget)?;
++ self.store_merged_channel(c, &raw, &mut data, &mut black);
++ release_bytes(&mut budget, &raw);
}
- let alpha = if self.merged_alpha && nch > cc { planes[cc].take() } else { None };
- let mut data = Vec::with_capacity(w * h);
- for i in 0..w * h {
- let [r, g, b] = self.to_rgb(&planes, i);
- let a = alpha.as_ref().map_or(1.0, |a| a[i]);
- data.push([r, g, b, a]);
+ for (i, p) in data.iter_mut().enumerate() {
+ let k = black.as_ref().and_then(|k| k.get(i)).copied().unwrap_or(0.0);
+ let [r, g, b] = self.rgb_from([p[0], p[1], p[2], k]);
+ *p = [r, g, b, p[3]];
}
Ok(Pixels { width: w as u32, height: h as u32, data })
}
@@@ -1080,16 -1150,77 +1247,77 @@@
};
let (ys, oy) = span(src.top, sh, out_rect.top, oh);
let (xs, ox) = span(src.left, sw, out_rect.left, ow);
- for y in ys {
- let dy = (y as i64 - oy) as usize;
- for x in xs.clone() {
- let dx = (x as i64 - ox) as usize;
- let i = y * sw + x;
- let (rgb, a) = match fill {
- Some(f) if !l.has_pixels() => (f, 1.0),
- _ => (self.to_rgb(&planes, i), alpha.as_ref().map_or(1.0, |a| a[i])),
- };
- out[dy * ow + dx] = [rgb[0], rgb[1], rgb[2], a];
+ let dest = |y: usize, x: usize| (y as i64 - oy) as usize * ow + (x as i64 - ox) as usize;
+ let fill = l.fill.map(|c| c.map(|v| v as f32));
+ match fill {
+ Some(f) if !l.has_pixels() => {
+ for y in ys {
+ for x in xs.clone() {
+ if let Some(p) = out.get_mut(dest(y, x)) {
+ *p = [f[0], f[1], f[2], 1.0];
+ }
+ }
+ }
+ }
+ _ => {
+ // Opaque unless there is an alpha channel.
+ for y in ys.clone() {
+ for x in xs.clone() {
+ if let Some(p) = out.get_mut(dest(y, x)) {
+ p[3] = 1.0;
+ }
+ }
+ }
+ let cc = self.mode.color_channels();
+ let mut black: Option<Vec<f32>> = None;
+ if l.has_pixels() {
+ for c in &l.channels {
+ let slot = match c.id {
+ -1 => 3,
+ id if id >= 0 && (id as usize) < cc => id as usize,
+ _ => continue,
+ };
+ let raw = self.channel_bytes(c.offset, c.len, sw, sh, &mut budget)?;
+ // The fourth CMYK channel is the black plate, not a slot of the result.
+ let to_black = c.id == 3;
+ if to_black && black.is_none() {
+ black = Some(budget.filled(out.len(), 0.0f32)?);
+ }
+ // Samples arrive in row-major order of the source.
+ let (mut sy, mut sx) = (0usize, 0usize);
+ self.for_each_sample(&raw, sw, sh, |_, v| {
+ if ys.contains(&sy) && xs.contains(&sx) {
+ let d = dest(sy, sx);
+ if to_black {
+ if let Some(o) = black.as_mut().and_then(|k| k.get_mut(d)) {
+ *o = v;
+ }
+ } else if let Some(p) = out.get_mut(d) {
+ p[slot] = v;
+ }
+ }
+ sx += 1;
+ if sx == sw {
+ sx = 0;
+ sy += 1;
+ }
+ });
- budget.release(raw.len() as u64);
++ release_bytes(&mut budget, &raw);
+ }
+ }
+ for y in ys {
+ for x in xs.clone() {
+ let d = dest(y, x);
+ let k = black.as_ref().and_then(|k| k.get(d)).copied().unwrap_or(0.0);
+ if let Some(p) = out.get_mut(d) {
+ let [r, g, b] = self.rgb_from([p[0], p[1], p[2], k]);
+ *p = [r, g, b, p[3]];
+ }
+ }
+ }
+ if let Some(k) = black {
+ budget.release(k.len() as u64 * 4);
+ }
}
}
}
@@@ -1261,31 -1363,7 +1489,33 @@@ fn lab_to_rgb(l: f32, a: f32, b: f32) -
[r, g, bb].map(|v| srgb_encode(v.clamp(0.0, 1.0)))
}
+ #[cfg(test)]
+ mod memory_tests;
#[cfg(test)]
mod tests;
+#[cfg(test)]
+mod tests_opt;
+
+/// Test-only call counters (per thread), to prove what the optimised paths avoid doing.
+#[cfg(test)]
+pub(crate) mod counters {
+ use std::cell::Cell;
+ use std::thread::LocalKey;
+
+ thread_local! {
+ /// Scratch rows allocated by the 32-bit ZIP un-predictor.
+ pub static SCRATCH: Cell<usize> = const { Cell::new(0) };
+ /// `inside the mask rect` evaluations of the layer-mask loop.
+ pub static INSIDE: Cell<usize> = const { Cell::new(0) };
+ /// `square_to_quad` solves.
+ pub static QUAD: Cell<usize> = const { Cell::new(0) };
+ }
+
+ pub fn bump(c: &'static LocalKey<Cell<usize>>) {
+ c.with(|c| c.set(c.get() + 1));
+ }
+ /// Read and reset.
+ pub fn take(c: &'static LocalKey<Cell<usize>>) -> usize {
+ c.with(|c| c.replace(0))
+ }
+}
diff --cc crates/psd/src/placed.rs
index ae140a9fc,25490e4da..dff525a89
--- a/crates/psd/src/placed.rs
+++ b/crates/psd/src/placed.rs
@@@ -278,25 -252,43 +282,44 @@@ impl SmartObject
/// The baked size for a `w`×`h` content at `k` pixels per document pixel.
pub fn placed_size(&self, w: f64, h: f64, k: f64) -> (u32, u32) {
- let bb = self.placed_bounds(w, h);
- (((bb[2] - bb[0]) * k).ceil().clamp(1.0, 16384.0) as u32, ((bb[3] - bb[1]) * k).ceil().clamp(1.0, 16384.0) as u32)
+ size_for(self.placed_bounds(w, h), k)
}
+ /// The scale and size to bake a `w`×`h` content at, wanting `k` pixels per document pixel but
+ /// never more than [`MAX_BAKE_PIXELS`] pixels, nor more than 4× the `doc` size across either
+ /// way: a quad corner far outside the document lowers `k` (possibly below 1) instead of asking
+ /// for a gigantic image. Returns the scale actually used and the size in pixels.
+ pub fn bake_scale(&self, w: f64, h: f64, k: f64, doc: (u32, u32)) -> (f64, (u32, u32)) {
+ let bb = self.placed_bounds(w, h);
+ let (bw, bh) = ((bb[2] - bb[0]).max(1.0), (bb[3] - bb[1]).max(1.0));
+ if !(bw.is_finite() && bh.is_finite() && k.is_finite() && k > 0.0) {
+ return (1.0, (1, 1));
+ }
+ let (max_w, max_h) = ((f64::from(doc.0) * 4.0).max(1.0), (f64::from(doc.1) * 4.0).max(1.0));
+ let capped = k.min(max_w / bw).min(max_h / bh).min((MAX_BAKE_PIXELS as f64 / (bw * bh)).sqrt());
+ // Rounding up could step over a cap, so a lowered scale rounds down.
+ let side = |len: f64| if capped < k { (len * capped).floor() } else { (len * capped).ceil() }.clamp(1.0, 16384.0) as u32;
+ (capped, (side(bw), side(bh)))
+ }
+
/// Bake the content (straight RGBA) as placed: warped and mapped by the quad, rendered at
/// `k` pixels per document pixel (into `size` pixels when given; see [`Self::placed_size`]).
- /// Returns the pixels and their document-space origin.
+ /// Returns the pixels and their document-space origin. `None` when the content is empty or
+ /// the baked image would exceed [`MAX_BAKE_PIXELS`].
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;
}
- let bb = self.placed_bounds(cw, ch);
+ // 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 => self.placed_size(cw, ch, k),
+ 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));
@@@ -441,17 -432,34 +466,48 @@@ mod tests
assert!(at(35, 10)[1] > 0.9, "{:?}", at(35, 10));
assert_eq!(at(38, 1)[3], 0.0, "outside the trapezoid");
}
+
+ #[test]
+ fn custom_warp_with_a_missing_or_short_mesh_does_not_panic() {
+ let base = Warp { style: "warpCustom".into(), bounds: [0.0, 0.0, 20.0, 10.0], cols: 1, rows: 1, ..Default::default() };
+ // Empty and too-short meshes leave the point where it is.
+ assert_eq!(base.apply([5.0, 5.0], 20.0, 10.0), [5.0, 5.0]);
+ let short = Warp { mesh: vec![[0.0, 0.0]; 5], ..base.clone() };
+ assert_eq!(short.apply([5.0, 5.0], 20.0, 10.0), [5.0, 5.0]);
+ for (cols, rows) in [(0, 0), (0, 3), (usize::MAX, 1), (1, usize::MAX), (usize::MAX, usize::MAX)] {
+ let w = Warp { cols, rows, ..base.clone() };
+ assert_eq!(w.apply([5.0, 5.0], 20.0, 10.0), [5.0, 5.0]);
+ }
+ }
++
+ #[test]
+ fn an_absurd_quad_corner_bakes_within_four_times_the_document_and_2_pow_24_pixels() {
+ let doc = (1920u32, 1080u32);
+ for far in [1e4, 1e6, 1e12] {
+ let s = SmartObject { uuid: "x".into(), quad: [[0.0, 0.0], [far, 5.0], [far, far], [0.0, 20.0]], size: None, warp: None };
+ assert!(s.needs_bake());
+ // What the importer asks for: the unbounded size is the 16384² clamp, 4 GiB as float RGBA.
+ assert_eq!(s.placed_size(100.0, 100.0, 4.0), (16384, 16384));
+ let (k, (w, h)) = s.bake_scale(100.0, 100.0, 4.0, doc);
+ assert!(k > 0.0 && k <= 4.0, "{k}");
+ assert!(w <= doc.0 * 4 && h <= doc.1 * 4, "{w}x{h}");
+ assert!(u64::from(w) * u64::from(h) <= MAX_BAKE_PIXELS, "{w}x{h}");
+ }
+ // A quad inside the document keeps the scale and the size it always had.
+ let s = SmartObject { uuid: "x".into(), quad: [[0.0, 0.0], [400.0, 50.0], [400.0, 150.0], [0.0, 200.0]], size: None, warp: None };
+ let (k, size) = s.bake_scale(100.0, 100.0, 2.0, doc);
+ assert_eq!((k, size), (2.0, s.placed_size(100.0, 100.0, 2.0)));
+ // Not-a-number corners stay small too.
+ let s = SmartObject { uuid: "x".into(), quad: [[f64::NAN; 2]; 4], size: None, warp: None };
+ let (_, (w, h)) = s.bake_scale(100.0, 100.0, 4.0, doc);
+ assert!(u64::from(w) * u64::from(h) <= MAX_BAKE_PIXELS);
+ }
+
+ #[test]
+ fn render_placed_refuses_an_output_over_the_pixel_cap() {
+ let content = Pixels { width: 2, height: 1, data: vec![[1.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 1.0]] };
+ let s = SmartObject { uuid: "x".into(), quad: [[0.0, 0.0], [40.0, 5.0], [40.0, 15.0], [0.0, 20.0]], size: None, warp: None };
+ assert!(s.render_placed(&content, 1.0, Some((16384, 16384))).is_none());
+ assert!(s.render_placed(&content, 1.0, Some((u32::MAX, u32::MAX))).is_none());
+ }
}