mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-26 08:26:04 +00:00
Merge pull request #6022 from mockydevs/fix/eps-huge-image-reduced
EPS import: images over 67 million pixels are read at a lower resolution instead of left out
This commit is contained in:
@@ -76,14 +76,28 @@ fn flate(raw: &[u8]) -> Res<(Vec<u8>, usize)> {
|
||||
|
||||
/// LZW data (`EarlyChange` 1) decoded, and how many bytes of `raw` it took.
|
||||
fn lzw(raw: &[u8]) -> Res<(Vec<u8>, usize)> {
|
||||
let mut out = vec![];
|
||||
let used = lzw_into(raw, &mut |bytes| {
|
||||
out.extend_from_slice(bytes);
|
||||
if out.len() > MAX_DATA {
|
||||
return Err(PsError::Limit("decoded data is too large"));
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok((out, used))
|
||||
}
|
||||
|
||||
/// LZW data (`EarlyChange` 1) decoded into `sink` as it goes, and how many bytes of `raw` it
|
||||
/// took.
|
||||
fn lzw_into(raw: &[u8], sink: &mut dyn FnMut(&[u8]) -> Res) -> Res<usize> {
|
||||
let mut table: Vec<Vec<u8>> = (0..=255u8).map(|b| vec![b]).collect();
|
||||
table.push(vec![]);
|
||||
table.push(vec![]);
|
||||
let (mut out, mut prev): (Vec<u8>, Option<Vec<u8>>) = (vec![], None);
|
||||
let mut prev: Option<Vec<u8>> = None;
|
||||
let (mut acc, mut bits, mut width, mut i) = (0u32, 0u32, 9u32, 0usize);
|
||||
loop {
|
||||
while bits < width {
|
||||
let Some(&b) = raw.get(i) else { return Ok((out, i)) };
|
||||
let Some(&b) = raw.get(i) else { return Ok(i) };
|
||||
i += 1;
|
||||
acc = (acc << 8) | u32::from(b);
|
||||
bits += 8;
|
||||
@@ -96,7 +110,7 @@ fn lzw(raw: &[u8]) -> Res<(Vec<u8>, usize)> {
|
||||
width = 9;
|
||||
prev = None;
|
||||
}
|
||||
257 => return Ok((out, i)),
|
||||
257 => return Ok(i),
|
||||
_ => {
|
||||
let entry = match (table.get(code), &prev) {
|
||||
(Some(e), _) if !e.is_empty() => e.clone(),
|
||||
@@ -107,7 +121,7 @@ fn lzw(raw: &[u8]) -> Res<(Vec<u8>, usize)> {
|
||||
}
|
||||
_ => return io("LZWDecode"),
|
||||
};
|
||||
out.extend_from_slice(&entry);
|
||||
sink(&entry)?;
|
||||
if let Some(mut p) = prev.take()
|
||||
&& table.len() < 4096
|
||||
{
|
||||
@@ -121,14 +135,78 @@ fn lzw(raw: &[u8]) -> Res<(Vec<u8>, usize)> {
|
||||
_ => 9,
|
||||
};
|
||||
prev = Some(entry);
|
||||
if out.len() > MAX_DATA {
|
||||
return Err(PsError::Limit("decoded data is too large"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// zlib data inflated into `sink` as it goes (64 KiB at a time), and how many bytes of `raw` it
|
||||
/// took.
|
||||
fn flate_into(raw: &[u8], sink: &mut dyn FnMut(&[u8]) -> Res) -> Res<usize> {
|
||||
let mut z = flate2::Decompress::new(true);
|
||||
let mut scratch = vec![0u8; 64 * 1024];
|
||||
loop {
|
||||
let before = (z.total_in(), z.total_out());
|
||||
let input = raw.get(usize::try_from(z.total_in()).unwrap_or(usize::MAX)..).unwrap_or_default();
|
||||
let status = z.decompress(input, &mut scratch, flate2::FlushDecompress::None).map_err(|_| PsError::Ps("ioerror", "FlateDecode".into()))?;
|
||||
let made = usize::try_from(z.total_out() - before.1).unwrap_or(0);
|
||||
sink(scratch.get(..made).unwrap_or_default())?;
|
||||
match status {
|
||||
flate2::Status::StreamEnd => break,
|
||||
_ if (z.total_in(), z.total_out()) == before => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(usize::try_from(z.total_in()).unwrap_or(raw.len()))
|
||||
}
|
||||
|
||||
/// Data compressed with filter `f` (`FlateDecode` or `LZWDecode` without a predictor) decoded
|
||||
/// into `sink` as it goes, and how many bytes of `raw` it took; `None` for other filters.
|
||||
pub(super) fn decode_into(f: &Filter, raw: &[u8], sink: &mut dyn FnMut(&[u8]) -> Res) -> Option<Res<usize>> {
|
||||
match &*f.name {
|
||||
_ if f.predictor.is_some() => None,
|
||||
"FlateDecode" => Some(flate_into(raw, sink)),
|
||||
"LZWDecode" => Some(lzw_into(raw, sink)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// How many bytes of `raw` filter `f` would read, found without keeping what it decodes, for
|
||||
/// data whose decoded form is too large to hold: compressed data (`FlateDecode`, `LZWDecode`,
|
||||
/// `RunLengthDecode`) is decoded and dropped as it goes, a JPEG ends at its end-of-image
|
||||
/// marker, as [`dct`] reads it. `None` for other filters, data that can't be decoded, or data
|
||||
/// that decodes to more than `most` bytes (what the caller's operation budget still pays for).
|
||||
/// With it, how many bytes were decoded on the way, for the caller to charge: measuring costs
|
||||
/// the work of decoding, so a program that measures the same data in a loop has to end.
|
||||
pub(super) fn encoded_len(f: &Filter, raw: &[u8], most: usize) -> (Option<usize>, usize) {
|
||||
let mut decoded = 0usize;
|
||||
let mut count = |bytes: &[u8]| -> Res {
|
||||
decoded = decoded.saturating_add(bytes.len());
|
||||
if decoded > most {
|
||||
return Err(PsError::Limit("the program runs too long"));
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
let used = match &*f.name {
|
||||
"FlateDecode" => flate_into(raw, &mut count).ok(),
|
||||
"LZWDecode" => lzw_into(raw, &mut count).ok(),
|
||||
"RunLengthDecode" => {
|
||||
let mut i = 0usize;
|
||||
while let Some(&n) = raw.get(i) {
|
||||
i += match n {
|
||||
128 => return (Some(i + 1), 0),
|
||||
0..=127 => 2 + usize::from(n),
|
||||
_ => 2,
|
||||
};
|
||||
}
|
||||
Some(raw.len())
|
||||
}
|
||||
"DCTDecode" => Some(find(raw, &[0xFF, 0xD9]).map_or(raw.len(), |e| e + 2)),
|
||||
_ => None,
|
||||
};
|
||||
(used, decoded)
|
||||
}
|
||||
|
||||
/// Most pixels a DCTDecode JPEG may have: twice the most an image is read with, so every image that
|
||||
/// was read before is still read.
|
||||
const MAX_DCT_PIXELS: u64 = 1 << 27;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::filters::{Filter, Predictor, Stream, decode, fax_settings, io};
|
||||
use super::filters::{Filter, Predictor, Stream, decode, decode_into, encoded_len, fax_settings, io};
|
||||
use super::pixels::{Pixels, Spec, by_rows, by_samples, masked, source};
|
||||
use super::{
|
||||
Affine, Color, DictRef, HashMap, ImageBlob, ImageObject, Inks, Interp, Key, Lexer, Node, NodeId, NodeKind, Obj, Op, OpacityMask, Paint, PsError,
|
||||
@@ -18,6 +18,8 @@ const MAX_PIXELS: usize = 1 << 26;
|
||||
|
||||
/// Why an image is missing.
|
||||
const TOO_LARGE: &str = "images too large to read were left out";
|
||||
/// Why an image is at a lower resolution than the file's.
|
||||
const REDUCED: &str = "images of more than 67 million pixels were read at a lower resolution";
|
||||
|
||||
/// Most distinct colours an image converts through a tint transform.
|
||||
const MAX_TINTS: usize = 1 << 16;
|
||||
@@ -479,25 +481,184 @@ impl Interp<'_> {
|
||||
/// their own end without decompressing (`ASCIIHexDecode`, `ASCII85Decode`, `SubFileDecode`)
|
||||
/// read the file up to it, the way the image reading all its data would leave it; the
|
||||
/// filters over them, which would only decode what those pass, aren't run. When the first
|
||||
/// filter decompresses, it is run alone, and a failure (data too large to hold) leaves the
|
||||
/// data where it was, as before.
|
||||
fn skip_data(&mut self, src: &Source) {
|
||||
/// filter decompresses, it is run alone; when it can't hold what it decompresses, it measures
|
||||
/// its data instead. Unfiltered data is read past by its `n` bytes. A failure that read
|
||||
/// nothing leaves the data where it was; one after a filter read its data leaves the file
|
||||
/// past it, with nothing more to read.
|
||||
fn skip_data(&mut self, src: &Source, n: usize) {
|
||||
// A procedure (`{ currentfile buf readhexstring pop }`) reads the data itself: it is
|
||||
// called, and what it gives dropped, until it has given the image's `n` bytes or ends.
|
||||
if let Source::Proc(p) = src {
|
||||
let mut given = 0usize;
|
||||
while given < n {
|
||||
let Ok(len) = self.call(p.clone()).and_then(|()| self.pop_str()).map(|s| s.len()) else { return };
|
||||
if len == 0 {
|
||||
return;
|
||||
}
|
||||
given = given.saturating_add(len);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let Source::File(f) = src else { return };
|
||||
let (chain, from) = match &*f.borrow() {
|
||||
let (chain, from) = match &mut *f.borrow_mut() {
|
||||
Stream::Pending { chain, from } => (chain.clone(), from.clone()),
|
||||
_ => return,
|
||||
// The data unfiltered: its `n` bytes are read past, as reading them would.
|
||||
Stream::Current => {
|
||||
let k = n.min(self.lex.data().len());
|
||||
self.lex.advance(k);
|
||||
return;
|
||||
}
|
||||
Stream::Buf { data, pos, .. } => {
|
||||
*pos = pos.saturating_add(n).min(data.len());
|
||||
return;
|
||||
}
|
||||
};
|
||||
let delimited = chain.iter().take_while(|c| matches!(&*c.name, "ASCIIHexDecode" | "ASCII85Decode" | "SubFileDecode")).count();
|
||||
let head = chain.get(..delimited.max(1)).unwrap_or_default().to_vec();
|
||||
*f.borrow_mut() = Stream::Pending { chain: head, from: from.clone() };
|
||||
// A failure leaves the file as it was; the import goes on without the image either way.
|
||||
// How much of the file the filters are over is left.
|
||||
let left = |me: &mut Self| match &from {
|
||||
None => Some(me.lex.data().len()),
|
||||
Some(r) => match &*r.borrow() {
|
||||
Stream::Buf { data, pos, .. } => Some(data.len().saturating_sub(*pos)),
|
||||
Stream::Current => Some(me.lex.data().len()),
|
||||
Stream::Pending { .. } => None,
|
||||
},
|
||||
};
|
||||
let before = left(self);
|
||||
if self.materialize(f).is_err() {
|
||||
*f.borrow_mut() = Stream::Pending { chain, from };
|
||||
return;
|
||||
// A filter that read its data before a later one failed has the file past that data,
|
||||
// where reading the image would leave it: the file is empty from there.
|
||||
if left(self) != before {
|
||||
*f.borrow_mut() = Stream::Buf { data: vec![], pos: 0, rgb: None };
|
||||
return;
|
||||
}
|
||||
// Decompressed data too large to hold: the first filter only measures it instead,
|
||||
// and the file is read past it. Data that can't be decoded at all leaves the file as
|
||||
// it was; the import goes on without the image either way.
|
||||
let Some(first) = chain.first() else { return };
|
||||
// Measuring decompresses the data, which is charged by the bytes decoded (one operation
|
||||
// per 256, as `spend_bytes` charges) and stops at what the budget still pays for:
|
||||
// data measured again and again (a reusable stream reset in a loop) runs out of the
|
||||
// budget instead of being decoded in full on every pass.
|
||||
let most = usize::try_from(self.ops_left().saturating_mul(256)).unwrap_or(usize::MAX);
|
||||
let (used, decoded) = match &from {
|
||||
Some(r) => match &*r.borrow() {
|
||||
Stream::Buf { data, pos, .. } => encoded_len(first, data.get(*pos..).unwrap_or_default(), most),
|
||||
_ => (None, 0),
|
||||
},
|
||||
None => encoded_len(first, self.lex.data(), most),
|
||||
};
|
||||
let paid = self.spend_bytes(decoded).is_ok();
|
||||
let Some(used) = used.filter(|_| paid) else {
|
||||
*f.borrow_mut() = Stream::Pending { chain, from };
|
||||
return;
|
||||
};
|
||||
match &from {
|
||||
Some(r) => {
|
||||
if let Stream::Buf { pos, .. } = &mut *r.borrow_mut() {
|
||||
*pos = pos.saturating_add(used);
|
||||
}
|
||||
}
|
||||
None => self.lex.advance(used),
|
||||
}
|
||||
}
|
||||
*f.borrow_mut() = Stream::Buf { data: vec![], pos: 0, rgb: None };
|
||||
}
|
||||
|
||||
/// The rows image `s` reads at `step` (rows of `row` bytes), when its one source is the
|
||||
/// program's data with Flate or LZW last among its filters (and no predictor): the filters
|
||||
/// before it are decoded as usual, and it decodes into the rows read alone, dropping the
|
||||
/// others as it goes. `None` (nothing read) for other data, or rows read that would still be
|
||||
/// more than the reader holds.
|
||||
fn read_rows(&mut self, s: &Spec, row: usize, step: usize) -> Res<Option<Vec<u8>>> {
|
||||
let ([Source::File(f)], oh) = (s.sources.as_slice(), s.h.div_ceil(step)) else { return Ok(None) };
|
||||
let (chain, from) = match &*f.borrow() {
|
||||
Stream::Pending { chain, from } => (chain.clone(), from.clone()),
|
||||
_ => return Ok(None),
|
||||
};
|
||||
let Some((last, head)) = chain.split_last() else { return Ok(None) };
|
||||
if last.predictor.is_some() || !matches!(&*last.name, "FlateDecode" | "LZWDecode") {
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(kept) = row.checked_mul(oh).filter(|k| *k <= MAX_DATA) else { return Ok(None) };
|
||||
self.alloc(kept)?;
|
||||
// The compressed data: what the filters before the last one decode, or the file itself.
|
||||
let compressed = if head.is_empty() {
|
||||
None
|
||||
} else {
|
||||
*f.borrow_mut() = Stream::Pending { chain: head.to_vec(), from: from.clone() };
|
||||
if let Err(e) = self.materialize(f) {
|
||||
*f.borrow_mut() = Stream::Pending { chain, from };
|
||||
return Err(e);
|
||||
}
|
||||
match std::mem::replace(&mut *f.borrow_mut(), Stream::Buf { data: vec![], pos: 0, rgb: None }) {
|
||||
Stream::Buf { data, pos, .. } => Some(data.get(pos..).unwrap_or_default().to_vec()),
|
||||
_ => Some(vec![]),
|
||||
}
|
||||
};
|
||||
let (mut rows, mut seen) = (Vec::with_capacity(kept), 0usize);
|
||||
// Past the image's data and as much again the data is not an image's: it stops there.
|
||||
let most = row.saturating_mul(s.h).saturating_add(MAX_DATA);
|
||||
let mut sink = |mut chunk: &[u8]| -> Res {
|
||||
while !chunk.is_empty() {
|
||||
let (r, off) = (seen / row.max(1), seen % row.max(1));
|
||||
let take = (row - off).min(chunk.len());
|
||||
if r < s.h && picked(r / step, step, s.h) == r {
|
||||
rows.extend_from_slice(chunk.get(..take).unwrap_or_default());
|
||||
}
|
||||
seen += take;
|
||||
chunk = chunk.get(take..).unwrap_or_default();
|
||||
}
|
||||
if seen > most {
|
||||
return Err(PsError::Limit("decoded data is too large"));
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
let used = match &compressed {
|
||||
Some(data) => decode_into(last, data, &mut sink),
|
||||
None => match &from {
|
||||
Some(r) => {
|
||||
let b = r.borrow();
|
||||
let Stream::Buf { data, pos, .. } = &*b else { return io("filter") };
|
||||
let used = decode_into(last, data.get(*pos..).unwrap_or_default(), &mut sink);
|
||||
drop(b);
|
||||
if let (Some(Ok(n)), Stream::Buf { pos, .. }) = (&used, &mut *r.borrow_mut()) {
|
||||
*pos = pos.saturating_add(*n);
|
||||
}
|
||||
used
|
||||
}
|
||||
None => {
|
||||
let used = decode_into(last, self.lex.data(), &mut sink);
|
||||
if let Some(Ok(n)) = &used {
|
||||
self.lex.advance(*n);
|
||||
}
|
||||
used
|
||||
}
|
||||
},
|
||||
};
|
||||
drop(sink);
|
||||
let Some(used) = used else { return Ok(None) };
|
||||
// What was decoded is charged whether or not the data decoded to its end.
|
||||
self.spend_bytes(seen)?;
|
||||
used?;
|
||||
*f.borrow_mut() = Stream::Buf { data: vec![], pos: 0, rgb: None };
|
||||
rows.resize(kept, 0);
|
||||
Ok(Some(rows))
|
||||
}
|
||||
|
||||
/// Leave out image `s` (too large to read), skipping its data: `None`, the image it gives.
|
||||
fn leave_out(&mut self, s: &Spec) -> Option<Pixels> {
|
||||
self.out.warn(TOO_LARGE);
|
||||
let n = if s.stencil.is_some() { 1 } else { s.space.n() };
|
||||
let per_source = if s.sources.len() > 1 { 1 } else { n };
|
||||
let bytes = (s.w.saturating_mul(per_source).saturating_mul(usize::from(s.bpc))).div_ceil(8).saturating_mul(s.h);
|
||||
for src in &s.sources {
|
||||
self.skip_data(src, bytes);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The bytes a data procedure gives, called until it gives an empty string or `n` bytes.
|
||||
fn gather(&mut self, p: &Obj, n: usize) -> Res<Vec<u8>> {
|
||||
Ok(self.read_sources(&[Source::Proc(p.clone())], n, n)?.pop().unwrap_or_default())
|
||||
@@ -640,13 +801,6 @@ impl Interp<'_> {
|
||||
let mut stencil = self.image_dict(&mask, false)?;
|
||||
stencil.space = Space::Gray;
|
||||
let n = image.space.n();
|
||||
if image.w.saturating_mul(image.h) > MAX_PIXELS || stencil.w.saturating_mul(stencil.h) > MAX_PIXELS {
|
||||
self.out.warn(TOO_LARGE);
|
||||
for src in image.sources.iter().chain(&stencil.sources) {
|
||||
self.skip_data(src);
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
// Interleaved data is read into this decoder's own buffers, split into the two images'
|
||||
// samples: those stop counting once both are decoded (their pixels still count).
|
||||
let mut charged = 0;
|
||||
@@ -655,18 +809,19 @@ impl Interp<'_> {
|
||||
let (pixels, samples) = if interleave == 2.0 {
|
||||
let (mrow, drow) = (stencil.row_bytes(1), image.row_bytes(n));
|
||||
let total = mrow.saturating_mul(stencil.h).saturating_add(drow.saturating_mul(image.h));
|
||||
self.alloc(total)?;
|
||||
charged = total;
|
||||
let raw = self.source_bytes(&src, total.min(MAX_DATA))?;
|
||||
// What is read: an image past the pixel cap is reduced from the samples read.
|
||||
charged = total.min(MAX_DATA);
|
||||
self.alloc(charged)?;
|
||||
let raw = self.source_bytes(&src, charged)?;
|
||||
by_rows(&raw, (mrow, stencil.h), (drow, image.h))
|
||||
} else {
|
||||
// Each sample: the mask's value, then the colour's, as many bits each.
|
||||
stencil.bpc = image.bpc;
|
||||
(stencil.w, stencil.h) = (image.w, image.h);
|
||||
let row = (image.w * (n + 1) * usize::from(image.bpc)).div_ceil(8);
|
||||
charged = row.saturating_mul(image.h);
|
||||
charged = row.saturating_mul(image.h).min(MAX_DATA);
|
||||
self.alloc(charged)?;
|
||||
let raw = self.source_bytes(&src, charged.min(MAX_DATA))?;
|
||||
let raw = self.source_bytes(&src, charged)?;
|
||||
by_samples(&raw, image.w, image.h, n, image.bpc)
|
||||
};
|
||||
stencil.sources = vec![Source::Str(pixels)];
|
||||
@@ -674,7 +829,12 @@ impl Interp<'_> {
|
||||
}
|
||||
let decoded = match self.decode_image(image) {
|
||||
Ok(Some(img)) => self.decode_image(stencil).map(|m| Some((img, m))),
|
||||
other => other.map(|_| None),
|
||||
Ok(None) => {
|
||||
// The mask's own data (`InterleaveType` 3) is skipped with the image's.
|
||||
let _ = self.leave_out(&stencil);
|
||||
Ok(None)
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
self.unalloc(charged);
|
||||
let Some((mut img, m)) = decoded? else { return Ok(None) };
|
||||
@@ -755,25 +915,53 @@ impl Interp<'_> {
|
||||
Ok(Spec { w, h, bpc, space, decode: vec![], matrix, sources, mask_color: None, stencil })
|
||||
}
|
||||
|
||||
/// Decode the filters image source `f` waits to run. `false` when the decoded data is past
|
||||
/// what the reader holds and the image is `reduced` (read at a lower resolution): a decode that
|
||||
/// fails leaves the file empty (`materialize`), but such an image is left out with its data
|
||||
/// still to skip, so its filters are put back for that.
|
||||
fn decode_source(&mut self, f: &Rc<RefCell<Stream>>, reduced: bool) -> Res<bool> {
|
||||
let pending = match &*f.borrow() {
|
||||
Stream::Pending { chain, from } => Some((chain.clone(), from.clone())),
|
||||
_ => None,
|
||||
};
|
||||
match self.materialize(f) {
|
||||
Ok(()) => Ok(true),
|
||||
Err(PsError::Limit(_)) if reduced => {
|
||||
if let Some((chain, from)) = pending {
|
||||
*f.borrow_mut() = Stream::Pending { chain, from };
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// The image's pixels, straight RGBA, rows from the first one read, and a CMYK image's ink
|
||||
/// amounts.
|
||||
fn decode_image(&mut self, s: Spec) -> Res<Option<Pixels>> {
|
||||
if !matches!(s.bpc, 1 | 2 | 4 | 8 | 12 | 16) {
|
||||
return ps_err("rangecheck", "BitsPerComponent");
|
||||
}
|
||||
if s.w.saturating_mul(s.h) > MAX_PIXELS {
|
||||
self.out.warn(TOO_LARGE);
|
||||
for src in &s.sources {
|
||||
self.skip_data(src);
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
self.alloc(s.w * s.h * 4)?;
|
||||
// An image of more pixels than the cap is read at a lower resolution: every `step`th
|
||||
// sample of every `step`th row (the middle one of each `step` × `step` block).
|
||||
let step = reduction(s.w, s.h);
|
||||
let (ow, oh) = (s.w.div_ceil(step), s.h.div_ceil(step));
|
||||
let n = if s.stencil.is_some() { 1 } else { s.space.n() };
|
||||
let bpc = usize::from(s.bpc);
|
||||
for src in &s.sources {
|
||||
if let Source::File(f) = src {
|
||||
self.materialize(f)?;
|
||||
// A reduced image compressed last with Flate or LZW keeps only the rows it reads, as they
|
||||
// are decoded: its whole data can be more than the reader holds.
|
||||
let streamed = match if step > 1 { self.read_rows(&s, (s.w * n * bpc).div_ceil(8), step) } else { Ok(None) } {
|
||||
Ok(rows) => rows,
|
||||
Err(PsError::Limit(_)) => return Ok(self.leave_out(&s)),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
for src in s.sources.iter().filter(|_| streamed.is_none()) {
|
||||
// Decoded data past the cap: a reduced image is left out (its data skipped) rather
|
||||
// than failing the file, as an image too large to read at all is.
|
||||
if let Source::File(f) = src
|
||||
&& !self.decode_source(f, step > 1)?
|
||||
{
|
||||
return Ok(self.leave_out(&s));
|
||||
}
|
||||
}
|
||||
// A decoded JPEG gives 8-bit gray, RGB or CMYK samples whatever the color space says.
|
||||
@@ -798,15 +986,39 @@ impl Interp<'_> {
|
||||
if sources.len() > n {
|
||||
return ps_err("rangecheck", "DataSource");
|
||||
}
|
||||
let plane = row.checked_mul(s.h).filter(|p| *p <= MAX_DATA).ok_or(PsError::Limit("decoded data is too large"))?;
|
||||
// The sample planes are this decoder's own and live only while the image is decoded: they
|
||||
// stop counting once it is (the pixels made from them still count). What the data source
|
||||
// procedures allocate is the program's and stays counted.
|
||||
let plane_bytes = plane.saturating_mul(sources.len());
|
||||
self.alloc(plane_bytes)?;
|
||||
let mut planes = self.read_sources(sources, row * s.h, if multi { row } else { row * s.h })?;
|
||||
for p in &mut planes {
|
||||
p.resize(row * s.h, 0);
|
||||
// With only the rows read kept, row `i` of the plane is the `i`th row read.
|
||||
let rows_kept = streamed.is_some();
|
||||
// The sample planes (or the rows kept) are this decoder's own and live only while the
|
||||
// image is decoded: they stop counting once it is (the pixels made from them still
|
||||
// count). What the data source procedures allocate is the program's and stays counted.
|
||||
let (planes, plane_bytes) = match streamed {
|
||||
Some(rows) => {
|
||||
let kept = rows.len();
|
||||
(vec![rows], kept)
|
||||
}
|
||||
None => {
|
||||
// More samples than the reader holds: a reduced image is left out (its data
|
||||
// skipped), while one within the pixel cap whose samples are still too much data
|
||||
// (16-bit CMYK, say) stops the read with the limit, as before (#3568: such a plane
|
||||
// is refused).
|
||||
let Some(plane) = row.checked_mul(s.h).filter(|p| *p <= MAX_DATA) else {
|
||||
if step > 1 {
|
||||
return Ok(self.leave_out(&s));
|
||||
}
|
||||
return Err(PsError::Limit("decoded data is too large"));
|
||||
};
|
||||
let plane_bytes = plane.saturating_mul(sources.len());
|
||||
self.alloc(plane_bytes)?;
|
||||
let mut planes = self.read_sources(sources, row * s.h, if multi { row } else { row * s.h })?;
|
||||
for p in &mut planes {
|
||||
p.resize(row * s.h, 0);
|
||||
}
|
||||
(planes, plane_bytes)
|
||||
}
|
||||
};
|
||||
self.alloc(ow * oh * 4)?;
|
||||
if step > 1 {
|
||||
self.out.warn(REDUCED);
|
||||
}
|
||||
let max = ((1u32 << bpc.min(16)) - 1) as f64;
|
||||
let sample = |plane: &[u8], y: usize, i: usize| -> u32 {
|
||||
@@ -830,19 +1042,19 @@ impl Interp<'_> {
|
||||
// with the default Decode array.
|
||||
let decode = if s.decode.len() >= 2 * n && jpeg.is_none_or(|c| c == 4) { s.decode.clone() } else { default_decode };
|
||||
let paint = self.g.paint.color().map(|c| c.to_rgba8(1.0));
|
||||
let mut rgba = Vec::with_capacity(s.w * s.h * 4);
|
||||
let mut rgba = Vec::with_capacity(ow * oh * 4);
|
||||
// CMYK samples keep their ink amounts, as the Decode array reads them.
|
||||
let mut inks = if matches!(space, Space::Cmyk) && s.stencil.is_none() {
|
||||
self.alloc(s.w * s.h * 4)?;
|
||||
Some(Vec::with_capacity(s.w * s.h * 4))
|
||||
self.alloc(ow * oh * 4)?;
|
||||
Some(Vec::with_capacity(ow * oh * 4))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut cache: HashMap<Vec<u32>, [u8; 3]> = HashMap::new();
|
||||
let mut raw = vec![0u32; n];
|
||||
let mut comps = vec![0f64; n];
|
||||
for y in 0..s.h {
|
||||
for x in 0..s.w {
|
||||
for y in (0..oh).map(|y| if rows_kept { y } else { picked(y, step, s.h) }) {
|
||||
for x in (0..ow).map(|x| picked(x, step, s.w)) {
|
||||
for (c, slot) in raw.iter_mut().enumerate() {
|
||||
*slot = match planes.as_slice() {
|
||||
[one] => sample(one, y, x * n + c),
|
||||
@@ -882,7 +1094,9 @@ impl Interp<'_> {
|
||||
}
|
||||
drop(planes);
|
||||
self.unalloc(plane_bytes);
|
||||
Ok(Some(Pixels { w: s.w as u32, h: s.h as u32, rgba, inks, matrix: s.matrix }))
|
||||
// The reduced samples cover the image's area: image space scaled to them.
|
||||
let matrix = Affine::scale_non_uniform(ow as f64 / s.w as f64, oh as f64 / s.h as f64) * s.matrix;
|
||||
Ok(Some(Pixels { w: ow as u32, h: oh as u32, rgba, inks, matrix }))
|
||||
}
|
||||
|
||||
/// One pixel's colour in `space` as display RGB.
|
||||
@@ -959,3 +1173,19 @@ impl Interp<'_> {
|
||||
Some(OpacityMask::new(Node::new(self.out.doc.alloc_id(), NodeKind::Image(Box::new(im))), true))
|
||||
}
|
||||
}
|
||||
|
||||
/// The sample (or row) of `len` a reduced image reads as its `i`th at `step`: the middle one of
|
||||
/// its block of `step`, the last one in a short last block.
|
||||
fn picked(i: usize, step: usize, len: usize) -> usize {
|
||||
(i * step + step / 2).min(len.saturating_sub(1))
|
||||
}
|
||||
|
||||
/// The step [`Interp::decode_image`] reads a `w` × `h` image at: 1 (every sample) within
|
||||
/// [`MAX_PIXELS`], else the least that brings the samples it reads within it.
|
||||
fn reduction(w: usize, h: usize) -> usize {
|
||||
let mut step = 1;
|
||||
while w.div_ceil(step).saturating_mul(h.div_ceil(step)) > MAX_PIXELS {
|
||||
step += 1;
|
||||
}
|
||||
step
|
||||
}
|
||||
|
||||
@@ -552,29 +552,153 @@ fn tiff_predicted_rows_at_every_depth() {
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
}
|
||||
|
||||
/// An image too large to read is left out, and its data is skipped, as reading it would leave
|
||||
/// the program: the art after it is read, not the data as PostScript. Here the data ends at its
|
||||
/// `~>` (an inline image of a content stream run as a file, as PDF-reading prologs write it), at
|
||||
/// a `SubFileDecode` end string, and at the end of compressed data that is read whole.
|
||||
/// An image over the reader's pixel cap is read at a lower resolution, or when its data is too
|
||||
/// large to hold left out with its data skipped; either way the program goes on after the data,
|
||||
/// as reading the whole image would leave it: the art after it is read, not the data as
|
||||
/// PostScript. Here the data ends at its `~>` (an inline image of a content stream run as a file,
|
||||
/// as PDF-reading prologs write it), at a `SubFileDecode` end string, and at the end of
|
||||
/// compressed data that is read whole.
|
||||
#[test]
|
||||
fn the_data_of_an_image_too_large_to_read_is_skipped() {
|
||||
let after = "0 0 1 setrgbcolor 10 10 80 80 rectfill";
|
||||
let packed = crate::ps::ascii85(&crate::ps::deflate(&[0u8; 64]));
|
||||
for program in [
|
||||
format!(
|
||||
"/ID {{ << /ImageType 1 /Width 10000 /Height 10000 /BitsPerComponent 8 /Decode [0 1 0 1 0 1] /ImageMatrix [1 0 0 1 0 0] \
|
||||
/DataSource currentfile 0 (~>) /SubFileDecode filter /ASCII85Decode filter /LZWDecode filter >> \
|
||||
/DataSource currentfile 0 (~>) /SubFileDecode filter /ASCII85Decode filter /FlateDecode filter >> \
|
||||
/DeviceRGB setcolorspace image }} def\n\
|
||||
currentfile 0 (endstream) /SubFileDecode filter cvx exec\nID\nJ1_V7fG\"r'\"b]2#:hXAd)~>\n{after}\nendstream\n"
|
||||
currentfile 0 (endstream) /SubFileDecode filter cvx exec\nID\n{packed}\n{after}\nendstream\n"
|
||||
),
|
||||
format!("10000 10000 8 [1 0 0 1 0 0] currentfile /ASCIIHexDecode filter false 3 colorimage\n0a1b 2c3d 4e5f>\n{after}"),
|
||||
format!(
|
||||
"10000 10000 8 [1 0 0 1 0 0] currentfile 0 (%%EndData) /SubFileDecode filter /FlateDecode filter image\n\
|
||||
x\u{9c}garbage\n%%EndData\n{after}"
|
||||
"10000 10000 8 [1 0 0 1 0 0] currentfile 0 (%%EndData) /SubFileDecode filter /ASCII85Decode filter /FlateDecode filter image\n\
|
||||
{packed}\n%%EndData\n{after}"
|
||||
),
|
||||
format!("10000 10000 true [1 0 0 1 0 0] currentfile /ASCII85Decode filter imagemask\n{packed}\n{after}"),
|
||||
] {
|
||||
let r = read(&program);
|
||||
assert!(r.warnings.iter().any(|w| w.contains("too large to read") || w.contains("lower resolution")), "{program}: {:?}", r.warnings);
|
||||
let o = super::tests::objects(&r.document);
|
||||
let last = o.last().expect("the art after the image");
|
||||
assert_eq!(super::tests::fill(last), Some(&vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))), "{program}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An image of more pixels than the reader's cap (2^26) is read at a lower resolution, every
|
||||
/// second sample of every second row here, over the same area, with a note; not left out.
|
||||
#[test]
|
||||
fn an_image_over_the_pixel_cap_is_read_at_a_lower_resolution() {
|
||||
// 9000 × 8000 one-bit samples, every row the same: its left half ones, painted.
|
||||
let row = format!("{}{}", "ff".repeat(563), "00".repeat(562));
|
||||
let r = read(&format!("0 0 1 setrgbcolor 90 80 scale 9000 8000 true [9000 0 0 -8000 0 8000] <{row}> imagemask"));
|
||||
assert!(r.warnings.iter().any(|w| w.contains("lower resolution")), "{:?}", r.warnings);
|
||||
let NodeKind::Image(im) = &all(&r.document).into_iter().find(|n| matches!(n.kind, NodeKind::Image(_))).expect("an image").kind else {
|
||||
panic!("an image")
|
||||
};
|
||||
assert_eq!((im.width, im.height), (4500, 4000));
|
||||
// Its 4500 × 4000 pixels cover the 90 × 80 points the image does.
|
||||
let corner = im.xf * kurbo::Point::new(4500.0, 4000.0);
|
||||
let origin = im.xf * kurbo::Point::ZERO;
|
||||
assert!(((corner - origin).x.abs() - 90.0).abs() < 1e-6 && ((corner - origin).y.abs() - 80.0).abs() < 1e-6, "{:?}", im.xf);
|
||||
// Left half painted, right half clear.
|
||||
assert_eq!(pixel(&r.document, 100, 2000)[3], 255);
|
||||
assert_eq!(pixel(&r.document, 4400, 2000)[3], 0);
|
||||
}
|
||||
|
||||
/// An image over the pixel cap whose samples are more data than the reader holds (9500 × 9500
|
||||
/// RGB is 270 MB) is read at a lower resolution too when Flate or LZW compresses it last: only
|
||||
/// the rows it reads are kept as they are decoded.
|
||||
#[test]
|
||||
fn an_image_of_more_data_than_the_reader_holds_keeps_only_the_rows_it_reads() {
|
||||
let (w, h) = (9500usize, 9500usize);
|
||||
let mut samples = Vec::with_capacity(w * h * 3);
|
||||
for y in 0..h {
|
||||
let px: [u8; 3] = if y < h / 2 { [255, 0, 0] } else { [0, 0, 255] };
|
||||
samples.extend(std::iter::repeat_n(px, w).flatten());
|
||||
}
|
||||
let data = crate::ps::ascii85(&crate::ps::deflate(&samples));
|
||||
drop(samples);
|
||||
let r = read(&format!(
|
||||
"95 95 scale {w} {h} 8 [{w} 0 0 -{h} 0 {h}] currentfile /ASCII85Decode filter /FlateDecode filter false 3 colorimage\n{data}\n\
|
||||
0 1 0 setrgbcolor 0 0 0.1 0.1 rectfill"
|
||||
));
|
||||
assert!(r.warnings.iter().any(|w| w.contains("lower resolution")), "{:?}", r.warnings);
|
||||
let NodeKind::Image(im) = &all(&r.document).into_iter().find(|n| matches!(n.kind, NodeKind::Image(_))).expect("an image").kind else {
|
||||
panic!("an image")
|
||||
};
|
||||
assert_eq!((im.width, im.height), (4750, 4750));
|
||||
// The rows read from the top half are red, from the bottom half blue.
|
||||
assert_eq!(pixel(&r.document, 10, 10), [255, 0, 0, 255]);
|
||||
assert_eq!(pixel(&r.document, 10, 4740), [0, 0, 255, 255]);
|
||||
// The art after the data is read.
|
||||
assert_eq!(super::tests::objects(&r.document).len(), 2);
|
||||
}
|
||||
|
||||
/// An image too large to read even at a lower resolution (its samples are more data than the
|
||||
/// reader holds) is left out, and its data is skipped: when a procedure reads it, the procedure
|
||||
/// is called until the data ends; when its first filter decompresses to more than the reader
|
||||
/// holds (and can't be read a row at a time), the compressed data is measured without keeping it.
|
||||
#[test]
|
||||
fn the_data_of_an_image_too_large_to_hold_is_skipped() {
|
||||
let after = "0 0 1 setrgbcolor 10 10 80 80 rectfill";
|
||||
let zeros = crate::ps::deflate(&vec![0u8; 300 << 20]);
|
||||
// Predicted rows aren't decoded a row at a time: such an image is left out.
|
||||
let mut flate =
|
||||
b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /FlateDecode filter false 3 colorimage\n".to_vec();
|
||||
flate.extend(&zeros);
|
||||
flate.extend(format!("\n{after}").as_bytes());
|
||||
for program in [
|
||||
format!(
|
||||
"10000 10000 true [1 0 0 1 0 0] currentfile /ASCII85Decode filter imagemask\n{}\n{after}",
|
||||
crate::ps::ascii85(&crate::ps::deflate(&[0u8; 64]))
|
||||
),
|
||||
"/F currentfile 0 (%%EndData) /SubFileDecode filter def \
|
||||
10000 10000 8 [1 0 0 1 0 0] {{ F 4096 string readstring pop }} false 3 colorimage\n@@@@ not PostScript @@@@\n%%EndData\n{after}"
|
||||
)
|
||||
.into_bytes(),
|
||||
flate,
|
||||
] {
|
||||
let text = String::from_utf8_lossy(program.get(..120).unwrap_or(&program)).into_owned();
|
||||
let mut file = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec();
|
||||
file.extend(&program);
|
||||
file.extend(b"\nshowpage\n%%EOF\n");
|
||||
let r = import(&file).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("too large to read")), "{text}: {:?}", r.warnings);
|
||||
let o = super::tests::objects(&r.document);
|
||||
assert_eq!(o.len(), 1, "{text}: {:?}", r.warnings);
|
||||
assert_eq!(super::tests::fill(&o[0]), Some(&vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))), "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Measuring the data of an image too large to hold decompresses it, and that is charged to the
|
||||
/// operation budget: a program kept in a reusable stream, whose image over 300 MB of compressed
|
||||
/// zeros is left out and measured again each time a loop runs the stream from its start, runs out
|
||||
/// of the budget.
|
||||
#[test]
|
||||
fn measuring_data_too_large_to_hold_in_a_loop_runs_out_of_the_budget() {
|
||||
let mut program =
|
||||
b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /FlateDecode filter false 3 colorimage\n".to_vec();
|
||||
program.extend(crate::ps::deflate(&vec![0u8; 300 << 20]));
|
||||
let hex: String = program.iter().map(|b| format!("{b:02x}")).collect();
|
||||
super::tests::runs_out_of_budget(&format!("/P <{hex}> /ReusableStreamDecode filter def {{ P 0 setfileposition P cvx exec }} loop"));
|
||||
}
|
||||
|
||||
/// When an image too large to read is left out, the data of its mask (`InterleaveType` 3) is
|
||||
/// skipped too: unfiltered from the program's own file by its byte count, and through a filter
|
||||
/// shared with later reads, which then find the file past the data (here the second filter fails
|
||||
/// on what the first decoded) rather than decoding the program after it.
|
||||
#[test]
|
||||
fn the_mask_data_of_an_image_left_out_is_skipped() {
|
||||
let after = "0 0 1 setrgbcolor 10 10 80 80 rectfill";
|
||||
let masked = |source: &str| {
|
||||
format!(
|
||||
"<< /ImageType 3 /InterleaveType 3 /DataDict << /ImageType 1 /Width 10000 /Height 10000 /BitsPerComponent 8 \
|
||||
/Decode [0 1 0 1 0 1] /ImageMatrix [1 0 0 1 0 0] /DataSource (x) >> \
|
||||
/MaskDict << /ImageType 1 /Width 10 /Height 10 /BitsPerComponent 1 /Decode [0 1] /ImageMatrix [1 0 0 1 0 0] \
|
||||
/DataSource {source} >> >> /DeviceRGB setcolorspace image"
|
||||
)
|
||||
};
|
||||
for program in [
|
||||
// 10 rows of 2 bytes, not PostScript.
|
||||
format!("{}\n{}\n{after}", masked("currentfile"), "@".repeat(20)),
|
||||
format!("/F currentfile /ASCIIHexDecode filter /ASCII85Decode filter def {}\n7676>\nF read {{ pop }} if {after}", masked("F")),
|
||||
] {
|
||||
let r = read(&program);
|
||||
assert!(r.warnings.iter().any(|w| w.contains("too large to read")), "{program}: {:?}", r.warnings);
|
||||
|
||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user