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