Skip to main content

rust_motion_affinity/
preview.rs

1//! The indexed PNG thumbnail Affinity stores next to the archive: Affinity's own render of the
2//! document, at most 512 pixels on the long side in real files, never the document itself.
3
4use crate::container::header;
5use crate::Error;
6
7pub const MAX_PREVIEW_BYTES: usize = 16 << 20;
8pub const MAX_PREVIEW_DIMENSION: u32 = 4096;
9
10/// Borrowed embedded thumbnail, at its own dimensions, never the native document dimensions.
11#[derive(Debug)]
12pub struct Preview<'a> {
13    pub png: &'a [u8],
14    pub width: u32,
15    pub height: u32,
16}
17
18fn bytes_at(bytes: &[u8], offset: usize, length: usize) -> Result<&[u8], Error> {
19    let end = offset
20        .checked_add(length)
21        .ok_or(Error::Malformed("offset overflow"))?;
22    bytes
23        .get(offset..end)
24        .ok_or(Error::Malformed("truncated record"))
25}
26
27fn le32(bytes: &[u8], offset: usize) -> Result<u32, Error> {
28    let b = bytes_at(bytes, offset, 4)?;
29    Ok(u32::from_le_bytes(
30        b.try_into().map_err(|_| Error::Malformed("integer"))?,
31    ))
32}
33
34fn be32(bytes: &[u8], offset: usize) -> Result<u32, Error> {
35    let b = bytes_at(bytes, offset, 4)?;
36    Ok(u32::from_be_bytes(
37        b.try_into().map_err(|_| Error::Malformed("PNG integer"))?,
38    ))
39}
40
41/// Read only the indexed `Thmb` record (identical in container versions 8 to 12), checking every PNG chunk CRC. Compressed
42/// pixels must still be validated by the consuming image decoder, with allocation limits.
43pub fn preview(bytes: &[u8]) -> Result<Preview<'_>, Error> {
44    let h = header(bytes)?;
45    if h.thumbnail_offset == 0 {
46        return Err(Error::Unsupported("no embedded preview"));
47    }
48    let offset = usize::try_from(h.thumbnail_offset)
49        .map_err(|_| Error::Malformed("thumbnail offset overflow"))?;
50    if offset < 72 {
51        return Err(Error::Malformed("thumbnail overlaps the file header"));
52    }
53    let record = bytes
54        .get(offset..)
55        .ok_or(Error::Malformed("thumbnail offset outside file"))?;
56    if bytes_at(record, 0, 8)? != b"\xff\xff\xff\xffThmb" {
57        return Err(Error::Malformed("missing indexed thumbnail"));
58    }
59    if le32(record, 8)? != 1 || bytes_at(record, 28, 1)? != [1] {
60        return Err(Error::Unsupported("thumbnail record version or encoding"));
61    }
62    let size = usize::try_from(le32(record, 24)?).map_err(|_| Error::Limit("encoded size"))?;
63    if size > MAX_PREVIEW_BYTES {
64        return Err(Error::Limit("encoded preview exceeds 16 MiB"));
65    }
66    if le32(record, 16)? != 29
67        || le32(record, 20)? != 0
68        || u64::from(le32(record, 12)?) != size as u64 + 13
69    {
70        return Err(Error::Malformed("inconsistent thumbnail record lengths"));
71    }
72    let png = bytes_at(record, 29, size)?;
73    if bytes_at(png, 0, 8)? != b"\x89PNG\r\n\x1a\n"
74        || be32(png, 8)? != 13
75        || bytes_at(png, 12, 4)? != b"IHDR"
76    {
77        return Err(Error::Malformed("thumbnail is not a PNG"));
78    }
79    let width = be32(png, 16)?;
80    let height = be32(png, 20)?;
81    if width == 0 || height == 0 || width > MAX_PREVIEW_DIMENSION || height > MAX_PREVIEW_DIMENSION
82    {
83        return Err(Error::Limit("preview dimensions must be 1..4096"));
84    }
85    // Bound work by bytes, not a file-supplied chunk count, and require exactly one complete PNG.
86    let mut pos = 8usize;
87    let (mut palette, mut image_data, mut image_data_ended) = (false, false, false);
88    loop {
89        let length =
90            usize::try_from(be32(png, pos)?).map_err(|_| Error::Limit("PNG chunk length"))?;
91        let chunk_size = length
92            .checked_add(12)
93            .ok_or(Error::Malformed("PNG chunk overflow"))?;
94        let chunk = bytes_at(png, pos, chunk_size)?;
95        let checksum_input = bytes_at(chunk, 4, chunk_size - 8)?;
96        if crc32fast::hash(checksum_input) != be32(chunk, chunk_size - 4)? {
97            return Err(Error::Malformed("PNG chunk checksum"));
98        }
99        let kind = bytes_at(chunk, 4, 4)?;
100        if !kind.iter().all(u8::is_ascii_alphabetic) {
101            return Err(Error::Malformed("PNG chunk type"));
102        }
103        match kind {
104            b"IHDR" if pos == 8 => {}
105            b"IHDR" => return Err(Error::Malformed("duplicate PNG header")),
106            b"PLTE" => {
107                if palette || image_data {
108                    return Err(Error::Malformed("PNG palette order"));
109                }
110                palette = true;
111            }
112            b"IDAT" => {
113                if image_data_ended {
114                    return Err(Error::Malformed("non-contiguous PNG image data"));
115                }
116                image_data = true;
117            }
118            b"IEND" => {
119                if !image_data {
120                    return Err(Error::Malformed("PNG has no image data"));
121                }
122            }
123            _ if kind.first().is_some_and(u8::is_ascii_uppercase) => {
124                return Err(Error::Unsupported("unknown critical PNG chunk"));
125            }
126            _ => {}
127        }
128        if image_data && kind != b"IDAT" {
129            image_data_ended = true;
130        }
131        // Native sample previews are plain, single-frame PNGs. Pixel allocation limits do not
132        // necessarily bound aggregate compressed metadata; leave these layouts unsupported.
133        if matches!(kind, b"zTXt" | b"iTXt" | b"iCCP") {
134            return Err(Error::Unsupported("compressed PNG metadata in the preview"));
135        }
136        if matches!(kind, b"acTL" | b"fcTL" | b"fdAT") {
137            return Err(Error::Unsupported("animated PNG preview"));
138        }
139        pos = pos
140            .checked_add(chunk_size)
141            .ok_or(Error::Malformed("PNG offset overflow"))?;
142        if kind == b"IEND" {
143            if length != 0 || pos != png.len() {
144                return Err(Error::Malformed("PNG end or trailing data"));
145            }
146            break;
147        }
148    }
149    Ok(Preview { png, width, height })
150}