flowcull 0.1.0

Fast photo culling with raw/JPEG pair support
//! Image decoding: JPEGs directly, raw files through their embedded JPEG preview.

use std::io::Cursor;
use std::path::Path;

use anyhow::{anyhow, Context, Result};
use image::{DynamicImage, ImageDecoder, ImageReader, RgbImage};

use crate::catalog::JPEG_EXTS;

/// Longest edge of a filmstrip thumbnail.
pub const THUMB_SIZE: u32 = 240;
/// Default longest edge of the main preview when the screen size is unknown.
pub const PREVIEW_SIZE: u32 = 2560;

/// Raw files are read up to here first; the embedded preview sits near the start in every
/// mainstream format, so the bulk of a 40 MB file is only read when nothing is found.
const RAW_HEAD_BYTES: u64 = 8 << 20;

/// Decode `path` downscaled so its longest edge is at most `max_edge`.
pub fn load(path: &Path, max_edge: u32) -> Result<RgbImage> {
    let is_jpeg = path
        .extension()
        .is_some_and(|e| JPEG_EXTS.contains(&e.to_string_lossy().to_ascii_lowercase().as_str()));
    let img = if is_jpeg {
        decode_jpeg(&read(path, None)?)?
    } else {
        // shortcut: a preview past the first 8 MB costs a second, full read.
        match decode_embedded(&read(path, Some(RAW_HEAD_BYTES))?) {
            Ok(img) => img,
            Err(_) => decode_embedded(&read(path, None)?)?,
        }
    };
    let (w, h) = (img.width(), img.height());
    let img = if w.max(h) > max_edge {
        let scale = max_edge as f32 / w.max(h) as f32;
        img.thumbnail((w as f32 * scale) as u32, (h as f32 * scale) as u32)
    } else {
        img
    };
    Ok(img.into_rgb8())
}

fn decode_jpeg(bytes: &[u8]) -> Result<DynamicImage> {
    let mut decoder =
        ImageReader::with_format(Cursor::new(bytes), image::ImageFormat::Jpeg).into_decoder()?;
    // shortcut: orientation comes from the JPEG's own EXIF only; raws whose preview lacks EXIF
    // (some NEF/CR2) show portrait shots rotated. Parse the TIFF IFD0 orientation to upgrade.
    let orientation = decoder
        .orientation()
        .unwrap_or(image::metadata::Orientation::NoTransforms);
    let mut img = DynamicImage::from_decoder(decoder)?;
    img.apply_orientation(orientation);
    Ok(img)
}

/// Read the whole file, or only its first `limit` bytes.
fn read(path: &Path, limit: Option<u64>) -> Result<Vec<u8>> {
    use std::io::Read;
    let file = std::fs::File::open(path).with_context(|| format!("reading {}", path.display()))?;
    let mut bytes = Vec::new();
    match limit {
        Some(n) => file.take(n).read_to_end(&mut bytes),
        None => (&file).read_to_end(&mut bytes),
    }
    .with_context(|| format!("reading {}", path.display()))?;
    Ok(bytes)
}

/// Decode the largest embedded JPEG that actually decodes. Every mainstream raw format (RAF,
/// NEF, CR2, CR3, ARW, DNG, ORF, RW2, PEF, ...) stores a full-size or near-full-size JPEG
/// preview; the cheapest way to show it across all of them is to scan for JPEG start markers
/// and try candidates from the largest declared dimensions down. The largest can be the sensor
/// data itself (lossless JPEG in CR2/DNG), which the decoder rejects, hence the fallback.
fn decode_embedded(bytes: &[u8]) -> Result<DynamicImage> {
    let mut candidates = embedded_jpegs(bytes);
    candidates.sort_by_key(|&(pixels, _)| std::cmp::Reverse(pixels));
    candidates
        .into_iter()
        .find_map(|(_, c)| decode_jpeg(c).ok())
        .ok_or_else(|| anyhow!("no embedded JPEG preview found"))
}

/// JPEG start-marker candidates with their declared pixel count.
fn embedded_jpegs(bytes: &[u8]) -> Vec<(u64, &[u8])> {
    const MAX_CANDIDATES: usize = 64;
    let mut found = Vec::new();
    let mut pos = 0;
    while found.len() < MAX_CANDIDATES {
        let Some(off) = find_soi(&bytes[pos..]) else {
            break;
        };
        let start = pos + off;
        pos = start + 2;
        let candidate = &bytes[start..];
        if let Ok((w, h)) =
            ImageReader::with_format(Cursor::new(candidate), image::ImageFormat::Jpeg)
                .into_dimensions()
        {
            found.push((u64::from(w) * u64::from(h), candidate));
        }
    }
    found
}

fn find_soi(hay: &[u8]) -> Option<usize> {
    hay.windows(3).position(|w| w == [0xFF, 0xD8, 0xFF])
}

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

    fn jpeg_bytes(w: u32, h: u32) -> Vec<u8> {
        let img = RgbImage::from_pixel(w, h, image::Rgb([10, 20, 30]));
        let mut out = Vec::new();
        image::codecs::jpeg::JpegEncoder::new(&mut out)
            .write_image(&img, w, h, image::ExtendedColorType::Rgb8)
            .unwrap();
        out
    }

    #[test]
    fn picks_largest_embedded_jpeg() {
        let small = jpeg_bytes(16, 12);
        let large = jpeg_bytes(64, 48);
        let mut raw = b"FUJIFILMCCD-RAW 0201FF".to_vec();
        raw.extend_from_slice(&small);
        raw.extend_from_slice(&[0u8; 100]);
        raw.extend_from_slice(&large);
        raw.extend_from_slice(&[0u8; 100]);

        let img = decode_embedded(&raw).unwrap();
        assert_eq!((img.width(), img.height()), (64, 48));
    }

    #[test]
    fn falls_back_when_largest_candidate_does_not_decode() {
        // The larger JPEG is rewritten as lossless (SOF0 -> SOF3), like the sensor data that
        // CR2/DNG files embed; the decoder does not support it and the smaller preview must win.
        let mut large = jpeg_bytes(64, 48);
        let sof = large.windows(2).position(|w| w == [0xFF, 0xC0]).unwrap();
        large[sof + 1] = 0xC3;
        let mut raw = large;
        raw.extend_from_slice(&[0u8; 64]);
        raw.extend_from_slice(&jpeg_bytes(32, 24));

        let img = decode_embedded(&raw).unwrap();
        assert_eq!((img.width(), img.height()), (32, 24));
    }

    #[test]
    fn load_downscales_to_max_edge() {
        let dir = std::env::temp_dir();
        let path = dir.join(format!("flowcull-decode-{}.jpg", std::process::id()));
        std::fs::write(&path, jpeg_bytes(200, 100)).unwrap();
        let img = load(&path, 50).unwrap();
        assert_eq!((img.width(), img.height()), (50, 25));
        std::fs::remove_file(&path).unwrap();
    }
}

#[cfg(test)]
mod real_file_tests {
    /// Run with `FLOWCULL_SAMPLE=/path/to/photo.raf cargo test -- --ignored --nocapture`.
    #[test]
    #[ignore]
    fn decodes_sample_file() {
        let path = std::path::PathBuf::from(std::env::var("FLOWCULL_SAMPLE").unwrap());
        let t = std::time::Instant::now();
        let img = super::load(&path, super::PREVIEW_SIZE).unwrap();
        println!(
            "{}: {}x{} in {:?}",
            path.display(),
            img.width(),
            img.height(),
            t.elapsed()
        );
        let t = std::time::Instant::now();
        let img = super::load(&path, super::THUMB_SIZE).unwrap();
        println!(
            "thumb {}x{} in {:?}",
            img.width(),
            img.height(),
            t.elapsed()
        );
    }
}