1use std::io::{Cursor, Read, Seek, SeekFrom};
28
29use crate::{error::Result, item::ItemKind, structure::Structure, thumbnail::Thumbnail};
30
31#[allow(dead_code)]
33mod tags {
34 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 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 pub const JPEG_INTERCHANGE_FORMAT: u16 = 0x0201;
55 pub const JPEG_INTERCHANGE_FORMAT_LENGTH: u16 = 0x0202;
56}
57
58#[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#[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#[derive(Debug)]
93pub struct ThumbnailInfo {
94 pub offset: u32,
96 pub size: u32,
98 pub width: Option<u32>,
100 pub height: Option<u32>,
102}
103
104#[derive(Debug, Default)]
106#[non_exhaustive]
107pub struct ExifInfo {
108 pub make: Option<String>,
110 pub model: Option<String>,
112 pub orientation: Option<u16>,
114 pub software: Option<String>,
116 pub date_time: Option<String>,
118 pub date_time_original: Option<String>,
120 pub artist: Option<String>,
122 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
146const MAX_IFD_TAGS: u16 = 1000;
148
149pub 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 let mut header = [0u8; 8];
162 cursor.read_exact(&mut header)?;
163
164 let byte_order = match &header[0..2] {
166 b"II" => ByteOrder::LittleEndian,
167 b"MM" => ByteOrder::BigEndian,
168 _ => return Ok(None), };
170
171 let magic = byte_order.read_u16(&header[2..4]);
173 if magic != 0x002a {
174 return Ok(None);
175 }
176
177 let ifd0_offset = byte_order.read_u32(&header[4..8]);
179
180 if ifd0_offset as usize >= exif_data.len() {
182 return Ok(None); }
184
185 let ifd1_offset = match parse_ifd(&mut cursor, ifd0_offset, byte_order, exif_data.len())? {
187 Some(offset) => offset,
188 None => return Ok(None), };
190
191 if ifd1_offset as usize >= exif_data.len() {
193 return Ok(None); }
195
196 parse_thumbnail_from_ifd(&mut cursor, ifd1_offset, byte_order, exif_data.len())
198}
199
200pub 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 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_exif_from_ifd(&cursor, ifd0_offset, byte_order, exif_data)
233}
234
235fn 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 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
312fn 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 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 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 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
348fn 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
384fn parse_ifd(
386 cursor: &mut Cursor<&[u8]>,
387 offset: u32,
388 byte_order: ByteOrder,
389 data_len: usize,
390) -> Result<Option<u32>> {
391 if offset as usize >= data_len {
393 return Ok(None);
394 }
395
396 cursor.seek(SeekFrom::Start(offset as u64))?;
397
398 let mut count_bytes = [0u8; 2];
400 if cursor.read_exact(&mut count_bytes).is_err() {
401 return Ok(None); }
403 let tag_count = byte_order.read_u16(&count_bytes);
404
405 if tag_count > MAX_IFD_TAGS {
407 return Ok(None); }
409
410 cursor.seek(SeekFrom::Current((tag_count as i64) * 12))?;
412
413 let mut next_bytes = [0u8; 4];
415 if cursor.read_exact(&mut next_bytes).is_err() {
416 return Ok(None); }
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
427fn 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 if offset as usize >= data_len {
436 return Ok(None);
437 }
438
439 cursor.seek(SeekFrom::Start(offset as u64))?;
440
441 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 if tag_count > MAX_IFD_TAGS {
450 return Ok(None);
451 }
452
453 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 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 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
493fn tiff_data(data: &[u8]) -> &[u8] {
496 data.strip_prefix(b"Exif\0\0").unwrap_or(data)
497}
498
499impl Structure {
502 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 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 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}