rosier 0.3.0

A fast picture and video viewer for large folders
//! Thumbnails: generate once (JPEG fast path, image crate fallback, libmpv for
//! video, AVIF, HEIC and JPEG XL), keep them in a disk cache, and hand BGRA
//! pixels to the UI.

use std::fs;
use std::io::Write as _;
use std::path::{Path, PathBuf};

use anyhow::{Result, bail};
use fast_image_resize::images::Image;
use fast_image_resize::{FilterType, PixelType, ResizeAlg, ResizeOptions, Resizer};

use crate::media::{Entry, Kind};
use crate::orient;
use crate::turbo::{self, Bgra};

/// Smallest side of the square grid thumbnails, used for tiles up to this
/// many pixels wide; larger tiles get 512 or 768 (see `side_for`).
pub const SQUARE_PX: u32 = 320;

pub fn cache_dir(side: u32) -> PathBuf {
    // Tests must not fill the user's own cache.
    #[cfg(test)]
    let base = std::env::temp_dir().join(format!("rosier-test-cache-{}", std::process::id()));
    #[cfg(not(test))]
    let base = std::env::var_os("XDG_CACHE_HOME")
        .map(PathBuf::from)
        .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cache")))
        .unwrap_or_else(std::env::temp_dir);
    // "-v2": thumbnails since EXIF orientation is applied. Older ones may
    // be sideways, so they are not reused (see `remove_old_cache`).
    base.join("rosier").join(format!("square-{side}-v2"))
}

/// Deletes thumbnail folders from before EXIF orientation was applied.
pub fn remove_old_cache() {
    let Some(root) = cache_dir(SQUARE_PX).parent().map(Path::to_path_buf) else { return };
    for side in [SQUARE_PX, 512, 768] {
        let _ = fs::remove_dir_all(root.join(format!("square-{side}")));
    }
}

/// Caps how many non-JPEG images decode at once. PNGs cannot be decoded at
/// reduced size, and a burst of 32 full-size 8K PNGs took 7 GB of RAM.
struct Gate {
    busy: std::sync::Mutex<usize>,
    free: std::sync::Condvar,
}

static HEAVY: Gate = Gate { busy: std::sync::Mutex::new(0), free: std::sync::Condvar::new() };
const HEAVY_SLOTS: usize = 4;

struct Slot;

impl Gate {
    fn enter(&'static self) -> Slot {
        let mut n = self.busy.lock().unwrap_or_else(|e| e.into_inner());
        while *n >= HEAVY_SLOTS {
            n = self.free.wait(n).unwrap_or_else(|e| e.into_inner());
        }
        *n += 1;
        Slot
    }
}

impl Drop for Slot {
    fn drop(&mut self) {
        let mut n = HEAVY.busy.lock().unwrap_or_else(|e| e.into_inner());
        *n -= 1;
        HEAVY.free.notify_one();
    }
}

/// FNV-1a: stable across Rust versions, unlike `DefaultHasher`.
fn fnv1a(bytes: &[u8], mut h: u64) -> u64 {
    for b in bytes {
        h ^= *b as u64;
        h = h.wrapping_mul(0x100000001b3);
    }
    h
}

fn cache_path(e: &Entry, side: u32) -> PathBuf {
    let mut h = fnv1a(e.path.as_os_str().as_encoded_bytes(), 0xcbf29ce484222325);
    h = fnv1a(&e.size.to_le_bytes(), h);
    h = fnv1a(&e.mtime.to_le_bytes(), h);
    let name = format!("{h:016x}");
    cache_dir(side).join(&name[..2]).join(format!("{name}.jpg"))
}

/// Resizes BGRA pixels so the longer side is at most `max_long`.
pub fn fit(b: Bgra, max_long: u32) -> Result<Bgra> {
    let long = b.width.max(b.height);
    if long <= max_long {
        return Ok(b);
    }
    let scale = max_long as f64 / long as f64;
    let w = ((b.width as f64 * scale).round() as u32).max(1);
    let h = ((b.height as f64 * scale).round() as u32).max(1);
    let src = Image::from_vec_u8(b.width, b.height, b.pixels, PixelType::U8x4)?;
    let mut dst = Image::new(w, h, PixelType::U8x4);
    // Pixels are opaque, so skip alpha premultiplication.
    let opts = ResizeOptions::new().resize_alg(ResizeAlg::Convolution(FilterType::Bilinear)).use_alpha(false);
    Resizer::new().resize(&src, &mut dst, &opts)?;
    Ok(Bgra { width: w, height: h, pixels: dst.into_vec() })
}

fn decode_generic(data: &[u8]) -> Result<Bgra> {
    use image::ImageDecoder as _;
    // Sniff the bytes: files named .jpg are sometimes PNGs and vice versa.
    let mut decoder = image::ImageReader::new(std::io::Cursor::new(data)).with_guessed_format()?.into_decoder()?;
    let orientation = decoder.orientation().unwrap_or(image::metadata::Orientation::NoTransforms);
    let mut img = image::DynamicImage::from_decoder(decoder)?;
    img.apply_orientation(orientation);
    let img = img.into_rgba8();
    let (width, height) = img.dimensions();
    let mut pixels = img.into_raw();
    for px in pixels.as_chunks_mut::<4>().0 {
        px.swap(0, 2);
    }
    Ok(Bgra { width, height, pixels })
}

/// Decodes a JPEG at reduced size, turned upright. `min_long` is the
/// smallest long side wanted (see `turbo::decode_scaled`).
fn decode_jpeg(data: &[u8], min_long: u32) -> Result<Bgra> {
    Ok(orient::apply(turbo::decode_scaled(data, min_long)?, orient::jpeg_orientation(data)))
}

/// A picture decoded for the viewer, and its full upright size.
pub struct Decoded {
    /// The picture, or the first frame of an animation.
    pub image: Bgra,
    pub full: (u32, u32),
    /// Every frame of an animated GIF or WebP and how long it shows; empty
    /// for a still picture.
    pub frames: Vec<(Bgra, std::time::Duration)>,
}

/// Decodes an image file so its longer side is at most `max_long`.
pub fn decode_image(e: &Entry, max_long: u32) -> Result<Decoded> {
    if e.decoded_by_mpv() {
        let _slot = HEAVY.enter();
        let (image, full) = crate::mpv::grab(&e.path, "0", max_long)?;
        return Ok(Decoded { image, full, frames: Vec::new() });
    }
    let data = fs::read(&e.path)?;
    if data.is_empty() {
        bail!("empty file");
    }
    if data.starts_with(&[0xFF, 0xD8])
        && let Ok((w, h)) = turbo::dimensions(&data)
        && let Ok(b) = decode_jpeg(&data, max_long)
    {
        // Orientations 5 to 8 turn the picture a quarter.
        let full = if orient::jpeg_orientation(&data) >= 5 { (h, w) } else { (w, h) };
        return Ok(Decoded { image: fit(b, max_long)?, full, frames: Vec::new() });
    }
    let _slot = HEAVY.enter();
    if let Ok(Some(a)) = crate::anim::decode(&data, max_long) {
        return Ok(Decoded { image: a.frames[0].0.clone(), full: a.full, frames: a.frames });
    }
    let b = decode_generic(&data)?;
    let full = (b.width, b.height);
    Ok(Decoded { image: fit(b, max_long)?, full, frames: Vec::new() })
}

/// Center-crops to a square and scales it to `side`.
pub fn square(b: Bgra, side: u32) -> Result<Bgra> {
    let short = b.width.min(b.height).max(1);
    let (x0, y0) = ((b.width - short) / 2, (b.height - short) / 2);
    let mut crop = Vec::with_capacity((short * short * 4) as usize);
    for y in y0..y0 + short {
        let row = (y * b.width + x0) as usize * 4;
        crop.extend_from_slice(&b.pixels[row..row + short as usize * 4]);
    }
    if short <= side {
        return Ok(Bgra { width: short, height: short, pixels: crop });
    }
    fit(Bgra { width: short, height: short, pixels: crop }, side)
}

/// Decodes so the *shorter* side is at least `side`, for square crops.
fn decode_for_square(e: &Entry, side: u32) -> Result<Bgra> {
    if e.decoded_by_mpv() {
        return crate::mpv::grab_frame(&e.path, "0", side * 2);
    }
    let data = fs::read(&e.path)?;
    if data.is_empty() {
        bail!("empty file");
    }
    if data.starts_with(&[0xFF, 0xD8])
        && let Ok((w, h)) = turbo::dimensions(&data)
    {
        let (long, short) = (w.max(h).max(1), w.min(h).max(1));
        let min_long = (side as u64 * long as u64).div_ceil(short as u64) as u32;
        if let Ok(b) = decode_jpeg(&data, min_long) {
            return Ok(b);
        }
    }
    let _slot = HEAVY.enter();
    decode_generic(&data)
}

fn generate(e: &Entry, side: u32) -> Result<Bgra> {
    let full = match e.kind {
        Kind::Image => decode_for_square(e, side)?,
        // 10% in skips most intros and title cards; very short or odd files
        // fall back to the first frame. Twice the side on the long edge keeps
        // the short edge above `side` for anything up to 2:1.
        Kind::Video => crate::mpv::grab_frame(&e.path, "10%", side * 2)
            .or_else(|_| crate::mpv::grab_frame(&e.path, "0", side * 2))?,
    };
    square(full, side)
}

fn write_cache(path: &Path, jpeg: &[u8]) -> Result<()> {
    if let Some(dir) = path.parent() {
        fs::create_dir_all(dir)?;
    }
    let tmp = path.with_extension("tmp");
    fs::File::create(&tmp)?.write_all(jpeg)?;
    fs::rename(tmp, path)?;
    Ok(())
}

/// The cached thumbnail, if there is one. Cheap: one small JPEG decode.
pub fn cached(e: &Entry, side: u32) -> Option<Bgra> {
    let data = fs::read(cache_path(e, side)).ok()?;
    turbo::decode_scaled(&data, u32::MAX).ok()
}

/// Generates a thumbnail and stores it in the cache.
pub fn make(e: &Entry, side: u32) -> Result<Bgra> {
    let b = generate(e, side)?;
    let jpeg = turbo::encode(&b, 82)?;
    // A failed cache write only costs speed next time.
    let _ = write_cache(&cache_path(e, side), &jpeg);
    Ok(b)
}

/// Whether making a thumbnail for `e` is slow or memory-hungry (video, or
/// an image format that cannot be decoded at reduced size).
pub fn is_heavy(e: &Entry) -> bool {
    e.kind == Kind::Video || !e.is_jpeg()
}

/// Square thumbnail size for tiles `tile_px` physical pixels wide.
pub fn side_for(tile_px: f32) -> u32 {
    if tile_px <= SQUARE_PX as f32 {
        SQUARE_PX
    } else if tile_px <= 512.0 {
        512
    } else {
        768
    }
}

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

    #[test]
    fn square_crops_the_center_and_scales_down() {
        // 8x4 image: left half black, right half white.
        let mut pixels = Vec::new();
        for _y in 0..4 {
            for x in 0..8 {
                let v = if x < 4 { 0 } else { 255 };
                pixels.extend_from_slice(&[v, v, v, 255]);
            }
        }
        let s = square(Bgra { width: 8, height: 4, pixels }, 2).unwrap();
        assert_eq!((s.width, s.height), (2, 2));
        // The center 4x4 is half black, half white.
        assert!(s.pixels[0] < 128 && s.pixels[4] > 128);
    }

    #[test]
    fn small_images_are_not_upscaled() {
        let s = square(Bgra { width: 3, height: 5, pixels: vec![9; 3 * 5 * 4] }, 320).unwrap();
        assert_eq!((s.width, s.height), (3, 3));
    }
}

#[cfg(test)]
mod orientation_tests {
    use super::*;
    use crate::library::tests::entry;

    /// A real JPEG, `w`x`h`, carrying EXIF orientation `o`.
    fn rotated_jpeg(path: &Path, w: u32, h: u32, o: u16) {
        let img = image::RgbImage::from_fn(w, h, |x, _| image::Rgb([if x < w / 2 { 0 } else { 255 }; 3]));
        let mut jpeg = Vec::new();
        image::codecs::jpeg::JpegEncoder::new(&mut jpeg).encode_image(&img).unwrap();
        let exif = crate::orient::tests::exif_jpeg(o, true);
        // Splice the EXIF segment (after its fake SOI and APP0) in after SOI.
        let app1 = exif.windows(2).position(|p| p == [0xFF, 0xE1]).unwrap();
        let sos = exif.windows(2).position(|p| p == [0xFF, 0xDA]).unwrap();
        let mut out = jpeg[..2].to_vec();
        out.extend(&exif[app1..sos]);
        out.extend(&jpeg[2..]);
        std::fs::write(path, out).unwrap();
    }

    #[test]
    fn portrait_photos_stand_upright_in_the_viewer_and_the_grid() {
        let dir = std::env::temp_dir().join(format!("rosier-orient-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("phone.jpg");
        // Stored 64x32 landscape, tagged "turn 90° clockwise".
        rotated_jpeg(&path, 64, 32, 6);
        let e = entry(1, path.to_str().unwrap(), Kind::Image, 1, 1);
        let d = decode_image(&e, 1000).unwrap();
        assert_eq!((d.image.width, d.image.height), (32, 64));
        assert_eq!(d.full, (32, 64));
        // The left half (black) is now on top.
        assert!(d.image.pixels[0] < 60);
        assert!(d.image.pixels[d.image.pixels.len() - 4] > 190);
        let t = generate(&e, 16).unwrap();
        assert_eq!((t.width, t.height), (16, 16));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn avif_heic_and_jpeg_xl_decode_through_libmpv() {
        if !crate::mpv::available() {
            eprintln!("libmpv not found: skipped");
            return;
        }
        let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
        for name in ["still.avif", "still.heic", "still.jxl"] {
            let path = fixtures.join(name);
            let e = entry(1, path.to_str().unwrap(), Kind::Image, 1, 1);
            assert!(e.decoded_by_mpv(), "{name}");
            match decode_image(&e, 48) {
                Ok(d) => {
                    assert_eq!((d.image.width, d.image.height, d.full), (48, 32, (96, 64)), "{name}");
                    let t = generate(&e, 16).unwrap();
                    assert_eq!((t.width, t.height), (16, 16), "{name}");
                }
                // HEIF arrived in FFmpeg 7; an older libmpv cannot read it,
                // and the tile shows as unreadable.
                Err(err) if name == "still.heic" => eprintln!("{name}: {err:#} (older FFmpeg)"),
                Err(err) => panic!("{name}: {err:#}"),
            }
        }
    }

    #[test]
    fn animated_gifs_keep_every_frame() {
        let dir = std::env::temp_dir().join(format!("rosier-anim-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("loop.gif");
        std::fs::write(&path, crate::anim::tests::gif(4, 60, 30, 8)).unwrap();
        let e = entry(1, path.to_str().unwrap(), Kind::Image, 1, 1);
        let d = decode_image(&e, 30).unwrap();
        assert_eq!((d.frames.len(), d.full), (4, (60, 30)));
        assert_eq!((d.image.width, d.image.height), (30, 15), "the first frame stands for it");
        // The grid shows the first frame.
        assert_eq!(generate(&e, 16).unwrap().width, 16);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn other_formats_decode_upright_too() {
        let dir = std::env::temp_dir().join(format!("rosier-orient-png-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("plain.png");
        image::RgbImage::new(40, 20).save(&path).unwrap();
        let e = entry(1, path.to_str().unwrap(), Kind::Image, 1, 1);
        let d = decode_image(&e, 10).unwrap();
        assert_eq!((d.image.width, d.image.height, d.full), (10, 5, (40, 20)));
        let _ = std::fs::remove_dir_all(&dir);
    }
}