diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 97292863be..decd9d4ba6 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -11,7 +11,7 @@ use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value}; #[cfg(test)] -use gridcraft_model::{Alignment, Image, SheetViewMode}; +use gridcraft_model::{Alignment, CellPicture, Image, SheetViewMode}; use gridcraft_model::{ Anchor, BorderLine, BorderStyle, Borders, Color, HAlign, Orientation, PageOrder, PatternType, PrintSettings, ReadingOrder, ShapeKind, Sheet, Style, StyleId, StyleTable, Underline, VAlign, Visibility, Workbook, @@ -34,49 +34,6 @@ use header_footer::draw_header_footer; pub use header_footer::{ HF_FIELDS, HfContext, HfSection, codes_to_fields, expand_header_footer, fields_to_codes, hf_date_time, join_header_footer, split_header_footer, }; -type DecodedPicture = (Vec, u32, u32); - -/// What one PDF render shares across the pages an object spans. -#[derive(Default)] -struct PicCache { - /// Decoded pictures (bytes, width, height) keyed by (sheet, picture); `None` = undecodable. - decoded: std::collections::HashMap<(usize, usize), Option>, - /// Laid-out charts (with their [`chart_cost`]) keyed by (sheet, chart), rendered once however - /// many pages they touch. Only charts that can still be drawn are kept. - charts: std::collections::HashMap<(usize, usize), (Vec, usize)>, - /// Charts too big for what was left of the budget: never drawn, so not rendered again. - rejected_charts: std::collections::HashSet<(usize, usize)>, - /// Bytes of picture pixels embedded so far, and chart cost units emitted so far. Each page an - /// object touches gets its own copy in the PDF, so a workbook-controlled anchor over thousands - /// of pages would multiply them without bound. - image_bytes: usize, - chart_prims: usize, -} - -impl PicCache { - /// The chart's primitives for one more page, or `None` once they no longer fit - /// [`MAX_CHART_PRIMS`]. `render` runs at most once per chart; a chart that doesn't fit is - /// dropped at once and remembered, so its vectors are never retained. - fn chart(&mut self, key: (usize, usize), render: impl FnOnce() -> Vec) -> Option<&[gridcraft_chart::Prim]> { - if self.rejected_charts.contains(&key) { - return None; - } - let (prims, cost) = match self.charts.remove(&key) { - Some(cached) => cached, - None => { - let prims = render(); - let cost = chart_cost(&prims); - (prims, cost) - } - }; - if self.chart_prims.saturating_add(cost) > MAX_CHART_PRIMS { - self.rejected_charts.insert(key); - return None; - } - self.chart_prims += cost; - Some(&self.charts.entry(key).or_insert((prims, cost)).0) - } -} /// What a chart's drawing costs in the PDF: one unit per primitive plus one per path point (a /// smoothed line holds thousands of points, each written out) and per point of a wedge's outline. @@ -93,8 +50,6 @@ fn chart_cost(prims: &[gridcraft_chart::Prim]) -> usize { .fold(0, usize::saturating_add) } -/// Most picture pixel bytes (RGBA, before PDF packing) one render embeds across all pages. -const MAX_EMBEDDED_IMAGE_BYTES: usize = 512 * 1024 * 1024; /// Most chart cost units (primitives and path points, see [`chart_cost`]) one render draws across all pages. const MAX_CHART_PRIMS: usize = 4_000_000; @@ -103,7 +58,7 @@ use layout::bands; pub(crate) use layout::split_bands; pub use layout::{PrintOptions, SheetLayout, layout_sheet, layouts, paper_size, print_range}; use layout::{known_paper, seg_size, segments}; -use objects::draw_objects; +use objects::{PicCache, draw_objects}; #[cfg(test)] use text::{center_across_width, wrap_lines}; @@ -164,7 +119,14 @@ const MISSING_ARABIC_FONT: &str = "Some Arabic text could not be drawn in this P /// Renders laid-out sheets to a PDF. pub fn render_pdf(wb: &Workbook, layouts: &[SheetLayout], file: &str, path: &str) -> Result { + render_pdf_with_image_budget(wb, layouts, file, path, gridcraft_pdf::MAX_DOC_IMAGE_BYTES) +} + +/// [`render_pdf`] keeping at most `image_bytes` of picture data in the document (tests lower it +/// to exercise the cap without building gigabytes of pictures). +fn render_pdf_with_image_budget(wb: &Workbook, layouts: &[SheetLayout], file: &str, path: &str, image_bytes: u64) -> Result { let mut doc = PdfDoc::new(); + doc.set_image_budget(image_bytes); doc.info.title = if wb.props.title.is_empty() { file.to_string() } else { wb.props.title.clone() }; doc.info.author = wb.props.author.clone(); let total: usize = layouts.iter().map(|l| l.pages.len()).sum(); @@ -173,7 +135,8 @@ pub fn render_pdf(wb: &Workbook, layouts: &[SheetLayout], file: &str, path: &str let mut pending_links = Vec::new(); let mut printed_blocks = Vec::new(); // Decoded pictures are reused across the pages their anchor covers: a floating picture - // spanning 40 pages was decoded (and pushed into the PDF) 40 times (#2389). + // spanning 40 pages was decoded 40 times (#2389). Each page still keeps its own copy in the + // PDF, within the document's image budget. let mut pics = PicCache::default(); for lay in layouts { let Some(sh) = wb.sheet(lay.sheet) else { continue }; @@ -197,7 +160,7 @@ pub fn render_pdf(wb: &Workbook, layouts: &[SheetLayout], file: &str, path: &str let mut x = ox + lay.heading_w * k; for (csi, cs) in csegs.iter().enumerate() { let b = make_block(wb, lay.sheet, sh, *rs, *cs, (x, y), lay); - draw_block(pg, &b, lay.settings.gridlines, &mut cf); + draw_block(pg, &b, lay.settings.gridlines, &mut cf, &mut pics); draw_block_links(pg, &b, page_index, &mut pending_links); printed_blocks.push(PrintedBlock { page: page_index, diff --git a/crates/engine/src/cmd/print/draw.rs b/crates/engine/src/cmd/print/draw.rs index 8d23a8c1f2..43a5eb07e5 100644 --- a/crates/engine/src/cmd/print/draw.rs +++ b/crates/engine/src/cmd/print/draw.rs @@ -1,5 +1,5 @@ use super::layout::{DENSE_BLOCK, SheetLayout}; -use super::objects::draw_cell_picture; +use super::objects::{PicCache, draw_cell_picture}; use super::text::{TextPlacement, draw_text}; use super::{ BorderLine, BorderStyle, Borders, CellRef, Color, Font, Page, PatternType, Point, RangeRef, Rgb, Sheet, Style, StyleId, Underline, Value, @@ -319,7 +319,7 @@ impl<'a> Covered<'a> { } /// Draws the cells of a block: fills, gridlines, data bars, borders and text. -pub(super) fn draw_block(pg: &mut Page, b: &Block, gridlines: bool, cf: &mut crate::cf::CfCache) { +pub(super) fn draw_block(pg: &mut Page, b: &Block, gridlines: bool, cf: &mut crate::cf::CfCache, pics: &mut PicCache) { let (bx, by) = (b.xs.first().copied().unwrap_or(0.0), b.ys.first().copied().unwrap_or(0.0)); let (bw, bh) = (b.xs.last().copied().unwrap_or(bx) - bx, b.ys.last().copied().unwrap_or(by) - by); if bw <= 0.0 || bh <= 0.0 { @@ -434,7 +434,7 @@ pub(super) fn draw_block(pg: &mut Page, b: &Block, gridlines: bool, cf: &mut cra continue; } if let Some(picture) = sh.cell_pictures.get(c) { - draw_cell_picture(pg, &picture.data, (b.text_x(x, w), y, w, h), b.k); + draw_cell_picture(pg, pics, (b.si, *c), &picture.data, (b.text_x(x, w), y, w, h), b.k); } else if let Some(on) = checkbox_state(l, &sh.value(*c)) { draw_checkbox(pg, (b.text_x(x, w), y, w, h), b.k, on); } else { diff --git a/crates/engine/src/cmd/print/objects.rs b/crates/engine/src/cmd/print/objects.rs index 517f1281e9..ddd9300a2c 100644 --- a/crates/engine/src/cmd/print/objects.rs +++ b/crates/engine/src/cmd/print/objects.rs @@ -1,9 +1,94 @@ use super::draw::{Block, PdfMeasure, Xf, draw_prims, rgb_of}; use super::text::wrap_lines; -use super::{Anchor, Baseline, Font, Page, Point, RangeRef, Rect, ShapeKind, Sheet, TextDirection, Value, Workbook}; +use super::{Anchor, Baseline, CellRef, Font, Page, Point, RangeRef, Rect, ShapeKind, Sheet, TextDirection, Value, Workbook}; +use std::borrow::Cow; +use std::collections::hash_map::Entry; + +/// A decoded picture: RGBA pixels, width, height. +type Decoded = (Vec, u32, u32); + +/// Most bytes of decoded pictures one render memoizes; a picture decoded past it is used once +/// and dropped (and decoded again on the next page that prints it). +const MAX_PIC_CACHE_BYTES: u64 = 256 * 1024 * 1024; + +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +enum PicKey { + /// A floating picture: sheet index and position in `Sheet::images`. + Floating(usize, usize), + /// A cell picture: sheet index, cell and the thumbnail size it is decoded at. + Cell(usize, CellRef, u32, u32), +} + +/// Decoded pictures reused across the pages (and repeated title rows) that print them, so a +/// picture is decoded once per render instead of once per page (#2389). +#[derive(Default)] +pub(super) struct PicCache { + map: std::collections::HashMap>, + /// Bytes of pixels in `map`. + bytes: u64, + /// Laid-out charts (with their [`chart_cost`](super::chart_cost)) keyed by (sheet, chart), + /// rendered once however many pages they touch. Only charts that can still be drawn are kept. + pub(super) charts: std::collections::HashMap<(usize, usize), (Vec, usize)>, + /// Charts too big for what was left of the budget: never drawn, so not rendered again. + pub(super) rejected_charts: std::collections::HashSet<(usize, usize)>, + /// Chart cost units emitted so far. Each page a chart touches gets its own copy in the PDF, + /// so a workbook-controlled anchor over thousands of pages would multiply them without bound. + pub(super) chart_prims: usize, +} + +impl PicCache { + /// The decoded picture for `key`, running `decode` the first time. A failed decode is + /// remembered too; a decode that does not fit in the cache is returned without being kept. + fn get(&mut self, key: PicKey, decode: impl FnOnce() -> Option) -> Option> { + let slot = match self.map.entry(key) { + Entry::Occupied(e) => e.into_mut(), + Entry::Vacant(e) => { + let decoded = decode(); + let size = decoded.as_ref().map_or(0, |d| d.0.len() as u64); + if self.bytes.saturating_add(size) > MAX_PIC_CACHE_BYTES { + return decoded.map(Cow::Owned); + } + self.bytes = self.bytes.saturating_add(size); + e.insert(decoded) + } + }; + slot.as_ref().map(Cow::Borrowed) + } + + /// The chart's primitives for one more page, or `None` once they no longer fit + /// [`MAX_CHART_PRIMS`](super::MAX_CHART_PRIMS). `render` runs at most once per chart; a chart + /// that doesn't fit is dropped at once and remembered, so its vectors are never retained. + pub(super) fn chart(&mut self, key: (usize, usize), render: impl FnOnce() -> Vec) -> Option<&[gridcraft_chart::Prim]> { + if self.rejected_charts.contains(&key) { + return None; + } + let (prims, cost) = match self.charts.remove(&key) { + Some(cached) => cached, + None => { + let prims = render(); + let cost = super::chart_cost(&prims); + (prims, cost) + } + }; + if self.chart_prims.saturating_add(cost) > super::MAX_CHART_PRIMS { + self.rejected_charts.insert(key); + return None; + } + self.chart_prims += cost; + Some(&self.charts.entry(key).or_insert((prims, cost)).0) + } +} + +/// Whether a picture decoded into at most `max_w`×`max_h` pixels can still be kept by the PDF. +/// The document's image room only shrinks while it is built, so a picture refused here would be +/// refused on every later page too and is not decoded at all. +fn fits(room: u64, max_w: u32, max_h: u32) -> bool { + u64::from(max_w).saturating_mul(u64::from(max_h)).saturating_mul(4) <= room +} /// Cell pictures fit the current cell (or merged-cell) rectangle without changing aspect ratio. -pub(super) fn draw_cell_picture(pg: &mut Page, data: &[u8], rect: (f32, f32, f32, f32), k: f32) { +/// `at` (sheet index and cell) keys the decode in `pics`. +pub(super) fn draw_cell_picture(pg: &mut Page, pics: &mut PicCache, at: (usize, CellRef), data: &[u8], rect: (f32, f32, f32, f32), k: f32) { let (x, y, w, h) = rect; let pad = 2.0 * k; let (w, h) = ((w - 2.0 * pad).max(0.0), (h - 2.0 * pad).max(0.0)); @@ -14,18 +99,30 @@ pub(super) fn draw_cell_picture(pg: &mut Page, data: &[u8], rect: (f32, f32, f32 if iw == 0 || ih == 0 || iw > 8192 || ih > 8192 || u64::from(iw) * u64::from(ih) > 16_000_000 { return; } - let Ok(mut reader) = image::ImageReader::new(std::io::Cursor::new(data)).with_guessed_format() else { return }; + let (tw, th) = (((w / 72.0) * 150.0).ceil().clamp(1.0, 4000.0) as u32, ((h / 72.0) * 150.0).ceil().clamp(1.0, 4000.0) as u32); + let room = pg.image_room(); + let Some(image) = pics.get(PicKey::Cell(at.0, at.1, tw, th), || decode_cell_picture(data, tw, th, room)) else { return }; + let (px, px_w, px_h) = &*image; + let fit = (w / iw as f32).min(h / ih as f32); + let (pw, ph) = (iw as f32 * fit, ih as f32 * fit); + pg.image_rgba(Rect::new(x + pad + (w - pw) / 2.0, y + pad + (h - ph) / 2.0, pw, ph), px, [*px_w, *px_h]); +} + +/// Decodes a cell picture to RGBA scaled to fit `tw`×`th` pixels, unless the PDF has no `room` +/// left for it. +fn decode_cell_picture(data: &[u8], tw: u32, th: u32, room: u64) -> Option { + if !fits(room, tw, th) { + return None; + } + let mut reader = image::ImageReader::new(std::io::Cursor::new(data)).with_guessed_format().ok()?; let mut limits = image::Limits::default(); limits.max_image_width = Some(8192); limits.max_image_height = Some(8192); limits.max_alloc = Some(64 * 1024 * 1024); reader.limits(limits); - let Ok(image) = reader.decode() else { return }; - let image = - image.thumbnail(((w / 72.0) * 150.0).ceil().clamp(1.0, 4000.0) as u32, ((h / 72.0) * 150.0).ceil().clamp(1.0, 4000.0) as u32).to_rgba8(); - let fit = (w / iw as f32).min(h / ih as f32); - let (pw, ph) = (iw as f32 * fit, ih as f32 * fit); - pg.image_rgba(Rect::new(x + pad + (w - pw) / 2.0, y + pad + (h - ph) / 2.0, pw, ph), image.as_raw(), [image.width(), image.height()]); + let image = reader.decode().ok()?.thumbnail(tw, th).to_rgba8(); + let (pw, ph) = (image.width(), image.height()); + Some((image.into_raw(), pw, ph)) } /// Sheet pixel rectangle of an anchor. @@ -53,10 +150,11 @@ fn anchor_rect(sh: &Sheet, a: &Anchor) -> (f64, f64, f64, f64) { (sh.col_left(a.cell.col) + a.dx as f64, sh.row_top(a.cell.row) + a.dy as f64, a.width.max(0.0) as f64, a.height.max(0.0) as f64) } -/// Decodes an embedded picture to RGBA, downscaled to at most `max_w`×`max_h` pixels. -fn decode_image(data: &[u8], max_w: u32, max_h: u32) -> Option<(Vec, u32, u32)> { +/// Decodes an embedded picture to RGBA, downscaled to at most `max_w`×`max_h` pixels, unless the +/// PDF has no `room` left for it. +fn decode_image(data: &[u8], max_w: u32, max_h: u32, room: u64) -> Option { let (w, h) = crate::io::image_size(data)?; - if w == 0 || h == 0 || w as u64 * h as u64 > 60_000_000 { + if w == 0 || h == 0 || w as u64 * h as u64 > 60_000_000 || !fits(room, w.min(max_w.max(1)), h.min(max_h.max(1))) { return None; } let img = image::load_from_memory(data).ok()?; @@ -69,7 +167,7 @@ fn decode_image(data: &[u8], max_w: u32, max_h: u32) -> Option<(Vec, u32, u3 /// Draws charts, pictures, shapes and sparklines overlapping the body block of a page. /// `pics` memoizes decoded pictures for the whole render (one page at a time draws each /// picture again, but the decode happens once). -pub(super) fn draw_objects(pg: &mut Page, wb: &Workbook, si: usize, sh: &Sheet, b: &Block, pics: &mut super::PicCache) { +pub(super) fn draw_objects(pg: &mut Page, wb: &Workbook, si: usize, sh: &Sheet, b: &Block, pics: &mut PicCache) { let block = b.range(); let (sx0, sy0) = (sh.col_left(block.start.col), sh.row_top(block.start.row)); let (sx1, sy1) = (sh.col_left(block.end.col.saturating_add(1)), sh.row_top(block.end.row.saturating_add(1))); @@ -90,14 +188,10 @@ pub(super) fn draw_objects(pg: &mut Page, wb: &Workbook, si: usize, sh: &Sheet, let (x, y, w, h) = place(r); // About 150 dpi is plenty for print. let (mw, mh) = (((w / 72.0) * 150.0).ceil().clamp(1.0, 4000.0) as u32, ((h / 72.0) * 150.0).ceil().clamp(1.0, 4000.0) as u32); - let decoded = pics.decoded.entry((si, imi)).or_insert_with(|| decode_image(&im.data, mw, mh)); - if let Some((px, pw, ph)) = decoded.as_ref() { - // Every page the picture touches embeds its own copy: past the budget it is left out. - let bytes = px.len(); - if pics.image_bytes.saturating_add(bytes) <= super::MAX_EMBEDDED_IMAGE_BYTES { - pics.image_bytes += bytes; - pg.image_rgba(Rect::new(x, y, w, h), px, [*pw, *ph]); - } + let room = pg.image_room(); + if let Some(decoded) = pics.get(PicKey::Floating(si, imi), || decode_image(&im.data, mw, mh, room)) { + let (px, pw, ph) = &*decoded; + pg.image_rgba(Rect::new(x, y, w, h), px, [*pw, *ph]); } } for shp in &sh.shapes { diff --git a/crates/engine/src/cmd/print/tests.rs b/crates/engine/src/cmd/print/tests.rs index fc7bf0ad3d..853e59937d 100644 --- a/crates/engine/src/cmd/print/tests.rs +++ b/crates/engine/src/cmd/print/tests.rs @@ -779,6 +779,98 @@ fn charts_and_images_are_drawn() { } } +/// Bytes of pixel data the pages of a PDF hold: 3 per RGB pixel plus 1 per soft-mask pixel, for +/// every image each page references. The writer shares identical images across pages, but each +/// page kept its own copy while the document was built, so a shared image counts once per page. +fn image_bytes(pdf: &[u8]) -> u64 { + let text = String::from_utf8_lossy(pdf); + let num_after = |s: &str, key: &str| -> u64 { + let at = s.find(key).unwrap() + key.len(); + s[at..].split_whitespace().next().unwrap().parse().unwrap() + }; + // Object id → (pixel bytes, soft mask id). + let mut images = std::collections::HashMap::new(); + let mut pages = vec![]; + for obj in text.split("endobj").filter(|o| o.contains(" 0 obj")) { + let head = &obj[..obj.find(" 0 obj").unwrap()]; + let id: u64 = head.split_whitespace().last().unwrap().parse().unwrap(); + let dict = &obj[..obj.find(">>").unwrap_or(obj.len())]; + if dict.contains("/Subtype /Image") { + let bytes = num_after(dict, "/Width ") * num_after(dict, "/Height ") * if dict.contains("/DeviceRGB") { 3 } else { 1 }; + let smask = dict.contains("/SMask ").then(|| num_after(dict, "/SMask ")); + images.insert(id, (bytes, smask)); + } else if obj.contains("/Type /Page /Parent") { + pages.push(obj); + } + } + let with_mask = |id: u64| -> u64 { + let (bytes, smask) = images[&id]; + bytes + smask.map_or(0, |m| images[&m].0) + }; + pages + .iter() + .filter_map(|page| page.find("/XObject << ").map(|at| &page[at + "/XObject << ".len()..])) + .map(|refs| { + let refs = &refs[..refs.find(">>").unwrap()]; + let tokens: Vec<&str> = refs.split_whitespace().collect(); + tokens.chunks(4).map(|c| with_mask(c[1].parse().unwrap())).sum::() + }) + .sum() +} + +/// A picture anchored across many pages keeps no more copies in the PDF than the image budget +/// allows, and the export still succeeds. +#[test] +fn picture_copies_across_pages_stay_within_the_image_budget() { + // Each page a picture overlaps kept its own decoded copy in the PDF with no document-wide + // bound: a 3 KB workbook with one tall picture reached 2 GiB before running out of pages. + let mut s = s(); + let mut png = Vec::new(); + let img = image::RgbaImage::from_pixel(64, 64, image::Rgba([10, 120, 200, 255])); + image::DynamicImage::ImageRgba8(img).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + s.execute("cell.set", json!({"cell": "A1", "input": "Title"})).unwrap(); + s.execute("pageLayout.pageSetup", json!({"titleRows": "1:1"})).unwrap(); + let d = s.doc_mut().unwrap(); + let wb = std::sync::Arc::make_mut(&mut d.wb); + let id = wb.next_object_id(); + let sh = wb.sheet_mut(0).unwrap(); + // A floating picture over some 20 pages, and a cell picture in the title row on every page. + sh.images.push(Image { + id, + anchor: Anchor { cell: CellRef::new(1, 1), dx: 0.0, dy: 0.0, width: 200.0, height: 19_990.0, mode: gridcraft_model::AnchorMode::MoveAndSize }, + data: std::sync::Arc::new(png.clone()), + mime: "image/png".into(), + alt: String::new(), + }); + // `set_picture` gives C1 the cell value `draw_block` needs to reach the picture at all. + sh.set_picture(CellRef::new(0, 2), std::sync::Arc::new(CellPicture { data: png, mime: "image/png".into(), alt: String::new() })); + let d = s.doc().unwrap(); + let lays = layouts(&d.wb, &PrintOptions::from_params(&json!({}), "file.exportPdf").unwrap()); + + let RenderedPdf { bytes: full, pages, .. } = render_pdf(&d.wb, &lays, "t", "").unwrap(); + assert!(pages >= 15, "{pages} pages"); + // Within the default budget every page draws (and holds while the PDF is built) its own copy. + // Identical copies are written to the file once, so the draws are what to count. + let draws = |pdf: &[u8]| String::from_utf8_lossy(pdf).matches(" Do Q").count(); + let full_draws = draws(&full); + // The cell picture, on its own: the same render without it draws one picture fewer per page. + let mut floating_only = (*d.wb).clone(); + floating_only.sheet_mut(0).unwrap().cell_pictures.clear(); + let floating_draws = draws(&render_pdf(&floating_only, &lays, "t", "").unwrap().bytes); + assert!(floating_draws >= pages - 1, "{floating_draws} floating picture draws on {pages} pages"); + assert_eq!(full_draws - floating_draws, pages, "the title-row cell picture draws once on each of {pages} pages"); + + // 64×64 RGB is 12,288 bytes: a 64 KiB budget holds a handful of page copies, not one per page. + let budget = 64 * 1024; + let RenderedPdf { bytes: capped, pages: capped_pages, .. } = render_pdf_with_image_budget(&d.wb, &lays, "t", "", budget).unwrap(); + assert_eq!(capped_pages, pages, "pages past the budget still print, without the pictures"); + let capped_draws = draws(&capped); + assert!((1..full_draws / 2).contains(&capped_draws), "{capped_draws} of {full_draws} picture draws kept with a {budget}-byte budget"); + let kept = image_bytes(&capped); + assert!((1..=budget).contains(&kept), "{kept} bytes of images kept with a {budget}-byte budget"); + assert!(contains(&capped, "%%EOF")); +} + #[test] fn page_setup_edits_settings() { let mut s = s(); @@ -1234,7 +1326,8 @@ fn chart_budget_counts_path_points_and_drops_charts_that_do_not_fit() { // A smoothed line is its points, not one unit. assert_eq!(chart_cost(&[line(4000), Prim::Circle { cx: 0.0, cy: 0.0, r: 1.0, fill: None, stroke: None }]), 4002); // Room for exactly two copies of a 1,000-point chart. - let mut pics = PicCache { chart_prims: MAX_CHART_PRIMS - 2002, ..Default::default() }; + let mut pics = PicCache::default(); + pics.chart_prims = MAX_CHART_PRIMS - 2002; let mut renders = 0; for expect in [true, true, false, false] { let got = pics.chart((0, 0), || { @@ -1246,7 +1339,8 @@ fn chart_budget_counts_path_points_and_drops_charts_that_do_not_fit() { assert_eq!(renders, 1, "a rejected chart is not rendered again"); assert!(pics.charts.is_empty(), "and its primitives are not kept"); // A chart too big for what is left is dropped without being cached at all. - let mut pics = PicCache { chart_prims: MAX_CHART_PRIMS - 10, ..Default::default() }; + let mut pics = PicCache::default(); + pics.chart_prims = MAX_CHART_PRIMS - 10; assert!(pics.chart((0, 1), || vec![line(1000)]).is_none()); assert!(pics.charts.is_empty() && pics.rejected_charts.contains(&(0, 1))); } diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index c7241eb255..8dc9cf3399 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -7,7 +7,9 @@ //! built-in encoding ([`symbol_code`]), for Greek letters and mathematical operators. //! - Arabic is shaped and set in embedded Type3 subsets, with exact shaped advances. //! - Vector drawing: rectangles, lines (solid or dashed), polygons, circles (Bézier), clipping. -//! - RGBA images as RGB image XObjects with a soft mask for alpha (run-length encoded). +//! - RGBA images as RGB image XObjects with a soft mask for alpha (run-length encoded). The +//! decoded image bytes one document keeps across all its pages are capped +//! ([`MAX_DOC_IMAGE_BYTES`]); images past the cap are left out. //! - Coordinates are points with a **top-left origin** (y grows down); text `y` is the baseline. //! //! Streams are written uncompressed (images use the RunLengthDecode filter). @@ -510,6 +512,11 @@ pub struct Page { content: String, fonts: [bool; FONT_SLOTS], images: Vec, + /// Image bytes this page may still keep before the document's image budget is spent. Set by + /// [`PdfDoc::add_page`] and [`PdfDoc::page_mut`], which hand out one page at a time. + image_room: u64, + /// Bytes of image data this page keeps, counted as images are added. + image_kept: u64, /// Indexes into `images`, by content hash; a hash match is confirmed with [`ImageData::same`]. image_index: HashMap>, /// Pixel comparisons made while looking up duplicate pictures (test instrumentation). @@ -532,6 +539,10 @@ pub struct Page { const MAX_PAGE_CONTENT: usize = 64 * 1024 * 1024; /// Largest image (pixels) embedded. const MAX_IMAGE_PIXELS: u64 = 40_000_000; +/// Most bytes of image data (RGB plus alpha planes) one document keeps across all its pages. +/// Each [`Page::image_rgba`] call keeps its own copy, so a picture repeated on every page of a +/// long export would otherwise grow without bound; images past the budget are left out. +pub const MAX_DOC_IMAGE_BYTES: u64 = 512 * 1024 * 1024; /// Deepest `q` nesting a PDF consumer must support (the PDF specification's implementation limits). const MAX_SAVE_DEPTH: usize = 28; /// Line join styles, as the `j` operator takes them. @@ -553,6 +564,22 @@ impl Page { fn full(&self) -> bool { self.content.len() > MAX_PAGE_CONTENT } + + /// Bytes of image data this page may still add before the document's image budget + /// ([`MAX_DOC_IMAGE_BYTES`]) is spent. An image of `pw`×`ph` pixels needs up to `pw * ph * 4`; + /// callers can skip decoding pictures that cannot fit (the room never grows back while a + /// document is built). + pub fn image_room(&self) -> u64 { + self.image_room + } + + /// Bytes of image data kept by this page, summed from its images (tests check the running + /// [`Page::image_kept`] count against it). + #[cfg(test)] + fn image_bytes(&self) -> u64 { + self.images.iter().fold(0u64, |acc, i| acc.saturating_add(i.rgb.len() as u64).saturating_add(i.alpha.as_ref().map_or(0, |a| a.len() as u64))) + } + fn op(&mut self, s: &str) { if !self.full() { self.content.push_str(s); @@ -914,7 +941,8 @@ impl Page { } /// Draws an RGBA image (`pw`×`ph` pixels, row-major, straight alpha) into the box - /// `(x, y, w, h)`. Malformed or oversized buffers are ignored. + /// `(x, y, w, h)`. Malformed or oversized buffers are ignored, and so are images that do not + /// fit in what is left of the document's image budget ([`Page::image_room`]). pub fn image_rgba(&mut self, destination: Rect, rgba: &[u8], pixel_size: [u32; 2]) { let Rect { x, y, width: w, height: h } = destination; let [pw, ph] = pixel_size; @@ -926,6 +954,16 @@ impl Page { if self.saved.len() >= MAX_SAVE_DEPTH { return; } + // Room for the worst case (RGB plus an alpha plane) is checked before anything is + // allocated, so the document's image bytes stay bounded however many pages it has. Past + // the budget, a picture this page already holds can still be drawn again: it is only + // built for the lookup when the page holds one of the same size, so the temporary copy + // made to compare is bounded by pixel dimensions the page already accepted (up to + // `px * 4` bytes) and is dropped when nothing matches. + let over_budget = px * 4 > self.image_room; + if over_budget && !self.images.iter().any(|o| o.width == pw && o.height == ph) { + return; + } let px = px as usize; let mut rgb = Vec::with_capacity(px * 3); // The alpha plane is only allocated once a non-opaque pixel shows up. @@ -944,23 +982,33 @@ impl Page { } } let img = ImageData::new(pw, ph, rgb, alpha); - // The same picture drawn again on this page shares one XObject. - let candidates = self.image_index.entry(img.hash).or_default(); + // The same picture drawn again on this page shares one XObject. The lookup does not + // insert: only an accepted picture gets an index entry, so refused pictures past the + // budget don't grow the index. #[cfg(test)] let comparisons = &mut self.image_comparisons; - let known = candidates.iter().copied().find(|&i| { - #[cfg(test)] - { - *comparisons += 1; - } - self.images.get(i).is_some_and(|o| o.same(&img)) + let images = &self.images; + let known = self.image_index.get(&img.hash).and_then(|candidates| { + candidates.iter().copied().find(|&i| { + #[cfg(test)] + { + *comparisons += 1; + } + images.get(i).is_some_and(|o| o.same(&img)) + }) }); let idx = match known { Some(i) => i, + None if over_budget => return, None => { - candidates.push(self.images.len()); + // Only a picture this page doesn't hold yet spends the document's image budget. + let kept = (img.rgb.len() as u64).saturating_add(img.alpha.as_ref().map_or(0, |a| a.len() as u64)); + self.image_room = self.image_room.saturating_sub(kept); + self.image_kept = self.image_kept.saturating_add(kept); + let idx = self.images.len(); + self.image_index.entry(img.hash).or_default().push(idx); self.images.push(img); - self.images.len() - 1 + idx } }; let s = format!("q {} 0 0 {} {} {} cm /Im{} Do Q", n(w), n(h), n(x), n(self.y(y + h)), idx + 1); @@ -981,6 +1029,14 @@ pub struct Info { pub struct PdfDoc { pages: Vec, pub info: Info, + /// Image budget lowered by [`PdfDoc::set_image_budget`]; `None` = [`MAX_DOC_IMAGE_BYTES`]. + image_budget: Option, + /// Image bytes kept by every page except [`PdfDoc::open_page`], kept up to date as pages are + /// handed out so the remaining room is found without scanning every page. + image_used: u64, + /// The page last handed out by [`PdfDoc::add_page`] or [`PdfDoc::page_mut`], whose images + /// may have grown since; its bytes are folded into `image_used` when another page is handed out. + open_page: Option, } /// PackBits-style run-length encoding (PDF `RunLengthDecode`). @@ -1016,12 +1072,17 @@ impl PdfDoc { pub fn add_page(&mut self, width_pt: f32, height_pt: f32) -> &mut Page { let width = if width_pt.is_finite() { width_pt.clamp(3.0, 14_400.0) } else { 612.0 }; let height = if height_pt.is_finite() { height_pt.clamp(3.0, 14_400.0) } else { 792.0 }; + self.close_open_page(); + let image_room = self.image_room(0); + self.open_page = Some(self.pages.len()); self.pages.push(Page { width, height, content: String::new(), fonts: [false; FONT_SLOTS], images: Vec::new(), + image_room, + image_kept: 0, image_index: HashMap::new(), #[cfg(test)] image_comparisons: 0, @@ -1037,13 +1098,44 @@ impl PdfDoc { &mut self.pages[i] } + /// Lowers the bytes of image data the whole document keeps (never above + /// [`MAX_DOC_IMAGE_BYTES`], nor above a budget set before); images drawn past it are left out. + pub fn set_image_budget(&mut self, bytes: u64) { + let cap = self.image_budget.unwrap_or(MAX_DOC_IMAGE_BYTES); + self.image_budget = Some(bytes.min(cap)); + } + + /// Image bytes the document may still keep: its budget minus what every closed page holds + /// and the `open_kept` bytes of the page being handed out. + fn image_room(&self, open_kept: u64) -> u64 { + self.image_budget.unwrap_or(MAX_DOC_IMAGE_BYTES).saturating_sub(self.image_used.saturating_add(open_kept)) + } + + /// Folds the images the open page added since it was handed out into the document's count. + fn close_open_page(&mut self) { + if let Some(kept) = self.open_page.take().and_then(|i| self.pages.get(i)).map(|p| p.image_kept) { + self.image_used = self.image_used.saturating_add(kept); + } + } + pub fn page_count(&self) -> usize { self.pages.len() } /// The page at `i`, to keep drawing on it. pub fn page_mut(&mut self, i: usize) -> Option<&mut Page> { - self.pages.get_mut(i) + if i >= self.pages.len() { + return None; + } + self.close_open_page(); + let kept = self.pages.get(i)?.image_kept; + // Page `i` is open again: its bytes leave the closed count until the next hand-out. + self.image_used = self.image_used.saturating_sub(kept); + let room = self.image_room(kept); + self.open_page = Some(i); + let page = self.pages.get_mut(i)?; + page.image_room = room; + Some(page) } /// Whether some Arabic text was set in the standard and CID fonts, which have no Arabic glyphs, diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 4dcb8fbce1..5b4aa0233f 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -923,6 +923,81 @@ fn cjk_text_is_not_replaced_by_question_marks() -> Result<(), Box> { Ok(()) } +/// A picture drawn on every page keeps only as many copies as the document-wide image budget +/// holds, and the running byte counts stay in step as pages are added and reopened. +#[test] +fn image_bytes_are_bounded_across_pages() -> Result<(), Box> { + // Each page keeps its own copy of a picture it draws, so a picture repeated on every page of + // a long export grew without bound (a 3 KB workbook reached 2 GiB). The document-wide budget + // stops adding copies once it is spent. + let mut d = PdfDoc::new(); + assert_eq!(d.add_page(100.0, 100.0).image_room(), MAX_DOC_IMAGE_BYTES); + d.set_image_budget(u64::MAX); + assert_eq!(d.add_page(100.0, 100.0).image_room(), MAX_DOC_IMAGE_BYTES, "the budget is never raised"); + let mut d = PdfDoc::new(); + d.set_image_budget(4); + d.set_image_budget(8); + assert_eq!(d.add_page(100.0, 100.0).image_room(), 4, "a later, higher budget doesn't raise a lower one"); + + let mut d = PdfDoc::new(); + d.set_image_budget(10_000); + // Opaque 32×32: 4096 bytes of room needed, 3072 bytes (RGB, no mask) kept. + let px = [200u8, 200, 200, 255].repeat(32 * 32); + for _ in 0..50 { + let p = d.add_page(100.0, 100.0); + p.image_rgba(Rect::new(0.0, 0.0, 50.0, 50.0), &px, [32, 32]); + } + let kept: u64 = d.pages.iter().map(Page::image_bytes).sum(); + assert_eq!(kept, 2 * 3072); + assert_eq!(d.pages.iter().filter(|p| !p.images.is_empty()).count(), 2); + assert!(d.pages.iter().skip(2).all(|p| p.images.is_empty() && p.content.is_empty())); + // A page reopened later sees what the whole document already holds. + let p = d.page_mut(0).ok_or_else(|| io::Error::other("missing page"))?; + assert_eq!(p.image_room(), 10_000 - 2 * 3072); + // The copy page 0 already holds is drawn again past the budget; a new picture of the same + // size is refused; a small one still fits. + p.image_rgba(Rect::new(0.0, 0.0, 50.0, 50.0), &px, [32, 32]); + p.image_rgba(Rect::new(0.0, 0.0, 50.0, 50.0), &[100u8, 100, 100, 255].repeat(32 * 32), [32, 32]); + p.image_rgba(Rect::new(0.0, 0.0, 10.0, 10.0), &[255; 4 * 4 * 4], [4, 4]); + assert_eq!(d.pages[0].images.len(), 2, "the new big picture is refused, the small one still fits"); + assert_eq!(d.pages[0].content.matches(" Do Q").count(), 3, "the held copy is drawn twice, the small one once"); + // The running per-page counts match the images each page holds, and a page handed out next + // sees what the reopened page added. + assert!(d.pages.iter().all(|p| p.image_kept == p.image_bytes())); + assert_eq!(d.add_page(100.0, 100.0).image_room(), 10_000 - 2 * 3072 - 4 * 4 * 3); + assert!(d.page_mut(10_000).is_none()); + assert_eq!(d.page_mut(1).map(|p| p.image_room()), Some(10_000 - 2 * 3072 - 4 * 4 * 3)); + let pdf = d.finish()?; + check_xref(&pdf)?; + // The identical 32×32 copies on pages 0 and 1 are written once; the 4×4 picture is the other. + assert_eq!(String::from_utf8_lossy(&pdf).matches("/Subtype /Image").count(), 2); + Ok(()) +} + +#[test] +fn a_picture_the_page_holds_is_drawn_again_after_the_budget_is_spent() -> Result<(), Box> { + let mut d = PdfDoc::new(); + // Room for exactly one translucent 1×1 picture (3 bytes of RGB plus 1 of alpha). + d.set_image_budget(4); + let p = d.add_page(100.0, 100.0); + let pixel = [10u8, 20, 30, 128]; + p.image_rgba(Rect::new(0.0, 0.0, 10.0, 10.0), &pixel, [1, 1]); + assert_eq!(p.image_room(), 0); + p.image_rgba(Rect::new(20.0, 0.0, 10.0, 10.0), &pixel, [1, 1]); + p.image_rgba(Rect::new(40.0, 0.0, 10.0, 10.0), &[10u8, 20, 30, 64], [1, 1]); + assert_eq!(p.images.len(), 1, "a new picture past the budget is refused"); + assert_eq!(p.content.matches("/Im1 Do Q").count(), 2, "the picture the page holds is drawn both times"); + // Refused pictures leave no trace in the duplicate index, however many distinct ones come. + for v in 0..=255u8 { + p.image_rgba(Rect::new(60.0, 0.0, 10.0, 10.0), &[v, 0, 0, 64], [1, 1]); + } + assert_eq!(p.images.len(), 1); + assert_eq!(p.image_index.len(), 1, "a refused picture adds no index entry"); + assert_eq!(p.image_index.values().map(Vec::len).sum::(), 1); + check_xref(&d.finish()?)?; + Ok(()) +} + #[test] fn arabic_is_shaped_and_preserved_or_falls_back_without_a_font() { let text = "مَرْحَبًا 123 (ABC)";