mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-25 16:44:12 +00:00
fix(render): a Type 3 glyph shown again isn't decoded again (hayro-interpret patch 87)
A Type 3 font now keeps each glyph procedure it decoded, so a glyph drawn many times isn't inflated again for every copy. A real file uses a one-glyph Type 3 font as a fill pattern and draws that glyph about 650,000 times on a page; it rendered in 11.2 s and now in 5.9 s, pixel for pixel the same. A procedure over 64 KiB isn't kept, and the fonts of one InterpreterCache keep at most 32 MiB together, as fonts live as long as the cache. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Pq7HyDBXygTf7jcqdsjcfn
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
97cef90e01
commit
05dca28601
@@ -8196,6 +8196,9 @@ fn decoded_images_serve_every_size_they_are_drawn_at() {
|
||||
// ICC profiles whose stream dictionaries are the same (vendored hayro-interpret patch 48).
|
||||
mod icc_profile_cache;
|
||||
|
||||
// A Type 3 glyph shown again decodes its procedure once (vendored hayro-interpret patch 87).
|
||||
mod type3_proc_cache;
|
||||
|
||||
// A symbolic TrueType font draws through its (3, 0) cmap subtable first (#4156).
|
||||
mod symbolic_truetype_cmap;
|
||||
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
//! A Type 3 glyph shown many times decodes its glyph procedure once (vendored hayro-interpret
|
||||
//! patch 87). hayro inflated the procedure again for every copy of the glyph, so a font used as
|
||||
//! a fill pattern, one glyph drawn hundreds of thousands of times, took seconds a page.
|
||||
|
||||
use super::image_cache_pdf;
|
||||
use hayro::hayro_interpret::font::Glyph;
|
||||
use hayro::hayro_interpret::hayro_syntax::Pdf;
|
||||
use hayro::hayro_interpret::{
|
||||
BlendMode, ClipPath, Context, Device, GlyphDrawMode, Image, InterpreterCache, InterpreterSettings, Paint, PathDrawMode, SoftMask, TransformExt,
|
||||
interpret_page,
|
||||
};
|
||||
use kurbo::{Affine, BezPath, Rect};
|
||||
use std::io::Write;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Counts the paths drawn, and draws each Type 3 glyph through its procedure, as the renderer does.
|
||||
#[derive(Default)]
|
||||
struct Paths(usize);
|
||||
|
||||
impl<'a> Device<'a> for Paths {
|
||||
fn set_soft_mask(&mut self, _: Option<SoftMask<'a>>) {}
|
||||
fn set_blend_mode(&mut self, _: BlendMode) {}
|
||||
fn draw_path(&mut self, _: &BezPath, _: Affine, _: &Paint<'a>, _: &PathDrawMode) {
|
||||
self.0 += 1;
|
||||
}
|
||||
fn push_clip_path(&mut self, _: &ClipPath) {}
|
||||
fn push_transparency_group(&mut self, _: f32, _: Option<SoftMask<'a>>, _: BlendMode) {}
|
||||
fn draw_glyph(&mut self, glyph: &Glyph<'a>, transform: Affine, glyph_transform: Affine, paint: &Paint<'a>, _: &GlyphDrawMode) {
|
||||
if let Glyph::Type3(glyph) = glyph {
|
||||
glyph.interpret(self, transform, glyph_transform, paint);
|
||||
}
|
||||
}
|
||||
fn draw_image(&mut self, _: Image<'a, '_>, _: Affine) {}
|
||||
fn pop_clip_path(&mut self) {}
|
||||
fn pop_transparency_group(&mut self) {}
|
||||
}
|
||||
|
||||
/// A Type 3 font whose one glyph, `!`, is a Flate-compressed procedure filling its 8 × 8 box,
|
||||
/// shown 200 times on one page and rendered twice through one cache: every copy draws, and the
|
||||
/// procedure is decoded once, on the first copy.
|
||||
#[test]
|
||||
fn a_type3_glyph_shown_again_decodes_its_procedure_once() {
|
||||
let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast());
|
||||
z.write_all(b"8 0 0 0 8 8 d1 0 0 8 8 re f").unwrap();
|
||||
let proc_bytes = z.finish().unwrap();
|
||||
let proc_dict = format!("<< /Filter /FlateDecode /Length {} >>", proc_bytes.len());
|
||||
let font = "<< /Type /Font /Subtype /Type3 /FontBBox [0 0 8 8] /FontMatrix [0.125 0 0 0.125 0 0] \
|
||||
/CharProcs << /dot 5 0 R >> /Encoding << /Type /Encoding /Differences [33 /dot] >> \
|
||||
/FirstChar 33 /LastChar 33 /Widths [8] >>";
|
||||
let content = format!("BT /F1 0.5 Tf 1 0 0 1 2 30 Tm ({}) Tj ET", "!".repeat(200));
|
||||
let bytes = image_cache_pdf(&content, &format!("<< /Font << /F1 {font} >> >>"), &[(&proc_dict, &proc_bytes)]);
|
||||
let parsed = Pdf::new(Arc::new(bytes)).expect("parses");
|
||||
let page = &parsed.pages()[0];
|
||||
let cache = InterpreterCache::new();
|
||||
for render in ["first", "second"] {
|
||||
let initial = page.initial_transform(true).to_kurbo();
|
||||
let mut ctx = Context::new(initial, Rect::new(0.0, 0.0, 130.0, 70.0), &cache, page.xref(), InterpreterSettings::default());
|
||||
let mut device = Paths::default();
|
||||
interpret_page(page, &mut ctx, &mut device);
|
||||
assert_eq!(device.0, 200, "the {render} render draws every copy of the glyph");
|
||||
assert_eq!(cache.type3_proc_decodes(), 1, "after the {render} render: the procedure is decoded once");
|
||||
}
|
||||
}
|
||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
+24
@@ -123,6 +123,22 @@ pub struct InterpreterCache<'a> {
|
||||
/// PdfCraft patch: decoded images, shared by every render through this cache so a tile
|
||||
/// no longer decodes its page's images again.
|
||||
pub(crate) decoded_cache: DecodedImageCache,
|
||||
/// PdfCraft patch (87): what the Type 3 fonts of this cache keep of their decoded glyph
|
||||
/// procedures, together (see `font::type3`).
|
||||
pub(crate) type3_procs: Rc<Type3Procs>,
|
||||
}
|
||||
|
||||
/// PdfCraft patch (87): decoded Type 3 glyph procedure bytes all the fonts of one
|
||||
/// [`InterpreterCache`] keep together. Fonts live as long as the cache, so the bound is on the
|
||||
/// cache, not on each font: a document can have thousands of Type 3 fonts.
|
||||
pub(crate) const MAX_CACHED_TYPE3_PROCS: usize = 32 << 20;
|
||||
|
||||
/// PdfCraft patch (87): the decoded glyph procedure bytes the Type 3 fonts of a cache keep,
|
||||
/// and how many procedures they decoded.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Type3Procs {
|
||||
pub(crate) held: core::cell::Cell<usize>,
|
||||
pub(crate) decodes: core::cell::Cell<usize>,
|
||||
}
|
||||
|
||||
impl<'a> Default for InterpreterCache<'a> {
|
||||
@@ -138,9 +154,17 @@ impl<'a> InterpreterCache<'a> {
|
||||
font_cache: Rc::new(RefCell::new(HashMap::new())),
|
||||
object_cache: Cache::new(),
|
||||
decoded_cache: DecodedImageCache::new(),
|
||||
type3_procs: Rc::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// PdfCraft patch (87): how many Type 3 glyph procedures the fonts of this cache decoded,
|
||||
/// for diagnostics and tests. A procedure kept from an earlier copy of its glyph isn't
|
||||
/// decoded again.
|
||||
pub fn type3_proc_decodes(&self) -> usize {
|
||||
self.type3_procs.decodes.get()
|
||||
}
|
||||
|
||||
/// PdfCraft patch (32): how many images were decoded through this cache (its misses, not
|
||||
/// counting images that are never cached), for diagnostics and tests.
|
||||
pub fn decoded_image_decodes(&self) -> usize {
|
||||
|
||||
+41
-4
@@ -1,5 +1,5 @@
|
||||
use crate::CMapResolverFn;
|
||||
use crate::context::Context;
|
||||
use crate::context::{Context, MAX_CACHED_TYPE3_PROCS, Type3Procs};
|
||||
use crate::device::Device;
|
||||
use crate::font::glyph_simulator::GlyphSimulator;
|
||||
use crate::font::true_type::{Width, read_encoding, read_widths};
|
||||
@@ -19,7 +19,9 @@ use hayro_syntax::object::dict::keys::{CHAR_PROCS, FONT_BBOX, FONT_MATRIX, RESOU
|
||||
use hayro_syntax::page::Resources;
|
||||
use kurbo::{Affine, BezPath, Rect};
|
||||
use skrifa::GlyphId;
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Type3<'a> {
|
||||
@@ -33,8 +35,17 @@ pub(crate) struct Type3<'a> {
|
||||
font_bbox: Rect,
|
||||
matrix: Affine,
|
||||
to_unicode: Option<CMap>,
|
||||
/// PdfCraft patch (87): glyph procedures already decoded, by glyph name, so a glyph shown
|
||||
/// again and again (a Type 3 font used as a fill pattern draws one glyph hundreds of
|
||||
/// thousands of times) isn't inflated again for every copy. Only procedures of at most
|
||||
/// [`MAX_CACHED_PROC`] bytes are kept, and the fonts of one interpreter cache keep at most
|
||||
/// `context::MAX_CACHED_TYPE3_PROCS` bytes together.
|
||||
decoded_procs: RefCell<HashMap<String, Rc<[u8]>>>,
|
||||
}
|
||||
|
||||
/// PdfCraft patch (87): the largest decoded glyph procedure [`Type3`] keeps.
|
||||
const MAX_CACHED_PROC: usize = 64 << 10;
|
||||
|
||||
impl<'a> Type3<'a> {
|
||||
pub(crate) fn new(dict: &Dict<'a>, cmap_resolver: &CMapResolverFn) -> Option<Self> {
|
||||
let (encoding, encodings) = read_encoding(dict);
|
||||
@@ -75,9 +86,36 @@ impl<'a> Type3<'a> {
|
||||
matrix,
|
||||
dict: dict.clone(),
|
||||
to_unicode,
|
||||
decoded_procs: RefCell::new(HashMap::new()),
|
||||
})
|
||||
}
|
||||
|
||||
/// PdfCraft patch (87): the decoded procedure of glyph `name`, decoded within the page's
|
||||
/// content budget the first time and kept, when small enough and while `procs` has room,
|
||||
/// for the next copies.
|
||||
fn decoded_proc(
|
||||
&self,
|
||||
name: &str,
|
||||
program: &Stream<'a>,
|
||||
procs: &Type3Procs,
|
||||
) -> Option<Rc<[u8]>> {
|
||||
if let Some(bytes) = self.decoded_procs.borrow().get(name) {
|
||||
return Some(bytes.clone());
|
||||
}
|
||||
// PdfCraft patch: see `context::MAX_PAGE_CONTENT`.
|
||||
let decoded = crate::context::decode_content(program)?;
|
||||
procs.decodes.set(procs.decodes.get().saturating_add(1));
|
||||
let bytes: Rc<[u8]> = Rc::from(decoded.as_ref());
|
||||
let held = procs.held.get().saturating_add(bytes.len());
|
||||
if bytes.len() <= MAX_CACHED_PROC && held <= MAX_CACHED_TYPE3_PROCS {
|
||||
procs.held.set(held);
|
||||
self.decoded_procs
|
||||
.borrow_mut()
|
||||
.insert(name.to_string(), bytes.clone());
|
||||
}
|
||||
Some(bytes)
|
||||
}
|
||||
|
||||
pub(crate) fn map_code(&self, code: u8) -> GlyphId {
|
||||
self.encodings
|
||||
.get(&code)
|
||||
@@ -144,9 +182,8 @@ impl<'a> Type3<'a> {
|
||||
|
||||
let name = self.glyph_simulator.glyph_to_string(glyph.glyph_id)?;
|
||||
let program = self.char_procs.get(&name)?;
|
||||
// PdfCraft patch: see `context::MAX_PAGE_CONTENT`.
|
||||
let decoded = crate::context::decode_content(program)?;
|
||||
let iter = TypedIter::new(decoded.as_ref());
|
||||
let decoded = self.decoded_proc(&name, program, &glyph.cache.type3_procs)?;
|
||||
let iter = TypedIter::new(&decoded);
|
||||
|
||||
let is_shape_glyph = {
|
||||
let mut iter = iter.clone();
|
||||
|
||||
Reference in New Issue
Block a user