Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

fix(optimize): bound the search for fragment runs on a page

aiongg6b62585339b3
diff --git a/crates/optimize/src/fragments.rs b/crates/optimize/src/fragments.rs
index caf617f71..44e165546 100644
--- a/crates/optimize/src/fragments.rs
+++ b/crates/optimize/src/fragments.rs
@@ -29,6 +29,19 @@ pub const MIN_FRAGMENTS: usize = 4;
/// Most pixels a merged image may have (memory).
const MAX_PIXELS: u64 = 80_000_000;
+/// Fragment groups a page's search for runs may read per content operator, and at least. A run
+/// that is not one picture is searched again from each of its groups, so without a limit images
+/// drawn over one another take time quadratic in their number; past it, the rest of the page is
+/// left as it is.
+const SCAN_PER_OP: usize = 16;
+const MIN_SCAN: usize = 1 << 16;
+
+#[cfg(test)]
+thread_local! {
+ /// Fragment groups read, for the test that keeps a page's search linear in its content.
+ static GROUP_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
+}
+
/// One fragment: its image, its box in the coordinates the run is drawn in, and its size.
struct Fragment {
image: ObjRef,
@@ -40,6 +53,8 @@ struct Fragment {
/// The ops `q`, one or more `cm`, `Do`, `Q` starting at `i`: the index after them, the matrix
/// and the name drawn.
fn group_at(ops: &[Op], i: usize) -> Option<(usize, Matrix, Vec<u8>)> {
+ #[cfg(test)]
+ GROUP_READS.with(|c| c.set(c.get().saturating_add(1)));
if !ops.get(i)?.is("q") {
return None;
}
@@ -226,7 +241,13 @@ fn merge_page(doc: &mut Document, page: ObjRef, report: &mut Report, progress: &
let ops = parsed.ops;
let mut out: Vec<Op> = Vec::with_capacity(ops.len());
let (mut i, mut merged, mut k) = (0, 0, 0);
+ let budget = ops.len().saturating_mul(SCAN_PER_OP).max(MIN_SCAN);
+ let mut scanned = 0usize;
while i < ops.len() {
+ if scanned > budget {
+ out.extend(ops.get(i..).unwrap_or_default().iter().cloned());
+ break;
+ }
// The longest run of fragment groups from here with one colour space.
let mut run = Vec::new();
let mut kind: Option<(Object, usize)> = None;
@@ -245,10 +266,12 @@ fn merge_page(doc: &mut Document, page: ObjRef, report: &mut Report, progress: &
run.push(Fragment { image, rect: [e, f, e + a, f + d], width, height });
j = next;
}
+ scanned = scanned.saturating_add(run.len()).saturating_add(1);
// Not one picture as a whole: the rows drawn one under the other from the start may be.
if run.len() >= MIN_FRAGMENTS && !stacked(&mut run) {
run = drawn_in_sequence(&ops, i, &xobjects, doc);
j = run_end(&ops, i, run.len());
+ scanned = scanned.saturating_add(run.len().saturating_mul(2)).saturating_add(2);
}
let Some((cs, n)) = kind.filter(|_| run.len() >= MIN_FRAGMENTS && stacked(&mut run)) else {
// Not a run: keep this op and look again from the next one.
@@ -304,6 +327,8 @@ pub(crate) fn run(doc: &mut Document, pages: &[ObjRef], report: &mut Report, pro
#[cfg(test)]
mod tests {
+ use pdfcraft_cos::{Dict, Document, Object, Stream};
+
use super::*;
#[test]
@@ -318,4 +343,34 @@ mod tests {
];
assert!(merge(&Document::new_empty(), &run, 3).is_none());
}
+
+ /// Many images drawn on top of each other are not one picture; looking for runs among them reads
+ /// a bounded number of groups per operator, not the rest of the page from every group.
+ #[test]
+ fn rejected_runs_read_a_bounded_number_of_groups() {
+ let mut doc = Document::new_empty();
+ let mut image = Dict::new();
+ for (k, v) in
+ [("Subtype", Object::name("Image")), ("Width", Object::Int(1)), ("Height", Object::Int(1)), ("BitsPerComponent", Object::Int(8))]
+ {
+ image.set(k.as_bytes().to_vec(), v);
+ }
+ image.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));
+ let image = doc.add(Object::Stream(Stream::from_raw(image, vec![0])));
+ let groups = 4000;
+ let content = doc.add(Object::Stream(Stream::flate(Dict::new(), "q 10 0 0 10 0 0 cm /Im Do Q\n".repeat(groups).as_bytes())));
+ let mut xobjects = Dict::new();
+ xobjects.set(b"Im".to_vec(), Object::Ref(image));
+ let mut resources = Dict::new();
+ resources.set(b"XObject".to_vec(), Object::Dict(xobjects));
+ let mut page = Dict::new();
+ page.set(b"Contents".to_vec(), Object::Ref(content));
+ page.set(b"Resources".to_vec(), Object::Dict(resources));
+ let page = doc.add(Object::Dict(page));
+ GROUP_READS.with(|c| c.set(0));
+ let merged = merge_page(&mut doc, page, &mut Report::default(), &mut |_| true);
+ assert_eq!(merged.ok(), Some(0));
+ let reads = GROUP_READS.with(|c| c.get());
+ assert!(reads <= 40 * 4 * groups, "{reads} group reads");
+ }
}