Skip to content

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

M2: heavy-sheet generator and page timing harness (item 8 of storytold/pdfcraft#623) (#2042)

cyfung10310bf49607bf5a
diff --git a/crates/render/examples/page_timing.rs b/crates/render/examples/page_timing.rs
new file mode 100644
index 000000000..f1d143a21
--- /dev/null
+++ b/crates/render/examples/page_timing.rs
@@ -0,0 +1,192 @@
+//! Times and hashes the renders the desktop canvas asks for on page 1 of a PDF, for before and after
+//! comparisons (storytold/pdfcraft#623, item 8).
+//!
+//! Each round queues one scenario's requests on a render pool with the engine's worker count and
+//! prints the time to the first answer, the wall time, the slowest request, the text glyph count,
+//! the warning count, the error count, and an FNV-1a hash of every answer's size, pixels and text
+//! layer in request order. Equal hashes mean equal output. Peak memory is not measured here; on
+//! macOS wrap the command in `/usr/bin/time -l`, and subtract the `load` scenario to get the
+//! render's share.
+//!
+//! Usage: `page_timing FILE SCENARIO [ROUNDS] [THREADS]`. Scenarios:
+//! - `load`: open the file and start the pool with no request.
+//! - `fit`: page 1 at 2800 device pixels wide.
+//! - `backdrop`: page 1 at 2048 pixels on its longest side, the canvas's low-resolution backdrop.
+//! - `thumb`: a 240 × 320 thumbnail at density 2.
+//! - `tiles100`, `tiles400`: four 1024 px tiles at 100% and 400% on a 2× display.
+//! - `tiny`: one 16 px tile, which shows the fixed cost of a request.
+//! - `text`: the text layer of page 1.
+//! - `sweep`: whole pages and tiles at six scales, the broadest identity check.
+
+use std::error::Error;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use pdfcraft_render::{PageText, RenderConfig, RenderPool, RenderRequest, RenderedPage, RequestKind, Tile};
+
+/// The canvas's tile side in device pixels.
+const TILE: u32 = 1024;
+const BACKDROP_SIDE: f32 = 2048.0;
+const FIT_WIDTH: f32 = 2800.0;
+const THUMB_W: f32 = 240.0;
+const THUMB_H: f32 = 320.0;
+const THUMB_DENSITY: f32 = 2.0;
+/// The tag bit that marks a thumbnail request, as the canvas sets it.
+const THUMB_TAG: u64 = 1 << 63;
+const TEXT_TAG: u64 = 1 << 62;
+/// Device pixels per point at 100% on a 2× display.
+const SCREEN_SCALE: f32 = 96.0 / 72.0 * 2.0;
+const TIMEOUT: Duration = Duration::from_secs(600);
+const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
+const FNV_PRIME: u64 = 0x0100_0000_01b3;
+
+fn main() -> Result<(), Box<dyn Error>> {
+ let args: Vec<String> = std::env::args().collect();
+ let (Some(path), Some(scenario)) = (args.get(1), args.get(2)) else {
+ return Err("usage: page_timing FILE SCENARIO [ROUNDS] [THREADS]".into());
+ };
+ let rounds: usize = match args.get(3) {
+ Some(s) => s.parse()?,
+ None => 1,
+ };
+ let threads: usize = match args.get(4) {
+ Some(s) => s.parse::<usize>()?.max(1),
+ None => std::thread::available_parallelism().map_or(4, |n| n.get()).clamp(2, 8) - 1,
+ };
+
+ let bytes = Arc::new(std::fs::read(path)?);
+ let (width, height) = {
+ let pdf = hayro_syntax::Pdf::new_with_password(bytes.clone(), "").map_err(|e| format!("{e:?}"))?;
+ let pages = pdf.pages();
+ pages.first().ok_or("the document has no pages")?.render_dimensions()
+ };
+ let requests = scenario_requests(scenario, width, height)?;
+
+ let pool = RenderPool::new(bytes, threads, RenderConfig::default());
+ for round in 0..rounds {
+ let (mut results, first, wall) = run(&pool, &requests)?;
+ results.sort_by_key(|r| (r.request.page, r.request.scale.to_bits(), r.request.tile.map(|t| (t.x, t.y, t.w, t.h))));
+ let slowest = results.iter().map(|r| r.millis).max().unwrap_or(0);
+ let glyphs: usize = results.iter().filter_map(|r| r.text.as_ref()).map(|t| t.glyphs.len()).sum();
+ let warnings: usize = results.iter().map(|r| r.warnings.len()).sum();
+ let errors: Vec<&str> = results.iter().filter_map(|r| r.error.as_deref()).collect();
+ let mut hash = FNV_OFFSET;
+ for r in &results {
+ hash = fnv1a(hash, &r.width.to_le_bytes());
+ hash = fnv1a(hash, &r.height.to_le_bytes());
+ hash = fnv1a(hash, &r.rgba[..]);
+ if let Some(text) = &r.text {
+ hash = hash_text(hash, text);
+ }
+ }
+ println!(
+ "round={round} scenario={scenario} page_pt={width}x{height} threads={threads} requests={} first_ms={} wall_ms={} slowest_ms={slowest} glyphs={glyphs} warnings={warnings} errors={} hash={hash:016x}",
+ requests.len(),
+ first.as_millis(),
+ wall.as_millis(),
+ errors.len()
+ );
+ if let Some(first_error) = errors.first() {
+ println!("first_error={first_error}");
+ }
+ if let Some(first_warning) = results.iter().flat_map(|r| r.warnings.iter()).next() {
+ println!("first_warning={first_warning:?}");
+ }
+ }
+ Ok(())
+}
+
+/// The requests of one scenario for a page of `width` × `height` points.
+fn scenario_requests(scenario: &str, width: f32, height: f32) -> Result<Vec<RenderRequest>, String> {
+ let page = |scale: f32, tile: Option<Tile>, preview: bool| RenderRequest {
+ page: 0,
+ kind: RequestKind::Pixels,
+ tile,
+ scale,
+ tag: scale_tag(scale),
+ preview,
+ };
+ let tiles = |scale: f32| -> Vec<RenderRequest> {
+ [(0, 0), (TILE, 0), (0, TILE), (TILE, TILE)].into_iter().map(|(x, y)| page(scale, Some(Tile { x, y, w: TILE, h: TILE }), false)).collect()
+ };
+ let requests = match scenario {
+ "load" => Vec::new(),
+ "fit" => vec![page(FIT_WIDTH / width, None, false)],
+ "backdrop" => vec![page(BACKDROP_SIDE / width.max(height), None, true)],
+ "thumb" => {
+ let scale = (THUMB_W / width).min(THUMB_H / height) * THUMB_DENSITY;
+ vec![RenderRequest { tag: THUMB_TAG | u64::from(scale.to_bits()), ..page(scale, None, true) }]
+ }
+ "tiles100" => tiles(SCREEN_SCALE),
+ "tiles400" => tiles(4.0 * SCREEN_SCALE),
+ "tiny" => vec![page(SCREEN_SCALE, Some(Tile { x: 0, y: 0, w: 16, h: 16 }), false)],
+ "text" => vec![RenderRequest { kind: RequestKind::Text, tag: TEXT_TAG, ..page(1.0, None, false) }],
+ "sweep" => {
+ let mut out = Vec::new();
+ for scale in [0.37_f32, 1.0, 1.7, 2.666_667, 5.5, 10.666_667] {
+ out.push(page(scale, None, false));
+ for side in [333_u32, 1024, 2048] {
+ for (x, y) in [(0_u32, 0_u32), (811, 507), (1500, 900)] {
+ out.push(page(scale, Some(Tile { x, y, w: side, h: side }), false));
+ }
+ }
+ }
+ out
+ }
+ other => return Err(format!("unknown scenario `{other}`")),
+ };
+ Ok(requests)
+}
+
+/// Queues `requests` as the canvas does and waits for every answer. Returns the answers, the time
+/// to the first one, and the wall time.
+fn run(pool: &RenderPool, requests: &[RenderRequest]) -> Result<(Vec<RenderedPage>, Duration, Duration), String> {
+ let start = Instant::now();
+ pool.set_queue(requests.to_vec());
+ let mut results = Vec::with_capacity(requests.len());
+ let mut first = None;
+ while results.len() < requests.len() {
+ match pool.try_recv() {
+ Some(page) => {
+ first.get_or_insert_with(|| start.elapsed());
+ results.push(page);
+ }
+ None if start.elapsed() > TIMEOUT => {
+ return Err(format!("{} of {} answers after {TIMEOUT:?}", results.len(), requests.len()));
+ }
+ None => std::thread::sleep(Duration::from_millis(1)),
+ }
+ }
+ Ok((results, first.unwrap_or_default(), start.elapsed()))
+}
+
+/// The canvas's tag for a scale: equal tags mean the same scale to 1/65536.
+fn scale_tag(scale: f32) -> u64 {
+ (f64::from(scale) * 65536.0).round() as u64
+}
+
+/// Folds `bytes` into an FNV-1a hash.
+fn fnv1a(mut hash: u64, bytes: &[u8]) -> u64 {
+ for &byte in bytes {
+ hash ^= u64::from(byte);
+ hash = hash.wrapping_mul(FNV_PRIME);
+ }
+ hash
+}
+
+/// Folds a text layer into `hash`: each glyph's text and boxes, then the line and space structure.
+fn hash_text(mut hash: u64, text: &PageText) -> u64 {
+ for glyph in &text.glyphs {
+ hash = fnv1a(hash, glyph.text.as_bytes());
+ for value in glyph.rect.iter().chain(glyph.quad.iter().flatten()).chain(glyph.direction.iter()) {
+ hash = fnv1a(hash, &value.to_bits().to_le_bytes());
+ }
+ }
+ for line in &text.line_of {
+ hash = fnv1a(hash, &line.to_le_bytes());
+ }
+ for &space in &text.space_before {
+ hash = fnv1a(hash, &[u8::from(space)]);
+ }
+ hash
+}
diff --git a/crates/render/examples/synth_sheet.rs b/crates/render/examples/synth_sheet.rs
new file mode 100644
index 000000000..2d31dbf7f
--- /dev/null
+++ b/crates/render/examples/synth_sheet.rs
@@ -0,0 +1,154 @@
+//! Writes a synthetic A1 engineering sheet, for timing large vector pages without the proprietary
+//! sample from storytold/pdfcraft#623 (item 8). It follows the sample's content layout: 1684 × 2384
+//! pt with `/Rotate 90`, one Flate stream of unit-length polyline strokes, each in its own `q … Q`
+//! block with `0.12 0 0 0.12 0 0 cm` and integer coordinates. Almost every stroke starts where the
+//! previous one ended, and most run vertically, as hatching does. Strokes are 2 units wide. A colour
+//! change comes before about 29% of strokes, a twelve-rectangle clip with one fill every 50,000
+//! strokes, and 1,143 labels come last, so a cut in the content loses the labels first. The colour
+//! space is named DeviceRGB, because the sample's ICC space renders at about the same cost, while
+//! CalRGB adds about 0.6 s to every request. The labels use non-embedded Helvetica, so the file
+//! carries no profile or font data.
+//!
+//! Usage: `synth_sheet OUT.pdf [STROKES]`. The default is 4,400,000 strokes (about 277 MB decoded).
+
+use std::error::Error;
+use std::io::Write as _;
+
+use flate2::Compression;
+use flate2::write::ZlibEncoder;
+
+const DEFAULT_STROKES: u64 = 4_400_000;
+/// The sheet spans this many content units (0.12 pt each).
+const SPAN: u64 = 14_000;
+const CLIP_EVERY: u64 = 50_000;
+const LABELS: u64 = 1_143;
+const SEED: u64 = 0x9E37_79B9_7F4A_7C15;
+
+/// xorshift64, so every run writes the same sheet.
+struct Rng(u64);
+
+impl Rng {
+ fn below(&mut self, n: u64) -> u64 {
+ let mut x = self.0;
+ x ^= x << 13;
+ x ^= x >> 7;
+ x ^= x << 17;
+ self.0 = x;
+ x % n
+ }
+}
+
+/// The content stream, compressed as it is written.
+struct Content {
+ encoder: ZlibEncoder<Vec<u8>>,
+ decoded: u64,
+}
+
+impl Content {
+ fn push(&mut self, text: &str) -> std::io::Result<()> {
+ self.encoder.write_all(text.as_bytes())?;
+ self.decoded += text.len() as u64;
+ Ok(())
+ }
+}
+
+/// A colour component in millionths, written with six decimals.
+fn micro(v: i64) -> String {
+ format!("{}.{:06}", v / 1_000_000, v % 1_000_000)
+}
+
+fn main() -> Result<(), Box<dyn Error>> {
+ let args: Vec<String> = std::env::args().collect();
+ let out = args.get(1).ok_or("usage: synth_sheet OUT.pdf [STROKES]")?;
+ let strokes: u64 = match args.get(2) {
+ Some(s) => s.parse()?,
+ None => DEFAULT_STROKES,
+ };
+
+ let mut content = Content { encoder: ZlibEncoder::new(Vec::new(), Compression::default()), decoded: 0 };
+ content.push("q\n0 1 -1 0 1684 0 cm\n1 J\n2 w\n")?;
+ let mut rng = Rng(SEED);
+ let mut colour = [49_509_i64, 49_175, 47_727];
+ let (mut x, mut y) = (rng.below(SPAN), rng.below(SPAN));
+ let (mut clips, mut colour_changes) = (0_u64, 0_u64);
+ for i in 0..strokes {
+ if i % CLIP_EVERY == 0 {
+ // A clip of twelve small rectangles with one fill, as the sample's clips are. The clip
+ // wraps no strokes.
+ content.push("q\n")?;
+ for _ in 0..12 {
+ let (rx, ry) = (rng.below(SPAN), rng.below(SPAN));
+ content.push(&format!("{} {} m\n{} {} l\n{} {} l\n{} {} l\nh\n", rx, ry, rx + 14, ry, rx + 14, ry + 30, rx, ry + 30))?;
+ }
+ content.push("W* n\n/Cs1 cs 0.930000 0.940000 0.960000 sc\n")?;
+ let (rx, ry) = (rng.below(SPAN), rng.below(SPAN));
+ content.push(&format!("{rx} {ry} 14 30 re f\nQ\n"))?;
+ clips += 1;
+ }
+ if rng.below(1000) < 293 {
+ for c in &mut colour {
+ *c = (*c + rng.below(4_001) as i64 - 2_000).clamp(0, 1_000_000);
+ }
+ content.push(&format!("/Cs1 CS {} {} {} SC\n", micro(colour[0]), micro(colour[1]), micro(colour[2])))?;
+ colour_changes += 1;
+ }
+ if rng.below(1000) < 11 {
+ x = rng.below(SPAN);
+ y = rng.below(SPAN);
+ }
+ let (dx, dy) = match rng.below(1000) {
+ 0..=693 => (0, 1),
+ 694..=845 => (1, 1),
+ 846..=992 => (1, 0),
+ _ => (0, 0),
+ };
+ let (nx, ny) = (x + dx, y + dy);
+ content.push(&format!("q\n0.12 0 0 0.12 0 0 cm\n{x} {y} m\n{nx} {ny} l\nS\nQ\n"))?;
+ (x, y) = (nx, ny);
+ }
+ for k in 0..LABELS {
+ let text = if k + 1 == LABELS { "END OF SHEET".to_string() } else { format!("CBL -{}", 100 + k) };
+ let (tx, ty) = (1210 + (k % 30) * 40, 497 + (k / 30) * 12);
+ content.push(&format!("q\n1 0 0 1 0 0 cm\n0 g\nBT\n/F3 1 Tf\n4 0 0 4 {tx} {ty} Tm\n({text}) Tj\nET\nQ\n"))?;
+ }
+ content.push("Q\n")?;
+
+ let Content { encoder, decoded } = content;
+ let stream = encoder.finish()?;
+ let mut stream_object = format!("<< /Length {} /Filter /FlateDecode >>\nstream\n", stream.len()).into_bytes();
+ stream_object.extend_from_slice(&stream);
+ stream_object.extend_from_slice(b"\nendstream");
+
+ let objects: Vec<Vec<u8>> = vec![
+ b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
+ b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
+ b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 1684 2384] /Rotate 90 /Contents 4 0 R /Resources << /ColorSpace << /Cs1 /DeviceRGB >> /Font << /F3 5 0 R >> >> >>"
+ .to_vec(),
+ stream_object,
+ b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>"
+ .to_vec(),
+ ];
+ let mut pdf = b"%PDF-1.4\n".to_vec();
+ let mut offsets = Vec::with_capacity(objects.len());
+ for (n, body) in objects.iter().enumerate() {
+ offsets.push(pdf.len());
+ pdf.extend_from_slice(format!("{} 0 obj\n", n + 1).as_bytes());
+ pdf.extend_from_slice(body);
+ pdf.extend_from_slice(b"\nendobj\n");
+ }
+ let xref_at = pdf.len();
+ let size = objects.len() + 1;
+ pdf.extend_from_slice(format!("xref\n0 {size}\n0000000000 65535 f \n").as_bytes());
+ for offset in &offsets {
+ pdf.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
+ }
+ pdf.extend_from_slice(format!("trailer\n<< /Size {size} /Root 1 0 R >>\nstartxref\n{xref_at}\n%%EOF\n").as_bytes());
+ std::fs::write(out, &pdf)?;
+
+ println!(
+ "wrote {out}: {strokes} strokes, {colour_changes} colour changes, {clips} clip groups, {LABELS} labels, {decoded} decoded bytes, {} stream bytes ({:.2}:1)",
+ stream.len(),
+ decoded as f64 / stream.len() as f64
+ );
+ Ok(())
+}