forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

exif.rs46 lines, 1.7 KiBHistoryRawDownload
1//! EXIF orientation, read from the TIFF block that JPEG, WebP and PNG all carry.
2//!
3//! The TIFF block is bare in WebP's `EXIF` chunk and in PNG's `eXIf` chunk (PNG 1.5
4//! and libwebp both define it that way, and `image` reads it that way). JPEG's APP1
5//! segment puts an `Exif\0\0` header in front, which the JPEG reader strips. Only
6//! IFD0's orientation tag (0x0112) is read, which is the one the EXIF spec defines.
7
8/// Orientation 1..=8 from a bare TIFF block, or `None` if the block is not a
9/// readable TIFF or carries no valid orientation entry.
10pub(crate) fn tiff_orientation(tiff: &[u8]) -> Option<u8> {
11 let little = match tiff.get(..2)? {
12 b"II" => true,
13 b"MM" => false,
14 _ => return None,
15 };
16 let u16_at = |at: usize| -> Option<u16> {
17 let b = tiff.get(at..at + 2)?;
18 Some(if little {
19 u16::from_le_bytes([b[0], b[1]])
20 } else {
21 u16::from_be_bytes([b[0], b[1]])
22 })
23 };
24 let u32_at = |at: usize| -> Option<u32> {
25 let b = tiff.get(at..at + 4)?;
26 Some(if little {
27 u32::from_le_bytes([b[0], b[1], b[2], b[3]])
28 } else {
29 u32::from_be_bytes([b[0], b[1], b[2], b[3]])
30 })
31 };
32 if u16_at(2)? != 42 {
33 return None;
34 }
35 let ifd = u32_at(4)? as usize;
36 let count = usize::from(u16_at(ifd)?);
37 for i in 0..count {
38 let entry = ifd + 2 + i * 12;
39 // Tag 0x0112, type SHORT (3), one value: the value sits in the first two bytes of the field.
40 if u16_at(entry)? == 0x0112 && u16_at(entry + 2)? == 3 && u32_at(entry + 4)? == 1 {
41 let value = u16_at(entry + 8)?;
42 return (1..=8).contains(&value).then_some(value as u8);
43 }
44 }
45 None
46}