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};
pub const SQUARE_PX: u32 = 320;
pub fn cache_dir(side: u32) -> PathBuf {
#[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);
base.join("rosier").join(format!("square-{side}-v2"))
}
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}")));
}
}
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();
}
}
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"))
}
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);
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 _;
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 })
}
fn decode_jpeg(data: &[u8], min_long: u32) -> Result<Bgra> {
Ok(orient::apply(turbo::decode_scaled(data, min_long)?, orient::jpeg_orientation(data)))
}
pub struct Decoded {
pub image: Bgra,
pub full: (u32, u32),
}
pub fn decode_image(e: &Entry, max_long: u32) -> Result<Decoded> {
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)
{
let full = if orient::jpeg_orientation(&data) >= 5 { (h, w) } else { (w, h) };
return Ok(Decoded { image: fit(b, max_long)?, full });
}
let _slot = HEAVY.enter();
let b = decode_generic(&data)?;
let full = (b.width, b.height);
Ok(Decoded { image: fit(b, max_long)?, full })
}
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)
}
fn decode_for_square(e: &Entry, side: u32) -> Result<Bgra> {
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)?,
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(())
}
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()
}
pub fn make(e: &Entry, side: u32) -> Result<Bgra> {
let b = generate(e, side)?;
let jpeg = turbo::encode(&b, 82)?;
let _ = write_cache(&cache_path(e, side), &jpeg);
Ok(b)
}
pub fn is_heavy(e: &Entry) -> bool {
e.kind == Kind::Video || !e.is_jpeg()
}
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() {
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));
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;
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);
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");
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));
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 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);
}
}