exprim 0.4.0

A concurrent, memory-bounded PDF reader and renderer: parse, extract text, and rasterize pages on an immutable document snapshot
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Page image export.
//!
//! The rest of this crate hands out raw rasters: a [`RasterPlane`] whose
//! caller is expected to know what a stride is. That is the right shape for
//! the processing pipeline, which feeds those bytes straight into
//! binarization and the encoders, but it is the wrong shape for everyone
//! else. "Give me page 3 as a PNG at 300 DPI" is the first thing every
//! consumer of a PDF renderer asks for, and until this module existed the
//! only answers in the tree were a `exprim-cli` subcommand that wrote
//! uncompressed PPM and a benchmark binary with a hand-rolled PNG writer.
//!
//! Two things make this thin rather than another rasterizer:
//!
//! * [`RenderSession::render`] already composites over
//!   [`Background::White`](crate::render_api::Background::White), so the surface
//!   that comes back is fully opaque and `rgb_surface_from_rgba` drops the
//!   alpha byte without any unpremultiply step. There is no alpha to
//!   preserve, and so no straight-vs-premultiplied decision to get wrong.
//! * `png` and `jpeg-encoder` are already workspace dependencies compiled for
//!   other members, so this adds no crate to the build graph.
//!
//! What this module owns is the arithmetic between the two: turning a DPI
//! into a pixel size via the *display* extent (so a `/Rotate 90` page exports
//! landscape), refusing sizes that would allocate more than the caller
//! budgeted, and packing a renderer surface whose stride may exceed its row
//! width into the tightly-packed buffer both encoders require.

use std::sync::Arc;

use crate::reader::session::{
    CancellationToken, CompiledDocumentPage, GraySurface, PageGeometry, RasterFormat, RasterPlane,
    RasterProduct, ReadError, RenderSession, RgbSurface,
};

/// Resolution used when a caller does not state one. Matches the `pdfr render`
/// default so the two entry points agree.
pub const DEFAULT_EXPORT_DPI: f64 = 150.0;

/// Default ceiling on `width * height` for one exported page, about 100
/// megapixels — a 300 DPI A0 sheet still fits, while a malformed or hostile
/// `/MediaBox` cannot talk the caller into a multi-gigabyte allocation.
pub const DEFAULT_MAX_EXPORT_PIXELS: u64 = 100_000_000;

/// Largest resolution accepted. Beyond this the pixel-size arithmetic stops
/// being meaningful long before the pixel budget is what stops you.
const MAX_EXPORT_DPI: f64 = 10_000.0;

/// Encoded container for an exported page.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImageFormat {
    /// Lossless, alpha-free (the surface is already composited over white).
    Png,
    /// Baseline JPEG. `quality` is clamped to `1..=100`.
    ///
    /// JPEG dimensions are 16-bit, so a page wider or taller than 65535
    /// pixels is rejected rather than silently truncated.
    Jpeg {
        /// Encoder quality, 1 (smallest) to 100 (best).
        quality: u8,
    },
}

/// Colour of the exported raster.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExportColor {
    /// 8-bit RGB.
    Rgb8,
    /// 8-bit grayscale. Cheaper to render and to encode; note the renderer
    /// produces this as a Rec.709 luma of the *composited* page, not a
    /// separate luminance channel.
    Gray8,
}

/// How to export one page.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ExportOptions {
    /// Resolution in dots per inch. A PDF point is 1/72 inch, so a page 612
    /// points wide exports 1,275 pixels wide at 150 DPI.
    pub dpi: f64,
    /// The file format to encode.
    pub format: ImageFormat,
    /// RGB or grayscale.
    pub color: ExportColor,
    /// Reject the export when `width * height` exceeds this.
    pub max_pixels: u64,
}

impl Default for ExportOptions {
    fn default() -> Self {
        Self {
            dpi: DEFAULT_EXPORT_DPI,
            format: ImageFormat::Png,
            color: ExportColor::Rgb8,
            max_pixels: DEFAULT_MAX_EXPORT_PIXELS,
        }
    }
}

impl ExportOptions {
    /// RGB PNG at `dpi`.
    pub fn png(dpi: f64) -> Self {
        Self {
            dpi,
            format: ImageFormat::Png,
            ..Self::default()
        }
    }

    /// RGB JPEG at `dpi` and `quality`.
    pub fn jpeg(dpi: f64, quality: u8) -> Self {
        Self {
            dpi,
            format: ImageFormat::Jpeg { quality },
            ..Self::default()
        }
    }

    /// The same export in a different colour mode.
    pub fn with_color(mut self, color: ExportColor) -> Self {
        self.color = color;
        self
    }

    /// The same export with a different pixel budget (see
    /// [`max_pixels`](Self::max_pixels)).
    pub fn with_max_pixels(mut self, max_pixels: u64) -> Self {
        self.max_pixels = max_pixels;
        self
    }

    fn raster_format(self) -> RasterFormat {
        match self.color {
            ExportColor::Rgb8 => RasterFormat::Rgb8,
            ExportColor::Gray8 => RasterFormat::Gray8,
        }
    }
}

/// Pixel size a page occupies at `dpi`, using the page's *display* extent so
/// that a page rotated by an odd multiple of 90 degrees reports the swapped
/// axes a viewer would show.
///
/// Both dimensions are at least 1: a degenerate `/CropBox` exports a 1-pixel
/// image rather than failing, which keeps page-range exports from aborting
/// partway through on one malformed page.
pub fn pixel_size_for_dpi(
    geometry: PageGeometry,
    dpi: f64,
    max_pixels: u64,
) -> Result<(u32, u32), ReadError> {
    if !dpi.is_finite() || dpi <= 0.0 {
        return Err(ReadError::InvalidExportOptions(
            "dpi must be finite and greater than zero",
        ));
    }
    if dpi > MAX_EXPORT_DPI {
        return Err(ReadError::InvalidExportOptions("dpi exceeds 10000"));
    }

    let scale = dpi / 72.0;
    let to_pixels = |points: f64| -> u32 {
        let pixels = (points * scale).round();
        if !pixels.is_finite() || pixels < 1.0 {
            1
        } else if pixels > u32::MAX as f64 {
            u32::MAX
        } else {
            pixels as u32
        }
    };

    let width = to_pixels(geometry.display_width());
    let height = to_pixels(geometry.display_height());

    if u64::from(width) * u64::from(height) > max_pixels {
        return Err(ReadError::ExportTooLarge {
            width,
            height,
            max_pixels,
        });
    }
    Ok((width, height))
}

impl RenderSession {
    /// Pixel size page `page` would export at, at `dpi`.
    ///
    /// Useful on its own: a caller sizing a thumbnail cache or a print
    /// preview wants this without paying for the render.
    pub fn page_pixel_size(&self, page: u32, dpi: f64) -> Result<(u32, u32), ReadError> {
        pixel_size_for_dpi(self.page_geometry(page)?, dpi, u64::MAX)
    }

    /// Render page `page` and encode it, returning the file bytes.
    ///
    /// This is the whole job in one call: compile, render at the resolution
    /// `options.dpi` implies, encode. Callers holding a
    /// [`CompiledDocumentPage`] they intend to reuse should prefer
    /// [`RenderSession::export_compiled_page`] to skip recompiling.
    ///
    /// # Errors
    ///
    /// [`ReadError::PageOutOfRange`], [`ReadError::InvalidExportOptions`] and
    /// [`ReadError::ExportTooLarge`] before any rendering;
    /// [`ReadError::Compile`], [`ReadError::Render`] or [`ReadError::Encode`]
    /// after.
    ///
    /// # Examples
    ///
    /// Save every page as a grayscale JPEG at 200 DPI:
    ///
    /// ```no_run
    /// use exprim::{ExportColor, ExportOptions};
    /// # let bytes: std::sync::Arc<[u8]> = std::fs::read("document.pdf")?.into();
    ///
    /// let session = exprim::RenderSession::open(bytes, None)?;
    /// let options = ExportOptions::jpeg(200.0, 85).with_color(ExportColor::Gray8);
    /// for page in 0..session.page_count() {
    ///     let jpeg = session.export_page(page, &options)?;
    ///     std::fs::write(format!("page-{:04}.jpg", page + 1), jpeg)?;
    /// }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn export_page(&self, page: u32, options: &ExportOptions) -> Result<Vec<u8>, ReadError> {
        self.export_page_cancellable(page, options, None)
    }

    /// [`RenderSession::export_page`] with cooperative cancellation.
    pub fn export_page_cancellable(
        &self,
        page: u32,
        options: &ExportOptions,
        cancellation: Option<&CancellationToken>,
    ) -> Result<Vec<u8>, ReadError> {
        let compiled = self.compile_cancellable(page, cancellation)?;
        self.export_compiled_page(&compiled, options, cancellation)
    }

    /// Export an already-compiled page.
    pub fn export_compiled_page(
        &self,
        page: &Arc<CompiledDocumentPage>,
        options: &ExportOptions,
        cancellation: Option<&CancellationToken>,
    ) -> Result<Vec<u8>, ReadError> {
        let geometry = self.page_geometry(page.page_index())?;
        let (width, height) = pixel_size_for_dpi(geometry, options.dpi, options.max_pixels)?;
        let product = RasterProduct {
            width,
            height,
            format: options.raster_format(),
            crop: None,
            decode_reference: None,
        };
        let plane = self.render_cancellable(page, &product, cancellation)?;
        encode_plane(&plane, options.format)
    }
}

/// Encode an already-rendered plane.
///
/// Split out from [`RenderSession::export_compiled_page`] so a caller that
/// rendered through [`RenderSession::render_output_plan`] — or that wants one
/// render encoded into two formats — does not have to rasterize twice.
///
/// # Examples
///
/// One render, two files:
///
/// ```no_run
/// use exprim::{ImageFormat, RasterProduct, encode_plane};
/// # let bytes: std::sync::Arc<[u8]> = std::fs::read("document.pdf")?.into();
///
/// let session = exprim::RenderSession::open(bytes, None)?;
/// let page = session.compile(0)?;
/// let plane = session.render(&page, &RasterProduct::rgb8(850, 1100))?;
/// std::fs::write("page.png", encode_plane(&plane, ImageFormat::Png)?)?;
/// std::fs::write("page.jpg", encode_plane(&plane, ImageFormat::Jpeg { quality: 85 })?)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn encode_plane(plane: &RasterPlane, format: ImageFormat) -> Result<Vec<u8>, ReadError> {
    match plane {
        RasterPlane::Rgb8(surface) => encode_rgb(surface, format),
        RasterPlane::Gray8(surface) => encode_gray(surface, format),
    }
}

fn encode_rgb(surface: &RgbSurface, format: ImageFormat) -> Result<Vec<u8>, ReadError> {
    let packed = pack_rows(
        &surface.pixels,
        surface.width,
        surface.height,
        surface.stride,
        3,
    )?;
    match format {
        ImageFormat::Png => encode_png(&packed, surface.width, surface.height, png::ColorType::Rgb),
        ImageFormat::Jpeg { quality } => encode_jpeg(
            &packed,
            surface.width,
            surface.height,
            quality,
            jpeg_encoder::ColorType::Rgb,
        ),
    }
}

fn encode_gray(surface: &GraySurface, format: ImageFormat) -> Result<Vec<u8>, ReadError> {
    let packed = pack_rows(
        &surface.pixels,
        surface.width,
        surface.height,
        surface.stride,
        1,
    )?;
    match format {
        ImageFormat::Png => encode_png(
            &packed,
            surface.width,
            surface.height,
            png::ColorType::Grayscale,
        ),
        ImageFormat::Jpeg { quality } => encode_jpeg(
            &packed,
            surface.width,
            surface.height,
            quality,
            jpeg_encoder::ColorType::Luma,
        ),
    }
}

/// Copy `height` rows of `width * bytes_per_pixel` out of a possibly-padded
/// surface into a tightly-packed buffer.
///
/// Both encoders want packed rows, and the renderer only guarantees
/// `stride >= width * bytes_per_pixel`. When the surface is already packed
/// this borrows instead of copying, which is the common case for RGB (the
/// facade repacks to `width * 3` on the way out) and for full-page grayscale.
fn pack_rows<'a>(
    pixels: &'a Arc<[u8]>,
    width: u32,
    height: u32,
    stride: usize,
    bytes_per_pixel: usize,
) -> Result<std::borrow::Cow<'a, [u8]>, ReadError> {
    let row_bytes = (width as usize)
        .checked_mul(bytes_per_pixel)
        .ok_or(ReadError::InvalidRasterProduct("row size overflow"))?;
    let height = height as usize;

    if stride == row_bytes {
        let needed = row_bytes
            .checked_mul(height)
            .ok_or(ReadError::InvalidRasterProduct("surface size overflow"))?;
        let packed = pixels
            .get(..needed)
            .ok_or_else(|| ReadError::Encode("surface is shorter than its dimensions".into()))?;
        return Ok(std::borrow::Cow::Borrowed(packed));
    }

    let capacity = row_bytes
        .checked_mul(height)
        .ok_or(ReadError::InvalidRasterProduct("surface size overflow"))?;
    let mut packed = Vec::with_capacity(capacity);
    for row in 0..height {
        let start = row
            .checked_mul(stride)
            .ok_or(ReadError::InvalidRasterProduct("row offset overflow"))?;
        let end = start
            .checked_add(row_bytes)
            .ok_or(ReadError::InvalidRasterProduct("row end overflow"))?;
        let row = pixels
            .get(start..end)
            .ok_or_else(|| ReadError::Encode("surface row is out of bounds".into()))?;
        packed.extend_from_slice(row);
    }
    Ok(std::borrow::Cow::Owned(packed))
}

fn encode_png(
    packed: &[u8],
    width: u32,
    height: u32,
    color: png::ColorType,
) -> Result<Vec<u8>, ReadError> {
    let mut out = Vec::new();
    let mut encoder = png::Encoder::new(&mut out, width, height);
    encoder.set_color(color);
    encoder.set_depth(png::BitDepth::Eight);
    let mut writer = encoder
        .write_header()
        .map_err(|error| ReadError::Encode(format!("writing PNG header: {error}")))?;
    writer
        .write_image_data(packed)
        .map_err(|error| ReadError::Encode(format!("writing PNG pixels: {error}")))?;
    writer
        .finish()
        .map_err(|error| ReadError::Encode(format!("finishing PNG stream: {error}")))?;
    Ok(out)
}

fn encode_jpeg(
    packed: &[u8],
    width: u32,
    height: u32,
    quality: u8,
    color: jpeg_encoder::ColorType,
) -> Result<Vec<u8>, ReadError> {
    let width = u16::try_from(width)
        .map_err(|_| ReadError::Encode("JPEG width exceeds 65535 pixels".into()))?;
    let height = u16::try_from(height)
        .map_err(|_| ReadError::Encode("JPEG height exceeds 65535 pixels".into()))?;

    let mut out = Vec::new();
    let encoder = jpeg_encoder::Encoder::new(&mut out, quality.clamp(1, 100));
    encoder
        .encode(packed, width, height, color)
        .map_err(|error| ReadError::Encode(format!("encoding JPEG: {error}")))?;
    Ok(out)
}