Skip to main content

smriti/services/
raw_containers.rs

1//! Embedded-JPEG previews and basic metadata for the two common RAW
2//! formats that are *not* TIFF-based, so `raw_preview`'s IFD walker can't
3//! read them:
4//!
5//! - **CR3** (Canon, 2018+): an ISO base-media ("MP4") container. Track 1
6//!   holds a full-size JPEG; a smaller `PRVW` JPEG sits in a Canon `uuid`
7//!   box as a fallback. Capture date, make, model and orientation live in
8//!   the `CMT1` / `CMT2` TIFF blocks of the Canon metadata box.
9//! - **RAF** (Fujifilm): a fixed header whose bytes 84..92 give the offset
10//!   and length of an embedded JPEG, which also carries normal EXIF.
11//!
12//! Like the TIFF path, this shows the camera's own rendering rather than
13//! demosaicing sensor data.
14
15use std::fs::File;
16use std::io::{Read, Seek, SeekFrom};
17use std::path::Path;
18
19/// Anything larger is more likely a corrupt length than a real preview.
20const MAX_PREVIEW_BYTES: u64 = 128 * 1024 * 1024;
21/// Metadata blocks are a few KB; cap what we read for them.
22const MAX_META_BOX_BYTES: u64 = 4 * 1024 * 1024;
23/// Bounds for walking boxes, so malformed files can't loop or recurse.
24const MAX_BOXES: usize = 512;
25const MAX_DEPTH: usize = 8;
26
27const CANON_META_UUID: [u8; 16] = [
28    0x85, 0xc0, 0xb6, 0x87, 0x82, 0x0f, 0x11, 0xe0, 0x81, 0x11, 0xf4, 0xce, 0x46, 0x2b, 0x6a, 0x48,
29];
30const CANON_PREVIEW_UUID: [u8; 16] = [
31    0xea, 0xf4, 0x2b, 0x5e, 0x1c, 0x98, 0x4b, 0x88, 0xb9, 0xfb, 0xb7, 0xdc, 0x40, 0x6e, 0x4d, 0x16,
32];
33const RAF_MAGIC: &[u8] = b"FUJIFILMCCD-RAW";
34
35/// Capture metadata recovered from a CR3's Canon metadata box.
36#[derive(Debug, Default, Clone, PartialEq, Eq)]
37pub struct Cr3Metadata {
38    /// EXIF `DateTimeOriginal`, as written (`YYYY:MM:DD HH:MM:SS`).
39    pub date_time_original: Option<String>,
40    pub make: Option<String>,
41    pub model: Option<String>,
42    pub orientation: Option<u16>,
43}
44
45/// Largest embedded JPEG in a CR3, or `None` if none was found.
46pub fn cr3_preview(path: &Path) -> Result<Option<Vec<u8>>, String> {
47    let mut file = File::open(path).map_err(|e| format!("open: {e}"))?;
48    let len = file.metadata().map_err(|e| format!("stat: {e}"))?.len();
49    let layout = scan_cr3(&mut file, len)?;
50    for (offset, size) in [layout.track1_jpeg, layout.prvw_jpeg].into_iter().flatten() {
51        if let Some(bytes) = read_jpeg(&mut file, len, offset, size)? {
52            return Ok(Some(bytes));
53        }
54    }
55    Ok(None)
56}
57
58/// Capture date, make, model and orientation from a CR3.
59pub fn cr3_metadata(path: &Path) -> Result<Cr3Metadata, String> {
60    let mut file = File::open(path).map_err(|e| format!("open: {e}"))?;
61    let len = file.metadata().map_err(|e| format!("stat: {e}"))?.len();
62    let layout = scan_cr3(&mut file, len)?;
63    let mut meta = Cr3Metadata::default();
64    if let Some((offset, size)) = layout.cmt1 {
65        let tiff = read_bounded(&mut file, len, offset, size, MAX_META_BOX_BYTES)?;
66        meta.make = tiff_ascii(&tiff, 0x010F);
67        meta.model = tiff_ascii(&tiff, 0x0110);
68        meta.orientation = tiff_short(&tiff, 0x0112);
69    }
70    if let Some((offset, size)) = layout.cmt2 {
71        let tiff = read_bounded(&mut file, len, offset, size, MAX_META_BOX_BYTES)?;
72        meta.date_time_original = tiff_ascii(&tiff, 0x9003);
73    }
74    Ok(meta)
75}
76
77/// The embedded JPEG of a Fujifilm RAF (it carries the photo's EXIF too).
78pub fn raf_preview(path: &Path) -> Result<Option<Vec<u8>>, String> {
79    let mut file = File::open(path).map_err(|e| format!("open: {e}"))?;
80    let len = file.metadata().map_err(|e| format!("stat: {e}"))?.len();
81    let mut header = [0u8; 92];
82    file.read_exact(&mut header)
83        .map_err(|e| format!("read RAF header: {e}"))?;
84    if !header.starts_with(RAF_MAGIC) {
85        return Err("not a Fujifilm RAF (bad magic)".into());
86    }
87    let offset = u64::from(u32::from_be_bytes([
88        header[84], header[85], header[86], header[87],
89    ]));
90    let size = u64::from(u32::from_be_bytes([
91        header[88], header[89], header[90], header[91],
92    ]));
93    read_jpeg(&mut file, len, offset, size)
94}
95
96// ----- CR3 box walking ------------------------------------------------
97
98#[derive(Debug, Default)]
99struct Cr3Layout {
100    /// (offset, size) of the full-size JPEG sample in track 1.
101    track1_jpeg: Option<(u64, u64)>,
102    /// (offset, size) of the PRVW preview JPEG.
103    prvw_jpeg: Option<(u64, u64)>,
104    /// (offset, size) of the CMT1 / CMT2 TIFF payloads.
105    cmt1: Option<(u64, u64)>,
106    cmt2: Option<(u64, u64)>,
107}
108
109struct BoxHeader {
110    kind: [u8; 4],
111    /// Offset of the payload (after size/type/largesize).
112    payload: u64,
113    /// Offset just past the end of the box.
114    end: u64,
115}
116
117struct Walker<'a> {
118    file: &'a mut File,
119    len: u64,
120    boxes: usize,
121    layout: Cr3Layout,
122    tracks_seen: usize,
123    /// Sample table of the track currently being walked.
124    stsz_first: Option<u64>,
125    chunk_first: Option<u64>,
126}
127
128fn scan_cr3(file: &mut File, len: u64) -> Result<Cr3Layout, String> {
129    let mut ftyp = [0u8; 12];
130    file.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?;
131    file.read_exact(&mut ftyp)
132        .map_err(|e| format!("read CR3 header: {e}"))?;
133    if &ftyp[4..8] != b"ftyp" || &ftyp[8..12] != b"crx " {
134        return Err("not a Canon CR3 (bad ftyp)".into());
135    }
136    let mut walker = Walker {
137        file,
138        len,
139        boxes: 0,
140        layout: Cr3Layout::default(),
141        tracks_seen: 0,
142        stsz_first: None,
143        chunk_first: None,
144    };
145    walker.walk(0, len, 0)?;
146    Ok(walker.layout)
147}
148
149impl Walker<'_> {
150    fn header_at(&mut self, at: u64, parent_end: u64) -> Result<Option<BoxHeader>, String> {
151        if at.saturating_add(8) > parent_end {
152            return Ok(None);
153        }
154        let mut head = [0u8; 8];
155        self.file
156            .seek(SeekFrom::Start(at))
157            .map_err(|e| e.to_string())?;
158        self.file.read_exact(&mut head).map_err(|e| e.to_string())?;
159        let size32 = u64::from(u32::from_be_bytes([head[0], head[1], head[2], head[3]]));
160        let kind = [head[4], head[5], head[6], head[7]];
161        let (payload, size) = match size32 {
162            0 => (at + 8, parent_end - at),
163            1 => {
164                let mut large = [0u8; 8];
165                self.file
166                    .read_exact(&mut large)
167                    .map_err(|e| e.to_string())?;
168                (at + 16, u64::from_be_bytes(large))
169            }
170            n => (at + 8, n),
171        };
172        let end = at.saturating_add(size);
173        if size < 8 || end > parent_end || payload > end {
174            return Ok(None); // malformed: stop walking this level
175        }
176        Ok(Some(BoxHeader { kind, payload, end }))
177    }
178
179    fn walk(&mut self, start: u64, end: u64, depth: usize) -> Result<(), String> {
180        if depth > MAX_DEPTH {
181            return Ok(());
182        }
183        let mut at = start;
184        while let Some(header) = self.header_at(at, end)? {
185            self.boxes += 1;
186            if self.boxes > MAX_BOXES {
187                return Ok(());
188            }
189            self.visit(&header, depth)?;
190            at = header.end;
191        }
192        Ok(())
193    }
194
195    fn visit(&mut self, header: &BoxHeader, depth: usize) -> Result<(), String> {
196        match &header.kind {
197            b"moov" | b"mdia" | b"minf" | b"stbl" => {
198                self.walk(header.payload, header.end, depth + 1)?;
199            }
200            b"trak" => {
201                self.tracks_seen += 1;
202                self.stsz_first = None;
203                self.chunk_first = None;
204                self.walk(header.payload, header.end, depth + 1)?;
205                if self.tracks_seen == 1 {
206                    if let (Some(offset), Some(size)) = (self.chunk_first, self.stsz_first) {
207                        self.layout.track1_jpeg = Some((offset, size));
208                    }
209                }
210            }
211            b"stsz" => self.stsz_first = self.read_stsz(header)?,
212            b"co64" => self.chunk_first = self.read_chunk_offset(header, true)?,
213            b"stco" => self.chunk_first = self.read_chunk_offset(header, false)?,
214            b"uuid" => {
215                let mut uuid = [0u8; 16];
216                self.file
217                    .seek(SeekFrom::Start(header.payload))
218                    .map_err(|e| e.to_string())?;
219                if self.file.read_exact(&mut uuid).is_err() {
220                    return Ok(());
221                }
222                if uuid == CANON_META_UUID {
223                    self.walk(header.payload + 16, header.end, depth + 1)?;
224                } else if uuid == CANON_PREVIEW_UUID {
225                    // 16-byte uuid, then 8 bytes Canon puts before the PRVW box.
226                    self.walk(header.payload + 24, header.end, depth + 1)?;
227                }
228            }
229            b"CMT1" => self.layout.cmt1 = Some((header.payload, header.end - header.payload)),
230            b"CMT2" => self.layout.cmt2 = Some((header.payload, header.end - header.payload)),
231            b"PRVW" => {
232                // The JPEG starts at the first SOI marker inside the box.
233                let size = (header.end - header.payload).min(64);
234                let head = read_bounded(self.file, self.len, header.payload, size, 64)?;
235                if let Some(pos) = head.windows(2).position(|w| w == [0xFF, 0xD8]) {
236                    let offset = header.payload + pos as u64;
237                    self.layout.prvw_jpeg = Some((offset, header.end - offset));
238                }
239            }
240            _ => {}
241        }
242        Ok(())
243    }
244
245    /// First sample size from an `stsz` box.
246    fn read_stsz(&mut self, header: &BoxHeader) -> Result<Option<u64>, String> {
247        let body = read_bounded(self.file, self.len, header.payload, 16, 16)?;
248        if body.len() < 12 {
249            return Ok(None);
250        }
251        let uniform = u64::from(u32::from_be_bytes([body[4], body[5], body[6], body[7]]));
252        let count = u32::from_be_bytes([body[8], body[9], body[10], body[11]]);
253        if uniform > 0 {
254            return Ok(Some(uniform));
255        }
256        if count == 0 || body.len() < 16 {
257            return Ok(None);
258        }
259        Ok(Some(u64::from(u32::from_be_bytes([
260            body[12], body[13], body[14], body[15],
261        ]))))
262    }
263
264    /// First chunk offset from a `co64` / `stco` box.
265    fn read_chunk_offset(&mut self, header: &BoxHeader, wide: bool) -> Result<Option<u64>, String> {
266        let body = read_bounded(self.file, self.len, header.payload, 16, 16)?;
267        if body.len() < 8 || u32::from_be_bytes([body[4], body[5], body[6], body[7]]) == 0 {
268            return Ok(None);
269        }
270        Ok(if wide {
271            body.get(8..16)
272                .map(|b| u64::from_be_bytes(b.try_into().unwrap_or_default()))
273        } else {
274            body.get(8..12)
275                .map(|b| u64::from(u32::from_be_bytes(b.try_into().unwrap_or_default())))
276        })
277    }
278}
279
280// ----- shared helpers --------------------------------------------------
281
282/// Read `size` bytes at `offset` if they start with a JPEG SOI marker.
283fn read_jpeg(file: &mut File, len: u64, offset: u64, size: u64) -> Result<Option<Vec<u8>>, String> {
284    if !(4..=MAX_PREVIEW_BYTES).contains(&size) || offset.saturating_add(size) > len {
285        return Ok(None);
286    }
287    let bytes = read_bounded(file, len, offset, size, MAX_PREVIEW_BYTES)?;
288    Ok(bytes.starts_with(&[0xFF, 0xD8]).then_some(bytes))
289}
290
291fn read_bounded(
292    file: &mut File,
293    len: u64,
294    offset: u64,
295    size: u64,
296    cap: u64,
297) -> Result<Vec<u8>, String> {
298    let size = size.min(cap).min(len.saturating_sub(offset));
299    let mut buf = vec![0u8; size as usize];
300    file.seek(SeekFrom::Start(offset))
301        .map_err(|e| e.to_string())?;
302    file.read_exact(&mut buf)
303        .map_err(|e| format!("read: {e}"))?;
304    Ok(buf)
305}
306
307/// Locate `tag` in IFD0 of a TIFF block: returns (type, count, value bytes).
308fn tiff_entry(tiff: &[u8], tag: u16) -> Option<(u16, u32, Vec<u8>)> {
309    let little = match tiff.get(0..2)? {
310        b"II" => true,
311        b"MM" => false,
312        _ => return None,
313    };
314    let u16_at = |at: usize| -> Option<u16> {
315        let b: [u8; 2] = tiff.get(at..at + 2)?.try_into().ok()?;
316        Some(if little {
317            u16::from_le_bytes(b)
318        } else {
319            u16::from_be_bytes(b)
320        })
321    };
322    let u32_at = |at: usize| -> Option<u32> {
323        let b: [u8; 4] = tiff.get(at..at + 4)?.try_into().ok()?;
324        Some(if little {
325            u32::from_le_bytes(b)
326        } else {
327            u32::from_be_bytes(b)
328        })
329    };
330    let ifd = u32_at(4)? as usize;
331    let count = u16_at(ifd)? as usize;
332    for i in 0..count.min(512) {
333        let entry = ifd + 2 + i * 12;
334        if u16_at(entry)? != tag {
335            continue;
336        }
337        let kind = u16_at(entry + 2)?;
338        let n = u32_at(entry + 4)?;
339        let unit = match kind {
340            2 | 7 | 1 => 1,
341            3 => 2,
342            4 => 4,
343            _ => return None,
344        };
345        let total = (n as usize).checked_mul(unit)?;
346        let data = if total <= 4 {
347            tiff.get(entry + 8..entry + 8 + total)?.to_vec()
348        } else {
349            let at = u32_at(entry + 8)? as usize;
350            tiff.get(at..at.checked_add(total)?)?.to_vec()
351        };
352        return Some((kind, n, data_with_order(data, kind, little)));
353    }
354    None
355}
356
357/// Normalise SHORT values to big-endian so callers read them one way.
358fn data_with_order(mut data: Vec<u8>, kind: u16, little: bool) -> Vec<u8> {
359    if kind == 3 && little {
360        for pair in data.as_chunks_mut::<2>().0 {
361            pair.swap(0, 1);
362        }
363    }
364    data
365}
366
367fn tiff_ascii(tiff: &[u8], tag: u16) -> Option<String> {
368    let (kind, _, data) = tiff_entry(tiff, tag)?;
369    if kind != 2 {
370        return None;
371    }
372    let text = String::from_utf8_lossy(&data);
373    let text = text.trim_end_matches('\0').trim();
374    (!text.is_empty()).then(|| text.to_string())
375}
376
377fn tiff_short(tiff: &[u8], tag: u16) -> Option<u16> {
378    let (kind, _, data) = tiff_entry(tiff, tag)?;
379    if kind != 3 {
380        return None;
381    }
382    Some(u16::from_be_bytes(data.get(0..2)?.try_into().ok()?))
383}
384
385#[cfg(test)]
386mod tests {
387    use super::*;
388    use std::io::Write;
389
390    fn tiny_jpeg() -> Vec<u8> {
391        let img = image::RgbImage::from_pixel(8, 6, image::Rgb([200, 100, 50]));
392        let mut out = std::io::Cursor::new(Vec::new());
393        image::DynamicImage::ImageRgb8(img)
394            .write_to(&mut out, image::ImageFormat::Jpeg)
395            .unwrap();
396        out.into_inner()
397    }
398
399    fn bmff_box(kind: &[u8; 4], payload: &[u8]) -> Vec<u8> {
400        let mut out = Vec::new();
401        out.extend_from_slice(&((payload.len() + 8) as u32).to_be_bytes());
402        out.extend_from_slice(kind);
403        out.extend_from_slice(payload);
404        out
405    }
406
407    /// Little-endian TIFF with ASCII and SHORT entries in IFD0.
408    fn tiny_tiff(ascii: &[(u16, &str)], shorts: &[(u16, u16)]) -> Vec<u8> {
409        let count = ascii.len() + shorts.len();
410        let ifd_len = 2 + count * 12 + 4;
411        let mut data_at = 8 + ifd_len;
412        let mut out = b"II*\0".to_vec();
413        out.extend_from_slice(&8u32.to_le_bytes());
414        out.extend_from_slice(&(count as u16).to_le_bytes());
415        let mut blobs = Vec::new();
416        for (tag, text) in ascii {
417            let mut value = text.as_bytes().to_vec();
418            value.push(0);
419            out.extend_from_slice(&tag.to_le_bytes());
420            out.extend_from_slice(&2u16.to_le_bytes());
421            out.extend_from_slice(&(value.len() as u32).to_le_bytes());
422            out.extend_from_slice(&(data_at as u32).to_le_bytes());
423            data_at += value.len();
424            blobs.extend_from_slice(&value);
425        }
426        for (tag, value) in shorts {
427            out.extend_from_slice(&tag.to_le_bytes());
428            out.extend_from_slice(&3u16.to_le_bytes());
429            out.extend_from_slice(&1u32.to_le_bytes());
430            out.extend_from_slice(&value.to_le_bytes());
431            out.extend_from_slice(&[0, 0]);
432        }
433        out.extend_from_slice(&0u32.to_le_bytes());
434        out.extend_from_slice(&blobs);
435        out
436    }
437
438    fn write_temp(bytes: &[u8], name: &str) -> (tempfile::TempDir, std::path::PathBuf) {
439        let dir = tempfile::tempdir().unwrap();
440        let path = dir.path().join(name);
441        std::fs::File::create(&path)
442            .unwrap()
443            .write_all(bytes)
444            .unwrap();
445        (dir, path)
446    }
447
448    #[test]
449    fn reads_raf_embedded_jpeg() {
450        let jpeg = tiny_jpeg();
451        let mut raf = vec![0u8; 100];
452        raf[..RAF_MAGIC.len()].copy_from_slice(RAF_MAGIC);
453        raf[84..88].copy_from_slice(&100u32.to_be_bytes());
454        raf[88..92].copy_from_slice(&(jpeg.len() as u32).to_be_bytes());
455        raf.extend_from_slice(&jpeg);
456        let (_dir, path) = write_temp(&raf, "photo.raf");
457        assert_eq!(raf_preview(&path).unwrap(), Some(jpeg));
458    }
459
460    #[test]
461    fn rejects_non_raf() {
462        let (_dir, path) = write_temp(&[0u8; 120], "bogus.raf");
463        assert!(raf_preview(&path).is_err());
464    }
465
466    /// ftyp, moov{Canon uuid{CMT1,CMT2}, trak{mdia{minf{stbl{stsz,co64}}}}}, mdat{jpeg}.
467    fn build_cr3(jpeg: &[u8]) -> Vec<u8> {
468        let ftyp = bmff_box(b"ftyp", b"crx \0\0\0\x01crx isom");
469        let cmt1 = bmff_box(
470            b"CMT1",
471            &tiny_tiff(
472                &[(0x010F, "Canon"), (0x0110, "Canon EOS R6")],
473                &[(0x0112, 6)],
474            ),
475        );
476        let cmt2 = bmff_box(b"CMT2", &tiny_tiff(&[(0x9003, "2024:03:15 10:20:30")], &[]));
477        let mut canon = CANON_META_UUID.to_vec();
478        canon.extend_from_slice(&cmt1);
479        canon.extend_from_slice(&cmt2);
480        let canon_box = bmff_box(b"uuid", &canon);
481
482        let mut stsz = vec![0u8; 4];
483        stsz.extend_from_slice(&(jpeg.len() as u32).to_be_bytes());
484        stsz.extend_from_slice(&1u32.to_be_bytes());
485        // co64 offset is patched once the layout is known.
486        let build = |offset: u64| {
487            let mut co64 = vec![0u8; 4];
488            co64.extend_from_slice(&1u32.to_be_bytes());
489            co64.extend_from_slice(&offset.to_be_bytes());
490            let stbl = bmff_box(
491                b"stbl",
492                &[bmff_box(b"stsz", &stsz), bmff_box(b"co64", &co64)].concat(),
493            );
494            let trak = bmff_box(b"trak", &bmff_box(b"mdia", &bmff_box(b"minf", &stbl)));
495            bmff_box(b"moov", &[canon_box.clone(), trak].concat())
496        };
497        let moov_len = build(0).len();
498        let jpeg_offset = (ftyp.len() + moov_len + 8) as u64;
499        [ftyp.clone(), build(jpeg_offset), bmff_box(b"mdat", jpeg)].concat()
500    }
501
502    #[test]
503    fn reads_cr3_track1_jpeg_and_metadata() {
504        let jpeg = tiny_jpeg();
505        let (_dir, path) = write_temp(&build_cr3(&jpeg), "photo.cr3");
506        assert_eq!(cr3_preview(&path).unwrap(), Some(jpeg));
507        let meta = cr3_metadata(&path).unwrap();
508        assert_eq!(
509            meta.date_time_original.as_deref(),
510            Some("2024:03:15 10:20:30")
511        );
512        assert_eq!(meta.make.as_deref(), Some("Canon"));
513        assert_eq!(meta.model.as_deref(), Some("Canon EOS R6"));
514        assert_eq!(meta.orientation, Some(6));
515    }
516
517    #[test]
518    fn rejects_non_cr3_and_survives_truncation() {
519        let (_dir, path) = write_temp(&bmff_box(b"ftyp", b"isom\0\0\0\x01"), "clip.cr3");
520        assert!(cr3_preview(&path).is_err());
521        let full = build_cr3(&tiny_jpeg());
522        let (_dir2, cut) = write_temp(&full[..full.len() / 2], "cut.cr3");
523        assert_eq!(cr3_preview(&cut).unwrap(), None);
524    }
525}