Skip to main content

docling_pdf/
pdfium_backend.rs

1//! The page walk of the PDF pipeline: per page, the geometry and links from
2//! the object model (`pdf_meta`), the text layer from the pure-Rust parser
3//! (`textparse`), the model-input bitmaps from the docling-parse renderer
4//! plugin, the Rust raster or the Rust page renderer — and, behind the
5//! `pdfium` feature, the pdfium library for `DOCLING_RS_RENDERER=pdfium`
6//! (docling's pypdfium2 chain) and for a file lopdf cannot read ([`native`]).
7//! The module keeps its historical name; every type in it is pdfium-free.
8
9#[cfg(feature = "render")]
10use crate::PdfError;
11#[cfg(feature = "ocr-prep")]
12use image::RgbImage;
13
14/// A run of text with its bounding box, in PDF points with a **top-left** origin
15/// (pdfium's native origin is bottom-left; we flip it to match docling's
16/// `BoundingBox(..., origin=TOPLEFT)`).
17#[derive(Debug, Clone)]
18pub struct TextCell {
19    pub text: String,
20    pub l: f32,
21    pub t: f32,
22    pub r: f32,
23    pub b: f32,
24}
25
26/// Pixels-per-point used to render page images. Layout is scale-invariant (it
27/// scales normalized boxes by the page point size), but OCR benefits from the
28/// extra resolution.
29pub const RENDER_SCALE: f32 = 2.0;
30
31/// One page's geometry, extracted text cells, and a rendered RGB image. The
32/// image is rendered at [`RENDER_SCALE`] pixels per PDF point; `image px =
33/// page point × scale`.
34#[derive(Clone)]
35pub struct PdfPage {
36    pub width: f32,
37    pub height: f32,
38    pub scale: f32,
39    pub cells: Vec<TextCell>,
40    /// Same text grouped for code regions: split only at pdfium space glyphs, so
41    /// monospace runs keep their source spacing instead of the prose heuristic's.
42    pub code_cells: Vec<TextCell>,
43    /// Per-word cells (one per word, not joined into lines) for TableFormer cell
44    /// matching.
45    pub word_cells: Vec<TextCell>,
46    /// Checkbox squares drawn on the page (#609): assembly gives each line
47    /// with one in front of it its own checkbox item. Empty without a text
48    /// layer (OCR pages) or vector paths.
49    pub checkboxes: Vec<crate::checkbox::CheckBox>,
50    /// The rendered page bitmap. Present whenever pixels are available at all
51    /// (`ocr-prep` ⊂ `ml`): the native pipeline renders it with pdfium, the
52    /// browser pipeline receives it from the host canvas. Picture regions are
53    /// cropped out of it.
54    #[cfg(feature = "ocr-prep")]
55    pub image: RgbImage,
56    /// The **scale-1.0** page image the layout model runs on (parity with
57    /// docling's `PyPdfiumDocumentBackend`: the layout stage calls
58    /// `page.get_image(scale=1.0)`, which that backend serves as pdfium at
59    /// 1.5×, PIL-BICUBIC down to point size — a *different* image from the 2×
60    /// OCR/crop bitmap above, and a different resampling regime than
61    /// stretching that bitmap; docling 2.123+'s default docling-parse backend
62    /// renders the same request with its own Blend2D/FreeType renderer, whose
63    /// glyph anti-aliasing differs — #478). `None` on paths without a pdfium
64    /// renderer (browser, METS/TIFF), which fall back to stretching
65    /// [`Self::image`].
66    #[cfg(feature = "ocr-prep")]
67    pub image_layout: Option<RgbImage>,
68    /// The 2x bitmap of a page with a text layer, deferred to the page
69    /// walk's helper thread (#682): [`Self::image`] holds a 1×1 placeholder
70    /// until [`Self::resolve_image`] installs the render. The ML pipeline
71    /// resolves it after layout — the stage that reads
72    /// [`Self::image_layout`] instead — and only for a page whose detections
73    /// read the bitmap (tables, pictures, …; #897), so a text-only page never
74    /// draws it. `None` once resolved, and on every path that renders
75    /// synchronously (scanned pages, the plugin and pdfium renderers,
76    /// images, METS).
77    #[cfg(feature = "render")]
78    pub pending_image: Option<PendingImage>,
79    /// Hyperlink annotations on the page (rect in top-left page coords + target
80    /// URI), restricted to web/mail/tel schemes. Used only by strict Markdown.
81    pub links: Vec<LinkAnnot>,
82    /// The page's `/Rotate` value (0/90/180/270) when it was normalized away
83    /// before inference: a scanned page with `/Rotate` displays its raster
84    /// rotated, which turns OCR into garbage — so extraction un-rotates the
85    /// bitmaps (and swaps `width`/`height`) and records the display rotation
86    /// here. Assembly rotates the finished geometry *back* by this many
87    /// degrees clockwise, so emitted locations and the page size stay in
88    /// display space (matching docling and every PDF viewer). Always 0 for
89    /// text-layer pages (their cells live in display space already) and on
90    /// paths without a pdfium renderer.
91    pub rotation: u16,
92    /// Keep typographic punctuation as drawn — curly and low quotes, dashes,
93    /// `…`, `⁄`, `•` — instead of folding it to ASCII the way docling-parse's
94    /// sanitizer does (`pdf_keep_typography`, #921). Read by assembly.
95    pub keep_typography: bool,
96}
97
98impl PdfPage {
99    /// A page built from recognized cells alone — the browser pipeline's
100    /// shape (#157), where the bitmap lives on the JS side. Exists so callers
101    /// compile identically with and without the `ml` feature: under a
102    /// feature-unified workspace build the struct carries the `image` field,
103    /// which a plain literal in a non-`ml` consumer can't spell.
104    #[cfg(feature = "ocr-prep")]
105    pub fn from_cells(width: f32, height: f32, scale: f32, cells: Vec<TextCell>) -> Self {
106        Self {
107            width,
108            height,
109            scale,
110            cells,
111            code_cells: Vec::new(),
112            word_cells: Vec::new(),
113            checkboxes: Vec::new(),
114            #[cfg(feature = "ocr-prep")]
115            image: RgbImage::new(0, 0),
116            #[cfg(feature = "ocr-prep")]
117            image_layout: None,
118            #[cfg(feature = "render")]
119            pending_image: None,
120            links: Vec::new(),
121            rotation: 0,
122            keep_typography: false,
123        }
124    }
125
126    /// Wait for a deferred 2x render (#682) — starting it first when it was
127    /// left for on demand ([`BitmapRender::OnDemand`], #897) — and install it
128    /// as [`Self::image`]; a no-op when nothing is pending. The ML pipeline
129    /// calls it after layout for a page whose detections need the bitmap,
130    /// before anything reads it.
131    #[cfg(feature = "render")]
132    pub fn resolve_image(&mut self) -> Result<(), PdfError> {
133        if let Some(pending) = self.pending_image.take() {
134            self.image = crate::timing::timed("render.wait", || pending.wait())?;
135        }
136        Ok(())
137    }
138
139    /// Whether [`Self::image`] is still a placeholder for a deferred 2x
140    /// render ([`Self::resolve_image`] installs it).
141    #[cfg(feature = "render")]
142    pub fn image_pending(&self) -> bool {
143        self.pending_image.is_some()
144    }
145
146    /// Nothing is going to read this page's deferred 2x bitmap (#897): the
147    /// helper skips its render if it has not begun it. The page stays
148    /// pending — a later [`Self::resolve_image`] still gets the bitmap,
149    /// rendering it then if it was skipped.
150    #[cfg(feature = "render")]
151    pub fn decline_image(&self) {
152        if let Some(pending) = &self.pending_image {
153            pending.decline();
154        }
155    }
156
157    /// Same as [`from_cells`](Self::from_cells) but carrying the rendered page
158    /// bitmap, so picture regions can be cropped out of it (#157: the browser
159    /// pipeline gets the same figure bytes the native one does).
160    #[cfg(feature = "ocr-prep")]
161    pub fn from_cells_with_image(
162        width: f32,
163        height: f32,
164        scale: f32,
165        cells: Vec<TextCell>,
166        image: RgbImage,
167    ) -> Self {
168        Self {
169            image,
170            ..Self::from_cells(width, height, scale, cells)
171        }
172    }
173
174    /// Un-rotate the page's bitmaps by `deg` (clockwise 90° steps) and record
175    /// the compensating display rotation, composing with any rotation already
176    /// recorded: the raster becomes upright for inference while assembly
177    /// still maps the finished geometry back into display space. Handles both
178    /// `/Rotate` normalization (extraction) and content-detected orientation
179    /// (#225) — the two compose additively (axis-aligned 90° rotations
180    /// commute through the dimension swaps). Link rectangles follow the
181    /// raster; `width`/`height` swap on odd quarter-turns.
182    #[cfg(feature = "ocr-prep")]
183    pub(crate) fn unrotate(&mut self, deg: u16) {
184        if deg == 0 {
185            return;
186        }
187        use image::imageops::{rotate180, rotate270, rotate90};
188        // Display = upright rotated `deg`° clockwise, so upright = display
189        // rotated the complementary amount clockwise.
190        let un = |img: &RgbImage| match deg {
191            90 => rotate270(img),
192            180 => rotate180(img),
193            _ => rotate90(img),
194        };
195        if self.image.width() > 1 {
196            self.image = un(&self.image);
197        }
198        self.image_layout = self.image_layout.as_ref().map(&un);
199        let (width, height) = (self.width, self.height);
200        // Link rects follow the raster from display into upright space (the
201        // inverse of the geometry rotation assembly applies at the end).
202        for l in &mut self.links {
203            let (nl, nt, nr, nb) = match deg {
204                90 => (l.t, width - l.r, l.b, width - l.l),
205                180 => (width - l.r, height - l.b, width - l.l, height - l.t),
206                _ => (height - l.b, l.l, height - l.t, l.r),
207            };
208            (l.l, l.t, l.r, l.b) = (nl, nt, nr, nb);
209        }
210        // The text layer of a page with only a sparse one (a page number
211        // beside outlined text, #936) follows the raster the same way; a
212        // scan has none.
213        for c in self
214            .cells
215            .iter_mut()
216            .chain(&mut self.word_cells)
217            .chain(&mut self.code_cells)
218        {
219            let (nl, nt, nr, nb) = match deg {
220                90 => (c.t, width - c.r, c.b, width - c.l),
221                180 => (width - c.r, height - c.b, width - c.l, height - c.t),
222                _ => (height - c.b, c.l, height - c.t, c.r),
223            };
224            (c.l, c.t, c.r, c.b) = (nl, nt, nr, nb);
225        }
226        // Checkbox squares likewise (a scan has none; kept consistent).
227        for c in &mut self.checkboxes {
228            let (nl, nt, nr, nb) = match deg {
229                90 => (c.t, width - c.r, c.b, width - c.l),
230                180 => (width - c.r, height - c.b, width - c.l, height - c.t),
231                _ => (height - c.b, c.l, height - c.t, c.r),
232            };
233            (c.l, c.t, c.r, c.b) = (nl, nt, nr, nb);
234        }
235        if deg != 180 {
236            (self.width, self.height) = (height, width);
237        }
238        self.rotation = (self.rotation + deg) % 360;
239    }
240}
241
242/// A PDF link annotation: its rectangle (top-left page coordinates, matching
243/// [`TextCell`]) and target URI.
244#[derive(Debug, Clone)]
245pub struct LinkAnnot {
246    pub l: f32,
247    pub t: f32,
248    pub r: f32,
249    pub b: f32,
250    pub uri: String,
251}
252
253#[cfg(feature = "render")]
254/// A parsed PDF: per-page text cells and page images.
255pub struct PdfDocument {
256    pub pages: Vec<PdfPage>,
257}
258
259#[cfg(feature = "render")]
260impl PdfDocument {
261    /// Parse a PDF from bytes, optionally decrypting with `password`.
262    ///
263    /// Note: this materialises **every** page's rendered bitmap in memory at
264    /// once. For large documents prefer [`for_each_page`], which streams.
265    pub fn open(bytes: &[u8], password: Option<&str>) -> Result<Self, PdfError> {
266        let mut pages = Vec::new();
267        for_each_page::<PdfError, _>(bytes, password, true, true, None, |_, _, mut page| {
268            // Every page's bitmap, as documented — not the placeholder of a
269            // render still on the helper thread (#682).
270            page.resolve_image()?;
271            pages.push(page);
272            Ok(())
273        })?;
274        Ok(PdfDocument { pages })
275    }
276}
277
278#[cfg(feature = "render")]
279/// The document's text layer: the pure-Rust text parser (docling-parse's
280/// char geometry; the only text source since phase 4 of "Retiring pdfium" —
281/// on the whole corpus every page it reads no text from is one pdfium read
282/// no text from either, i.e. a scan for the OCR path). `None` for a file
283/// lopdf cannot open at all.
284fn rust_parser_cells(
285    bytes: &[u8],
286    password: Option<&str>,
287    word_gap: Option<crate::dp_lines::WordGap>,
288) -> Option<crate::textparse::PageTextParser> {
289    // Only the document load happens here; pages are parsed as the walk
290    // reaches them (`cells_timed`), so nothing is decoded for pages outside
291    // a `--pages` window and the parse overlaps the workers' inference.
292    crate::timing::timed("textparse.open", || {
293        let mut parser = crate::textparse::PageTextParser::open_with_password(bytes, password)?;
294        parser.set_word_gap(word_gap);
295        Some(parser)
296    })
297}
298
299impl crate::textparse::PageTextParser {
300    /// [`cells`](Self::cells) under the `textparse` timing stage (per page).
301    fn cells_timed(&mut self, index: usize) -> crate::textparse::PageParserCells {
302        crate::timing::timed("textparse", || self.cells(index))
303    }
304}
305
306#[cfg(feature = "render")]
307/// Number of pages in a PDF, without rendering any of them — used to decide
308/// whether a document is worth spinning up the parallel worker pool.
309pub fn page_count(bytes: &[u8], password: Option<&str>) -> Result<usize, PdfError> {
310    // The pure-Rust object model first, then the docling-parse plugin's
311    // count, then pdfium (the `pdfium` feature) — the order every entry point
312    // here follows.
313    if let Some(meta) = crate::timing::timed("meta.open", || {
314        crate::pdf_meta::PdfMeta::open_with_password(bytes, password)
315    })? {
316        return Ok(meta.page_count());
317    }
318    if let Some(dp) = crate::dparse_render::Doc::open_if_enabled(bytes, password) {
319        return Ok(dp.page_count());
320    }
321    crate::timing::timed("pdfium.page_count", || {
322        let lib = native::bind()?;
323        let n = lib.open(bytes, password)?.page_count();
324        Ok(n)
325    })
326}
327
328#[cfg(feature = "render")]
329/// Render + extract pages one at a time, handing each (owned) [`PdfPage`] to `f`.
330/// Only one page bitmap is resident at a time — a rendered page is ~5 MB, so a
331/// large PDF would otherwise hold gigabytes of bitmaps at once. `f` receives the
332/// zero-based page index and the total page count.
333///
334/// `render_image` controls whether the page bitmap is rasterized at all: layout,
335/// OCR, TableFormer, and picture cropping all need it, but a caller that skips
336/// every one of those (the `no_ocr` fast path) doesn't, and rasterizing +
337/// downsampling a page is by far the most expensive step per page — skipping it
338/// is most of `no_ocr`'s speedup. `PdfPage::image` is a 1×1 placeholder when
339/// `false`; do not read it.
340///
341/// `extract_text` decodes the page's text layer (parser or pdfium cells); pass
342/// `false` when full-page OCR is forced and the cells would be discarded
343/// unread (docling#4061).
344///
345/// `range` restricts the walk to a **0-based inclusive** page window (issue
346/// #80's `--pages`); out-of-window pages are skipped *before* text extraction
347/// and rasterization, so a 3-page window over a 500-page PDF costs three
348/// pages, not five hundred. `f` still receives the absolute page index, so
349/// downstream page numbering refers to the source document.
350///
351/// `E` is the caller's error type; [`PdfError`]s convert into it via `From`.
352///
353/// A page with a text layer may arrive with its 2x bitmap still rendering
354/// (#682): call [`PdfPage::resolve_image`] before reading [`PdfPage::image`].
355/// The render starts as the page leaves the walk; [`walk_pages`] with
356/// [`BitmapRender::OnDemand`] starts it only when resolved (#897).
357pub fn for_each_page<E, F>(
358    bytes: &[u8],
359    password: Option<&str>,
360    render_image: bool,
361    extract_text: bool,
362    range: Option<(usize, usize)>,
363    f: F,
364) -> Result<(), E>
365where
366    E: From<PdfError>,
367    F: FnMut(usize, usize, PdfPage) -> Result<(), E>,
368{
369    walk_pages(
370        bytes,
371        password,
372        render_image,
373        extract_text,
374        range,
375        BitmapRender::Eager,
376        TextOptions::from_env(),
377        f,
378    )
379}
380
381#[cfg(feature = "render")]
382/// When the 2x bitmap of a page with a text layer is rendered.
383#[derive(Clone, Copy, Debug, PartialEq, Eq)]
384pub enum BitmapRender {
385    /// As soon as the page leaves the walk, on the helper thread while
386    /// layout runs (#682) — for a caller that reads every page's bitmap.
387    Eager,
388    /// Started like [`Self::Eager`] while the document's recent pages mostly
389    /// read their bitmap, left [`Self::OnDemand`] while they mostly do not
390    /// (#897). Layout reads the separate 1x render, and a page whose
391    /// detections hold no table, picture or other bitmap consumer never
392    /// needs the 2x one: on a paper with a figure or table on most pages
393    /// the render overlaps layout as before; on prose the wasted renders go.
394    /// A started render the page then declines ([`PdfPage::decline_image`])
395    /// is still skipped if the helper has not begun it.
396    Adaptive,
397    /// Only once [`PdfPage::resolve_image`] asks for it (#897): no render is
398    /// ever wasted, but a page that needs one waits for it after layout
399    /// instead of having it drawn meanwhile.
400    OnDemand,
401}
402
403/// The text layer's settings a page walk applies (#921): the word-gap rule
404/// of the line and word cells, and whether assembly keeps typographic
405/// punctuation as drawn ([`PdfPage::keep_typography`]).
406#[derive(Clone, Copy, Debug, Default, PartialEq)]
407pub struct TextOptions {
408    /// `None` = the process default (`DOCLING_RS_PDF_WORD_GAP`).
409    pub word_gap: Option<crate::dp_lines::WordGap>,
410    pub keep_typography: bool,
411}
412
413impl TextOptions {
414    /// The process defaults: `DOCLING_RS_PDF_WORD_GAP` and
415    /// `DOCLING_RS_PDF_KEEP_TYPOGRAPHY`.
416    pub fn from_env() -> Self {
417        Self {
418            word_gap: None,
419            keep_typography: crate::assemble::keep_typography_from_env(),
420        }
421    }
422}
423
424#[cfg(feature = "render")]
425/// [`for_each_page`] with the 2x bitmaps rendered as `bitmap` says, and the
426/// text layer's words split by `word_gap` (#921; `None` = the process
427/// default).
428#[allow(clippy::too_many_arguments)]
429pub fn walk_pages<E, F>(
430    bytes: &[u8],
431    password: Option<&str>,
432    render_image: bool,
433    extract_text: bool,
434    range: Option<(usize, usize)>,
435    bitmap: BitmapRender,
436    text: TextOptions,
437    mut f: F,
438) -> Result<(), E>
439where
440    E: From<PdfError>,
441    F: FnMut(usize, usize, PdfPage) -> Result<(), E>,
442{
443    // The pure-Rust object model: page count, geometry, `/Rotate`, links.
444    // `None` only for a file lopdf cannot read even after the parser's
445    // repairs; pdfium (the `pdfium` feature) then answers for it.
446    let meta = crate::timing::timed("meta.open", || {
447        crate::pdf_meta::PdfMeta::open_with_password(bytes, password)
448    })?;
449    // The docling-parse renderer (#478, `DOCLING_RS_RENDERER=docling-parse`):
450    // the page images the models see come from it when it is asked for.
451    let dparse = if render_image {
452        crate::dparse_render::Doc::open_if_enabled(bytes, password)
453    } else {
454        None
455    };
456    // pdfium, when it has a job (`bind_or_skip`).
457    let pdfium = bind_or_skip(meta.is_some())?;
458    let session = match &pdfium {
459        Some(p) => Some(p.open(bytes, password)?),
460        None => None,
461    };
462    // `extract_text = false` (full-page OCR forced, docling#4061 / 2.122):
463    // the text layer would be cleared unread, so neither the pure-Rust parser
464    // nor pdfium's text page is decoded at all — on vector-dense pages (CAD
465    // drawings as 100k+ path segments) that decode is most of the page cost.
466    let mut rust = if extract_text {
467        rust_parser_cells(bytes, password, text.word_gap)
468    } else {
469        None
470    };
471    // pdfium's count when it is loaded (a damaged file can make the two
472    // object models disagree, and pdfium's pages are the ones rendered), the
473    // object model's otherwise.
474    let total = match (&session, &meta) {
475        (Some(s), _) => s.page_count(),
476        (None, Some(m)) => m.page_count(),
477        (None, None) => 0,
478    };
479    // The object model's geometry and links are used whenever it read the same
480    // number of pages pdfium did (or pdfium is absent); a disagreeing file keeps
481    // pdfium's answers throughout.
482    //
483    // Shared, because the helper thread that renders the deferred 2x bitmaps
484    // (#682) outlives the walk: a page resolved on demand (#897) asks for its
485    // render after the walk has handed the last page over.
486    let meta = meta
487        .filter(|m| {
488            session
489                .as_ref()
490                .is_none_or(|s| s.page_count() == m.page_count())
491        })
492        .map(std::sync::Arc::new);
493    // The pure-Rust renderer (phase 3 of retiring pdfium): the model inputs
494    // of every page the plugin does not render and the Rust raster declines
495    // — the default renderer.
496    let renderer = match (&meta, render_image) {
497        (Some(m), true) => Some(crate::render::Renderer::new(m)),
498        _ => None,
499    };
500    let (first, last) = range.unwrap_or((0, total.saturating_sub(1)));
501    // The 2x bitmap of a page with a text layer renders on a helper thread
502    // (#682, `DeferredRender`) when the pure-Rust renderer is the only one
503    // drawing: the plugin and pdfium hold per-document handles the walk
504    // thread owns, so their pages render in place as before.
505    let defer = match (&meta, &renderer, &dparse, &session) {
506        (Some(m), Some(_), None, None) => DeferredRender::spawn(m.clone(), bitmap),
507        _ => None,
508    };
509    {
510        // Index the window directly: iterating pdfium's pages from page 0 and
511        // skipping to `first` would load (and close) every page before the
512        // window — ~0.7 ms each, 1.3 s of pure overhead for a one-page window
513        // over the 1913-page .NET reference.
514        for i in first..=last {
515            if i >= total {
516                break;
517            }
518            let page = match &session {
519                Some(s) => Some(s.page(i)?),
520                None => None,
521            };
522            let geom = match (&meta, &page) {
523                (Some(m), _) => m.geometry(i).ok_or_else(|| no_raster(i as i32))?,
524                (None, Some(p)) => p.geom(),
525                (None, None) => return Err(no_raster(i as i32).into()),
526            };
527            let links = match (&meta, &page) {
528                (Some(m), _) => m.links(i),
529                (None, Some(p)) => p.links(geom.unrotated().1),
530                (None, None) => Vec::new(),
531            };
532            let rc = rust.as_mut().map(|p| p.cells_timed(i));
533            let mut extracted = extract_page(
534                PageSources {
535                    page: page.as_ref(),
536                    dparse: dparse.as_ref(),
537                    meta: meta.as_deref(),
538                    renderer: renderer.as_ref(),
539                    defer: defer.as_ref(),
540                },
541                geom,
542                links,
543                i as i32,
544                rc,
545                render_image,
546            )?;
547            extracted.keep_typography = text.keep_typography;
548            f(i, total, extracted)?;
549        }
550        // The helper ends once this sender and every page's handle are gone.
551        drop(defer);
552    }
553    // Tearing down the parsed document (hundreds of thousands of lopdf
554    // objects on a long PDF — 250 ms for the 1913-page .NET reference) is
555    // nobody's business but the allocator's: hand it to a detached thread so
556    // the last page's output isn't held up by it. `Arc`, not `Rc`, in the
557    // caches is what makes the parser `Send`.
558    if let Some(parser) = rust {
559        std::thread::spawn(move || crate::timing::timed("textparse.close", || drop(parser)));
560    }
561    Ok(())
562}
563
564/// One rasterized page from [`render_pages`] (#243): the absolute 1-based page
565/// number in the source document, the pixel dimensions, and the PNG bytes.
566#[cfg(feature = "render")]
567#[derive(Debug, Clone)]
568pub struct RenderedPage {
569    pub page_no: usize,
570    pub width: u32,
571    pub height: u32,
572    pub png: Vec<u8>,
573    /// The images the page's render drew as a placeholder block or left out,
574    /// each with the reason (#916) — empty when everything decoded. Only the
575    /// pure-Rust renderer reports; the docling-parse plugin and pdfium
576    /// renders leave it empty.
577    pub omissions: Vec<crate::render::Omission>,
578}
579
580/// Upper bound, in pixels, on a rendered page bitmap's side. A crafted PDF can
581/// declare an enormous `MediaBox` in a few hundred bytes; the page render then
582/// asks pdfium — and `into_rgb8` — to allocate `w * h * 4` bytes. At the
583/// pipeline's 3x supersample a 12000 pt box is 36000x36000 ~ 5 GB: pdfium
584/// returns an opaque internal error at the extreme, and just below it the
585/// `image` crate *panics* (a `TryReserveError`, not a recoverable error) when
586/// the allocation fails. Real pages, even large-format (A0 at 3x ~ 10110 px),
587/// stay well under this cap; it only rejects the implausible, turning an abort
588/// into a clean error. Mirrors `decode_image_limited`'s guard on the
589/// standalone-image path. `DOCLING_RS_MAX_RENDER_PIXELS` overrides it.
590#[cfg(feature = "render")]
591fn max_render_side() -> u32 {
592    static M: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
593    *M.get_or_init(|| docling_core::env::parse("DOCLING_RS_MAX_RENDER_PIXELS").unwrap_or(15_000))
594}
595
596/// Round float pixel dimensions to the `i32` pdfium wants, rejecting a page
597/// whose bitmap would exceed [`max_render_side`] on either side before either
598/// pdfium or `image` tries to allocate it.
599#[cfg(feature = "render")]
600fn checked_render_dims(
601    w_px: f64,
602    h_px: f64,
603    page_no: usize,
604) -> Result<(i32, i32), crate::PdfError> {
605    let cap = max_render_side();
606    let w = w_px.round().max(1.0);
607    let h = h_px.round().max(1.0);
608    if w > f64::from(cap) || h > f64::from(cap) {
609        return Err(crate::PdfError::Pdfium(format!(
610            "page {page_no}: render size {w:.0}x{h:.0} px exceeds the {cap}px per-side cap \
611             (raise DOCLING_RS_MAX_RENDER_PIXELS); the page's declared size is implausibly large"
612        )));
613    }
614    Ok((w as i32, h as i32))
615}
616
617#[cfg(feature = "render")]
618/// Rasterize a PDF's pages to PNG (#243) — the lean path behind serve's
619/// `to=images`: pdfium render only, no text extraction, no models, and only
620/// one page bitmap resident at a time (each is PNG-encoded and dropped before
621/// the next renders). `scale` is pixels per PDF point — 2.0 matches the
622/// pipeline's [`RENDER_SCALE`] (144 dpi). Unlike the pipeline's render there
623/// is no 1.5× supersample + downsample pass: that dance exists only because
624/// TableFormer is pixel-pinned to docling's bitmaps, and nothing downstream
625/// of this output is — a single render is nearly twice as fast.
626///
627/// `range` is a **1-based** inclusive page window (issue #80's `pages`
628/// semantics: the end clamps to the document, a start past the end errors).
629///
630/// pdfium is not thread-safe — callers must serialize this against any other
631/// pdfium use (docling-serve holds its pipeline mutex around this call for
632/// exactly that reason).
633pub fn render_pages(
634    bytes: &[u8],
635    password: Option<&str>,
636    range: Option<(usize, usize)>,
637    scale: f32,
638) -> Result<Vec<RenderedPage>, crate::PdfError> {
639    // The docling-parse renderer plugin renders the display bitmap when it is
640    // asked for (full-resolution bitmap decode: this is a viewer's render,
641    // not a model input); the Rust raster / renderer otherwise, pdfium under
642    // `DOCLING_RS_RENDERER=pdfium` or for a file lopdf cannot read.
643    let dparse = crate::dparse_render::Doc::open_if_enabled(bytes, password);
644    // The object model: the page count and the Rust raster / renderer.
645    let meta = crate::pdf_meta::PdfMeta::open_with_password(bytes, password)?;
646    let pdfium = match &dparse {
647        Some(_) => None,
648        None => bind_or_skip(meta.is_some())?,
649    };
650    let session = match &pdfium {
651        Some(p) => Some(p.open(bytes, password)?),
652        None => None,
653    };
654    let total = match (&session, &dparse, &meta) {
655        (Some(s), _, _) => s.page_count(),
656        (None, Some(dp), _) => dp.page_count(),
657        (None, None, Some(m)) => m.page_count(),
658        (None, None, None) => 0,
659    };
660    let (first, last) = match range {
661        None => (0, total.saturating_sub(1)),
662        Some((first, last)) => {
663            if first == 0 || last < first {
664                return Err(PdfError::Document(format!(
665                    "invalid page range {first}-{last} (pages are 1-based, first <= last)"
666                )));
667            }
668            if first > total {
669                return Err(PdfError::Document(format!(
670                    "page range {first}-{last} is outside the document ({total} page(s))"
671                )));
672            }
673            (first - 1, last.min(total) - 1)
674        }
675    };
676    let renderer = match (&dparse, &meta) {
677        // Page rasters a caller keeps decode every image at full size (the
678        // shim is asked with bitmap hint 0.0 below for the same reason).
679        (None, Some(m)) => Some(crate::render::Renderer::with_bitmap_hint(m, 0.0)),
680        _ => None,
681    };
682    let mut out = Vec::with_capacity(last.saturating_sub(first) + 1);
683    for i in first..=last {
684        if i >= total {
685            break;
686        }
687        // Both renderers apply /Rotate themselves, so the bitmap is the page as
688        // a viewer shows it — no orientation handling needed (the pipeline's
689        // scanned-page un-rotation is an OCR-conformance concern, not a display
690        // one).
691        // The plugin's canvas first (the renderer whenever it resolves), then
692        // the Rust raster of an image-only page (pdfium's bitmap byte for
693        // byte, no library needed) or the Rust page renderer, then pdfium
694        // (`DOCLING_RS_RENDERER=pdfium`, or a file lopdf cannot read).
695        // A page the per-side cap refuses is an error naming the cap (#916),
696        // not a missing renderer.
697        let rust = || -> Result<Option<RgbImage>, PdfError> {
698            let Some(g) = meta.as_ref().and_then(|m| m.geometry(i)) else {
699                return Ok(None);
700            };
701            let (tw, th) = checked_render_dims(
702                f64::from(g.width * scale),
703                f64::from(g.height * scale),
704                i + 1,
705            )?;
706            Ok(rust_bitmap(
707                meta.as_ref(),
708                renderer.as_ref(),
709                session.is_some(),
710                i as i32,
711                tw as u32,
712                th as u32,
713                0.0,
714            ))
715        };
716        let bitmap = match (&dparse, &session) {
717            (Some(dp), _) => {
718                crate::timing::timed("dparse.rasterize", || dp.render(i, f64::from(scale), 0.0))
719                    .map_err(PdfError::Document)?
720            }
721            (None, session) => match rust()? {
722                Some(img) => img,
723                None => {
724                    let Some(s) = session else {
725                        return Err(no_raster(i as i32));
726                    };
727                    let page = s.page(i)?;
728                    let (pw, ph) = page.size();
729                    let (tw, th) =
730                        checked_render_dims(f64::from(pw * scale), f64::from(ph * scale), i + 1)?;
731                    page.render(tw, th, "pdfium.rasterize")?
732                }
733            },
734        };
735        let mut png = Vec::new();
736        bitmap
737            .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
738            .map_err(|e| PdfError::Document(format!("PNG-encoding page {}: {e}", i + 1)))?;
739        out.push(RenderedPage {
740            page_no: i + 1,
741            width: bitmap.width(),
742            height: bitmap.height(),
743            png,
744            omissions: renderer
745                .as_ref()
746                .map(crate::render::Renderer::take_omissions)
747                .unwrap_or_default(),
748        });
749    }
750    Ok(out)
751}
752
753#[cfg(feature = "render")]
754/// The error for a page that needs a raster when the object model could not
755/// be read and neither the docling-parse renderer plugin nor pdfium is there.
756fn no_raster(index: i32) -> PdfError {
757    PdfError::Document(format!(
758        "page {}: no page renderer — the file's object model could not be read (lopdf), \
759         the docling-parse renderer plugin is not installed (.docling-parse/lib) and \
760         pdfium is not available (the `pdfium` feature + PDFIUM_DYNAMIC_LIB_PATH / \
761         .pdfium/lib)",
762        index + 1
763    ))
764}
765
766/// The pure-Rust bitmap of a page at `width` × `height`: the raster of an
767/// image-only page (`raster::render`, pdfium's bytes) when the page
768/// qualifies, the page renderer (`render`) otherwise — `None` only when the
769/// object model is not loaded, or when `DOCLING_RS_RENDERER=pdfium` asks for
770/// pdfium's render of a page the raster declines *and* pdfium's page is open
771/// (`pdfium_page`; a build or machine without the library degrades to the
772/// Rust renderer, as [`bind_or_skip`] warned).
773#[cfg(feature = "render")]
774fn rust_bitmap(
775    meta: Option<&crate::pdf_meta::PdfMeta>,
776    renderer: Option<&crate::render::Renderer<'_>>,
777    pdfium_page: bool,
778    index: i32,
779    width: u32,
780    height: u32,
781    bitmap_hint: f64,
782) -> Option<RgbImage> {
783    let meta = meta?;
784    if let Some(img) = crate::timing::timed("raster.render", || {
785        crate::raster::render(meta, index as usize, width, height)
786    }) {
787        return Some(img);
788    }
789    if pdfium_page && crate::dparse_render::choice() == crate::dparse_render::Choice::Pdfium {
790        return None;
791    }
792    let renderer = renderer?;
793    crate::timing::timed("render.page", || {
794        renderer.render_with_hint(index as usize, width, height, bitmap_hint)
795    })
796}
797
798#[cfg(feature = "render")]
799/// Bind pdfium for a conversion, or decide it can run without it. pdfium has
800/// a job in two cases only: its own render was asked for
801/// (`DOCLING_RS_RENDERER=pdfium`, which only the `pdfium` feature offers), or
802/// the pure-Rust object model could not read the file (`meta_ok` false) — then
803/// pdfium's page tree, geometry and render stand in, and a build without the
804/// feature (or without the library) fails the conversion with the hint.
805/// Otherwise the library is never loaded.
806fn bind_or_skip(meta_ok: bool) -> Result<Option<native::Lib>, PdfError> {
807    if meta_ok && crate::dparse_render::choice() != crate::dparse_render::Choice::Pdfium {
808        return Ok(None);
809    }
810    match native::bind() {
811        Ok(p) => Ok(Some(p)),
812        Err(e) if meta_ok => {
813            // The library was asked for by name and is not there: say so
814            // once, then degrade — the Rust renderer draws every page.
815            static WARNED: std::sync::Once = std::sync::Once::new();
816            WARNED.call_once(|| {
817                eprintln!(
818                    "docling-pdf: DOCLING_RS_RENDERER=pdfium but the pdfium library could not be \
819                     loaded ({e}); rendering with the Rust renderer"
820                );
821            });
822            Ok(None)
823        }
824        Err(e) => Err(e),
825    }
826}
827
828/// The native sources a page may draw on, each optional: pdfium's page handle
829/// (present only when [`bind_or_skip`] opened the library) and the
830/// docling-parse renderer (absent when the plugin is not asked for or no
831/// raster is wanted).
832#[cfg(feature = "render")]
833#[derive(Clone, Copy)]
834struct PageSources<'a> {
835    page: Option<&'a native::Page<'a>>,
836    dparse: Option<&'a crate::dparse_render::Doc>,
837    /// The object model, for the Rust raster of an image-only page.
838    meta: Option<&'a crate::pdf_meta::PdfMeta>,
839    /// The pure-Rust page renderer over the same object model (its
840    /// per-document caches live for the whole conversion).
841    renderer: Option<&'a crate::render::Renderer<'a>>,
842    /// The helper thread that renders the 2x bitmap of pages with a text
843    /// layer off the walk (#682); `None` when another renderer draws.
844    defer: Option<&'a DeferredRender>,
845}
846
847/// A page's 2x bitmap, rendered on the walk's helper thread (#682): queued
848/// until something asks for it ([`BitmapRender::OnDemand`]) or sent at once
849/// ([`BitmapRender::Eager`], [`BitmapRender::Adaptive`]), the result
850/// arriving through a one-shot channel. A sent job can be declined: the
851/// helper then skips it if it has not started it, and a later resolve sends
852/// it again (#897). Cloning a page clones the handle; whichever copy
853/// resolves first gets the bitmap. A handle dropped while still queued, or
854/// declined in time, costs nothing — the render never happens.
855#[cfg(feature = "render")]
856#[derive(Clone)]
857pub struct PendingImage(std::sync::Arc<std::sync::Mutex<Pending>>);
858
859/// The channel a sent job's bitmap comes back through.
860#[cfg(feature = "render")]
861type Reply = std::sync::mpsc::Receiver<Result<RgbImage, PdfError>>;
862
863/// Where a [`PendingImage`] stands: the job and the helper to send it to,
864/// plus — once sent — the reply channel and the flag that lets the helper
865/// skip it.
866#[cfg(feature = "render")]
867struct Pending {
868    spec: RenderSpec,
869    tx: std::sync::mpsc::Sender<RenderJob>,
870    sent: Option<(Reply, std::sync::Arc<std::sync::atomic::AtomicBool>)>,
871    taken: bool,
872    /// The document's recent verdicts, which [`BitmapRender::Adaptive`]
873    /// schedules by; this page's goes in once.
874    stats: std::sync::Arc<Verdicts>,
875    /// This page's verdict so far (`Some(true)` = read).
876    verdict: Option<bool>,
877}
878
879/// Whether the last [`Verdicts::WINDOW`] pages that reached a verdict read
880/// their 2x bitmap — what [`BitmapRender::Adaptive`] decides a new page's
881/// render by (#897).
882#[cfg(feature = "render")]
883#[derive(Default)]
884struct Verdicts(std::sync::Mutex<std::collections::VecDeque<bool>>);
885
886#[cfg(feature = "render")]
887impl Verdicts {
888    const WINDOW: usize = 8;
889
890    /// Record a page's verdict, or turn a declined page's into a read one.
891    fn record(&self, read: bool, replaces_decline: bool) {
892        let mut w = self.0.lock().unwrap_or_else(|p| p.into_inner());
893        if replaces_decline {
894            if let Some(v) = w.iter_mut().rev().find(|v| !**v) {
895                *v = true;
896            }
897            return;
898        }
899        if w.len() == Self::WINDOW {
900            w.pop_front();
901        }
902        w.push_back(read);
903    }
904
905    /// Start the next render now? Yes until a few verdicts are in (most
906    /// documents' first pages are not representative either way, and a
907    /// wrong "yes" costs one render, a wrong "no" one page's latency), then
908    /// while at least half of the window read theirs.
909    fn start_eagerly(&self) -> bool {
910        let w = self.0.lock().unwrap_or_else(|p| p.into_inner());
911        w.len() < 3 || 2 * w.iter().filter(|v| **v).count() >= w.len()
912    }
913}
914
915#[cfg(feature = "render")]
916impl Pending {
917    /// Send the job (again, after a skipped one) and keep its reply channel.
918    /// The helper runs while any job sender lives — this one included — so a
919    /// failed send means it died (a render panicked).
920    fn send(&mut self) -> Result<(), PdfError> {
921        let (reply, rx) = std::sync::mpsc::sync_channel(1);
922        let declined = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
923        self.tx
924            .send(RenderJob {
925                spec: self.spec,
926                declined: declined.clone(),
927                reply,
928            })
929            .map_err(|_| PdfError::Pdfium("page render thread ended early".into()))?;
930        self.sent = Some((rx, declined));
931        Ok(())
932    }
933}
934
935#[cfg(feature = "render")]
936impl PendingImage {
937    fn lock(&self) -> std::sync::MutexGuard<'_, Pending> {
938        self.0.lock().unwrap_or_else(|p| p.into_inner())
939    }
940
941    /// Hand the job to the helper, unless that happened already.
942    fn start(&self) {
943        let mut p = self.lock();
944        if p.sent.is_none() && !p.taken {
945            // A dead helper surfaces as the page's resolve error.
946            let _ = p.send();
947        }
948    }
949
950    /// Nothing will read this bitmap: let the helper skip the job if it has
951    /// not begun it (a job never sent stays unsent).
952    fn decline(&self) {
953        let mut p = self.lock();
954        if p.verdict.is_none() {
955            p.verdict = Some(false);
956            p.stats.record(false, false);
957        }
958        if let Some((_, declined)) = &p.sent {
959            declined.store(true, std::sync::atomic::Ordering::Relaxed);
960        }
961    }
962
963    fn wait(self) -> Result<RgbImage, PdfError> {
964        let mut p = self.lock();
965        if p.taken {
966            return Err(PdfError::Pdfium("page bitmap resolved twice".into()));
967        }
968        if p.verdict != Some(true) {
969            p.stats.record(true, p.verdict == Some(false));
970            p.verdict = Some(true);
971        }
972        loop {
973            match &p.sent {
974                None => p.send()?,
975                Some((rx, declined)) => {
976                    // Asked for after all: a job not yet begun renders.
977                    declined.store(false, std::sync::atomic::Ordering::Relaxed);
978                    match rx.recv() {
979                        Ok(out) => {
980                            p.taken = true;
981                            p.sent = None;
982                            return out;
983                        }
984                        // Skipped while declined (or the helper died, which
985                        // the next send reports): send it again.
986                        Err(_) => p.sent = None,
987                    }
988                }
989            }
990        }
991    }
992}
993
994#[cfg(feature = "render")]
995impl std::fmt::Debug for PendingImage {
996    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
997        f.write_str("PendingImage")
998    }
999}
1000
1001/// One deferred render: the 3x supersample of page `index` at `w` × `h`
1002/// with the decode `hint`, box-downscaled to `dw` × `dh` — exactly the
1003/// synchronous path's steps, on another thread.
1004#[cfg(feature = "render")]
1005#[derive(Clone, Copy)]
1006struct RenderSpec {
1007    index: i32,
1008    w: u32,
1009    h: u32,
1010    hint: f64,
1011    dw: u32,
1012    dh: u32,
1013}
1014
1015#[cfg(feature = "render")]
1016struct RenderJob {
1017    spec: RenderSpec,
1018    /// Set when the page turned out not to read the bitmap (#897): the
1019    /// helper skips the job if it gets to it after that — dropping `reply`,
1020    /// which tells a later resolve to send it again.
1021    declined: std::sync::Arc<std::sync::atomic::AtomicBool>,
1022    reply: std::sync::mpsc::SyncSender<Result<RgbImage, PdfError>>,
1023}
1024
1025/// The walk's render helper (#682): a second pure-Rust renderer, with its
1026/// own per-document caches, on its own thread, fed one [`RenderJob`] per
1027/// 2x bitmap asked for. Its bitmaps are the ones the walk thread would have
1028/// drawn — the same renderer code over the same object model — so the
1029/// output is byte-identical; what changes is that the page leaves the walk
1030/// as soon as its 1x layout image is drawn, and the 2x bitmap lands while
1031/// layout runs ([`BitmapRender::Eager`]) or when the page turns out to need
1032/// it ([`BitmapRender::OnDemand`], #897). Not scoped to the walk: a page
1033/// resolved on demand asks after the walk is over, so the thread holds the
1034/// object model and runs until the walk and every page's handle have let go
1035/// of the job sender.
1036#[cfg(feature = "render")]
1037struct DeferredRender {
1038    tx: std::sync::mpsc::Sender<RenderJob>,
1039    mode: BitmapRender,
1040    stats: std::sync::Arc<Verdicts>,
1041}
1042
1043#[cfg(feature = "render")]
1044impl DeferredRender {
1045    /// The helper for `meta`; `None` (render in place, as without one) when
1046    /// the thread cannot be spawned.
1047    fn spawn(meta: std::sync::Arc<crate::pdf_meta::PdfMeta>, mode: BitmapRender) -> Option<Self> {
1048        let (tx, rx) = std::sync::mpsc::channel();
1049        std::thread::Builder::new()
1050            .name("docling-pdf-render".into())
1051            .spawn(move || Self::serve(&meta, rx))
1052            .ok()?;
1053        Some(Self {
1054            tx,
1055            mode,
1056            stats: Default::default(),
1057        })
1058    }
1059
1060    fn submit(&self, index: i32, w: u32, h: u32, hint: f64, dw: u32, dh: u32) -> PendingImage {
1061        let spec = RenderSpec {
1062            index,
1063            w,
1064            h,
1065            hint,
1066            dw,
1067            dh,
1068        };
1069        let pending = PendingImage(std::sync::Arc::new(std::sync::Mutex::new(Pending {
1070            spec,
1071            tx: self.tx.clone(),
1072            sent: None,
1073            taken: false,
1074            stats: self.stats.clone(),
1075            verdict: None,
1076        })));
1077        let start = match self.mode {
1078            BitmapRender::Eager => true,
1079            BitmapRender::Adaptive => self.stats.start_eagerly(),
1080            BitmapRender::OnDemand => false,
1081        };
1082        if start {
1083            pending.start();
1084        }
1085        pending
1086    }
1087
1088    /// The helper's loop: runs until every job sender is dropped.
1089    fn serve(meta: &crate::pdf_meta::PdfMeta, jobs: std::sync::mpsc::Receiver<RenderJob>) {
1090        let renderer = crate::render::Renderer::new(meta);
1091        for RenderJob {
1092            spec,
1093            declined,
1094            reply,
1095        } in jobs
1096        {
1097            if declined.load(std::sync::atomic::Ordering::Relaxed) {
1098                if crate::timing::enabled() {
1099                    crate::timing::record("render.skipped", 0);
1100                }
1101                continue;
1102            }
1103            let out = rust_bitmap(
1104                Some(meta),
1105                Some(&renderer),
1106                false,
1107                spec.index,
1108                spec.w,
1109                spec.h,
1110                spec.hint,
1111            )
1112            .map(|big| {
1113                crate::timing::timed("image.resize", || fast_downscale(&big, spec.dw, spec.dh))
1114            })
1115            .ok_or_else(|| no_raster(spec.index));
1116            let _ = reply.send(out);
1117        }
1118    }
1119}
1120
1121#[cfg(feature = "render")]
1122fn extract_page(
1123    sources: PageSources<'_>,
1124    geom: crate::pdf_meta::PageGeom,
1125    links: Vec<LinkAnnot>,
1126    index: i32,
1127    rust_cells: Option<crate::textparse::PageParserCells>,
1128    render_image: bool,
1129) -> Result<PdfPage, PdfError> {
1130    let PageSources {
1131        page,
1132        dparse,
1133        meta,
1134        renderer,
1135        defer,
1136    } = sources;
1137    // The page size (and the render) is the *display* frame — `/Rotate`
1138    // applied — while every text coordinate (pdfium's own text page, the
1139    // pure-Rust parser's MediaBox-based glyphs, link annotation rects) lives
1140    // in the unrotated frame (docling#4008, 2.121). Keep the unrotated box
1141    // around for the y-flips and bring every rect into the display frame.
1142    let width = geom.width;
1143    let height = geom.height;
1144    let rotation = geom.rotation;
1145    let (unrot_w, unrot_h) = geom.unrotated();
1146
1147    // The text layer: the pure-Rust parser's prose, word and code cells (its
1148    // word grouping reproduces docling-parse's, which TableFormer matches
1149    // against). A page it reads nothing from is a scanned page for the OCR
1150    // path — pdfium's text page is gone (phase 4 of "Retiring pdfium").
1151    let rc = rust_cells.unwrap_or_default();
1152    let (mut cells, mut code_cells, mut word_cells) = (rc.prose, rc.code, rc.words);
1153    let mut checkboxes = rc.checkboxes;
1154    if rotation != 0 {
1155        for c in cells
1156            .iter_mut()
1157            .chain(word_cells.iter_mut())
1158            .chain(code_cells.iter_mut())
1159        {
1160            let (l, t, r, b) = to_display_frame((c.l, c.t, c.r, c.b), rotation, unrot_w, unrot_h);
1161            (c.l, c.t, c.r, c.b) = (l, t, r, b);
1162        }
1163        for c in &mut checkboxes {
1164            let (l, t, r, b) = to_display_frame((c.l, c.t, c.r, c.b), rotation, unrot_w, unrot_h);
1165            (c.l, c.t, c.r, c.b) = (l, t, r, b);
1166        }
1167    }
1168
1169    // The docling-parse renderer (#478, `dparse_render.rs`): the model inputs
1170    // come from docling-parse's Blend2D canvas, requested in docling's order
1171    // and with its decode hint — the scale-1.0 layout image (docling decodes
1172    // the page once, at its `render_scale` of 1.0), then the scale-2.0 bitmap
1173    // TableFormer crops from (`_render_image_at_scale` on the same decoder,
1174    // hence the same hint). One deliberate exception: a *scanned* page — no
1175    // text layer, the OCR path — keeps pdfium's bitmap. docling's 2.0/3.0
1176    // re-renders draw the raster its decoders reduced to 72 dpi, and Blend2D's
1177    // blit of a scan differs from pdfium's render + downscale in a way the
1178    // `ch` conformance recognizer feels (`scanned/ocr_test.pdf` read `JsON` for
1179    // `JSON` from either docling-parse raster, hint 1.0 or full resolution);
1180    // pdfium's raster is the one the scanned groundtruth was matched with, so
1181    // OCR keeps it (recorded in PDF_CONFORMANCE.md) — as long as pdfium is
1182    // loaded: a checkout with the plugin and no `libpdfium` OCRs the
1183    // docling-parse raster rather than failing the page (degradation over
1184    // failure). The canvases are `ceil`-sized where pdfium's are `round`ed;
1185    // every consumer maps points through `RENDER_SCALE`, not through the
1186    // image size, so the extra row/column is harmless.
1187    let scanned = cells.is_empty() && word_cells.is_empty() && code_cells.is_empty();
1188    let mut pending_image = None;
1189    let (mut dp_image, mut dp_layout) = (None, None);
1190    if let (true, Some(dp)) = (render_image, dparse) {
1191        let layout = crate::timing::timed("dparse.render_layout", || {
1192            dp.render(index as usize, 1.0, 1.0)
1193        })
1194        .map_err(PdfError::Document)?;
1195        if !scanned {
1196            let full = crate::timing::timed("dparse.render", || {
1197                dp.render(index as usize, f64::from(RENDER_SCALE), 1.0)
1198            })
1199            .map_err(PdfError::Document)?;
1200            dp_image = Some(full);
1201        }
1202        dp.release_page(index as usize);
1203        dp_layout = Some(layout);
1204    }
1205    // A scanned page's bitmap, in order: the pure-Rust raster (pdfium's bytes;
1206    // `raster`), pdfium itself, and — with neither — the plugin's scale-2.0
1207    // canvas rather than a failed page.
1208    let scanned_fallback = |page: Option<&native::Page<'_>>| match (page, dparse) {
1209        (None, Some(dp)) if scanned => {
1210            let full = crate::timing::timed("dparse.render", || {
1211                dp.render(index as usize, f64::from(RENDER_SCALE), 1.0)
1212            })
1213            .map_err(PdfError::Document)?;
1214            dp.release_page(index as usize);
1215            Ok(Some(full))
1216        }
1217        _ => Ok::<_, PdfError>(None),
1218    };
1219    let image = if let Some(img) = dp_image.take() {
1220        img
1221    } else if render_image {
1222        // docling's pypdfium2 backend renders at 1.5× the target scale and
1223        // downsamples "to make it sharper" (pypdfium2 → PIL BICUBIC). Replicate
1224        // exactly: the TableFormer model is pixel-sensitive, so the page bitmap
1225        // must match that backend's byte-for-byte (docling 2.123+'s default
1226        // docling-parse backend renders it itself — #478).
1227        // `CatmullRom` is the same a=-0.5 cubic kernel as PIL's BICUBIC.
1228        const SUPERSAMPLE: f32 = 1.5;
1229        // The 3x supersample is the largest bitmap the pipeline renders, so the
1230        // per-side cap is enforced here; the 1.5x layout render below is always
1231        // smaller and needs no separate guard.
1232        let (tw, th) = checked_render_dims(
1233            f64::from(width * RENDER_SCALE * SUPERSAMPLE),
1234            f64::from(height * RENDER_SCALE * SUPERSAMPLE),
1235            (index + 1) as usize,
1236        )?;
1237        // An image-only page (a scan) is rendered by the pure-Rust raster —
1238        // pdfium's bitmap byte for byte (`raster`, its oracle test) — and any
1239        // other page by the pure-Rust renderer (`render`), so the OCR path
1240        // needs no `libpdfium`; pdfium renders only when asked for
1241        // (`DOCLING_RS_RENDERER=pdfium`).
1242        let dw = (width * RENDER_SCALE).round().max(1.0) as u32;
1243        let dh = (height * RENDER_SCALE).round().max(1.0) as u32;
1244        // A page without a text layer takes this bitmap to OCR: decode its
1245        // images at full size (hint 0.0); a digital page's TableFormer input
1246        // follows docling's hint 1.0 like the layout image below.
1247        let hint = if cells.is_empty() { 0.0 } else { 1.0 };
1248        // A page with a text layer needs this bitmap only after layout
1249        // (TableFormer, crops): the helper thread draws it meanwhile (#682).
1250        // A scanned page reads it first (orientation, OCR) and renders here.
1251        if let (Some(defer), false) = (defer, scanned) {
1252            pending_image = Some(defer.submit(index, tw as u32, th as u32, hint, dw, dh));
1253            RgbImage::new(1, 1)
1254        } else {
1255            let big = match rust_bitmap(
1256                meta,
1257                renderer,
1258                page.is_some(),
1259                index,
1260                tw as u32,
1261                th as u32,
1262                hint,
1263            ) {
1264                Some(img) => Some(img),
1265                None if page.is_some() => {
1266                    let page = page.ok_or_else(|| no_raster(index))?;
1267                    Some(page.render(tw, th, "pdfium.render")?)
1268                }
1269                None => None,
1270            };
1271            match (big, scanned_fallback(page)?) {
1272                (Some(big), _) => {
1273                    crate::timing::timed("image.resize", || fast_downscale(&big, dw, dh))
1274                }
1275                (None, Some(canvas)) => canvas,
1276                (None, None) => return Err(no_raster(index)),
1277            }
1278        }
1279    } else {
1280        RgbImage::new(1, 1)
1281    };
1282    // The layout model's input image, built exactly like docling's pypdfium2
1283    // `get_page_image(scale=1.0)`: a pdfium render at 1.5× (pypdfium2 sizes
1284    // with `ceil`), PIL-BICUBIC down to the point-size image (PIL `resize`'s
1285    // default kernel; Python `round` = ties-to-even). Distinct from the 2×
1286    // bitmap above — resampling 1224→640 and 612→640 are different regimes,
1287    // and the heron model's borderline scores follow the pixels. "Exactly" is
1288    // against the pypdfium2 backend: docling 2.123+'s default docling-parse
1289    // backend renders this image with its own renderer (#478, see
1290    // docs/PDF_CONFORMANCE.md).
1291    let image_layout = if let Some(img) = dp_layout.take() {
1292        Some(img)
1293    } else if render_image {
1294        let tw = f64::from(width * 1.5).ceil().max(1.0) as i32;
1295        let th = f64::from(height * 1.5).ceil().max(1.0) as i32;
1296        let big = match rust_bitmap(
1297            meta,
1298            renderer,
1299            page.is_some(),
1300            index,
1301            tw as u32,
1302            th as u32,
1303            1.0,
1304        ) {
1305            Some(img) => img,
1306            None => {
1307                let page = page.ok_or_else(|| no_raster(index))?;
1308                page.render(tw, th, "pdfium.render_layout")?
1309            }
1310        };
1311        let dw = f64::from(width).round_ties_even().max(1.0) as u32;
1312        let dh = f64::from(height).round_ties_even().max(1.0) as u32;
1313        Some(crate::timing::timed("image.resize_layout", || {
1314            crate::resample::pil_resize(&big, dw, dh, crate::resample::PilFilter::Bicubic)
1315        }))
1316    } else {
1317        None
1318    };
1319
1320    let mut links = links;
1321    if rotation != 0 {
1322        for l in &mut links {
1323            let (a, t, r, b) = to_display_frame((l.l, l.t, l.r, l.b), rotation, unrot_w, unrot_h);
1324            (l.l, l.t, l.r, l.b) = (a, t, r, b);
1325        }
1326    }
1327
1328    // `/Rotate` normalization for scanned pages: pdfium renders the page as a
1329    // viewer displays it — `/Rotate` applied — so a rotated scan hands layout
1330    // and OCR a sideways/upside-down raster and the recognition output is
1331    // garbage. A page with a text layer needs none of this (its cells carry
1332    // the geometry; the models never see its pixels decide text), so the
1333    // normalization is gated to pages with no cells at all — exactly the set
1334    // the OCR path fires on. The bitmaps are un-rotated to upright (lossless
1335    // 90° steps), `width`/`height` swap to the upright box, and the display
1336    // rotation is recorded so assembly can rotate the finished geometry back
1337    // into display space (docling reports rotated pages in display coords).
1338    let mut page = PdfPage {
1339        width,
1340        height,
1341        scale: RENDER_SCALE,
1342        image_layout,
1343        pending_image,
1344        cells,
1345        code_cells,
1346        word_cells,
1347        checkboxes,
1348        image,
1349        links,
1350        rotation: 0,
1351        keep_typography: false,
1352    };
1353    if rotation != 0 && scanned && render_image {
1354        page.unrotate(rotation);
1355    }
1356    Ok(page)
1357}
1358
1359#[cfg(feature = "render")]
1360/// The supersample→target downscale via `fast_image_resize` (SIMD convolution;
1361/// the same a=-0.5 Catmull-Rom kernel as `image::imageops::resize(...,
1362/// CatmullRom)` and PIL BICUBIC — see the render comment above). Set
1363/// `DOCLING_RS_SLOW_RESIZE=1` to fall back to the `image`-crate scalar resize
1364/// (byte-parity with the pre-SIMD pipeline, several times slower).
1365fn fast_downscale(big: &RgbImage, dw: u32, dh: u32) -> RgbImage {
1366    use fast_image_resize as fir;
1367    static SLOW: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1368    let slow = *SLOW.get_or_init(|| docling_core::env::flag("DOCLING_RS_SLOW_RESIZE"));
1369    if !slow {
1370        if let Some(out) = (|| {
1371            let src = fir::images::ImageRef::new(
1372                big.width(),
1373                big.height(),
1374                big.as_raw(),
1375                fir::PixelType::U8x3,
1376            )
1377            .ok()?;
1378            let mut dst = fir::images::Image::new(dw, dh, fir::PixelType::U8x3);
1379            fir::Resizer::new()
1380                .resize(
1381                    &src,
1382                    &mut dst,
1383                    &fir::ResizeOptions::new()
1384                        .resize_alg(fir::ResizeAlg::Convolution(fir::FilterType::CatmullRom)),
1385                )
1386                .ok()?;
1387            RgbImage::from_raw(dw, dh, dst.into_vec())
1388        })() {
1389            return out;
1390        }
1391        // Unreachable in practice; fall through to the scalar path on any error.
1392    }
1393    image::imageops::resize(big, dw, dh, image::imageops::FilterType::CatmullRom)
1394}
1395
1396/// Map a top-left-origin rect from a page's unrotated (MediaBox) frame into its
1397/// `/Rotate`d display frame — the counterpart of docling's pypdfium2
1398/// `_rect_to_display_frame` (docling#4008) for our y-down coordinates.
1399/// `unrot_w`/`unrot_h` are the unrotated page box; the display box is the same
1400/// for 180° and swapped for 90°/270°.
1401pub(crate) fn to_display_frame(
1402    (l, t, r, b): (f32, f32, f32, f32),
1403    rotation: u16,
1404    unrot_w: f32,
1405    unrot_h: f32,
1406) -> (f32, f32, f32, f32) {
1407    match rotation {
1408        // Page turned 90° clockwise for display: the unrotated top edge becomes
1409        // the display right edge, so x' runs from the old bottom edge up.
1410        90 => (unrot_h - b, l, unrot_h - t, r),
1411        180 => (unrot_w - r, unrot_h - b, unrot_w - l, unrot_h - t),
1412        270 => (t, unrot_w - r, b, unrot_w - l),
1413        _ => (l, t, r, b),
1414    }
1415}
1416
1417/// One glyph: codepoint + native (y-up) box edges. `l/b/r/t` is pdfium's *tight*
1418/// ink box (used by the legacy `lines_from_glyphs`); `ll/lb/lr/lt` is the *loose*
1419/// box (font ascent/descent + advance — uniform per font/size), which the
1420/// docling-parse-style sanitizer needs so adjacent glyphs share a top edge.
1421pub(crate) struct Glyph {
1422    pub(crate) ch: char,
1423    pub(crate) l: f32,
1424    pub(crate) b: f32,
1425    pub(crate) r: f32,
1426    pub(crate) t: f32,
1427    pub(crate) ll: f32,
1428    pub(crate) lb: f32,
1429    pub(crate) lr: f32,
1430    pub(crate) lt: f32,
1431    /// Hash of the font's docling-parse name — `/FontDescriptor/FontName`,
1432    /// else `/Name`, else `/BaseFont` (#728: not the page's resource key, which
1433    /// binds one face under several keys) — 0 when not fetched. The sanitizer
1434    /// uses it for docling-parse's `enforce_same_font` (keeps a bold label and
1435    /// regular value as separate line cells, e.g. `LABEL : value`).
1436    pub(crate) font: u64,
1437    /// The loose box as the text matrix actually lays it — corners
1438    /// bottom-left, bottom-right, top-right, top-left as `[x0, y0, … x3, y3]`
1439    /// (docling-parse's `r_x0…r_y3`) — for a glyph whose baseline is **not**
1440    /// upright: rotated 90°/180°/270° or tilted (#528). `ll/lb/lr/lt` are then
1441    /// this quad's axis-aligned extent. `None` for upright text, whose quad is
1442    /// the `ll/lb/lr/lt` rectangle itself — that path stays exactly as it was.
1443    pub(crate) quad: Option<[f32; 8]>,
1444    /// Where the pen sets the glyph — the text origin on the baseline, rise
1445    /// included — and the font size in the same space, as `[x, y, size]`
1446    /// (docling-parse's `text_origin_x/y` and `nominal_text_height`). The
1447    /// word contraction tests a baseline shift on these (#921): the loose
1448    /// box's bottom sits a descent below the baseline, which differs between
1449    /// sizes, so a superscript read as shifted further than it is. `None`
1450    /// when unknown (a synthetic glyph); the box stands in then.
1451    pub(crate) pen: Option<[f32; 3]>,
1452    /// The glyph's font is a math face by its name (docling-parse's
1453    /// `has_math_positioning_semantics`): a sub- or superscript in it next to
1454    /// its base is attached, not a new word (#921).
1455    pub(crate) math_font: bool,
1456}
1457
1458impl Glyph {
1459    /// The font's height on the glyph's own axis (ascent − descent): the
1460    /// loose box's height for upright text, the quad's left edge otherwise —
1461    /// a 90°-turned glyph's vertical extent is its advance, not its size.
1462    pub(crate) fn height(&self) -> f32 {
1463        match self.quad {
1464            Some(q) => (q[6] - q[0]).hypot(q[7] - q[1]),
1465            None => self.lt - self.lb,
1466        }
1467    }
1468}
1469
1470/// How [`lines_from_glyphs`] splits a line into words. Two more modes lived
1471/// here — the prose gap heuristic with punctuation glue and pdfium's
1472/// space-glyph-only code split — for pdfium's glyph stream; the parser's
1473/// prose goes through `dp_lines` and pdfium's text page is gone.
1474#[derive(Clone, Copy, PartialEq)]
1475enum Grouping {
1476    /// Split on the inter-glyph **gap** (or a space glyph), but never glue — for
1477    /// the parser's code cells: the parser emits no space glyphs (a source space
1478    /// is a positioning gap), and its clean advance boxes make the gap reliable.
1479    /// There is no punctuation glue, so a real gap always splits (`et al.
1480    /// 2000`, not `et al.2000`) while genuinely touching tokens stay joined
1481    /// (`add(a,` / `b)`).
1482    CodeGap,
1483}
1484
1485/// Group glyphs (document order) into words then lines, the way docling-parse
1486/// does: a new **word** starts where the horizontal gap to the previous glyph
1487/// exceeds ~0.2 × the font height (a real space is ~0.3 × height; letter
1488/// tracking is smaller, so titles don't shatter); a new **line** starts where
1489/// the baseline drops by ~half the font height (a superscript rises without
1490/// dropping, so it stays on its line). Coordinates are flipped to top-left.
1491/// See [`Grouping`] for how each mode decides word boundaries.
1492fn lines_from_glyphs(gs: &[Glyph], page_h: f32, mode: Grouping) -> Vec<TextCell> {
1493    let mut cells: Vec<TextCell> = Vec::new();
1494    let mut words: Vec<String> = Vec::new(); // words on the current line
1495    let mut word = String::new();
1496    // current line bounding box, native
1497    let (mut ll, mut lb, mut lr, mut lt) = (
1498        f32::INFINITY,
1499        f32::INFINITY,
1500        f32::NEG_INFINITY,
1501        f32::NEG_INFINITY,
1502    );
1503    // Tallest glyph seen on the current line: the word-gap threshold is relative
1504    // to it, so a small-font run on the line (a superscript citation) isn't split
1505    // at its tight digit gaps, while a big display title isn't split at its wider
1506    // letter tracking. A real inter-word space is ~0.3× the font height.
1507    let mut line_h: f32 = 0.0;
1508    let mut prev: Option<&Glyph> = None;
1509    // A space glyph between non-space glyphs pins a word split the gap heuristic
1510    // can miss (tight justified spacing); it carries no geometry.
1511    let mut pending_space = false;
1512
1513    for g in gs {
1514        if g.ch == ' ' {
1515            pending_space = true;
1516            continue;
1517        }
1518        let h = (g.t - g.b).abs().max(1.0);
1519        let (mut new_word, mut new_line) = (false, false);
1520        if let Some(p) = prev {
1521            // A new line drops the baseline *and* resets x leftward; requiring the
1522            // x-reset avoids a descending comma/semicolon faking a line break. A
1523            // *large* drop (≥1.5× the line height — a skipped line, e.g. a centered
1524            // page-number footer below a short last word) is always a new line,
1525            // even without the x-reset.
1526            // LTR wraps reset x leftward (`g.l < p.r`); RTL (Arabic) wraps reset
1527            // rightward (the new line begins at the far right). A large drop
1528            // (≥1.5× line height) is a new line regardless of x.
1529            let x_reset = if is_arabic(g.ch) || is_arabic(p.ch) {
1530                g.l > p.r
1531            } else {
1532                g.l < p.r
1533            };
1534            new_line = (p.b - g.b > h * 0.5 && x_reset) || (p.b - g.b > line_h.max(h) * 1.5);
1535            let word_gap = line_h.max(h) * 0.25;
1536            new_word = match mode {
1537                // Gap-based, no glue: a real gap always splits, touching tokens join.
1538                Grouping::CodeGap => new_line || pending_space || g.l - p.r > word_gap,
1539            };
1540        }
1541        pending_space = false;
1542        if new_line {
1543            push_word(&mut word, &mut words);
1544            push_line(&mut words, (ll, lb, lr, lt), page_h, &mut cells);
1545            (ll, lb, lr, lt) = (
1546                f32::INFINITY,
1547                f32::INFINITY,
1548                f32::NEG_INFINITY,
1549                f32::NEG_INFINITY,
1550            );
1551            line_h = 0.0;
1552        } else if new_word {
1553            push_word(&mut word, &mut words);
1554        }
1555        word.push(g.ch);
1556        ll = ll.min(g.l);
1557        lb = lb.min(g.b);
1558        lr = lr.max(g.r);
1559        lt = lt.max(g.t);
1560        line_h = line_h.max(h);
1561        prev = Some(g);
1562    }
1563    push_word(&mut word, &mut words);
1564    push_line(&mut words, (ll, lb, lr, lt), page_h, &mut cells);
1565    cells
1566}
1567
1568/// Code line cells from the parser's glyph stream. The parser emits no space
1569/// glyphs — a source space is a positioning gap — so code cells use
1570/// [`Grouping::CodeGap`], which splits on the inter-glyph gap (a space
1571/// wherever it exceeds ~0.25× the line height) but never glues punctuation,
1572/// so `et al. 2000` keeps its space while `add(a,` / `b)` stay joined. The
1573/// parser's clean advance boxes make the gap heuristic reliable here, where
1574/// pdfium's overhanging loose boxes used to over-split (`f un c t i o n`).
1575pub(crate) fn code_cells_from_glyphs(gs: &[Glyph], page_h: f32) -> Vec<TextCell> {
1576    lines_from_glyphs(gs, page_h, Grouping::CodeGap)
1577}
1578
1579fn is_arabic(c: char) -> bool {
1580    ('\u{0600}'..='\u{06FF}').contains(&c)
1581}
1582
1583fn push_word(word: &mut String, words: &mut Vec<String>) {
1584    if !word.is_empty() {
1585        words.push(std::mem::take(word));
1586    }
1587}
1588
1589fn push_line(
1590    words: &mut Vec<String>,
1591    bbox: (f32, f32, f32, f32),
1592    page_h: f32,
1593    cells: &mut Vec<TextCell>,
1594) {
1595    if words.is_empty() {
1596        return;
1597    }
1598    let text = std::mem::take(words).join(" ");
1599    let (l, b, r, t) = bbox;
1600    cells.push(TextCell {
1601        text,
1602        l,
1603        t: page_h - t,
1604        r,
1605        b: page_h - b,
1606    });
1607}
1608
1609/// The pdfium library, behind the `pdfium` feature (phase 5 of "Retiring
1610/// pdfium"): the render `DOCLING_RS_RENDERER=pdfium` asks for — docling's
1611/// pypdfium2 chain — the last resort for a file lopdf cannot read, and the
1612/// oracle of the raster and object-model tests. The default build has the
1613/// stub below and never links or loads pdfium.
1614#[cfg(feature = "pdfium")]
1615mod native {
1616    use super::LinkAnnot;
1617    use crate::PdfError;
1618    use image::RgbImage;
1619    use pdfium_render::prelude::*;
1620
1621    /// The bound library.
1622    pub(super) struct Lib(Pdfium);
1623    /// An open document.
1624    pub(super) struct Session<'a> {
1625        doc: PdfDocument<'a>,
1626    }
1627    /// A loaded page.
1628    pub(super) struct Page<'a>(PdfPage<'a>);
1629
1630    /// Try binding pdfium from a directory (or a literal library file path):
1631    /// `<dir>/<platform library name>` first, else `<dir>` itself as the file.
1632    fn try_bind_dir(path: &str) -> Option<Box<dyn PdfiumLibraryBindings>> {
1633        let name = Pdfium::pdfium_platform_library_name_at_path(path);
1634        if let Ok(b) = Pdfium::bind_to_library(&name) {
1635            return Some(b);
1636        }
1637        Pdfium::bind_to_library(path).ok()
1638    }
1639
1640    /// Bind to the pdfium dynamic library. Honors `PDFIUM_DYNAMIC_LIB_PATH` (a
1641    /// directory or file) first; else falls back to `.pdfium/lib` relative to
1642    /// the current directory (the layout `scripts/install/pdf_setup.sh`
1643    /// produces); else the system library.
1644    pub(super) fn bind() -> Result<Lib, PdfError> {
1645        if let Some(path) = docling_core::env::nonempty("PDFIUM_DYNAMIC_LIB_PATH") {
1646            if let Some(b) = try_bind_dir(&path) {
1647                return Ok(Lib(Pdfium::new(b)));
1648            }
1649        }
1650        if let Some(b) = try_bind_dir(&crate::resolve_asset(".pdfium/lib")) {
1651            return Ok(Lib(Pdfium::new(b)));
1652        }
1653        Pdfium::bind_to_system_library()
1654            .map(|b| Lib(Pdfium::new(b)))
1655            .map_err(Into::into)
1656    }
1657
1658    /// `bind()` for unit tests: point `PDFIUM_DYNAMIC_LIB_PATH` at the
1659    /// repo-root `.pdfium/lib` first (tests run with CWD = the crate dir,
1660    /// where the CWD-relative default cannot see it).
1661    #[cfg(test)]
1662    pub(crate) fn bind_for_tests() -> Result<Pdfium, PdfError> {
1663        if std::env::var_os("PDFIUM_DYNAMIC_LIB_PATH").is_none() {
1664            let lib = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.pdfium/lib");
1665            if lib.is_dir() {
1666                std::env::set_var("PDFIUM_DYNAMIC_LIB_PATH", &lib);
1667            }
1668        }
1669        bind().map(|l| l.0)
1670    }
1671
1672    impl Lib {
1673        pub(super) fn open<'a>(
1674            &'a self,
1675            bytes: &'a [u8],
1676            password: Option<&str>,
1677        ) -> Result<Session<'a>, PdfError> {
1678            crate::timing::timed("pdfium.open", || {
1679                self.0
1680                    .load_pdf_from_byte_slice(bytes, password)
1681                    .map(|doc| Session { doc })
1682                    .map_err(Into::into)
1683            })
1684        }
1685    }
1686
1687    impl Session<'_> {
1688        pub(super) fn page_count(&self) -> usize {
1689            self.doc.pages().len() as usize
1690        }
1691
1692        pub(super) fn page(&self, index: usize) -> Result<Page<'_>, PdfError> {
1693            self.doc
1694                .pages()
1695                .get(index as PdfPageIndex)
1696                .map(Page)
1697                .map_err(Into::into)
1698        }
1699    }
1700
1701    impl Page<'_> {
1702        /// The display size in points.
1703        pub(super) fn size(&self) -> (f32, f32) {
1704            (self.0.width().value, self.0.height().value)
1705        }
1706
1707        /// pdfium's view of the page's geometry, for the files lopdf cannot
1708        /// read — the same numbers `pdf_meta` computes from the object model.
1709        pub(super) fn geom(&self) -> crate::pdf_meta::PageGeom {
1710            crate::pdf_meta::PageGeom {
1711                width: self.0.width().value,
1712                height: self.0.height().value,
1713                rotation: match self.0.rotation() {
1714                    Ok(PdfPageRenderRotation::Degrees90) => 90u16,
1715                    Ok(PdfPageRenderRotation::Degrees180) => 180,
1716                    Ok(PdfPageRenderRotation::Degrees270) => 270,
1717                    _ => 0,
1718                },
1719            }
1720        }
1721
1722        /// Render the page into a `w` × `h` RGB bitmap under timing `stage`.
1723        pub(super) fn render(
1724            &self,
1725            w: i32,
1726            h: i32,
1727            stage: &'static str,
1728        ) -> Result<RgbImage, PdfError> {
1729            let cfg = PdfRenderConfig::new()
1730                .set_target_width(w)
1731                .set_target_height(h);
1732            crate::timing::timed(stage, || {
1733                self.0
1734                    .render_with_config(&cfg)
1735                    .map(|b| b.as_image().into_rgb8())
1736                    .map_err(Into::into)
1737            })
1738        }
1739
1740        /// Collect web/mail/tel hyperlink annotations on the page, mapping
1741        /// each link's rectangle into top-left page coordinates (like
1742        /// [`super::TextCell`]). `file://` and in-document destinations are
1743        /// skipped — only externally meaningful targets are rendered. pdfium
1744        /// occasionally lists a link twice; rects are kept as-is and the
1745        /// caller dedupes by resolved anchor text.
1746        pub(super) fn links(&self, page_h: f32) -> Vec<LinkAnnot> {
1747            let mut out = Vec::new();
1748            for link in self.0.links().iter() {
1749                let Some(uri) = link
1750                    .action()
1751                    .and_then(|a| a.as_uri_action().and_then(|u| u.uri().ok()))
1752                else {
1753                    continue;
1754                };
1755                let scheme_ok = ["http://", "https://", "mailto:", "tel:"]
1756                    .iter()
1757                    .any(|s| uri.starts_with(s));
1758                if !scheme_ok {
1759                    continue;
1760                }
1761                if let Ok(rect) = link.rect() {
1762                    out.push(LinkAnnot {
1763                        l: rect.left().value,
1764                        t: page_h - rect.top().value,
1765                        r: rect.right().value,
1766                        b: page_h - rect.bottom().value,
1767                        uri,
1768                    });
1769                }
1770            }
1771            out
1772        }
1773    }
1774}
1775
1776/// The `pdfium`-less build: pdfium never binds, so every entry point falls
1777/// through to the pure-Rust stack, and a file the object model cannot read
1778/// fails with [`no_raster`]'s hint.
1779#[cfg(all(feature = "render", not(feature = "pdfium")))]
1780mod native {
1781    use super::LinkAnnot;
1782    use crate::PdfError;
1783    use image::RgbImage;
1784    use std::convert::Infallible;
1785    use std::marker::PhantomData;
1786
1787    pub(super) struct Lib(Infallible);
1788    pub(super) struct Session<'a>(Infallible, PhantomData<&'a ()>);
1789    pub(super) struct Page<'a>(Infallible, PhantomData<&'a ()>);
1790
1791    /// Reached only for a file the pure-Rust object model could not read
1792    /// (every entry point tries it first), so the error is about the file:
1793    /// naming the missing library sent users of a corrupt or non-PDF upload
1794    /// looking for a pdfium install that would not have helped either.
1795    pub(super) fn bind() -> Result<Lib, PdfError> {
1796        Err(PdfError::Document(crate::UNREADABLE.into()))
1797    }
1798
1799    impl Lib {
1800        pub(super) fn open<'a>(
1801            &'a self,
1802            _bytes: &'a [u8],
1803            _password: Option<&str>,
1804        ) -> Result<Session<'a>, PdfError> {
1805            match self.0 {}
1806        }
1807    }
1808
1809    impl Session<'_> {
1810        pub(super) fn page_count(&self) -> usize {
1811            match self.0 {}
1812        }
1813
1814        pub(super) fn page(&self, _index: usize) -> Result<Page<'_>, PdfError> {
1815            match self.0 {}
1816        }
1817    }
1818
1819    impl Page<'_> {
1820        pub(super) fn size(&self) -> (f32, f32) {
1821            match self.0 {}
1822        }
1823
1824        pub(super) fn geom(&self) -> crate::pdf_meta::PageGeom {
1825            match self.0 {}
1826        }
1827
1828        pub(super) fn render(
1829            &self,
1830            _w: i32,
1831            _h: i32,
1832            _stage: &'static str,
1833        ) -> Result<RgbImage, PdfError> {
1834            match self.0 {}
1835        }
1836
1837        pub(super) fn links(&self, _page_h: f32) -> Vec<LinkAnnot> {
1838            match self.0 {}
1839        }
1840    }
1841}
1842
1843#[cfg(all(test, feature = "pdfium"))]
1844pub(crate) use native::bind_for_tests;
1845
1846#[cfg(test)]
1847mod tests {
1848    use super::{checked_render_dims, max_render_side, to_display_frame};
1849
1850    /// #897: the adaptive schedule starts renders eagerly for the first
1851    /// pages, then while at least half of the last 8 verdicts read the
1852    /// bitmap; a declined page that turns out to read it counts as read.
1853    #[cfg(feature = "render")]
1854    #[test]
1855    fn adaptive_verdicts() {
1856        let v = super::Verdicts::default();
1857        assert!(v.start_eagerly(), "no verdict yet");
1858        v.record(false, false);
1859        v.record(false, false);
1860        assert!(v.start_eagerly(), "still warming up");
1861        v.record(false, false);
1862        assert!(!v.start_eagerly(), "three text-only pages");
1863        v.record(true, true); // the last declined one was read after all
1864        v.record(true, false);
1865        assert!(v.start_eagerly(), "2 of 4 read");
1866        for _ in 0..8 {
1867            v.record(false, false);
1868        }
1869        assert!(!v.start_eagerly(), "the window forgets the read ones");
1870        for _ in 0..4 {
1871            v.record(true, false);
1872        }
1873        assert!(v.start_eagerly(), "4 of the last 8 read");
1874    }
1875
1876    /// The pure-Rust object model must answer exactly what pdfium answers —
1877    /// page count, display size, `/Rotate`, URI links — on every corpus PDF,
1878    /// or a checkout without pdfium would convert differently. Needs the
1879    /// library; skips cleanly without it (CI has no pdfium).
1880    #[test]
1881    #[cfg(feature = "pdfium")]
1882    fn pdf_meta_matches_pdfium_on_the_corpus() {
1883        let Ok(_) = super::bind_for_tests() else {
1884            eprintln!("skipping: pdfium not found");
1885            return;
1886        };
1887        let lib = super::native::bind().unwrap();
1888        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
1889        let mut files: Vec<std::path::PathBuf> = Vec::new();
1890        for dir in ["tests/data/pdf/sources", "tests/data/scanned/sources"] {
1891            let Ok(rd) = std::fs::read_dir(root.join(dir)) else {
1892                continue;
1893            };
1894            files.extend(
1895                rd.flatten()
1896                    .map(|e| e.path())
1897                    .filter(|p| p.extension().is_some_and(|e| e == "pdf")),
1898            );
1899        }
1900        files.sort();
1901        assert!(!files.is_empty(), "corpus not found");
1902        let mut checked = 0;
1903        for path in files {
1904            let bytes = std::fs::read(&path).unwrap();
1905            let Ok(doc) = lib.open(&bytes, None) else {
1906                continue; // password fixtures etc.
1907            };
1908            let Some(meta) = crate::pdf_meta::PdfMeta::open(&bytes) else {
1909                panic!(
1910                    "{}: lopdf could not read a file pdfium reads",
1911                    path.display()
1912                );
1913            };
1914            assert_eq!(meta.page_count(), doc.page_count(), "{}", path.display());
1915            for i in 0..meta.page_count() {
1916                let page = doc.page(i).unwrap();
1917                let want = page.geom();
1918                let got = meta.geometry(i).unwrap();
1919                assert!(
1920                    (got.width - want.width).abs() < 0.01
1921                        && (got.height - want.height).abs() < 0.01
1922                        && got.rotation == want.rotation,
1923                    "{} p{}: meta {got:?} vs pdfium {want:?}",
1924                    path.display(),
1925                    i + 1
1926                );
1927                let mut want_links = page.links(want.unrotated().1);
1928                let mut got_links = meta.links(i);
1929                let key = |l: &super::LinkAnnot| {
1930                    (
1931                        l.uri.clone(),
1932                        (l.l * 10.0) as i64,
1933                        (l.t * 10.0) as i64,
1934                        (l.r * 10.0) as i64,
1935                        (l.b * 10.0) as i64,
1936                    )
1937                };
1938                want_links.sort_by_key(key);
1939                got_links.sort_by_key(key);
1940                let want_keys: Vec<_> = want_links.iter().map(key).collect();
1941                let got_keys: Vec<_> = got_links.iter().map(key).collect();
1942                assert_eq!(got_keys, want_keys, "{} p{}: links", path.display(), i + 1);
1943                checked += 1;
1944            }
1945        }
1946        eprintln!("pdf_meta checked against pdfium on {checked} pages");
1947    }
1948
1949    /// A page whose declared size renders past the per-side cap is rejected
1950    /// with a recoverable error, before pdfium or `image` allocates the
1951    /// multi-gigabyte bitmap that would otherwise abort the process; a normal
1952    /// page passes through with its dimensions rounded to `i32`.
1953    #[test]
1954    fn oversized_render_is_rejected_not_allocated() {
1955        let cap = f64::from(max_render_side());
1956        // A 12000 pt box at the pipeline's 3x supersample is 36000 px/side.
1957        let huge = checked_render_dims(cap + 1.0, 10.0, 1);
1958        assert!(huge.is_err(), "over-cap width must be rejected");
1959        let tall = checked_render_dims(10.0, cap + 1.0, 7);
1960        assert!(tall.is_err(), "over-cap height must be rejected");
1961        assert!(
1962            tall.unwrap_err().to_string().contains("page 7"),
1963            "the error names the offending page"
1964        );
1965        // A Letter page at 2x supersample (612x792 pt -> 1836x2376 px) is fine.
1966        assert_eq!(
1967            checked_render_dims(1836.4, 2375.6, 1).unwrap(),
1968            (1836, 2376)
1969        );
1970        // Exactly at the cap is allowed; a zero-or-negative size floors to 1.
1971        assert_eq!(
1972            checked_render_dims(cap, cap, 1).unwrap(),
1973            (cap as i32, cap as i32)
1974        );
1975        assert_eq!(checked_render_dims(0.0, 0.0, 1).unwrap(), (1, 1));
1976    }
1977
1978    /// A 612×792 portrait page displayed under `/Rotate`: a rect near the
1979    /// unrotated top-left lands where a viewer shows it (docling#4008).
1980    #[test]
1981    fn display_frame_follows_the_page_rotation() {
1982        let r = (72.0, 63.0, 387.0, 74.0); // top-left origin, unrotated
1983        assert_eq!(to_display_frame(r, 0, 612.0, 792.0), r);
1984        // 90° clockwise: the page becomes 792×612; the old top edge is the
1985        // display right edge, old left edge the display top.
1986        assert_eq!(
1987            to_display_frame(r, 90, 612.0, 792.0),
1988            (718.0, 72.0, 729.0, 387.0)
1989        );
1990        // 180°: both axes mirror inside the same box.
1991        assert_eq!(
1992            to_display_frame(r, 180, 612.0, 792.0),
1993            (225.0, 718.0, 540.0, 729.0)
1994        );
1995        // 270°: the old top edge is the display left edge, old right edge the
1996        // display top.
1997        assert_eq!(
1998            to_display_frame(r, 270, 612.0, 792.0),
1999            (63.0, 225.0, 74.0, 540.0)
2000        );
2001    }
2002
2003    #[test]
2004    fn display_frame_rotations_compose_to_identity() {
2005        let r = (10.0, 20.0, 110.0, 40.0);
2006        // 90° then 270° from the intermediate (792×612) box round-trips.
2007        let once = to_display_frame(r, 90, 612.0, 792.0);
2008        assert_eq!(to_display_frame(once, 270, 792.0, 612.0), r);
2009        let twice = to_display_frame(to_display_frame(r, 180, 612.0, 792.0), 180, 612.0, 792.0);
2010        assert_eq!(twice, r);
2011    }
2012}