asset-io 0.8.1

Streaming, container-agnostic access to media file structure and metadata (JUMBF, XMP)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
// Copyright 2026 Adobe. All rights reserved.
// This file is licensed to you under the Apache License,
// Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
// or the MIT license (http://opensource.org/licenses/MIT),
// at your option.

// Unless required by applicable law or agreed to in writing,
// this software is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
// implied. See the LICENSE-MIT and LICENSE-APACHE files for the
// specific language governing permissions and limitations under
// each license.

//! Minimal TIFF/EXIF parser
//!
//! This module provides lightweight TIFF parsing for:
//! - Extracting embedded thumbnails from EXIF data
//! - Reading basic EXIF metadata (Make, Model, DateTime, etc.)
//!
//! TIFF/DNG container support is the `tiff` feature.
//!
//! TIFF Structure:
//! - Header: byte order (II/MM), magic (0x002A), IFD offset
//! - IFD (Image File Directory): tag count, tags (12 bytes each), next IFD offset
//! - Tags: tag ID (2), type (2), count (4), value/offset (4)

use std::io::{Cursor, Read, Seek, SeekFrom};

use crate::{error::Result, item::ItemKind, structure::Structure, thumbnail::Thumbnail};

/// TIFF/EXIF tag IDs
#[allow(dead_code)]
mod tags {
    // IFD0 (main image) tags
    pub const IMAGE_WIDTH: u16 = 0x0100;
    pub const IMAGE_LENGTH: u16 = 0x0101;
    pub const MAKE: u16 = 0x010f;
    pub const MODEL: u16 = 0x0110;
    pub const ORIENTATION: u16 = 0x0112;
    pub const SOFTWARE: u16 = 0x0131;
    pub const DATE_TIME: u16 = 0x0132;
    pub const ARTIST: u16 = 0x013b;
    pub const COPYRIGHT: u16 = 0x8298;
    pub const EXIF_IFD_POINTER: u16 = 0x8769;

    // EXIF sub-IFD tags
    pub const EXPOSURE_TIME: u16 = 0x829a;
    pub const F_NUMBER: u16 = 0x829d;
    pub const ISO_SPEED: u16 = 0x8827;
    pub const DATE_TIME_ORIGINAL: u16 = 0x9003;
    pub const FOCAL_LENGTH: u16 = 0x920a;

    // IFD1 (thumbnail) tags
    pub const JPEG_INTERCHANGE_FORMAT: u16 = 0x0201;
    pub const JPEG_INTERCHANGE_FORMAT_LENGTH: u16 = 0x0202;
}

/// TIFF data types
#[allow(dead_code)]
mod types {
    pub const BYTE: u16 = 1;
    pub const ASCII: u16 = 2;
    pub const SHORT: u16 = 3;
    pub const LONG: u16 = 4;
    pub const RATIONAL: u16 = 5;
}

/// Byte order for reading multi-byte values
#[derive(Debug, Clone, Copy)]
enum ByteOrder {
    LittleEndian,
    BigEndian,
}

impl ByteOrder {
    fn read_u16(&self, data: &[u8]) -> u16 {
        match self {
            ByteOrder::LittleEndian => u16::from_le_bytes([data[0], data[1]]),
            ByteOrder::BigEndian => u16::from_be_bytes([data[0], data[1]]),
        }
    }

    fn read_u32(&self, data: &[u8]) -> u32 {
        match self {
            ByteOrder::LittleEndian => u32::from_le_bytes([data[0], data[1], data[2], data[3]]),
            ByteOrder::BigEndian => u32::from_be_bytes([data[0], data[1], data[2], data[3]]),
        }
    }
}

/// Information about an embedded thumbnail
#[derive(Debug)]
pub struct ThumbnailInfo {
    /// Offset of thumbnail JPEG data within the EXIF segment
    pub offset: u32,
    /// Size of thumbnail JPEG data in bytes
    pub size: u32,
    /// Width in pixels (if present)
    pub width: Option<u32>,
    /// Height in pixels (if present)
    pub height: Option<u32>,
}

/// Basic EXIF metadata extracted from IFD0
#[derive(Debug, Default)]
#[non_exhaustive]
pub struct ExifInfo {
    /// Camera manufacturer (e.g., "Canon", "Nikon")
    pub make: Option<String>,
    /// Camera model (e.g., "EOS R5", "D850")
    pub model: Option<String>,
    /// Image orientation (1-8, where 1 is normal)
    pub orientation: Option<u16>,
    /// Software used to create/edit the image
    pub software: Option<String>,
    /// Date and time of image creation (format: "YYYY:MM:DD HH:MM:SS")
    pub date_time: Option<String>,
    /// Original capture date/time (from EXIF sub-IFD)
    pub date_time_original: Option<String>,
    /// Artist/photographer name
    pub artist: Option<String>,
    /// Copyright notice
    pub copyright: Option<String>,
}

impl std::fmt::Display for ExifInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut parts = Vec::new();
        if let Some(ref make) = self.make {
            parts.push(make.clone());
        }
        if let Some(ref model) = self.model {
            parts.push(model.clone());
        }
        if let Some(dt) = self.date_time_original.as_ref().or(self.date_time.as_ref()) {
            parts.push(dt.clone());
        }
        if parts.is_empty() {
            write!(f, "(no metadata)")
        } else {
            write!(f, "{}", parts.join(" | "))
        }
    }
}

/// Maximum number of tags in an IFD (prevents DOS attacks)
const MAX_IFD_TAGS: u16 = 1000;

/// Parse EXIF data to find embedded thumbnail location
///
/// This expects the EXIF data starting AFTER the "Exif\0\0" signature,
/// i.e., starting with the TIFF header.
pub fn parse_thumbnail_info(exif_data: &[u8]) -> Result<Option<ThumbnailInfo>> {
    if exif_data.len() < 8 {
        return Ok(None);
    }

    let mut cursor = Cursor::new(exif_data);

    // Parse TIFF header
    let mut header = [0u8; 8];
    cursor.read_exact(&mut header)?;

    // Byte order: "II" (0x4949) = little endian, "MM" (0x4D4D) = big endian
    let byte_order = match &header[0..2] {
        b"II" => ByteOrder::LittleEndian,
        b"MM" => ByteOrder::BigEndian,
        _ => return Ok(None), // Not valid TIFF
    };

    // Check magic number (0x002A)
    let magic = byte_order.read_u16(&header[2..4]);
    if magic != 0x002a {
        return Ok(None);
    }

    // Get IFD0 offset
    let ifd0_offset = byte_order.read_u32(&header[4..8]);

    // Validate IFD0 offset is within bounds
    if ifd0_offset as usize >= exif_data.len() {
        return Ok(None); // Invalid offset
    }

    // Parse IFD0 to find IFD1 offset
    let ifd1_offset = match parse_ifd(&mut cursor, ifd0_offset, byte_order, exif_data.len())? {
        Some(offset) => offset,
        None => return Ok(None), // No IFD1
    };

    // Validate IFD1 offset is within bounds
    if ifd1_offset as usize >= exif_data.len() {
        return Ok(None); // Invalid offset
    }

    // Parse IFD1 to find thumbnail tags
    parse_thumbnail_from_ifd(&mut cursor, ifd1_offset, byte_order, exif_data.len())
}

/// Parse EXIF data to extract basic metadata
///
/// This expects the EXIF data starting AFTER the "Exif\0\0" signature,
/// i.e., starting with the TIFF header.
pub fn parse_exif_info(exif_data: &[u8]) -> Result<Option<ExifInfo>> {
    if exif_data.len() < 8 {
        return Ok(None);
    }

    let mut cursor = Cursor::new(exif_data);

    // Parse TIFF header
    let mut header = [0u8; 8];
    cursor.read_exact(&mut header)?;

    let byte_order = match &header[0..2] {
        b"II" => ByteOrder::LittleEndian,
        b"MM" => ByteOrder::BigEndian,
        _ => return Ok(None),
    };

    let magic = byte_order.read_u16(&header[2..4]);
    if magic != 0x002a {
        return Ok(None);
    }

    let ifd0_offset = byte_order.read_u32(&header[4..8]);
    if ifd0_offset as usize >= exif_data.len() {
        return Ok(None);
    }

    // Parse IFD0 for basic EXIF info
    parse_exif_from_ifd(&cursor, ifd0_offset, byte_order, exif_data)
}

/// Parse IFD0 to extract basic EXIF metadata
fn parse_exif_from_ifd(
    cursor: &Cursor<&[u8]>,
    offset: u32,
    byte_order: ByteOrder,
    data: &[u8],
) -> Result<Option<ExifInfo>> {
    if offset as usize >= data.len() {
        return Ok(None);
    }

    let mut cursor = cursor.clone();
    cursor.seek(SeekFrom::Start(offset as u64))?;

    let mut count_bytes = [0u8; 2];
    if cursor.read_exact(&mut count_bytes).is_err() {
        return Ok(None);
    }
    let tag_count = byte_order.read_u16(&count_bytes);

    if tag_count > MAX_IFD_TAGS {
        return Ok(None);
    }

    let mut info = ExifInfo::default();
    let mut exif_ifd_offset: Option<u32> = None;

    for _ in 0..tag_count {
        let mut tag_bytes = [0u8; 12];
        if cursor.read_exact(&mut tag_bytes).is_err() {
            break;
        }

        let tag_id = byte_order.read_u16(&tag_bytes[0..2]);
        let tag_type = byte_order.read_u16(&tag_bytes[2..4]);
        let count = byte_order.read_u32(&tag_bytes[4..8]);
        let value_or_offset = byte_order.read_u32(&tag_bytes[8..12]);

        match tag_id {
            tags::MAKE => {
                info.make = read_ascii_tag(data, tag_type, count, value_or_offset, byte_order);
            }
            tags::MODEL => {
                info.model = read_ascii_tag(data, tag_type, count, value_or_offset, byte_order);
            }
            tags::ORIENTATION if tag_type == types::SHORT => {
                info.orientation = Some(value_or_offset as u16)
            }
            tags::SOFTWARE => {
                info.software = read_ascii_tag(data, tag_type, count, value_or_offset, byte_order);
            }
            tags::DATE_TIME => {
                info.date_time = read_ascii_tag(data, tag_type, count, value_or_offset, byte_order);
            }
            tags::ARTIST => {
                info.artist = read_ascii_tag(data, tag_type, count, value_or_offset, byte_order);
            }
            tags::COPYRIGHT => {
                info.copyright = read_ascii_tag(data, tag_type, count, value_or_offset, byte_order);
            }
            tags::EXIF_IFD_POINTER if tag_type == types::LONG => {
                exif_ifd_offset = Some(value_or_offset)
            }
            _ => {}
        }
    }

    // Parse EXIF sub-IFD for DateTimeOriginal if present
    if let Some(exif_offset) = exif_ifd_offset {
        if let Some(dt_orig) = parse_exif_subifd_datetime(data, exif_offset, byte_order) {
            info.date_time_original = Some(dt_orig);
        }
    }

    Ok(Some(info))
}

/// Read an ASCII string tag value
fn read_ascii_tag(
    data: &[u8],
    tag_type: u16,
    count: u32,
    value_or_offset: u32,
    byte_order: ByteOrder,
) -> Option<String> {
    if tag_type != types::ASCII || count == 0 {
        return None;
    }

    let bytes = if count <= 4 {
        // Value is inline in the tag
        let val_bytes = match byte_order {
            ByteOrder::LittleEndian => value_or_offset.to_le_bytes(),
            ByteOrder::BigEndian => value_or_offset.to_be_bytes(),
        };
        val_bytes[..count as usize].to_vec()
    } else {
        // Value is at offset
        let offset = value_or_offset as usize;
        let end = offset + count as usize;
        if end > data.len() {
            return None;
        }
        data[offset..end].to_vec()
    };

    // Convert to string, trimming null terminator
    String::from_utf8(bytes)
        .ok()
        .map(|s| s.trim_end_matches('\0').trim().to_string())
        .filter(|s| !s.is_empty())
}

/// Parse EXIF sub-IFD to get DateTimeOriginal
fn parse_exif_subifd_datetime(data: &[u8], offset: u32, byte_order: ByteOrder) -> Option<String> {
    if offset as usize >= data.len() {
        return None;
    }

    let mut cursor = Cursor::new(data);
    cursor.seek(SeekFrom::Start(offset as u64)).ok()?;

    let mut count_bytes = [0u8; 2];
    cursor.read_exact(&mut count_bytes).ok()?;
    let tag_count = byte_order.read_u16(&count_bytes);

    if tag_count > MAX_IFD_TAGS {
        return None;
    }

    for _ in 0..tag_count {
        let mut tag_bytes = [0u8; 12];
        if cursor.read_exact(&mut tag_bytes).is_err() {
            break;
        }

        let tag_id = byte_order.read_u16(&tag_bytes[0..2]);
        let tag_type = byte_order.read_u16(&tag_bytes[2..4]);
        let count = byte_order.read_u32(&tag_bytes[4..8]);
        let value_or_offset = byte_order.read_u32(&tag_bytes[8..12]);

        if tag_id == tags::DATE_TIME_ORIGINAL {
            return read_ascii_tag(data, tag_type, count, value_or_offset, byte_order);
        }
    }

    None
}

/// Parse an IFD and return the offset to the next IFD (if any)
fn parse_ifd(
    cursor: &mut Cursor<&[u8]>,
    offset: u32,
    byte_order: ByteOrder,
    data_len: usize,
) -> Result<Option<u32>> {
    // Validate offset
    if offset as usize >= data_len {
        return Ok(None);
    }

    cursor.seek(SeekFrom::Start(offset as u64))?;

    // Read tag count
    let mut count_bytes = [0u8; 2];
    if cursor.read_exact(&mut count_bytes).is_err() {
        return Ok(None); // Can't read tag count
    }
    let tag_count = byte_order.read_u16(&count_bytes);

    // Validate tag count to prevent DOS attacks
    if tag_count > MAX_IFD_TAGS {
        return Ok(None); // Suspiciously large number of tags
    }

    // Skip all tags (12 bytes each)
    cursor.seek(SeekFrom::Current((tag_count as i64) * 12))?;

    // Read next IFD offset
    let mut next_bytes = [0u8; 4];
    if cursor.read_exact(&mut next_bytes).is_err() {
        return Ok(None); // Can't read next offset
    }
    let next_offset = byte_order.read_u32(&next_bytes);

    if next_offset == 0 || next_offset as usize >= data_len {
        Ok(None)
    } else {
        Ok(Some(next_offset))
    }
}

/// Parse IFD1 to extract thumbnail information
fn parse_thumbnail_from_ifd(
    cursor: &mut Cursor<&[u8]>,
    offset: u32,
    byte_order: ByteOrder,
    data_len: usize,
) -> Result<Option<ThumbnailInfo>> {
    // Validate offset
    if offset as usize >= data_len {
        return Ok(None);
    }

    cursor.seek(SeekFrom::Start(offset as u64))?;

    // Read tag count
    let mut count_bytes = [0u8; 2];
    if cursor.read_exact(&mut count_bytes).is_err() {
        return Ok(None);
    }
    let tag_count = byte_order.read_u16(&count_bytes);

    // Validate tag count
    if tag_count > MAX_IFD_TAGS {
        return Ok(None);
    }

    // Extract thumbnail information from tags
    let mut thumb_offset = None;
    let mut thumb_size = None;
    let mut width = None;
    let mut height = None;

    for _ in 0..tag_count {
        let mut tag_bytes = [0u8; 12];
        if cursor.read_exact(&mut tag_bytes).is_err() {
            break;
        }

        let tag_id = byte_order.read_u16(&tag_bytes[0..2]);
        let tag_type = byte_order.read_u16(&tag_bytes[2..4]);
        let value = byte_order.read_u32(&tag_bytes[8..12]);

        // We only care about SHORT and LONG types for thumbnail tags
        if tag_type == types::SHORT || tag_type == types::LONG {
            match tag_id {
                tags::JPEG_INTERCHANGE_FORMAT => thumb_offset = Some(value),
                tags::JPEG_INTERCHANGE_FORMAT_LENGTH => thumb_size = Some(value),
                tags::IMAGE_WIDTH => width = Some(value),
                tags::IMAGE_LENGTH => height = Some(value),
                _ => {}
            }
        }
    }

    // Both offset and size are required for a valid thumbnail
    match (thumb_offset, thumb_size) {
        (Some(offset), Some(size)) => Ok(Some(ThumbnailInfo {
            offset,
            size,
            width,
            height,
        })),
        _ => Ok(None),
    }
}

/// The TIFF header onward. Some writers put the JPEG-style `Exif\0\0` prefix in
/// containers (WebP) that do not use it; it is skipped when present.
fn tiff_data(data: &[u8]) -> &[u8] {
    data.strip_prefix(b"Exif\0\0").unwrap_or(data)
}

/// EXIF access for any container that reports [`ItemKind::Exif`] items
/// (JPEG `APP1`, PNG `eXIf`, HEIF `Exif`). The item starts at the TIFF header.
impl Structure {
    /// Basic EXIF fields from the first EXIF item, or `None` if there is none or
    /// it is not valid TIFF.
    pub fn exif_info<R: Read + Seek>(&self, src: &mut R) -> Result<Option<ExifInfo>> {
        match self.items_of(ItemKind::Exif).next() {
            Some(e) => parse_exif_info(tiff_data(&self.read_item(src, e)?)),
            None => Ok(None),
        }
    }

    /// The JPEG thumbnail embedded in the first EXIF item, if present and
    /// entirely inside it.
    pub(crate) fn exif_thumbnail<R: Read + Seek>(&self, src: &mut R) -> Result<Option<Thumbnail>> {
        let Some(e) = self.items_of(ItemKind::Exif).next() else {
            return Ok(None);
        };
        let data = self.read_item(src, e)?;
        let exif = tiff_data(&data);
        let Some(info) = parse_thumbnail_info(exif)? else {
            return Ok(None);
        };
        let start = info.offset as usize;
        let Some(end) = start.checked_add(info.size as usize) else {
            return Ok(None);
        };
        // The JPEGInterchangeFormat tags exist only for JPEG thumbnails.
        Ok(exif.get(start..end).map(|bytes| {
            let mut t = Thumbnail::new(bytes.to_vec()).with_media_type("image/jpeg");
            if let (Some(w), Some(h)) = (info.width, info.height) {
                t = t.with_dimensions(w, h);
            }
            t
        }))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_byte_order() {
        let be = ByteOrder::BigEndian;
        let le = ByteOrder::LittleEndian;

        assert_eq!(be.read_u16(&[0x12, 0x34]), 0x1234);
        assert_eq!(le.read_u16(&[0x34, 0x12]), 0x1234);

        assert_eq!(be.read_u32(&[0x12, 0x34, 0x56, 0x78]), 0x12345678);
        assert_eq!(le.read_u32(&[0x78, 0x56, 0x34, 0x12]), 0x12345678);
    }
}