Skip to content

A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.

19.7 KB
Raw Blame
//! A camera picture's thumbnail from the preview the camera put inside the file, instead of the whole picture decoded.
//!
//! WHY. The shell makes the thumbnail of a camera JPEG or a RAW file by decoding the full picture: measured on this project's
//! `thumb_probe` (2026-12-01, 256 px, files already in the system's cache), 137 ms for an 18 MB Sony JPEG and 76 ms for its ARW,
//! one file after the other (the shell does not make two at once: a folder of 40 JPEGs took 6.3 s). The same files carry a ready
//! JPEG preview of about 1600 x 1080 (a JPEG's Multi-Picture block, a RAW's preview directory); reading only the file's head and
//! that preview and decoding it took 7 ms, on as many threads as there are workers.
//!
//! WHAT IT TAKES. Only files that name such a preview: a JPEG with an MPF block or an EXIF thumbnail directory, a TIFF-based RAW
//! (`handles`). Of the previews named, the smallest one that is still at least as large as the size asked for. A preview smaller
//! than `MIN_SIDE` is never taken: the 160 x 120 thumbnail of the EXIF block is drawn with black bars by many cameras. When there
//! is no such preview, or anything about the file is not as expected, the answer is `None` and the shell makes the thumbnail as
//! before. The picture is turned upright by the orientation the file's own first directory states, as the shell does.
//!
//! NOT TRIED: cameras other than Sony (the directory layout is the standard one, but only Sony's files were at hand), and a
//! preview whose colours differ from the main picture's. `set_enabled(false)` (the `own_thumbnails` setting) leaves every
//! thumbnail to the shell again.

use std::fs::File;
use std::io::{Read, Seek, SeekFrom};
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};

use crate::thumbs::Bgra;

/// How much of the file's beginning is read to find the directories.
const HEAD: usize = 256 * 1024;
/// A preview smaller than this on its long side is not used (see the module's notes).
const MIN_SIDE: u32 = 320;
/// A preview larger than this in bytes is not read (a full-size JPEG inside a RAW: the shell's way is no slower then).
const MAX_BYTES: usize = 24 << 20;

static ENABLED: AtomicBool = AtomicBool::new(true);

/// Settings › `own_thumbnails`: off leaves every thumbnail to the shell.
pub fn set_enabled(on: bool) {
    ENABLED.store(on, Ordering::Relaxed);
}

/// Whether a file of this name may carry a preview this module reads (by its extension only: nothing is opened).
pub fn handles(path: &Path) -> bool {
    ENABLED.load(Ordering::Relaxed)
        && path.extension().and_then(|e| e.to_str()).is_some_and(|e| ["jpg", "jpeg", "arw", "cr2", "nef", "dng"].iter().any(|k| e.eq_ignore_ascii_case(k)))
}

/// The file's embedded preview, its long side at most `size` and turned upright; `None` when the file has none that fits.
pub fn thumbnail(path: &Path, size: u32) -> Option<Bgra> {
    let size = size.max(16);
    let mut file = File::open(path).ok()?;
    let total = file.metadata().ok()?.len();
    let mut head = vec![0u8; HEAD.min(total as usize)];
    file.read_exact(&mut head).ok()?;
    let found = previews(&head)?;
    // each preview's size from its own first bytes; the smallest one that is large enough
    let mut best: Option<(u32, u64, usize)> = None;
    for (at, len) in found.jpegs {
        if len < 1024 || len > MAX_BYTES || at.checked_add(len as u64).is_none_or(|end| end > total) {
            continue;
        }
        let mut start = vec![0u8; len.min(64 * 1024)];
        if file.seek(SeekFrom::Start(at)).is_err() || file.read_exact(&mut start).is_err() {
            continue;
        }
        let Ok((w, h)) = image::ImageReader::with_format(std::io::Cursor::new(&start), image::ImageFormat::Jpeg).into_dimensions() else { continue };
        let side = w.max(h);
        // a JPEG's preview has to have the picture's own proportions (see `same_shape`)
        if found.main.is_some_and(|main| !same_shape(main, (w, h))) {
            continue;
        }
        if side >= size.max(MIN_SIDE) && best.is_none_or(|(b, _, _)| side < b) {
            best = Some((side, at, len));
        }
    }
    let (_, at, len) = best?;
    let mut jpeg = vec![0u8; len];
    file.seek(SeekFrom::Start(at)).ok()?;
    file.read_exact(&mut jpeg).ok()?;
    let orientation = found.orientation;
    // (a broken preview must not take the worker down: a decoder's panic is an answer of "none" here)
    std::panic::catch_unwind(move || {
        let mut img = image::load_from_memory_with_format(&jpeg, image::ImageFormat::Jpeg).ok()?;
        if let Some(o) = image::metadata::Orientation::from_exif(orientation) {
            img.apply_orientation(o);
        }
        Some(crate::look::decode::bgra_within(img.into_rgba8(), size))
    })
    .ok()
    .flatten()
}

/// What a file's head names: where its JPEG previews are (offset in the file, length) and the picture's orientation (1 to 8).
struct Previews {
    jpegs: Vec<(u64, usize)>,
    orientation: u8,
    /// A JPEG's own width and height: its previews are checked against them. `None` for a RAW file.
    main: Option<(u32, u32)>,
}

/// Whether a preview has the proportions of the picture it stands for (within 2 %).
///
/// WHY. A JPEG can be edited by a program that writes the new picture and leaves the old preview in place: a cropped or turned
/// photo would then show its old self as the thumbnail. A preview of another shape than the picture is such a leftover (or a
/// thumbnail with bars) and is not used; the shell then decodes the picture itself. It does not catch an edit that keeps the
/// shape (a colour change): programs that keep a Multi-Picture block while rewriting the picture are rare, and the block's
/// offsets would be wrong after it, which fails the read. A RAW file is not edited in place, so it is not checked.
fn same_shape(main: (u32, u32), preview: (u32, u32)) -> bool {
    if main.0 == 0 || main.1 == 0 || preview.0 == 0 || preview.1 == 0 {
        return false;
    }
    let (a, b) = (main.0 as f64 / main.1 as f64, preview.0 as f64 / preview.1 as f64);
    ((a - b).abs() / a) < 0.02
}

/// Reads the directories in a file's head. `None` when it is neither a JPEG with an EXIF or MPF block nor a TIFF-based file.
fn previews(head: &[u8]) -> Option<Previews> {
    if head.starts_with(&[0xFF, 0xD8]) {
        // a JPEG: the EXIF block (APP1 "Exif\0\0", then a TIFF header) and the Multi-Picture block (APP2 "MPF\0"), both before the
        // picture's own data begins
        let mut jpegs = Vec::new();
        let mut orientation = 1;
        let mut main = None;
        let mut i = 2;
        while i + 4 <= head.len() && head[i] == 0xFF {
            let marker = head[i + 1];
            if marker == 0xDA {
                break;
            }
            let len = u16::from_be_bytes([head[i + 2], head[i + 3]]) as usize;
            let end = (i + 2 + len).min(head.len());
            // the picture's own size: a start-of-frame segment (all of 0xC0..0xCF but the three that are tables)
            if (0xC0..=0xCF).contains(&marker) && ![0xC4, 0xC8, 0xCC].contains(&marker) && i + 9 <= head.len() {
                let (h, w) = (u16::from_be_bytes([head[i + 5], head[i + 6]]), u16::from_be_bytes([head[i + 7], head[i + 8]]));
                main = Some((w as u32, h as u32));
            }
            if marker == 0xE1 && head.get(i + 4..i + 10) == Some(b"Exif\0\0") {
                let base = i + 10;
                if let Some(t) = head.get(base..end) {
                    orientation = tiff_orientation(t).unwrap_or(1);
                    jpegs.extend(tiff_jpegs(t).into_iter().map(|(o, l)| ((base + o) as u64, l)));
                }
            }
            if marker == 0xE2 && head.get(i + 4..i + 8) == Some(b"MPF\0") {
                let base = i + 8;
                if let Some(t) = head.get(base..end) {
                    jpegs.extend(mp_entries(t).into_iter().map(|(o, l)| ((base + o) as u64, l)));
                }
            }
            i += 2 + len;
        }
        // (a picture whose size was not found in the head cannot be checked against its previews: left to the shell)
        return (!jpegs.is_empty() && main.is_some()).then_some(Previews { jpegs, orientation, main });
    }
    if head.starts_with(b"II\x2a\0") || head.starts_with(b"MM\0\x2a") {
        let jpegs: Vec<(u64, usize)> = tiff_jpegs(head).into_iter().map(|(o, l)| (o as u64, l)).collect();
        return (!jpegs.is_empty()).then(|| Previews { jpegs, orientation: tiff_orientation(head).unwrap_or(1), main: None });
    }
    None
}

/// Reads numbers of a TIFF block in its own byte order. `None` for a block that does not begin as one.
struct Tiff<'a> {
    bytes: &'a [u8],
    little: bool,
}

impl<'a> Tiff<'a> {
    fn new(bytes: &'a [u8]) -> Option<Self> {
        match bytes.get(0..2)? {
            b"II" => Some(Self { bytes, little: true }),
            b"MM" => Some(Self { bytes, little: false }),
            _ => None,
        }
    }

    fn u16(&self, at: usize) -> Option<u16> {
        let b = self.bytes.get(at..at.checked_add(2)?)?;
        Some(if self.little { u16::from_le_bytes([b[0], b[1]]) } else { u16::from_be_bytes([b[0], b[1]]) })
    }

    fn u32(&self, at: usize) -> Option<u32> {
        let b = self.bytes.get(at..at.checked_add(4)?)?;
        Some(if self.little { u32::from_le_bytes([b[0], b[1], b[2], b[3]]) } else { u32::from_be_bytes([b[0], b[1], b[2], b[3]]) })
    }

    /// The entries of the directory at `ifd`: (tag, where its 12 bytes begin). Empty for a place that holds none.
    fn entries(&self, ifd: usize) -> Vec<(u16, usize)> {
        let Some(n) = self.u16(ifd) else { return Vec::new() };
        (0..n as usize).filter_map(|e| Some((self.u16(ifd + 2 + e * 12)?, ifd + 2 + e * 12))).collect()
    }

    /// The directory after the one at `ifd` (0: none).
    fn next(&self, ifd: usize) -> usize {
        self.u16(ifd).and_then(|n| self.u32(ifd + 2 + n as usize * 12)).unwrap_or(0) as usize
    }
}

/// The orientation (tag 0x0112) the first directory of a TIFF block states, when it is one of the eight.
fn tiff_orientation(t: &[u8]) -> Option<u8> {
    let tiff = Tiff::new(t)?;
    let ifd = tiff.u32(4)? as usize;
    let (_, at) = tiff.entries(ifd).into_iter().find(|(tag, _)| *tag == 0x0112)?;
    tiff.u16(at + 8).map(|v| v as u8).filter(|v| (1..=8).contains(v))
}

/// (offset, length) of each JPEG a TIFF block names (tags 0x201 and 0x202), offsets from the block's beginning: through the chain
/// of directories and the sub-directories they list (tag 0x14A, where some cameras keep their previews), a bounded number of them.
fn tiff_jpegs(t: &[u8]) -> Vec<(usize, usize)> {
    let Some(tiff) = Tiff::new(t) else { return Vec::new() };
    let mut out = Vec::new();
    let mut todo = vec![tiff.u32(4).unwrap_or(0) as usize];
    let mut seen = 0;
    while let Some(ifd) = todo.pop() {
        if ifd == 0 || seen >= 16 {
            continue;
        }
        seen += 1;
        let (mut off, mut len) = (None, None);
        for (tag, at) in tiff.entries(ifd) {
            match tag {
                0x201 => off = tiff.u32(at + 8),
                0x202 => len = tiff.u32(at + 8),
                0x14A => {
                    // one sub-directory is written in the entry itself, several at the place it points to
                    let count = tiff.u32(at + 4).unwrap_or(0) as usize;
                    if count == 1 {
                        todo.extend(tiff.u32(at + 8).map(|v| v as usize));
                    } else if let Some(list) = tiff.u32(at + 8) {
                        todo.extend((0..count.min(8)).filter_map(|k| tiff.u32(list as usize + k * 4)).map(|v| v as usize));
                    }
                }
                _ => {}
            }
        }
        if let (Some(o), Some(l)) = (off, len) {
            out.push((o as usize, l as usize));
        }
        todo.push(tiff.next(ifd));
    }
    out
}

/// (offset, length) of each picture but the first in a Multi-Picture block's entry list (tag 0xB002), offsets from the block's
/// own TIFF header. The first entry is the picture itself (offset 0).
fn mp_entries(t: &[u8]) -> Vec<(usize, usize)> {
    let Some(tiff) = Tiff::new(t) else { return Vec::new() };
    let ifd = tiff.u32(4).unwrap_or(0) as usize;
    let mut out = Vec::new();
    for (tag, at) in tiff.entries(ifd) {
        if tag != 0xB002 {
            continue;
        }
        let (count, list) = (tiff.u32(at + 4).unwrap_or(0) as usize, tiff.u32(at + 8).unwrap_or(0) as usize);
        for k in 0..(count / 16).min(16) {
            let (size, offset) = (tiff.u32(list + k * 16 + 4).unwrap_or(0) as usize, tiff.u32(list + k * 16 + 8).unwrap_or(0) as usize);
            if offset != 0 && size != 0 {
                out.push((offset, size));
            }
        }
    }
    out
}

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

    /// A JPEG of `w` x `h` whose left half is red and right half green.
    fn halves_jpeg(w: u32, h: u32) -> Vec<u8> {
        let img = image::RgbImage::from_fn(w, h, |x, _| if x < w / 2 { image::Rgb([230, 20, 20]) } else { image::Rgb([20, 230, 20]) });
        let mut out = Vec::new();
        image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 92).encode_image(&img).unwrap();
        out
    }

    /// A little-endian TIFF block whose first directory has the given orientation and names one JPEG at `at`, `len` bytes long.
    fn tiff_naming(orientation: u16, at: u32, len: u32) -> Vec<u8> {
        let mut t = b"II\x2a\0\x08\0\0\0".to_vec();
        t.extend_from_slice(&3u16.to_le_bytes());
        for (tag, kind, value) in [(0x0112u16, 3u16, orientation as u32), (0x0201, 4, at), (0x0202, 4, len)] {
            t.extend_from_slice(&tag.to_le_bytes());
            t.extend_from_slice(&kind.to_le_bytes());
            t.extend_from_slice(&1u32.to_le_bytes());
            t.extend_from_slice(&value.to_le_bytes());
        }
        t.extend_from_slice(&0u32.to_le_bytes());
        t
    }

    /// (a folder of its own for each test: they run side by side and each removes its folder at the end)
    fn temp(name: &str, bytes: &[u8]) -> std::path::PathBuf {
        let test = std::thread::current().name().unwrap_or("t").replace("::", "-");
        let dir = std::env::temp_dir().join(format!("rf-embedded-{}-{test}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let p = dir.join(name);
        std::fs::write(&p, bytes).unwrap();
        p
    }

    /// A RAW-like file (a TIFF whose directory names a preview): the preview is found, shrunk to the size asked for and, with
    /// orientation 6, turned so that what was its left half is at the top.
    #[test]
    fn a_tiff_based_files_preview_is_read_shrunk_and_turned_upright() {
        let preview = halves_jpeg(1200, 800);
        let header = tiff_naming(6, 512, preview.len() as u32);
        let mut file = header.clone();
        file.resize(512, 0);
        file.extend_from_slice(&preview);
        file.extend_from_slice(&[0u8; 4096]);
        let p = temp("turned.arw", &file);
        assert!(handles(&p));
        let b = thumbnail(&p, 256).expect("a thumbnail");
        assert_eq!((b.width, b.height), (171, 256), "1200 x 800 turned a quarter is 800 x 1200, within 256");
        let px = |x: u32, y: u32| {
            let i = ((y * b.width + x) * 4) as usize;
            (b.data[i + 2], b.data[i + 1], b.data[i])
        };
        let (top, bottom) = (px(b.width / 2, 20), px(b.width / 2, b.height - 20));
        assert!(top.0 > 180 && top.1 < 80, "red (the preview's left half) is at the top: {top:?}");
        assert!(bottom.1 > 180 && bottom.0 < 80, "green is at the bottom: {bottom:?}");
        let _ = std::fs::remove_dir_all(p.parent().unwrap());
    }

    /// A preview that is too small for the size asked for, or too small to be trusted at all, is not used; neither is one whose
    /// place lies outside the file.
    #[test]
    fn a_preview_that_does_not_fit_gives_none() {
        let small = halves_jpeg(160, 120);
        let mut file = tiff_naming(1, 512, small.len() as u32);
        file.resize(512, 0);
        file.extend_from_slice(&small);
        let p = temp("small.dng", &file);
        assert!(thumbnail(&p, 96).is_none(), "the 160 px thumbnail with its black bars is never taken");
        let medium = halves_jpeg(800, 600);
        let mut file = tiff_naming(1, 512, medium.len() as u32);
        file.resize(512, 0);
        file.extend_from_slice(&medium);
        let p2 = temp("medium.dng", &file);
        assert!(thumbnail(&p2, 256).is_some());
        assert!(thumbnail(&p2, 1024).is_none(), "800 px is not enough for a 1024 px tile");
        let outside = tiff_naming(1, 9_000_000, 50_000);
        let p3 = temp("outside.nef", &outside);
        assert!(thumbnail(&p3, 256).is_none());
        let p4 = temp("plain.jpg", &halves_jpeg(1200, 800));
        assert!(thumbnail(&p4, 256).is_none(), "a JPEG with no EXIF and no MPF block names no preview");
        let _ = std::fs::remove_dir_all(p.parent().unwrap());
    }

    /// A camera JPEG: the Multi-Picture block after the EXIF block names the preview that follows the main picture.
    #[test]
    fn a_jpegs_multi_picture_preview_is_found() {
        let main = halves_jpeg(96, 64);
        let preview = halves_jpeg(1616, 1080);
        // APP2 "MPF\0" + a TIFF block with one entry 0xB002 (two 16-byte records at offset 26: the main picture, then the preview)
        let mut mpf = b"II\x2a\0\x08\0\0\0".to_vec();
        mpf.extend_from_slice(&1u16.to_le_bytes());
        mpf.extend_from_slice(&0xB002u16.to_le_bytes());
        mpf.extend_from_slice(&7u16.to_le_bytes());
        mpf.extend_from_slice(&32u32.to_le_bytes());
        mpf.extend_from_slice(&26u32.to_le_bytes());
        mpf.extend_from_slice(&0u32.to_le_bytes());
        assert_eq!(mpf.len(), 26);
        let seg_len = 2 + 4 + mpf.len() + 32;
        // the preview's offset is counted from the MPF block's TIFF header, which begins 8 bytes into the segment (after SOI)
        let mpf_base = 2 + 8;
        let preview_at = 2 + 2 + seg_len + (main.len() - 2);
        for (size, offset) in [(main.len() as u32, 0u32), (preview.len() as u32, (preview_at - mpf_base) as u32)] {
            mpf.extend_from_slice(&0u32.to_le_bytes());
            mpf.extend_from_slice(&size.to_le_bytes());
            mpf.extend_from_slice(&offset.to_le_bytes());
            mpf.extend_from_slice(&0u32.to_le_bytes());
        }
        let mut file = vec![0xFF, 0xD8, 0xFF, 0xE2];
        file.extend_from_slice(&(seg_len as u16).to_be_bytes());
        file.extend_from_slice(b"MPF\0");
        file.extend_from_slice(&mpf);
        file.extend_from_slice(&main[2..]);
        assert_eq!(file.len(), preview_at);
        file.extend_from_slice(&preview);
        let p = temp("camera.jpg", &file);
        let b = thumbnail(&p, 256).expect("the preview after the main picture");
        assert_eq!((b.width, b.height), (256, 171));
        let _ = std::fs::remove_dir_all(p.parent().unwrap());
    }

    /// A preview of another shape than the picture (left behind by a crop, or drawn with bars) is not the picture's.
    #[test]
    fn a_preview_of_another_shape_than_its_jpeg_is_not_used() {
        assert!(same_shape((6000, 4000), (1616, 1080)), "a camera's 3:2 picture and its preview");
        assert!(same_shape((4000, 6000), (1080, 1616)));
        assert!(!same_shape((4000, 4000), (1616, 1080)), "cropped square, the old preview left in");
        assert!(!same_shape((6000, 4000), (1080, 1616)), "turned, the old preview left in");
        assert!(!same_shape((6000, 4000), (160, 120)), "a 4:3 thumbnail with bars for a 3:2 picture");
        assert!(!same_shape((0, 0), (1616, 1080)));
    }

    #[test]
    fn only_camera_types_are_handled_and_the_switch_turns_it_off() {
        assert!(handles(Path::new("a.JPG")) && handles(Path::new("b.arw")) && handles(Path::new("c.dng")));
        assert!(!handles(Path::new("d.png")) && !handles(Path::new("e.mp4")) && !handles(Path::new("noext")));
    }
}