Skip to main content

laminapdf_render/
hayro.rs

1//! The hayro adapter (feature `hayro`): ADR 0004's CI oracle and debug choice, pure Rust.
2//!
3//! hayro needs the whole file in memory, so `open` reads the source with [`read_all`]
4//! (bounded by [`RenderLimits::max_input_bytes`]). Tiles are drawn with
5//! [`hayro::render_into`] into a context the size of the tile, under a transform that scales
6//! the page, applies the view rotation and shifts the tile to the origin, so no backend call
7//! allocates more than one tile.
8//!
9//! hayro can't be paused, so the cancel token is checked before and after each call. An engine
10//! panic (seen on a tiling pattern with large steps) is caught where unwinding is available and
11//! reported as `render-failed`.
12//!
13//! Known differences from PDFium, so the nightly hayro-vs-PDFium diff (`cargo xtask render-diff`)
14//! must compare with default flags:
15//! hayro has no print intent (`print` is ignored) and no switch for widgets alone (it draws
16//! them with the other annotations, so `form_widgets: false` is ignored too). A
17//! [`RenderCache`] lives for one call: its lifetime is tied to the page borrowed from the
18//! document, so it can't be kept on the document without a self-referential type.
19
20use std::cell::RefCell;
21use std::collections::BTreeMap;
22use std::panic::{AssertUnwindSafe, catch_unwind};
23use std::sync::Arc;
24
25use hayro::hayro_interpret::font::GlyphRun;
26use hayro::hayro_interpret::util::{RectExt as _, TransformExt as _};
27use hayro::hayro_interpret::{
28    BlendMode, ClipPath, Context, Device, DrawMode, DrawProps, Image, ImageDrawProps, InterpreterCache,
29    InterpreterSettings, SoftMask, interpret_page,
30};
31use hayro::hayro_syntax::object::dict::keys::{ANNOTS, F, MASK, RECT, SMASK};
32use hayro::hayro_syntax::object::{Array, Dict, Rect as PdfRect};
33use hayro::hayro_syntax::page::Rotation as HayroRotation;
34use hayro::hayro_syntax::{Pdf, PdfData};
35use hayro::kurbo::{Affine, BezPath, Rect};
36use hayro::vello_cpu::color::AlphaColor;
37use hayro::vello_cpu::color::palette::css::TRANSPARENT;
38use hayro::vello_cpu::{Pixmap, RasterizerSettings, RenderContext, Resources, TargetInit};
39use hayro::{RenderCache, RenderSettings};
40use laminapdf_cos::ByteSource;
41use laminapdf_syntax::CancelToken;
42use laminapdf_syntax::Rotation;
43
44use crate::appearance::{Annotated, Kept, Quad, mostly_changed, recolour_tile};
45use crate::backend::{RenderBackend, RenderDocument};
46use crate::error::RenderError;
47use crate::request::{RenderLimits, RenderOpenOptions, RenderPage, RenderRequest, Rgba8, TilePlan};
48use crate::source::read_all;
49
50const NAME: &str = "hayro";
51
52/// The pure-Rust renderer: hayro 0.8 with its standard 14 fonts and predefined CMaps built in.
53///
54/// Added in 0.2.0.
55#[derive(Debug, Clone, Copy, Default)]
56pub struct HayroBackend;
57
58impl HayroBackend {
59    /// The backend.
60    ///
61    /// Added in 0.2.0.
62    #[must_use]
63    pub const fn new() -> Self {
64        Self
65    }
66}
67
68impl RenderBackend for HayroBackend {
69    fn name(&self) -> &'static str {
70        NAME
71    }
72
73    fn version(&self) -> &'static str {
74        // The workspace pins hayro exactly (`=0.8.0`).
75        "0.8.0"
76    }
77
78    fn open(
79        &self,
80        source: Arc<dyn ByteSource>,
81        options: &RenderOpenOptions,
82    ) -> Result<Box<dyn RenderDocument>, RenderError> {
83        let limits = *options.limits();
84        // An in-memory source is borrowed, not copied (ADR 0004: never a second copy);
85        // anything else is read whole, which hayro needs.
86        let data: PdfData = if source.as_slice().is_some() {
87            if source.len() > limits.max_input_bytes {
88                return Err(RenderError::InputTooLarge {
89                    len: source.len(),
90                    limit: limits.max_input_bytes,
91                });
92            }
93            Arc::new(InMemory(source)).into()
94        } else {
95            Arc::new(read_all(source.as_ref(), limits.max_input_bytes)?).into()
96        };
97        let password = options.password().unwrap_or("");
98        let loaded =
99            catch_unwind(AssertUnwindSafe(|| Pdf::new_with_password(data, password))).map_err(|_| failed("open"))?;
100        let pdf = loaded.map_err(|e| match e {
101            hayro::hayro_syntax::LoadPdfError::Decryption(hayro::hayro_syntax::DecryptionError::PasswordProtected) => {
102                if options.password().is_some() {
103                    RenderError::WrongPassword
104                } else {
105                    RenderError::PasswordRequired
106                }
107            }
108            _ => failed("open"),
109        })?;
110        Ok(Box::new(HayroDocument {
111            pdf,
112            limits,
113            whole: RefCell::default(),
114        }))
115    }
116}
117
118/// An in-memory [`ByteSource`] as hayro's input, without a copy.
119struct InMemory(Arc<dyn ByteSource>);
120
121impl AsRef<[u8]> for InMemory {
122    fn as_ref(&self) -> &[u8] {
123        // Only built for sources whose `as_slice` is `Some`.
124        self.0.as_slice().unwrap_or_default()
125    }
126}
127
128/// A document open in hayro.
129struct HayroDocument {
130    pdf: Pdf,
131    limits: RenderLimits,
132    /// Per page, which annotations keep their whole rectangle when recoloured
133    /// ([`mostly_changed`], decided once on a small drawing of the page).
134    whole: RefCell<BTreeMap<u32, Vec<bool>>>,
135}
136
137impl HayroDocument {
138    fn count(&self) -> u32 {
139        u32::try_from(self.pdf.pages().len()).unwrap_or(u32::MAX)
140    }
141
142    fn out_of_range(&self, index: u32) -> RenderError {
143        RenderError::PageIndexOutOfRange {
144            index,
145            count: self.count(),
146        }
147    }
148}
149
150impl HayroDocument {
151    /// Which of `page`'s annotations keep their whole rectangle, from a drawing of the whole
152    /// page at most [`DECISION_SIDE`] pixels on a side; cached per page.
153    fn whole_rects(
154        &self,
155        page: &hayro::hayro_syntax::page::Page<'_>,
156        request: &RenderRequest,
157        info: &RenderPage,
158    ) -> Result<Vec<bool>, RenderError> {
159        if let Some(flags) = self.whole.borrow().get(&request.page) {
160            return Ok(flags.clone());
161        }
162        let longest = info.width.max(info.height).max(1.0);
163        let small = RenderRequest::page(request.page, DECISION_SIDE / longest)
164            .with_flags(request.flags)
165            .with_background(request.background);
166        let plan = TilePlan::new(info, &small, &self.limits)?;
167        let transform =
168            Affine::new(plan.page_to_tile(info, Rotation::None).to_array()) * page.initial_transform(true).to_kurbo();
169        let size = (
170            u16::try_from(plan.tile.width).map_err(|_| failed("render"))?,
171            u16::try_from(plan.tile.height).map_err(|_| failed("render"))?,
172        );
173        let mut without = vec![0; plan.byte_len()];
174        let mut annotated = vec![0; plan.byte_len()];
175        draw(page, &small, transform, size, false, &mut without)?;
176        draw(page, &small, transform, size, true, &mut annotated)?;
177        let flags = mostly_changed(
178            &annotation_rects(page, transform),
179            &without,
180            &annotated,
181            plan.tile.width,
182        );
183        self.whole.borrow_mut().insert(request.page, flags.clone());
184        Ok(flags)
185    }
186}
187
188/// The longest side of the page drawing [`mostly_changed`] decides on.
189const DECISION_SIDE: f32 = 256.0;
190
191impl RenderDocument for HayroDocument {
192    fn page_count(&self) -> u32 {
193        self.count()
194    }
195
196    fn page(&self, index: u32) -> Result<RenderPage, RenderError> {
197        let pages = self.pdf.pages();
198        let page = usize::try_from(index)
199            .ok()
200            .and_then(|i| pages.get(i))
201            .ok_or_else(|| self.out_of_range(index))?;
202        Ok(geometry(page))
203    }
204
205    fn limits(&self) -> &RenderLimits {
206        &self.limits
207    }
208
209    fn render(&self, request: &RenderRequest, out: &mut [u8], cancel: &CancelToken) -> Result<TilePlan, RenderError> {
210        let pages = self.pdf.pages();
211        let page = usize::try_from(request.page)
212            .ok()
213            .and_then(|i| pages.get(i))
214            .ok_or_else(|| self.out_of_range(request.page))?;
215        let info = geometry(page);
216        let plan = TilePlan::new(&info, request, &self.limits)?;
217        plan.check_buffer(out)?;
218        let (Ok(tw), Ok(th)) = (u16::try_from(plan.tile.width), u16::try_from(plan.tile.height)) else {
219            return Err(RenderError::TooLarge {
220                width: plan.tile.width.into(),
221                height: plan.tile.height.into(),
222                limit: u16::MAX.into(),
223                unit: "pixels per side (hayro)",
224            });
225        };
226        if cancel.is_cancelled() {
227            return Err(RenderError::Cancelled);
228        }
229
230        // initial_transform(true) is the displayed page space (points, y down, /Rotate applied).
231        let transform = Affine::new(plan.page_to_tile(&info, request.rotation).to_array())
232            * page.initial_transform(true).to_kurbo();
233        let size = (tw, th);
234        let annotations = request.flags.annotations;
235        if request.appearance.recolours() {
236            // Recoloured: the content alone, then (when the page has any) the annotations drawn
237            // again over it, whose pixels keep their colours; images keep theirs too.
238            draw(page, request, transform, size, false, out)?;
239            let rects = if annotations {
240                annotation_rects(page, transform)
241            } else {
242                Vec::new()
243            };
244            let (with, whole) = if rects.is_empty() {
245                (None, Vec::new())
246            } else {
247                let mut with = vec![0; out.len()];
248                draw(page, request, transform, size, true, &mut with)?;
249                let flags = self.whole_rects(page, request, &info)?;
250                let whole = rects.iter().zip(flags).filter(|(_, w)| *w).map(|(q, _)| *q).collect();
251                (Some(with), whole)
252            };
253            let images = image_quads(page, transform, size)?;
254            let kept = Kept {
255                images: &images.opaque,
256                see_through: &images.see_through,
257                background: request.background,
258                annotated: with.as_deref().map(|pixels| Annotated { pixels, whole: &whole }),
259            };
260            recolour_tile(request.appearance, plan.tile.width, out, &kept);
261        } else {
262            draw(page, request, transform, size, annotations, out)?;
263        }
264        if cancel.is_cancelled() {
265            return Err(RenderError::Cancelled);
266        }
267        Ok(plan)
268    }
269}
270
271/// Draws `page` under `transform` into the `size` tile `out`, with or without annotations.
272fn draw(
273    page: &hayro::hayro_syntax::page::Page<'_>,
274    request: &RenderRequest,
275    transform: Affine,
276    (tw, th): (u16, u16),
277    annotations: bool,
278    out: &mut [u8],
279) -> Result<(), RenderError> {
280    let settings = InterpreterSettings {
281        render_annotations: annotations,
282        ..InterpreterSettings::default()
283    };
284    // Grayscale applies to the content only (as PDFium's FPDF_GRAYSCALE): draw on transparent,
285    // gray it, then lay it over the background.
286    let grayscale = request.flags.grayscale;
287    let background = match request.background {
288        Some(c) if !grayscale => AlphaColor::from_rgba8(c.r, c.g, c.b, c.a),
289        _ => TRANSPARENT,
290    };
291    let pixmap = catch_unwind(AssertUnwindSafe(|| {
292        let cache = RenderCache::new();
293        let mut ctx = RenderContext::new(tw, th);
294        hayro::render_into(page, &cache, &settings, &RenderSettings::default(), &mut ctx, transform);
295        ctx.flush();
296        let mut pixmap = Pixmap::new(tw, th);
297        ctx.render_with(
298            &mut pixmap,
299            &mut Resources::default(),
300            RasterizerSettings {
301                target_init: TargetInit::Clear(background),
302                ..RasterizerSettings::default()
303            },
304        );
305        pixmap
306    }))
307    .map_err(|_| failed("render"))?;
308    let under = if grayscale { request.background } else { None };
309    unpremultiply_into(pixmap.data_as_u8_slice(), out, grayscale, under);
310    Ok(())
311}
312
313/// Where the page's raster images land in the tile, read by interpreting the page without
314/// drawing it. Stencil masks are painted in the fill colour, like text, so they are recoloured.
315fn image_quads(
316    page: &hayro::hayro_syntax::page::Page<'_>,
317    transform: Affine,
318    (tw, th): (u16, u16),
319) -> Result<ImageScan, RenderError> {
320    catch_unwind(AssertUnwindSafe(|| {
321        let cache = InterpreterCache::new();
322        let settings = InterpreterSettings {
323            render_annotations: false,
324            ..InterpreterSettings::default()
325        };
326        let bbox = Rect::new(0.0, 0.0, f64::from(tw), f64::from(th));
327        let mut ctx = Context::new(transform, bbox, &cache, page.xref(), settings);
328        let mut scan = ImageScan::default();
329        interpret_page(page, &mut ctx, &mut scan);
330        scan
331    }))
332    .map_err(|_| failed("image scan"))
333}
334
335/// Where each shown annotation's `/Rect` lands in the tile (hidden ones, `/F` bit 2, are left out,
336/// as hayro leaves them undrawn).
337fn annotation_rects(page: &hayro::hayro_syntax::page::Page<'_>, transform: Affine) -> Vec<Quad> {
338    let Some(annots) = page.raw().get::<Array<'_>>(ANNOTS) else {
339        return Vec::new();
340    };
341    annots
342        .iter::<Dict<'_>>()
343        .filter(|annot| annot.get::<u32>(F).unwrap_or(0) & 2 == 0)
344        .filter_map(|annot| annot.get::<PdfRect>(RECT))
345        .map(|rect| {
346            let r = rect.to_kurbo();
347            let box_ = Affine::new([r.width(), 0.0, 0.0, r.height(), r.x0, r.y0]);
348            Quad::from_transform((transform * box_).as_coeffs())
349        })
350        .collect()
351}
352
353/// A device that only records each raster image's quad (its transform maps image pixels),
354/// sorted by whether the page shows through it.
355#[derive(Default)]
356struct ImageScan {
357    opaque: Vec<Quad>,
358    see_through: Vec<Quad>,
359}
360
361impl<'a> Device<'a> for ImageScan {
362    fn draw_path(&mut self, _: &BezPath, _: DrawProps<'a>, _: &DrawMode) {}
363    fn push_clip_path(&mut self, _: &ClipPath) {}
364    fn push_transparency_group(&mut self, _: f32, _: Option<SoftMask<'a>>, _: BlendMode) {}
365    fn draw_glyph_run(&mut self, _: &GlyphRun<'_, 'a>, _: DrawProps<'a>, _: &DrawMode) {}
366    fn draw_image(&mut self, image: Image<'a, '_>, props: ImageDrawProps<'a>) {
367        if let Image::Raster(raster) = image {
368            let to_unit = Affine::scale_non_uniform(f64::from(raster.width()), f64::from(raster.height()));
369            let quad = Quad::from_transform((props.transform * to_unit).as_coeffs());
370            let dict = raster.stream().dict();
371            let masked = dict.contains_key(SMASK) || dict.contains_key(MASK);
372            if masked || props.soft_mask.is_some() || props.blend_mode != BlendMode::Normal {
373                self.see_through.push(quad);
374            } else {
375                self.opaque.push(quad);
376            }
377        }
378    }
379    fn pop_clip(&mut self) {}
380    fn pop_transparency_group(&mut self) {}
381}
382
383/// A page's displayed size and `/Rotate`.
384fn geometry(page: &hayro::hayro_syntax::page::Page<'_>) -> RenderPage {
385    let (width, height) = page.render_dimensions();
386    RenderPage {
387        width,
388        height,
389        rotate: match page.rotation() {
390            HayroRotation::None => Rotation::None,
391            HayroRotation::Horizontal => Rotation::Clockwise90,
392            HayroRotation::Flipped => Rotation::Half,
393            HayroRotation::FlippedHorizontal => Rotation::Clockwise270,
394        },
395    }
396}
397
398const fn failed(stage: &'static str) -> RenderError {
399    RenderError::Failed { backend: NAME, stage }
400}
401
402/// hayro's premultiplied RGBA8 into straight-alpha RGBA8, same size: optionally gray (Rec. 601
403/// luma, which is linear, so it applies to premultiplied channels), then laid over `under`.
404fn unpremultiply_into(src: &[u8], out: &mut [u8], grayscale: bool, under: Option<Rgba8>) {
405    for (&[r, g, b, a], d) in src.as_chunks::<4>().0.iter().zip(out.as_chunks_mut::<4>().0) {
406        let [r, g, b] = if grayscale { [luma(r, g, b); 3] } else { [r, g, b] };
407        // Source-over in premultiplied space: c + u·ua·(1 − a), alpha a + ua·(1 − a).
408        let (r, g, b, a) = match under {
409            Some(u) if a < 255 => {
410                let rest = 255 - u32::from(a);
411                let ua = u32::from(u.a);
412                let over = |c: u8, uc: u8| clamp(u32::from(c) + (u32::from(uc) * ua * rest + 255 * 127) / (255 * 255));
413                (
414                    over(r, u.r),
415                    over(g, u.g),
416                    over(b, u.b),
417                    clamp(u32::from(a) + (ua * rest + 127) / 255),
418                )
419            }
420            _ => (r, g, b, a),
421        };
422        *d = if a == 0 {
423            [0, 0, 0, 0]
424        } else if a == 255 {
425            [r, g, b, a]
426        } else {
427            [unpremultiply(r, a), unpremultiply(g, a), unpremultiply(b, a), a]
428        };
429    }
430}
431
432fn clamp(v: u32) -> u8 {
433    u8::try_from(v.min(255)).unwrap_or(u8::MAX)
434}
435
436/// `round(c × 255 / a)`, clamped (a premultiplied channel can't exceed alpha, but rounding in
437/// the rasteriser may).
438fn unpremultiply(c: u8, a: u8) -> u8 {
439    let v = (u32::from(c) * 255 + u32::from(a) / 2) / u32::from(a);
440    u8::try_from(v.min(255)).unwrap_or(u8::MAX)
441}
442
443/// Rec. 601 luma, rounded.
444fn luma(r: u8, g: u8, b: u8) -> u8 {
445    let v = (u32::from(r) * 299 + u32::from(g) * 587 + u32::from(b) * 114 + 500) / 1000;
446    u8::try_from(v.min(255)).unwrap_or(u8::MAX)
447}
448
449#[cfg(test)]
450mod tests {
451    use super::{luma, unpremultiply, unpremultiply_into};
452    use crate::Rgba8;
453
454    #[test]
455    fn unpremultiply_restores_straight_channels() {
456        assert_eq!(unpremultiply(64, 128), 128);
457        assert_eq!(unpremultiply(128, 128), 255);
458        assert_eq!(unpremultiply(200, 128), 255);
459    }
460
461    #[test]
462    fn transparent_pixels_become_zero() {
463        let mut out = [9; 4];
464        unpremultiply_into(&[10, 20, 30, 0], &mut out, false, None);
465        assert_eq!(out, [0, 0, 0, 0]);
466    }
467
468    #[test]
469    fn grayscale_keeps_the_background_colour() {
470        let sepia = Rgba8 {
471            r: 255,
472            g: 240,
473            b: 200,
474            a: 255,
475        };
476        let mut out = [0; 4];
477        // A fully transparent content pixel: the background shows, ungrayed.
478        unpremultiply_into(&[0, 0, 0, 0], &mut out, true, Some(sepia));
479        assert_eq!(out, [255, 240, 200, 255]);
480        // Opaque red content: gray, background hidden.
481        unpremultiply_into(&[255, 0, 0, 255], &mut out, true, Some(sepia));
482        assert_eq!(out, [76, 76, 76, 255]);
483    }
484
485    #[test]
486    fn grayscale_uses_rec_601_luma() {
487        assert_eq!(luma(255, 255, 255), 255);
488        assert_eq!(luma(255, 0, 0), 76);
489    }
490}