Skip to main content

pltrs_codec/tiff/
encode.rs

1//! Baseline TIFF encoding of RGBA images: little-endian, uncompressed, one
2//! strip, unassociated alpha and the resolution in pixels per inch — the
3//! layout Pillow writes for `Image.save(format="tiff", dpi=...)`.
4
5use std::fmt;
6
7use pltrs_core::alloc::{self, OutOfMemory};
8
9/// Why an image could not be encoded.
10#[derive(Clone, Debug, PartialEq, Eq)]
11pub enum TiffError {
12    /// A side is zero.
13    InvalidDimensions {
14        /// The requested width.
15        width: u32,
16        /// The requested height.
17        height: u32,
18    },
19    /// The pixel data does not have `width × height × 4` bytes.
20    DataLengthMismatch {
21        /// The bytes needed.
22        expected: usize,
23        /// The bytes given.
24        actual: usize,
25    },
26    /// The file would pass TIFF's 4 GiB limit.
27    TooLarge,
28    /// The memory for the file cannot be allocated.
29    OutOfMemory(OutOfMemory),
30}
31
32impl fmt::Display for TiffError {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        match self {
35            Self::InvalidDimensions { width, height } => {
36                write!(f, "a TIFF image cannot be {width} × {height} pixels")
37            }
38            Self::DataLengthMismatch { expected, actual } => write!(
39                f,
40                "the image has {actual} bytes of pixel data, expected {expected}"
41            ),
42            Self::TooLarge => f.write_str("the image is too large for a TIFF file"),
43            Self::OutOfMemory(err) => write!(f, "cannot write the TIFF file: {err}"),
44        }
45    }
46}
47
48impl std::error::Error for TiffError {
49    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
50        match self {
51            Self::OutOfMemory(err) => Some(err),
52            _ => None,
53        }
54    }
55}
56
57/// The number of directory entries written.
58const ENTRY_COUNT: u16 = 14;
59
60/// The field types used.
61#[derive(Clone, Copy)]
62enum FieldType {
63    Short = 3,
64    Long = 4,
65    Rational = 5,
66}
67
68/// A directory entry: tag, type, count and the value or the offset of the
69/// values.
70struct Entry {
71    tag: u16,
72    kind: FieldType,
73    count: u32,
74    value: u32,
75}
76
77/// Encodes `width × height` straight RGBA pixels, row by row, as a TIFF
78/// file with a resolution of `dpi` pixels per inch.
79///
80/// ```
81/// let tiff = pltrs_codec::tiff::encode_rgba8(2, 1, &[255; 8], 100.0)?;
82/// assert!(tiff.starts_with(b"II*\0"));
83/// # Ok::<(), pltrs_codec::tiff::TiffError>(())
84/// ```
85///
86/// # Errors
87///
88/// When a side is zero, the data has the wrong length, the file would be
89/// larger than 4 GiB or its memory cannot be allocated.
90pub fn encode_rgba8(width: u32, height: u32, data: &[u8], dpi: f64) -> Result<Vec<u8>, TiffError> {
91    if width == 0 || height == 0 {
92        return Err(TiffError::InvalidDimensions { width, height });
93    }
94    let expected = usize::try_from(u64::from(width) * u64::from(height) * 4)
95        .map_err(|_| TiffError::TooLarge)?;
96    if data.len() != expected {
97        return Err(TiffError::DataLengthMismatch {
98            expected,
99            actual: data.len(),
100        });
101    }
102    // The header, the directory, then the values that do not fit in an
103    // entry: the bits per sample and the two resolutions.
104    let directory_end = 8 + 2 + u32::from(ENTRY_COUNT) * 12 + 4;
105    let bits_at = directory_end;
106    let x_resolution_at = bits_at + 8;
107    let y_resolution_at = x_resolution_at + 8;
108    let strip_at = y_resolution_at + 8;
109    let strip_len = u32::try_from(data.len()).map_err(|_| TiffError::TooLarge)?;
110    strip_at.checked_add(strip_len).ok_or(TiffError::TooLarge)?;
111    let entry = |tag, kind, count, value| Entry {
112        tag,
113        kind,
114        count,
115        value,
116    };
117    let entries = [
118        entry(256, FieldType::Long, 1, width),
119        entry(257, FieldType::Long, 1, height),
120        entry(258, FieldType::Short, 4, bits_at),
121        // No compression.
122        entry(259, FieldType::Short, 1, 1),
123        // RGB.
124        entry(262, FieldType::Short, 1, 2),
125        entry(273, FieldType::Long, 1, strip_at),
126        entry(277, FieldType::Short, 1, 4),
127        entry(278, FieldType::Long, 1, height),
128        entry(279, FieldType::Long, 1, strip_len),
129        entry(282, FieldType::Rational, 1, x_resolution_at),
130        entry(283, FieldType::Rational, 1, y_resolution_at),
131        // Samples interleaved.
132        entry(284, FieldType::Short, 1, 1),
133        // Resolution in inches.
134        entry(296, FieldType::Short, 1, 2),
135        // The fourth sample is unassociated alpha.
136        entry(338, FieldType::Short, 1, 2),
137    ];
138    let mut tiff = alloc::try_with_capacity(data.len() + 256).map_err(TiffError::OutOfMemory)?;
139    tiff.extend_from_slice(b"II*\0");
140    tiff.extend_from_slice(&8_u32.to_le_bytes());
141    tiff.extend_from_slice(
142        &u16::try_from(entries.len())
143            .expect("14 entries")
144            .to_le_bytes(),
145    );
146    for entry in &entries {
147        tiff.extend_from_slice(&entry.tag.to_le_bytes());
148        tiff.extend_from_slice(&(entry.kind as u16).to_le_bytes());
149        tiff.extend_from_slice(&entry.count.to_le_bytes());
150        match (entry.kind, entry.count) {
151            // A single short sits in the first two bytes of the field.
152            (FieldType::Short, 1) => {
153                let short = u16::try_from(entry.value).expect("short values fit");
154                tiff.extend_from_slice(&short.to_le_bytes());
155                tiff.extend_from_slice(&[0, 0]);
156            }
157            _ => tiff.extend_from_slice(&entry.value.to_le_bytes()),
158        }
159    }
160    tiff.extend_from_slice(&0_u32.to_le_bytes());
161    for _ in 0..4 {
162        tiff.extend_from_slice(&8_u16.to_le_bytes());
163    }
164    let (numerator, denominator) = rational(dpi);
165    for _ in 0..2 {
166        tiff.extend_from_slice(&numerator.to_le_bytes());
167        tiff.extend_from_slice(&denominator.to_le_bytes());
168    }
169    tiff.extend_from_slice(data);
170    Ok(tiff)
171}
172
173/// The closest fraction to a positive `value` with 32-bit terms, by
174/// continued fractions; values that are not finite and positive give
175/// `1/1`.
176fn rational(value: f64) -> (u32, u32) {
177    if !(value.is_finite() && value > 0.0) {
178        return (1, 1);
179    }
180    let limit = f64::from(u32::MAX);
181    if value >= limit {
182        return (u32::MAX, 1);
183    }
184    // Convergents h/k of the continued fraction of `value`.
185    let (mut h, mut h_prev) = (1.0_f64, 0.0_f64);
186    let (mut k, mut k_prev) = (0.0_f64, 1.0_f64);
187    let mut rest = value;
188    let mut best = (value.round().max(1.0), 1.0);
189    for _ in 0..64 {
190        let term = rest.floor();
191        let (h_next, k_next) = (term * h + h_prev, term * k + k_prev);
192        if h_next > limit || k_next > limit {
193            break;
194        }
195        (h_prev, h, k_prev, k) = (h, h_next, k, k_next);
196        if h > 0.0 {
197            best = (h, k);
198        }
199        let fraction = rest - term;
200        if fraction < 1e-12 || (h / k - value).abs() <= f64::EPSILON * value {
201            break;
202        }
203        rest = 1.0 / fraction;
204    }
205    let term = |x: f64| {
206        // Convergents are whole numbers within u32 by construction.
207        x as u32
208    };
209    (term(best.0), term(best.1))
210}
211
212#[cfg(test)]
213mod tests {
214    use super::*;
215
216    fn u16_at(data: &[u8], at: usize) -> u16 {
217        u16::from_le_bytes([data[at], data[at + 1]])
218    }
219
220    fn u32_at(data: &[u8], at: usize) -> u32 {
221        u32::from_le_bytes(data[at..at + 4].try_into().unwrap())
222    }
223
224    #[test]
225    fn layout_matches_pillow() {
226        let pixels: Vec<u8> = (0..24).collect();
227        let tiff = encode_rgba8(3, 2, &pixels, 100.0).unwrap();
228        assert_eq!(tiff.len(), 230, "Pillow's file for the same image");
229        assert_eq!(u16_at(&tiff, 8), 14);
230        let tags: Vec<_> = (0..14).map(|i| u16_at(&tiff, 10 + 12 * i)).collect();
231        assert_eq!(
232            tags,
233            [
234                256, 257, 258, 259, 262, 273, 277, 278, 279, 282, 283, 284, 296, 338
235            ]
236        );
237        assert_eq!(u32_at(&tiff, 10 + 12 * 5 + 8), 206, "strip offset");
238        assert_eq!(&tiff[206..], &pixels[..]);
239        assert_eq!((u32_at(&tiff, 190), u32_at(&tiff, 194)), (100, 1));
240    }
241
242    #[test]
243    fn resolutions_become_fractions() {
244        assert_eq!(rational(72.0), (72, 1));
245        assert_eq!(rational(72.5), (145, 2));
246        assert_eq!(rational(0.1), (1, 10));
247        assert_eq!(rational(f64::NAN), (1, 1));
248        assert_eq!(rational(1e12), (u32::MAX, 1));
249        let (n, d) = rational(std::f64::consts::PI);
250        assert!((f64::from(n) / f64::from(d) - std::f64::consts::PI).abs() < 1e-15);
251    }
252
253    #[test]
254    fn bad_input_is_rejected() {
255        assert_eq!(
256            encode_rgba8(0, 1, &[], 72.0),
257            Err(TiffError::InvalidDimensions {
258                width: 0,
259                height: 1
260            })
261        );
262        assert_eq!(
263            encode_rgba8(1, 1, &[0; 3], 72.0),
264            Err(TiffError::DataLengthMismatch {
265                expected: 4,
266                actual: 3
267            })
268        );
269    }
270}