Skip to main content

utopia_image/
format.rs

1//! The raster formats an image may be read from, told apart by signature.
2
3use crate::error::{Error, Result};
4
5/// A raster format [`Image::new`](crate::Image::new) accepts, identified
6/// from the file signature, so only decoders for these formats ever see the
7/// data.
8///
9/// ```
10/// use utopia_image::Format;
11///
12/// assert_eq!(Format::detect(b"\x89PNG\r\n\x1a\n")?, Format::Png);
13/// assert_eq!(Format::Png.value(), "PNG");
14/// assert!(Format::detect(b"P3\n1 1\n255\n").is_err());
15/// # Ok::<(), utopia_image::Error>(())
16/// ```
17///
18/// ```php
19/// use Utopia\Image\Format;
20///
21/// echo Format::detect("\x89PNG\r\n\x1A\n")->value, "\n"; // PNG
22/// try {
23///     Format::detect("P3\n1 1\n255\n");
24/// } catch (\Utopia\Image\Exception\UnsupportedFormatException $e) {
25///     echo $e->getMessage(), "\n";
26/// }
27/// ```
28///
29/// PHP: `Utopia\Image\Format` (a string-backed enum).
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
31pub enum Format {
32    /// PHP: `Format::Jpeg` (`JPEG`).
33    Jpeg,
34    /// PHP: `Format::Png` (`PNG`).
35    Png,
36    /// PHP: `Format::Gif` (`GIF`).
37    Gif,
38    /// PHP: `Format::Webp` (`WEBP`).
39    Webp,
40    /// PHP: `Format::Avif` (`AVIF`).
41    Avif,
42    /// PHP: `Format::Heic` (`HEIC`).
43    Heic,
44}
45
46const AVIF_BRANDS: [&[u8]; 2] = [b"avif", b"avis"];
47
48const HEIC_BRANDS: [&[u8]; 10] =
49    [b"heic", b"heix", b"hevc", b"hevx", b"heim", b"heis", b"hevm", b"hevs", b"mif1", b"msf1"];
50
51const HEADER_LENGTH: i64 = 8;
52
53/// A box size of 1 means a 64-bit size follows the box type, so the brands
54/// start after it.
55const EXTENDED_SIZE: i64 = 1;
56
57const EXTENDED_HEADER_LENGTH: i64 = 16;
58
59const BRAND_LENGTH: i64 = 4;
60
61/// Upper bound on the bytes of a file type box that are inspected; real
62/// boxes hold a handful of brands.
63const FILE_TYPE_BOX_LIMIT: i64 = 4096;
64
65impl Format {
66    /// The enum's backing value, ImageMagick's name for the format (`JPEG`,
67    /// `PNG`, `GIF`, `WEBP`, `AVIF`, `HEIC`).
68    ///
69    /// PHP: `$format->value`.
70    pub fn value(self) -> &'static str {
71        match self {
72            Format::Jpeg => "JPEG",
73            Format::Png => "PNG",
74            Format::Gif => "GIF",
75            Format::Webp => "WEBP",
76            Format::Avif => "AVIF",
77            Format::Heic => "HEIC",
78        }
79    }
80
81    /// The format the data's signature announces: JPEG, PNG, GIF87a/89a,
82    /// a RIFF WebP, or an ISO base media file whose file type box lists an
83    /// AVIF brand (AVIF) or a HEIF brand (HEIC), among its first 4096
84    /// bytes.
85    ///
86    /// Fails with [`Error::UnsupportedFormat`] for anything else.
87    ///
88    /// PHP: `Format::detect($data)`.
89    pub fn detect(data: &[u8]) -> Result<Format> {
90        if data.starts_with(&[0xFF, 0xD8, 0xFF]) {
91            Ok(Format::Jpeg)
92        } else if data.starts_with(b"\x89PNG\r\n\x1a\n") {
93            Ok(Format::Png)
94        } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
95            Ok(Format::Gif)
96        } else if data.starts_with(b"RIFF") && data.get(8..12) == Some(b"WEBP") {
97            Ok(Format::Webp)
98        } else if data.get(4..8) == Some(b"ftyp") {
99            from_brands(data)
100        } else {
101            Err(Error::unsupported())
102        }
103    }
104}
105
106fn from_brands(data: &[u8]) -> Result<Format> {
107    let mut size = read_size(data, 4, 0);
108    let mut start = HEADER_LENGTH;
109    if size == EXTENDED_SIZE {
110        size = read_size(data, 8, HEADER_LENGTH as usize);
111        start = EXTENDED_HEADER_LENGTH;
112    }
113    let length = i64::try_from(data.len()).unwrap_or(i64::MAX);
114    let end = size.min(FILE_TYPE_BOX_LIMIT).min(length);
115    let minor_version = start + BRAND_LENGTH;
116
117    let mut heic = false;
118    let mut offset = start;
119    while offset + BRAND_LENGTH <= end {
120        if offset != minor_version {
121            let brand = &data[offset as usize..(offset + BRAND_LENGTH) as usize];
122            if AVIF_BRANDS.contains(&brand) {
123                return Ok(Format::Avif);
124            }
125            heic = heic || HEIC_BRANDS.contains(&brand);
126        }
127        offset += BRAND_LENGTH;
128    }
129    if heic { Ok(Format::Heic) } else { Err(Error::unsupported()) }
130}
131
132/// A big-endian box size of `width` bytes at `offset` (`unpack('N')` or
133/// `unpack('J')`, the 64-bit one read as PHP's signed integer); 0 when the
134/// data is too short.
135fn read_size(data: &[u8], width: usize, offset: usize) -> i64 {
136    let Some(bytes) = data.get(offset..offset + width) else {
137        return 0;
138    };
139    bytes.iter().fold(0u64, |size, &b| (size << 8) | u64::from(b)) as i64
140}