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_root() -> PathBuf {
#[cfg(test)]
let base = std::env::temp_dir().join(format!("rosier-test-cache-{}", std::process::id()));
#[cfg(not(test))]
let base = crate::dirs::cache_home().unwrap_or_else(std::env::temp_dir);
base.join("rosier")
}
fn cache_dir(side: u32) -> PathBuf {
cache_root().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 (w, h) = crate::pixels::fit_size(b.width, b.height, max_long);
if (w, h) == (b.width, b.height) {
return Ok(b);
}
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();
Ok(crate::icc::correct(data, Bgra::from_rgba(width, height, img.into_raw())))
}
fn decode_jpeg(data: &[u8], min_long: u32) -> Result<Bgra> {
let b = crate::icc::correct(data, turbo::decode_scaled(data, min_long)?);
Ok(orient::apply(b, orient::jpeg_orientation(data)))
}
pub struct Decoded {
pub image: Bgra,
pub full: (u32, u32),
pub frames: Vec<(Bgra, std::time::Duration)>,
pub more: bool,
}
impl Decoded {
fn still(image: Bgra, full: (u32, u32)) -> Self {
Self { image, full, frames: Vec::new(), more: false }
}
}
fn checker_under(b: &mut Bgra) {
if !b.pixels.as_chunks::<4>().0.iter().any(|p| p[3] != 255) {
return;
}
const LIGHT: u32 = 0x5a;
const DARK: u32 = 0x40;
let sq = (b.width.max(b.height) / 48).max(4);
let w = b.width as usize;
for (k, p) in b.pixels.as_chunks_mut::<4>().0.iter_mut().enumerate() {
let a = u32::from(p[3]);
if a == 255 {
continue;
}
let (x, y) = ((k % w) as u32, (k / w) as u32);
let bg = if ((x / sq) + (y / sq)).is_multiple_of(2) { LIGHT } else { DARK };
for c in &mut p[..3] {
*c = ((u32::from(*c) * a + bg * (255 - a)) / 255) as u8;
}
p[3] = 255;
}
}
pub fn decode_image(e: &Entry, max_long: u32) -> Result<Decoded> {
decode_with(e, max_long, true)
}
pub fn decode_first(e: &Entry, max_long: u32) -> Result<Decoded> {
decode_with(e, max_long, false)
}
fn decode_with(e: &Entry, max_long: u32, all_frames: bool) -> Result<Decoded> {
let mut d = decode_image_raw(e, max_long, all_frames)?;
if d.frames.is_empty() && !d.more && may_be_transparent(e) {
checker_under(&mut d.image);
}
Ok(d)
}
fn may_be_transparent(e: &Entry) -> bool {
let ext = crate::media::ext_lower(&e.path).unwrap_or_default();
!(e.decoded_by_mpv()
|| matches!(ext.as_str(), "jpg" | "jpeg" | "jpe" | "jfif")
|| crate::formats::RAW.contains(&ext.as_str()))
}
fn decode_image_raw(e: &Entry, max_long: u32, all_frames: bool) -> Result<Decoded> {
if e.decoded_by_mpv() {
let _slot = HEAVY.enter();
let (image, full) = crate::mpv::grab(&e.path, "0", max_long, true)?;
return Ok(Decoded::still(image, full));
}
let data = crate::book::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::still(fit(b, max_long)?, full));
}
if let Some(b) = decode_other(e, &data, max_long) {
let b = b?;
let full = (b.width, b.height);
return Ok(Decoded::still(fit(b, max_long)?, full));
}
if crate::formats::is_webp(&data)
&& let Some(r) = crate::formats::decode_webp(&data, max_long)
{
let (b, full) = r?;
let b = crate::icc::correct(&data, b);
return Ok(Decoded::still(fit(b, max_long)?, full));
}
let _slot = HEAVY.enter();
if !all_frames && let Ok(Some((image, full))) = crate::anim::first(&data, max_long) {
return Ok(Decoded { image, full, frames: Vec::new(), more: true });
}
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, more: false });
}
let b = decode_generic(&data)?;
let full = (b.width, b.height);
Ok(Decoded::still(fit(b, max_long)?, full))
}
pub fn cut(b: &Bgra, n: [f32; 4], size: (u32, u32), nearest: bool) -> Result<Bgra> {
let (w, h) = (b.width as f64, b.height as f64);
let (x0, y0) = (n[0] as f64 * w, n[1] as f64 * h);
let (cw, ch) = ((n[2] - n[0]) as f64 * w, (n[3] - n[1]) as f64 * h);
let src = fast_image_resize::images::ImageRef::new(b.width, b.height, &b.pixels, PixelType::U8x4)?;
let mut dst = Image::new(size.0.max(1), size.1.max(1), PixelType::U8x4);
let opts = ResizeOptions::new()
.resize_alg(if nearest { ResizeAlg::Nearest } else { ResizeAlg::Convolution(FilterType::Bilinear) })
.use_alpha(false)
.crop(x0, y0, cw, ch);
Resizer::new().resize(&src, &mut dst, &opts)?;
Ok(Bgra { width: dst.width(), height: dst.height(), pixels: dst.into_vec() })
}
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> {
if e.decoded_by_mpv() {
return crate::mpv::grab_frame(&e.path, "0", side * 2);
}
let data = crate::book::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);
}
}
if let Some(b) = decode_other(e, &data, side * 2) {
return b;
}
if crate::formats::is_webp(&data)
&& let Some(r) = crate::formats::decode_webp(&data, side * 2)
{
return r.map(|(b, _)| crate::icc::correct(&data, b));
}
let _slot = HEAVY.enter();
decode_generic(&data)
}
fn decode_other(e: &Entry, data: &[u8], min_long: u32) -> Option<Result<Bgra>> {
use crate::formats;
let ext = crate::media::ext_lower(&e.path)?;
Some(match ext.as_str() {
"svg" => formats::decode_svg(data, min_long),
"psd" => {
let _slot = HEAVY.enter();
formats::decode_psd(data)
}
e if formats::RAW.contains(&e) => match formats::raw_preview(data) {
Some((jpeg, raw_orientation)) => {
let o = match orient::jpeg_orientation(jpeg) {
1 => raw_orientation,
o => o,
};
turbo::decode_scaled(jpeg, min_long).map(|b| orient::apply(b, o))
}
None => Err(anyhow::anyhow!("no preview in the raw file")),
},
_ => return None,
})
}
fn generate(e: &Entry, side: u32) -> Result<Bgra> {
let full = match e.kind {
Kind::Image => {
let mut b = decode_for_square(e, side)?;
if may_be_transparent(e) {
checker_under(&mut b);
}
b
}
Kind::Video => crate::mpv::grab_frame(&e.path, "10%", side * 2)
.or_else(|_| crate::mpv::grab_frame(&e.path, "0", side * 2))?,
Kind::Book => {
let pages = crate::book::pages(&e.path)?;
let cover = crate::book::page_entry(e, pages.first().map_or("", String::as_str));
decode_for_square(&cover, side)?
}
};
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 {
#[test]
fn transparent_parts_get_a_checkerboard_and_opaque_pictures_stay() {
let mut px = Vec::new();
for x in 0..96u32 {
for _ in 0..1 {
px.extend_from_slice(if x < 48 { &[0, 0, 0, 0] } else { &[0, 0, 255, 255] });
}
}
px.extend(px.clone());
px[50 * 4..50 * 4 + 4].copy_from_slice(&[0, 0, 255, 128]);
let mut b = Bgra { width: 96, height: 2, pixels: px };
checker_under(&mut b);
let at = |x: usize| &b.pixels[x * 4..x * 4 + 4];
assert!(b.pixels.as_chunks::<4>().0.iter().all(|p| p[3] == 255), "opaque afterwards");
assert_eq!(at(0), &[0x5a, 0x5a, 0x5a, 255]);
assert_eq!(at(4), &[0x40, 0x40, 0x40, 255]);
assert_eq!(at(60), &[0, 0, 255, 255], "opaque pixels untouched");
assert!(at(50)[2] > 0x80 && at(50)[0] < 0x40, "half see-through red over the board: {:?}", at(50));
let mut opaque = Bgra { width: 1, height: 1, pixels: vec![1, 2, 3, 255] };
checker_under(&mut opaque);
assert_eq!(opaque.pixels, vec![1, 2, 3, 255]);
}
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 avif_heic_and_jpeg_xl_decode_through_libmpv() {
if !crate::mpv::can_load() {
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}");
}
Err(err) if name == "still.heic" => eprintln!("{name}: {err:#} (older FFmpeg)"),
Err(err) => panic!("{name}: {err:#}"),
}
}
}
fn off_reference(b: &Bgra) -> f64 {
let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
let want = decode_generic(&std::fs::read(fixtures.join("still.png")).unwrap()).unwrap();
assert_eq!((b.width, b.height), (want.width, want.height));
let sum: u64 = b
.pixels
.as_chunks::<4>()
.0
.iter()
.zip(want.pixels.as_chunks::<4>().0)
.map(|(p, q)| (0..3).map(|c| p[c].abs_diff(q[c]) as u64).sum::<u64>())
.sum();
sum as f64 / (b.width * b.height * 3) as f64
}
#[test]
fn svg_psd_and_raw_previews_match_the_reference_picture() {
let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
let dir = std::env::temp_dir().join(format!("rosier-formats-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let reference = decode_generic(&std::fs::read(fixtures.join("still.png")).unwrap()).unwrap();
let turned = orient::apply(reference, 8);
let jpeg = turbo::encode(&turned, 95).unwrap();
let raw = crate::formats::tests::tiff(
&[(0x0112, 3, 1, 6), (0x0201, 4, 1, u32::MAX), (0x0202, 4, 1, jpeg.len() as u32)],
&[],
&[jpeg],
);
std::fs::write(dir.join("still.nef"), raw).unwrap();
let cases =
[(fixtures.join("still.svg"), 1.0), (fixtures.join("still.psd"), 0.0), (dir.join("still.nef"), 3.0)];
for (path, tolerance) in cases {
let e = entry(1, path.to_str().unwrap(), Kind::Image, 1, 1);
let d = decode_image(&e, 96).unwrap_or_else(|err| panic!("{}: {err:#}", path.display()));
assert_eq!(d.full, (96, 64), "{}", path.display());
let off = off_reference(&d.image);
assert!(off <= tolerance, "{}: {off:.2} off the reference", path.display());
let t = generate(&e, 16).unwrap();
assert_eq!((t.width, t.height), (16, 16), "{}", path.display());
}
std::fs::remove_dir_all(&dir).unwrap();
}
#[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");
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);
}
}