Skip to main content

laminapdf_render/
tiff_writer.rs

1//! TIFF files written a page at a time: Deflate-compressed RGBA, each page with its resolution.
2//! [`export_pages`](crate::export_pages) writes its TIFFs through it, and a caller that draws
3//! its own pages (the web reader's worker) feeds it their pixels.
4
5use std::cell::RefCell;
6use std::io::{self, Cursor, Seek, SeekFrom, Write};
7use std::rc::Rc;
8
9use tiff::encoder::{Compression, DeflateLevel, Rational, TiffEncoder, colortype::RGBA8};
10use tiff::tags::ResolutionUnit;
11
12use crate::RenderError;
13
14/// The file being written, shared with the encoder, which takes its writer by value and never
15/// gives it back.
16#[derive(Clone, Default)]
17struct Shared(Rc<RefCell<Cursor<Vec<u8>>>>);
18
19impl Write for Shared {
20    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
21        self.0.borrow_mut().write(buf)
22    }
23
24    fn flush(&mut self) -> io::Result<()> {
25        Ok(())
26    }
27}
28
29impl Seek for Shared {
30    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
31        self.0.borrow_mut().seek(pos)
32    }
33}
34
35/// A TIFF file in memory, one page per [`TiffWriter::add_page`]: straight 8-bit RGBA,
36/// Deflate-compressed, each page with its resolution in dots per inch. It is neither `Send` nor
37/// `Sync`: the file and its encoder share one buffer through an `Rc`, so a writer stays on the
38/// thread that made it (the web reader's worker has only one).
39///
40/// ```
41/// use laminapdf_render::TiffWriter;
42///
43/// let mut tiff = TiffWriter::new()?;
44/// tiff.add_page(2, 1, &[255, 0, 0, 255, 0, 0, 255, 255], 300.0)?;
45/// let file = tiff.finish();
46/// assert!(file.starts_with(b"II*\0"));
47/// # Ok::<(), laminapdf_render::RenderError>(())
48/// ```
49///
50/// Added in 0.3.0.
51pub struct TiffWriter {
52    encoder: TiffEncoder<Shared>,
53    file: Shared,
54}
55
56impl std::fmt::Debug for TiffWriter {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        f.debug_struct("TiffWriter")
59            .field("bytes", &self.file.0.borrow().get_ref().len())
60            .finish_non_exhaustive()
61    }
62}
63
64impl TiffWriter {
65    /// An empty file.
66    ///
67    /// # Errors
68    /// [`RenderError::ExportFailed`] if the encoder can't write the file's header.
69    ///
70    /// Added in 0.3.0.
71    pub fn new() -> Result<Self, RenderError> {
72        let file = Shared::default();
73        let encoder = TiffEncoder::new(file.clone())
74            .map_err(|_| failed())?
75            .with_compression(Compression::Deflate(DeflateLevel::Balanced));
76        Ok(Self { encoder, file })
77    }
78
79    /// Adds a page of `width` × `height` straight RGBA pixels, row by row, drawn at `dpi`.
80    ///
81    /// # Errors
82    /// [`RenderError::InvalidRequest`] when `rgba` isn't `width × height × 4` bytes or `dpi`
83    /// isn't a positive finite number; [`RenderError::ExportFailed`] if the encoder fails.
84    ///
85    /// Added in 0.3.0.
86    pub fn add_page(&mut self, width: u32, height: u32, rgba: &[u8], dpi: f64) -> Result<(), RenderError> {
87        let expected = u64::from(width) * u64::from(height) * 4;
88        if width == 0 || height == 0 || rgba.len() as u64 != expected {
89            return Err(RenderError::InvalidRequest {
90                what: "a TIFF page's pixels must be width × height × 4 bytes of RGBA",
91            });
92        }
93        if !dpi.is_finite() || dpi <= 0.0 {
94            return Err(RenderError::InvalidRequest {
95                what: "a TIFF page's resolution must be a positive number of pixels per inch",
96            });
97        }
98        let mut image = self.encoder.new_image::<RGBA8>(width, height).map_err(|_| failed())?;
99        // TIFF resolutions are rationals: hundredths of a dot per inch.
100        #[expect(
101            clippy::cast_possible_truncation,
102            clippy::cast_sign_loss,
103            reason = "clamped to u32's range first"
104        )]
105        let hundredths = (dpi * 100.0).round().clamp(1.0, f64::from(u32::MAX)) as u32;
106        image.resolution(ResolutionUnit::Inch, Rational { n: hundredths, d: 100 });
107        image.write_data(rgba).map_err(|_| failed())
108    }
109
110    /// The file's bytes.
111    ///
112    /// Added in 0.3.0.
113    #[must_use]
114    pub fn finish(self) -> Vec<u8> {
115        let Self { encoder, file } = self;
116        // The encoder's copy of the file goes first, which leaves this one the only owner: the
117        // clone below never runs, but keeps the bytes if a later tiff version kept a copy.
118        drop(encoder);
119        match Rc::try_unwrap(file.0) {
120            Ok(cell) => cell.into_inner().into_inner(),
121            Err(shared) => shared.borrow().get_ref().clone(),
122        }
123    }
124}
125
126fn failed() -> RenderError {
127    RenderError::ExportFailed { format: "tiff" }
128}