Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_graphics/src/sniff.rs

3.8 KiB, 1 run

created by r1870400018:72300, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! Telling an image's format from its leading bytes.
2//!
3//! A file's name is a claim and its bytes are the fact: Zoapedia's prototype held three `.jpg`
4//! files that were PNGs, and a decoder chosen by the extension refused them. This reads the
5//! signature only, so it is cheap enough to run on every upload before anything is decoded.
6
7use crate::heif::Heif;
8use crate::jpeg;
9use crate::png;
10
11use oxedyne_fe2o3_core::prelude::*;
12
13/// A still-image format this crate decodes.
14#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
15pub enum ImageKind {
16 Jpeg,
17 Png,
18 Heic, // HEIF holding an HEVC picture
19}
20
21impl ImageKind {
22
23 pub fn mime(self) -> &'static str {
24 match self {
25 Self::Jpeg => "image/jpeg",
26 Self::Png => "image/png",
27 Self::Heic => "image/heic",
28 }
29 }
30
31 /// The usual file extension, without the dot.
32 pub fn ext(self) -> &'static str {
33 match self {
34 Self::Jpeg => "jpg",
35 Self::Png => "png",
36 Self::Heic => "heic",
37 }
38 }
39
40 /// The kind a MIME type names, the inverse of [`Self::mime`].
41 pub fn from_mime(s: &str) -> Option<Self> {
42 match s {
43 "image/jpeg" => Some(Self::Jpeg),
44 "image/png" => Some(Self::Png),
45 "image/heic" => Some(Self::Heic),
46 _ => None,
47 }
48 }
49
50 /// The width and height in pixels as coded, read from the header without decoding the
51 /// picture. Neither an Exif orientation nor a HEIF `irot` is applied, so the three formats
52 /// answer alike.
53 pub fn dimensions(self, buf: &[u8]) -> Outcome<(u32, u32)> {
54 let (w, h) = match self {
55 Self::Jpeg => res!(jpeg::dimensions(buf)),
56 Self::Png => res!(png::dimensions(buf)),
57 Self::Heic => {
58 let (w, h) = res!(res!(Heif::head(buf)).extent());
59 (w as usize, h as usize)
60 }
61 };
62 let w = res!(u32::try_from(w));
63 let h = res!(u32::try_from(h));
64 Ok((w, h))
65 }
66}
67
68const PNG_SIG: [u8; 8] = *b"\x89PNG\r\n\x1a\n";
69const HEIC_BRANDS: [&[u8; 4]; 4] = [b"heic", b"heix", b"heim", b"heis"];
70
71/// The format the leading bytes announce, or `None` for anything else. Only the signature is
72/// read, so a `Some` says what to decode with, not that the decode will succeed.
73pub fn sniff(buf: &[u8]) -> Option<ImageKind> {
74 if buf.starts_with(&PNG_SIG) {
75 return Some(ImageKind::Png);
76 }
77 if buf.starts_with(&[0xFF, 0xD8, 0xFF]) {
78 return Some(ImageKind::Jpeg);
79 }
80 // An ISO-BMFF `ftyp` box: size, "ftyp", major brand, minor version, compatible brands. A `mif1`
81 // file names its codec among the compatible brands, so every brand is looked at.
82 if buf.len() >= 16 && &buf[4..8] == b"ftyp" {
83 let size = u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]) as usize;
84 let end = size.min(buf.len());
85 if size < 16 {
86 return None;
87 }
88 let major = &buf[8..12];
89 let compat = buf[16..end].chunks_exact(4);
90 let is_heic = |b: &[u8]| HEIC_BRANDS.iter().any(|h| &h[..] == b);
91 if is_heic(major) || compat.into_iter().any(is_heic) {
92 return Some(ImageKind::Heic);
93 }
94 }
95 None
96}
97
98#[cfg(test)]
99mod tests {
100 use super::*;
101
102 #[test]
103 fn signatures_decide() {
104 assert_eq!(sniff(b"\x89PNG\r\n\x1a\n\0\0\0\x0dIHDR"), Some(ImageKind::Png));
105 assert_eq!(sniff(&[0xFF, 0xD8, 0xFF, 0xE0, 0, 16]), Some(ImageKind::Jpeg));
106 assert_eq!(sniff(b"\0\0\0\x18ftypheic\0\0\0\0mif1heic"), Some(ImageKind::Heic));
107 assert_eq!(sniff(b"\0\0\0\x18ftypmif1\0\0\0\0mif1heic"), Some(ImageKind::Heic));
108 }
109
110 #[test]
111 fn others_refused() {
112 assert_eq!(sniff(b""), None);
113 assert_eq!(sniff(b"\x89PN"), None);
114 assert_eq!(sniff(b"<svg xmlns=\"http://www.w3.org/2000/svg\"/>"), None);
115 assert_eq!(sniff(b"GIF89a\x01\0\x01\0"), None);
116 assert_eq!(sniff(b"\0\0\0\x18ftypavif\0\0\0\0mif1avif"), None, "AV1 is not decoded here");
117 assert_eq!(sniff(b"\0\0\0\x18ftypisom\0\0\0\0isomavc1"), None, "a video is not an image");
118 }
119
120 #[test]
121 fn mime_round_trips() {
122 for k in [ImageKind::Jpeg, ImageKind::Png, ImageKind::Heic] {
123 assert_eq!(ImageKind::from_mime(k.mime()), Some(k));
124 }
125 }
126}