Skip to main content

asset_io/
tiff.rs

1// Copyright 2026 Adobe. All rights reserved.
2// This file is licensed to you under the Apache License,
3// Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
4// or the MIT license (http://opensource.org/licenses/MIT),
5// at your option.
6
7// Unless required by applicable law or agreed to in writing,
8// this software is distributed on an "AS IS" BASIS, WITHOUT
9// WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
10// implied. See the LICENSE-MIT and LICENSE-APACHE files for the
11// specific language governing permissions and limitations under
12// each license.
13
14//! Minimal TIFF/EXIF parser
15//!
16//! This module provides lightweight TIFF parsing for:
17//! - Extracting embedded thumbnails from EXIF data
18//! - Reading basic EXIF metadata (Make, Model, DateTime, etc.)
19//!
20//! TIFF/DNG container support is the `tiff` feature.
21//!
22//! TIFF Structure:
23//! - Header: byte order (II/MM), magic (0x002A), IFD offset
24//! - IFD (Image File Directory): tag count, tags (12 bytes each), next IFD offset
25//! - Tags: tag ID (2), type (2), count (4), value/offset (4)
26
27use std::io::{Cursor, Read, Seek, SeekFrom};
28
29use crate::{error::Result, item::ItemKind, structure::Structure, thumbnail::Thumbnail};
30
31/// TIFF/EXIF tag IDs
32#[allow(dead_code)]
33mod tags {
34    // IFD0 (main image) tags
35    pub const IMAGE_WIDTH: u16 = 0x0100;
36    pub const IMAGE_LENGTH: u16 = 0x0101;
37    pub const MAKE: u16 = 0x010f;
38    pub const MODEL: u16 = 0x0110;
39    pub const ORIENTATION: u16 = 0x0112;
40    pub const SOFTWARE: u16 = 0x0131;
41    pub const DATE_TIME: u16 = 0x0132;
42    pub const ARTIST: u16 = 0x013b;
43    pub const COPYRIGHT: u16 = 0x8298;
44    pub const EXIF_IFD_POINTER: u16 = 0x8769;
45
46    // EXIF sub-IFD tags
47    pub const EXPOSURE_TIME: u16 = 0x829a;
48    pub const F_NUMBER: u16 = 0x829d;
49    pub const ISO_SPEED: u16 = 0x8827;
50    pub const DATE_TIME_ORIGINAL: u16 = 0x9003;
51    pub const FOCAL_LENGTH: u16 = 0x920a;
52
53    // IFD1 (thumbnail) tags
54    pub const JPEG_INTERCHANGE_FORMAT: u16 = 0x0201;
55    pub const JPEG_INTERCHANGE_FORMAT_LENGTH: u16 = 0x0202;
56}
57
58/// TIFF data types
59#[allow(dead_code)]
60mod types {
61    pub const BYTE: u16 = 1;
62    pub const ASCII: u16 = 2;
63    pub const SHORT: u16 = 3;
64    pub const LONG: u16 = 4;
65    pub const RATIONAL: u16 = 5;
66}
67
68/// Byte order for reading multi-byte values
69#[derive(Debug, Clone, Copy)]
70enum ByteOrder {
71    LittleEndian,
72    BigEndian,
73}
74
75impl ByteOrder {
76    fn read_u16(&self, data: &[u8]) -> u16 {
77        match self {
78            ByteOrder::LittleEndian => u16::from_le_bytes([data[0], data[1]]),
79            ByteOrder::BigEndian => u16::from_be_bytes([data[0], data[1]]),
80        }
81    }
82
83    fn read_u32(&self, data: &[u8]) -> u32 {
84        match self {
85            ByteOrder::LittleEndian => u32::from_le_bytes([data[0], data[1], data[2], data[3]]),
86            ByteOrder::BigEndian => u32::from_be_bytes([data[0], data[1], data[2], data[3]]),
87        }
88    }
89}
90
91/// Information about an embedded thumbnail
92#[derive(Debug)]
93pub struct ThumbnailInfo {
94    /// Offset of thumbnail JPEG data within the EXIF segment
95    pub offset: u32,
96    /// Size of thumbnail JPEG data in bytes
97    pub size: u32,
98    /// Width in pixels (if present)
99    pub width: Option<u32>,
100    /// Height in pixels (if present)
101    pub height: Option<u32>,
102}
103
104/// Basic EXIF metadata extracted from IFD0
105#[derive(Debug, Default)]
106#[non_exhaustive]
107pub struct ExifInfo {
108    /// Camera manufacturer (e.g., "Canon", "Nikon")
109    pub make: Option<String>,
110    /// Camera model (e.g., "EOS R5", "D850")
111    pub model: Option<String>,
112    /// Image orientation (1-8, where 1 is normal)
113    pub orientation: Option<u16>,
114    /// Software used to create/edit the image
115    pub software: Option<String>,
116    /// Date and time of image creation (format: "YYYY:MM:DD HH:MM:SS")
117    pub date_time: Option<String>,
118    /// Original capture date/time (from EXIF sub-IFD)
119    pub date_time_original: Option<String>,
120    /// Artist/photographer name
121    pub artist: Option<String>,
122    /// Copyright notice
123    pub copyright: Option<String>,
124}
125
126impl std::fmt::Display for ExifInfo {
127    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
128        let mut parts = Vec::new();
129        if let Some(ref make) = self.make {
130            parts.push(make.clone());
131        }
132        if let Some(ref model) = self.model {
133            parts.push(model.clone());
134        }
135        if let Some(dt) = self.date_time_original.as_ref().or(self.date_time.as_ref()) {
136            parts.push(dt.clone());
137        }
138        if parts.is_empty() {
139            write!(f, "(no metadata)")
140        } else {
141            write!(f, "{}", parts.join(" | "))
142        }
143    }
144}
145
146/// Maximum number of tags in an IFD (prevents DOS attacks)
147const MAX_IFD_TAGS: u16 = 1000;
148
149/// Parse EXIF data to find embedded thumbnail location
150///
151/// This expects the EXIF data starting AFTER the "Exif\0\0" signature,
152/// i.e., starting with the TIFF header.
153pub fn parse_thumbnail_info(exif_data: &[u8]) -> Result<Option<ThumbnailInfo>> {
154    if exif_data.len() < 8 {
155        return Ok(None);
156    }
157
158    let mut cursor = Cursor::new(exif_data);
159
160    // Parse TIFF header
161    let mut header = [0u8; 8];
162    cursor.read_exact(&mut header)?;
163
164    // Byte order: "II" (0x4949) = little endian, "MM" (0x4D4D) = big endian
165    let byte_order = match &header[0..2] {
166        b"II" => ByteOrder::LittleEndian,
167        b"MM" => ByteOrder::BigEndian,
168        _ => return Ok(None), // Not valid TIFF
169    };
170
171    // Check magic number (0x002A)
172    let magic = byte_order.read_u16(&header[2..4]);
173    if magic != 0x002a {
174        return Ok(None);
175    }
176
177    // Get IFD0 offset
178    let ifd0_offset = byte_order.read_u32(&header[4..8]);
179
180    // Validate IFD0 offset is within bounds
181    if ifd0_offset as usize >= exif_data.len() {
182        return Ok(None); // Invalid offset
183    }
184
185    // Parse IFD0 to find IFD1 offset
186    let ifd1_offset = match parse_ifd(&mut cursor, ifd0_offset, byte_order, exif_data.len())? {
187        Some(offset) => offset,
188        None => return Ok(None), // No IFD1
189    };
190
191    // Validate IFD1 offset is within bounds
192    if ifd1_offset as usize >= exif_data.len() {
193        return Ok(None); // Invalid offset
194    }
195
196    // Parse IFD1 to find thumbnail tags
197    parse_thumbnail_from_ifd(&mut cursor, ifd1_offset, byte_order, exif_data.len())
198}
199
200/// Parse EXIF data to extract basic metadata
201///
202/// This expects the EXIF data starting AFTER the "Exif\0\0" signature,
203/// i.e., starting with the TIFF header.
204pub fn parse_exif_info(exif_data: &[u8]) -> Result<Option<ExifInfo>> {
205    if exif_data.len() < 8 {
206        return Ok(None);
207    }
208
209    let mut cursor = Cursor::new(exif_data);
210
211    // Parse TIFF header
212    let mut header = [0u8; 8];
213    cursor.read_exact(&mut header)?;
214
215    let byte_order = match &header[0..2] {
216        b"II" => ByteOrder::LittleEndian,
217        b"MM" => ByteOrder::BigEndian,
218        _ => return Ok(None),
219    };
220
221    let magic = byte_order.read_u16(&header[2..4]);
222    if magic != 0x002a {
223        return Ok(None);
224    }
225
226    let ifd0_offset = byte_order.read_u32(&header[4..8]);
227    if ifd0_offset as usize >= exif_data.len() {
228        return Ok(None);
229    }
230
231    // Parse IFD0 for basic EXIF info
232    parse_exif_from_ifd(&cursor, ifd0_offset, byte_order, exif_data)
233}
234
235/// Parse IFD0 to extract basic EXIF metadata
236fn parse_exif_from_ifd(
237    cursor: &Cursor<&[u8]>,
238    offset: u32,
239    byte_order: ByteOrder,
240    data: &[u8],
241) -> Result<Option<ExifInfo>> {
242    if offset as usize >= data.len() {
243        return Ok(None);
244    }
245
246    let mut cursor = cursor.clone();
247    cursor.seek(SeekFrom::Start(offset as u64))?;
248
249    let mut count_bytes = [0u8; 2];
250    if cursor.read_exact(&mut count_bytes).is_err() {
251        return Ok(None);
252    }
253    let tag_count = byte_order.read_u16(&count_bytes);
254
255    if tag_count > MAX_IFD_TAGS {
256        return Ok(None);
257    }
258
259    let mut info = ExifInfo::default();
260    let mut exif_ifd_offset: Option<u32> = None;
261
262    for _ in 0..tag_count {
263        let mut tag_bytes = [0u8; 12];
264        if cursor.read_exact(&mut tag_bytes).is_err() {
265            break;
266        }
267
268        let tag_id = byte_order.read_u16(&tag_bytes[0..2]);
269        let tag_type = byte_order.read_u16(&tag_bytes[2..4]);
270        let count = byte_order.read_u32(&tag_bytes[4..8]);
271        let value_or_offset = byte_order.read_u32(&tag_bytes[8..12]);
272
273        match tag_id {
274            tags::MAKE => {
275                info.make = read_ascii_tag(data, tag_type, count, value_or_offset, byte_order);
276            }
277            tags::MODEL => {
278                info.model = read_ascii_tag(data, tag_type, count, value_or_offset, byte_order);
279            }
280            tags::ORIENTATION if tag_type == types::SHORT => {
281                info.orientation = Some(value_or_offset as u16)
282            }
283            tags::SOFTWARE => {
284                info.software = read_ascii_tag(data, tag_type, count, value_or_offset, byte_order);
285            }
286            tags::DATE_TIME => {
287                info.date_time = read_ascii_tag(data, tag_type, count, value_or_offset, byte_order);
288            }
289            tags::ARTIST => {
290                info.artist = read_ascii_tag(data, tag_type, count, value_or_offset, byte_order);
291            }
292            tags::COPYRIGHT => {
293                info.copyright = read_ascii_tag(data, tag_type, count, value_or_offset, byte_order);
294            }
295            tags::EXIF_IFD_POINTER if tag_type == types::LONG => {
296                exif_ifd_offset = Some(value_or_offset)
297            }
298            _ => {}
299        }
300    }
301
302    // Parse EXIF sub-IFD for DateTimeOriginal if present
303    if let Some(exif_offset) = exif_ifd_offset {
304        if let Some(dt_orig) = parse_exif_subifd_datetime(data, exif_offset, byte_order) {
305            info.date_time_original = Some(dt_orig);
306        }
307    }
308
309    Ok(Some(info))
310}
311
312/// Read an ASCII string tag value
313fn read_ascii_tag(
314    data: &[u8],
315    tag_type: u16,
316    count: u32,
317    value_or_offset: u32,
318    byte_order: ByteOrder,
319) -> Option<String> {
320    if tag_type != types::ASCII || count == 0 {
321        return None;
322    }
323
324    let bytes = if count <= 4 {
325        // Value is inline in the tag
326        let val_bytes = match byte_order {
327            ByteOrder::LittleEndian => value_or_offset.to_le_bytes(),
328            ByteOrder::BigEndian => value_or_offset.to_be_bytes(),
329        };
330        val_bytes[..count as usize].to_vec()
331    } else {
332        // Value is at offset
333        let offset = value_or_offset as usize;
334        let end = offset + count as usize;
335        if end > data.len() {
336            return None;
337        }
338        data[offset..end].to_vec()
339    };
340
341    // Convert to string, trimming null terminator
342    String::from_utf8(bytes)
343        .ok()
344        .map(|s| s.trim_end_matches('\0').trim().to_string())
345        .filter(|s| !s.is_empty())
346}
347
348/// Parse EXIF sub-IFD to get DateTimeOriginal
349fn parse_exif_subifd_datetime(data: &[u8], offset: u32, byte_order: ByteOrder) -> Option<String> {
350    if offset as usize >= data.len() {
351        return None;
352    }
353
354    let mut cursor = Cursor::new(data);
355    cursor.seek(SeekFrom::Start(offset as u64)).ok()?;
356
357    let mut count_bytes = [0u8; 2];
358    cursor.read_exact(&mut count_bytes).ok()?;
359    let tag_count = byte_order.read_u16(&count_bytes);
360
361    if tag_count > MAX_IFD_TAGS {
362        return None;
363    }
364
365    for _ in 0..tag_count {
366        let mut tag_bytes = [0u8; 12];
367        if cursor.read_exact(&mut tag_bytes).is_err() {
368            break;
369        }
370
371        let tag_id = byte_order.read_u16(&tag_bytes[0..2]);
372        let tag_type = byte_order.read_u16(&tag_bytes[2..4]);
373        let count = byte_order.read_u32(&tag_bytes[4..8]);
374        let value_or_offset = byte_order.read_u32(&tag_bytes[8..12]);
375
376        if tag_id == tags::DATE_TIME_ORIGINAL {
377            return read_ascii_tag(data, tag_type, count, value_or_offset, byte_order);
378        }
379    }
380
381    None
382}
383
384/// Parse an IFD and return the offset to the next IFD (if any)
385fn parse_ifd(
386    cursor: &mut Cursor<&[u8]>,
387    offset: u32,
388    byte_order: ByteOrder,
389    data_len: usize,
390) -> Result<Option<u32>> {
391    // Validate offset
392    if offset as usize >= data_len {
393        return Ok(None);
394    }
395
396    cursor.seek(SeekFrom::Start(offset as u64))?;
397
398    // Read tag count
399    let mut count_bytes = [0u8; 2];
400    if cursor.read_exact(&mut count_bytes).is_err() {
401        return Ok(None); // Can't read tag count
402    }
403    let tag_count = byte_order.read_u16(&count_bytes);
404
405    // Validate tag count to prevent DOS attacks
406    if tag_count > MAX_IFD_TAGS {
407        return Ok(None); // Suspiciously large number of tags
408    }
409
410    // Skip all tags (12 bytes each)
411    cursor.seek(SeekFrom::Current((tag_count as i64) * 12))?;
412
413    // Read next IFD offset
414    let mut next_bytes = [0u8; 4];
415    if cursor.read_exact(&mut next_bytes).is_err() {
416        return Ok(None); // Can't read next offset
417    }
418    let next_offset = byte_order.read_u32(&next_bytes);
419
420    if next_offset == 0 || next_offset as usize >= data_len {
421        Ok(None)
422    } else {
423        Ok(Some(next_offset))
424    }
425}
426
427/// Parse IFD1 to extract thumbnail information
428fn parse_thumbnail_from_ifd(
429    cursor: &mut Cursor<&[u8]>,
430    offset: u32,
431    byte_order: ByteOrder,
432    data_len: usize,
433) -> Result<Option<ThumbnailInfo>> {
434    // Validate offset
435    if offset as usize >= data_len {
436        return Ok(None);
437    }
438
439    cursor.seek(SeekFrom::Start(offset as u64))?;
440
441    // Read tag count
442    let mut count_bytes = [0u8; 2];
443    if cursor.read_exact(&mut count_bytes).is_err() {
444        return Ok(None);
445    }
446    let tag_count = byte_order.read_u16(&count_bytes);
447
448    // Validate tag count
449    if tag_count > MAX_IFD_TAGS {
450        return Ok(None);
451    }
452
453    // Extract thumbnail information from tags
454    let mut thumb_offset = None;
455    let mut thumb_size = None;
456    let mut width = None;
457    let mut height = None;
458
459    for _ in 0..tag_count {
460        let mut tag_bytes = [0u8; 12];
461        if cursor.read_exact(&mut tag_bytes).is_err() {
462            break;
463        }
464
465        let tag_id = byte_order.read_u16(&tag_bytes[0..2]);
466        let tag_type = byte_order.read_u16(&tag_bytes[2..4]);
467        let value = byte_order.read_u32(&tag_bytes[8..12]);
468
469        // We only care about SHORT and LONG types for thumbnail tags
470        if tag_type == types::SHORT || tag_type == types::LONG {
471            match tag_id {
472                tags::JPEG_INTERCHANGE_FORMAT => thumb_offset = Some(value),
473                tags::JPEG_INTERCHANGE_FORMAT_LENGTH => thumb_size = Some(value),
474                tags::IMAGE_WIDTH => width = Some(value),
475                tags::IMAGE_LENGTH => height = Some(value),
476                _ => {}
477            }
478        }
479    }
480
481    // Both offset and size are required for a valid thumbnail
482    match (thumb_offset, thumb_size) {
483        (Some(offset), Some(size)) => Ok(Some(ThumbnailInfo {
484            offset,
485            size,
486            width,
487            height,
488        })),
489        _ => Ok(None),
490    }
491}
492
493/// The TIFF header onward. Some writers put the JPEG-style `Exif\0\0` prefix in
494/// containers (WebP) that do not use it; it is skipped when present.
495fn tiff_data(data: &[u8]) -> &[u8] {
496    data.strip_prefix(b"Exif\0\0").unwrap_or(data)
497}
498
499/// EXIF access for any container that reports [`ItemKind::Exif`] items
500/// (JPEG `APP1`, PNG `eXIf`, HEIF `Exif`). The item starts at the TIFF header.
501impl Structure {
502    /// Basic EXIF fields from the first EXIF item, or `None` if there is none or
503    /// it is not valid TIFF.
504    pub fn exif_info<R: Read + Seek>(&self, src: &mut R) -> Result<Option<ExifInfo>> {
505        match self.items_of(ItemKind::Exif).next() {
506            Some(e) => parse_exif_info(tiff_data(&self.read_item(src, e)?)),
507            None => Ok(None),
508        }
509    }
510
511    /// The JPEG thumbnail embedded in the first EXIF item, if present and
512    /// entirely inside it.
513    pub(crate) fn exif_thumbnail<R: Read + Seek>(&self, src: &mut R) -> Result<Option<Thumbnail>> {
514        let Some(e) = self.items_of(ItemKind::Exif).next() else {
515            return Ok(None);
516        };
517        let data = self.read_item(src, e)?;
518        let exif = tiff_data(&data);
519        let Some(info) = parse_thumbnail_info(exif)? else {
520            return Ok(None);
521        };
522        let start = info.offset as usize;
523        let Some(end) = start.checked_add(info.size as usize) else {
524            return Ok(None);
525        };
526        // The JPEGInterchangeFormat tags exist only for JPEG thumbnails.
527        Ok(exif.get(start..end).map(|bytes| {
528            let mut t = Thumbnail::new(bytes.to_vec()).with_media_type("image/jpeg");
529            if let (Some(w), Some(h)) = (info.width, info.height) {
530                t = t.with_dimensions(w, h);
531            }
532            t
533        }))
534    }
535}
536
537#[cfg(test)]
538mod tests {
539    use super::*;
540
541    #[test]
542    fn test_byte_order() {
543        let be = ByteOrder::BigEndian;
544        let le = ByteOrder::LittleEndian;
545
546        assert_eq!(be.read_u16(&[0x12, 0x34]), 0x1234);
547        assert_eq!(le.read_u16(&[0x34, 0x12]), 0x1234);
548
549        assert_eq!(be.read_u32(&[0x12, 0x34, 0x56, 0x78]), 0x12345678);
550        assert_eq!(le.read_u32(&[0x78, 0x56, 0x34, 0x12]), 0x12345678);
551    }
552}