S017: thumbnail crate with freedesktop cache, generators and worker pool

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-18 10:10:46 -06:00
commit d02cd52413
6 changed files with 1084 additions and 27 deletions

View file

@ -4,3 +4,11 @@ version.workspace = true
edition.workspace = true
license.workspace = true
publish.workspace = true
[dependencies]
image.workspace = true
resvg.workspace = true
lofty.workspace = true
md-5.workspace = true
png.workspace = true
mime_guess.workspace = true

View file

@ -0,0 +1,54 @@
//! `cargo run -p tunal-thumbs --example thumb -- [--size normal|large|x-large] <file>...`
//! Prints the cache path of each file's thumbnail (honours `XDG_CACHE_HOME`).
use std::path::PathBuf;
use std::sync::mpsc;
use tunal_thumbs::{Config, Outcome, Priority, Request, ThumbSize, Thumbnailer};
fn main() {
let mut size = ThumbSize::Normal;
let mut files = Vec::new();
let mut args = std::env::args().skip(1);
while let Some(arg) = args.next() {
if arg == "--size" {
size = match args.next().as_deref() {
Some("normal") => ThumbSize::Normal,
Some("large") => ThumbSize::Large,
Some("x-large") => ThumbSize::XLarge,
_ => usage(),
};
} else {
files.push(arg);
}
}
if files.is_empty() {
usage();
}
let thumbnailer = Thumbnailer::new(Config::default());
let (tx, rx) = mpsc::channel();
for (i, file) in files.iter().enumerate() {
let path = std::path::absolute(PathBuf::from(file)).expect("absolute path");
let tx = tx.clone();
thumbnailer.request(Request {
path,
size,
priority: Priority::Normal,
remote: false,
done: Box::new(move |outcome| tx.send((i, outcome)).unwrap()),
});
}
let mut results: Vec<_> = (0..files.len()).map(|_| rx.recv().unwrap()).collect();
results.sort_by_key(|(i, _)| *i);
for (i, outcome) in results {
match outcome {
Outcome::Ready(p) => println!("{}: {}", files[i], p.display()),
other => println!("{}: {other:?}", files[i]),
}
}
}
fn usage() -> ! {
eprintln!("usage: thumb [--size normal|large|x-large] <file>...");
std::process::exit(1);
}

View file

@ -0,0 +1,176 @@
//! Freedesktop thumbnail cache: paths, validity checks and PNG writing with `Thumb::*` text.
use std::fs::{self, File};
use std::io::BufWriter;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt};
use std::path::{Path, PathBuf};
use std::time::UNIX_EPOCH;
use image::RgbaImage;
use md5::{Digest, Md5};
use crate::ThumbSize;
/// Name of our `fail/` subdirectory, so other apps' failures don't hide files from us.
fn fail_app() -> String {
format!("tunal-{}", env!("CARGO_PKG_VERSION"))
}
/// `$XDG_CACHE_HOME/thumbnails` (or `~/.cache/thumbnails`).
pub fn thumbnail_dir() -> PathBuf {
let base = std::env::var_os("XDG_CACHE_HOME")
.filter(|v| !v.is_empty())
.map(PathBuf::from)
.filter(|p| p.is_absolute())
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cache")))
.unwrap_or_else(|| PathBuf::from("/tmp"));
base.join("thumbnails")
}
/// `file://` URI of an absolute path, percent-encoded as the spec's MD5 input requires.
pub(crate) fn file_uri(path: &Path) -> String {
let mut uri = String::from("file://");
for &b in path.as_os_str().as_bytes() {
if b.is_ascii_alphanumeric() || b"-_.~/".contains(&b) {
uri.push(b as char);
} else {
uri.push_str(&format!("%{b:02X}"));
}
}
uri
}
fn md5_name(uri: &str) -> String {
let digest = Md5::digest(uri.as_bytes());
let mut name = String::with_capacity(36);
for b in digest {
name.push_str(&format!("{b:02x}"));
}
name.push_str(".png");
name
}
/// Where the thumbnail of `path` lives (or would live) in the cache.
pub fn cache_path(path: &Path, size: ThumbSize) -> PathBuf {
thumbnail_dir()
.join(size.dir_name())
.join(md5_name(&file_uri(path)))
}
fn fail_path(path: &Path) -> PathBuf {
thumbnail_dir()
.join("fail")
.join(fail_app())
.join(md5_name(&file_uri(path)))
}
pub(crate) fn in_cache(path: &Path) -> bool {
path.starts_with(thumbnail_dir())
}
pub(crate) fn mtime_secs(meta: &fs::Metadata) -> u64 {
meta.modified()
.ok()
.and_then(|t| t.duration_since(UNIX_EPOCH).ok())
.map_or(0, |d| d.as_secs())
}
/// Reads the `Thumb::MTime` text of a cached PNG.
fn stored_mtime(png_path: &Path) -> Option<u64> {
let decoder = png::Decoder::new(std::io::BufReader::new(File::open(png_path).ok()?));
let reader = decoder.read_info().ok()?;
reader
.info()
.uncompressed_latin1_text
.iter()
.find(|t| t.keyword == "Thumb::MTime")
.and_then(|t| t.text.trim().parse().ok())
}
/// Existing, up-to-date thumbnail.
pub(crate) fn valid(path: &Path, size: ThumbSize, mtime: u64) -> Option<PathBuf> {
let cached = cache_path(path, size);
(stored_mtime(&cached) == Some(mtime)).then_some(cached)
}
/// An earlier failure recorded for this unchanged file.
pub(crate) fn known_failure(path: &Path, mtime: u64) -> bool {
stored_mtime(&fail_path(path)) == Some(mtime)
}
fn write_png(
dest: &Path,
width: u32,
height: u32,
rgba: &[u8],
texts: &[(&str, String)],
) -> std::io::Result<()> {
let dir = dest.parent().expect("cache files have a parent");
fs::DirBuilder::new()
.recursive(true)
.mode(0o700)
.create(dir)?;
let tmp = dir.join(format!(
".tunal-{}-{:x}.tmp",
std::process::id(),
rand_suffix()
));
let result = (|| {
let file = fs::OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(&tmp)?;
let mut encoder = png::Encoder::new(BufWriter::new(file), width, height);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
for (key, value) in texts {
encoder
.add_text_chunk((*key).into(), value.clone())
.map_err(std::io::Error::other)?;
}
let mut writer = encoder.write_header().map_err(std::io::Error::other)?;
writer
.write_image_data(rgba)
.map_err(std::io::Error::other)?;
writer.finish().map_err(std::io::Error::other)?;
fs::rename(&tmp, dest)
})();
if result.is_err() {
let _ = fs::remove_file(&tmp);
}
result
}
fn rand_suffix() -> u64 {
use std::hash::{BuildHasher, RandomState};
RandomState::new().hash_one(std::time::SystemTime::now())
}
/// Stores a finished thumbnail and returns its cache path.
pub(crate) fn store(
path: &Path,
size: ThumbSize,
meta: &fs::Metadata,
img: &RgbaImage,
) -> std::io::Result<PathBuf> {
let dest = cache_path(path, size);
let texts = [
("Thumb::URI", file_uri(path)),
("Thumb::MTime", mtime_secs(meta).to_string()),
("Thumb::Size", meta.len().to_string()),
("Software", format!("Tunal {}", env!("CARGO_PKG_VERSION"))),
];
write_png(&dest, img.width(), img.height(), img.as_raw(), &texts)?;
Ok(dest)
}
/// Records a failure (a 1x1 transparent PNG) so the file isn't retried until it changes.
pub(crate) fn store_failure(path: &Path, meta: &fs::Metadata) {
let texts = [
("Thumb::URI", file_uri(path)),
("Thumb::MTime", mtime_secs(meta).to_string()),
];
let _ = write_png(&fail_path(path), 1, 1, &[0, 0, 0, 0], &texts);
}

View file

@ -0,0 +1,275 @@
//! Thumbnail generators: raster images, SVG, embedded cover art and video frames.
use std::io::Read;
use std::path::Path;
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, OnceLock};
use std::time::{Duration, Instant};
use image::{DynamicImage, ImageDecoder, ImageReader, RgbaImage, imageops::FilterType};
use lofty::file::TaggedFileExt;
use lofty::picture::PictureType;
/// Which frame of a video to use.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum VideoTime {
/// Percent of the duration (from `ffprobe`).
Percent(f64),
Seconds(f64),
}
pub(crate) enum GenError {
Cancelled,
Unsupported,
Failed(String),
}
impl<E: std::fmt::Display> From<E> for GenError {
fn from(e: E) -> Self {
Self::Failed(e.to_string())
}
}
#[derive(Clone, Copy, PartialEq)]
enum Kind {
Raster,
Svg,
Audio,
Video,
}
fn kind_of(path: &Path) -> Option<Kind> {
let mime = mime_guess::from_path(path).first()?;
match (mime.type_().as_str(), mime.essence_str()) {
(_, "image/svg+xml") => Some(Kind::Svg),
(
_,
"image/png"
| "image/jpeg"
| "image/gif"
| "image/webp"
| "image/bmp"
| "image/tiff"
| "image/x-icon"
| "image/vnd.microsoft.icon",
) => Some(Kind::Raster),
("audio", _) => Some(Kind::Audio),
("video", _) => Some(Kind::Video),
_ => None,
}
}
/// Whether the file type is one we may thumbnail, and whether it is bounded by the size limit.
pub(crate) fn supported(path: &Path) -> Option<bool> {
kind_of(path).map(|k| matches!(k, Kind::Raster | Kind::Svg))
}
/// `ffmpeg` and `ffprobe` can both be started.
pub fn ffmpeg_available() -> bool {
static FOUND: OnceLock<bool> = OnceLock::new();
*FOUND.get_or_init(|| {
["ffmpeg", "ffprobe"].iter().all(|tool| {
Command::new(tool)
.arg("-version")
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.is_ok_and(|s| s.success())
})
})
}
pub(crate) struct Settings {
pub video_time: VideoTime,
pub tool_timeout: Duration,
}
pub(crate) fn generate(
path: &Path,
px: u32,
settings: &Settings,
cancel: &AtomicBool,
) -> Result<RgbaImage, GenError> {
let img = match kind_of(path).ok_or(GenError::Unsupported)? {
Kind::Raster => raster(path)?,
Kind::Svg => svg(path, px)?,
Kind::Audio => cover(path)?,
Kind::Video => video(path, px, settings, cancel)?,
};
if cancel.load(Ordering::Relaxed) {
return Err(GenError::Cancelled);
}
Ok(fit(img, px))
}
/// Shrinks to fit `px` on the longest edge; never enlarges.
fn fit(img: DynamicImage, px: u32) -> RgbaImage {
if img.width() <= px && img.height() <= px {
img.into_rgba8()
} else {
img.resize(px, px, FilterType::Lanczos3).into_rgba8()
}
}
fn raster(path: &Path) -> Result<DynamicImage, GenError> {
let mut decoder = ImageReader::open(path)?
.with_guessed_format()?
.into_decoder()?;
let orientation = decoder.orientation()?;
let mut img = DynamicImage::from_decoder(decoder)?;
img.apply_orientation(orientation);
Ok(img)
}
fn svg(path: &Path, px: u32) -> Result<DynamicImage, GenError> {
use resvg::{tiny_skia, usvg};
static FONTS: OnceLock<Arc<usvg::fontdb::Database>> = OnceLock::new();
let fonts = FONTS.get_or_init(|| {
let mut db = usvg::fontdb::Database::new();
db.load_system_fonts();
Arc::new(db)
});
let options = usvg::Options {
fontdb: fonts.clone(),
font_family: "sans-serif".into(),
..usvg::Options::default()
};
let tree = usvg::Tree::from_data(&std::fs::read(path)?, &options)?;
let size = tree.size();
let scale = px as f32 / size.width().max(size.height());
let width = ((size.width() * scale).round() as u32).max(1);
let height = ((size.height() * scale).round() as u32).max(1);
let mut pixmap = tiny_skia::Pixmap::new(width, height).ok_or("empty SVG")?;
resvg::render(
&tree,
tiny_skia::Transform::from_scale(scale, scale),
&mut pixmap.as_mut(),
);
let mut out = RgbaImage::new(width, height);
for (dst, src) in out.pixels_mut().zip(pixmap.pixels()) {
let c = src.demultiply();
dst.0 = [c.red(), c.green(), c.blue(), c.alpha()];
}
Ok(DynamicImage::ImageRgba8(out))
}
fn cover(path: &Path) -> Result<DynamicImage, GenError> {
let tagged = lofty::read_from_path(path)?;
let pictures = || tagged.tags().iter().flat_map(|t| t.pictures());
let picture = pictures()
.find(|p| p.pic_type() == PictureType::CoverFront)
.or_else(|| pictures().next())
.ok_or(GenError::Unsupported)?;
Ok(image::load_from_memory(picture.data())?)
}
/// Runs a tool without a shell; kills it on timeout or cancel. Returns its stdout.
fn run_tool(mut cmd: Command, timeout: Duration, cancel: &AtomicBool) -> Result<Vec<u8>, GenError> {
let mut child = cmd
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()?;
let mut stdout = child.stdout.take().expect("stdout is piped");
let reader = std::thread::spawn(move || {
let mut buf = Vec::new();
let _ = stdout.read_to_end(&mut buf);
buf
});
let deadline = Instant::now() + timeout;
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
let cancelled = cancel.load(Ordering::Relaxed);
if cancelled || Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
let _ = reader.join();
return Err(if cancelled {
GenError::Cancelled
} else {
GenError::Failed("timed out".into())
});
}
std::thread::sleep(Duration::from_millis(15));
};
let out = reader.join().unwrap_or_default();
if status.success() {
Ok(out)
} else {
Err(GenError::Failed(format!(
"{:?} exited with {status}",
cmd.get_program()
)))
}
}
fn video_duration(path: &Path, settings: &Settings, cancel: &AtomicBool) -> Result<f64, GenError> {
let mut cmd = Command::new("ffprobe");
cmd.args([
"-v",
"error",
"-show_entries",
"format=duration",
"-of",
"csv=p=0",
])
.arg(path);
let out = run_tool(cmd, settings.tool_timeout, cancel)?;
Ok(String::from_utf8_lossy(&out).trim().parse()?)
}
fn video_frame(
path: &Path,
seconds: f64,
px: u32,
settings: &Settings,
cancel: &AtomicBool,
) -> Result<Vec<u8>, GenError> {
let mut cmd = Command::new("ffmpeg");
cmd.args([
"-nostdin",
"-v",
"error",
"-ss",
&format!("{seconds:.3}"),
"-i",
])
.arg(path)
.args(["-frames:v", "1", "-vf"])
.arg(format!(
"scale={px}:{px}:force_original_aspect_ratio=decrease"
))
.args(["-f", "image2pipe", "-c:v", "png", "-"]);
run_tool(cmd, settings.tool_timeout, cancel)
}
fn video(
path: &Path,
px: u32,
settings: &Settings,
cancel: &AtomicBool,
) -> Result<DynamicImage, GenError> {
if !ffmpeg_available() {
return Err(GenError::Unsupported);
}
let seconds = match settings.video_time {
VideoTime::Seconds(s) => s,
// A missing duration (live or odd containers) falls back to the first frame.
VideoTime::Percent(p) => {
video_duration(path, settings, cancel).map_or(0.0, |d| d * p / 100.0)
}
};
let mut frame = video_frame(path, seconds.max(0.0), px, settings, cancel)?;
if frame.is_empty() && seconds > 0.0 {
// The seek point was past the last frame.
frame = video_frame(path, 0.0, px, settings, cancel)?;
}
if frame.is_empty() {
return Err(GenError::Failed("no frame".into()));
}
Ok(image::load_from_memory(&frame)?)
}

View file

@ -1 +1,55 @@
//! Thumbnails for images, video frames and embedded album art.
//! Thumbnails for images, SVG, embedded album art and video frames, stored in the shared
//! freedesktop thumbnail cache (`$XDG_CACHE_HOME/thumbnails`).
//!
//! [`Thumbnailer::request`] queues a file; the result comes back through a callback on a worker
//! thread as an [`Outcome`] holding the cache path of the PNG.
mod cache;
mod generate;
mod pool;
pub use cache::{cache_path, thumbnail_dir};
pub use generate::{VideoTime, ffmpeg_available};
pub use pool::{Config, Outcome, Priority, Request, Thumbnailer, Ticket};
/// The three cache sizes of the freedesktop spec (longest edge in pixels).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ThumbSize {
Normal,
Large,
XLarge,
}
impl ThumbSize {
pub fn pixels(self) -> u32 {
match self {
Self::Normal => 128,
Self::Large => 256,
Self::XLarge => 512,
}
}
pub(crate) fn dir_name(self) -> &'static str {
match self {
Self::Normal => "normal",
Self::Large => "large",
Self::XLarge => "x-large",
}
}
}
/// Why no thumbnail exists.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Skip {
/// The file type has no generator, or the tool it needs (ffmpeg) is missing, or the audio
/// file has no cover.
Unsupported,
/// A remote location while remote thumbnails are off.
Remote,
/// Larger than [`Config::max_file_size`].
TooLarge,
/// The file lies inside the thumbnail cache.
InCache,
/// An earlier attempt failed and the file is unchanged.
KnownFailure,
}

View file

@ -0,0 +1,231 @@
//! Worker pool: prioritized, cancellable thumbnail requests.
use std::collections::BinaryHeap;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::time::Duration;
use crate::cache;
use crate::generate::{self, GenError, Settings, VideoTime};
use crate::{Skip, ThumbSize};
/// Higher runs first; equal priorities run in request order.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Priority {
/// Prefetch outside the viewport.
Low,
/// Items on screen.
Normal,
/// The item under the pointer or selection.
High,
}
#[derive(Clone, Debug)]
pub struct Config {
pub workers: usize,
/// Images and SVG above this size are skipped (video and audio are read in part only).
pub max_file_size: u64,
/// Thumbnail files on remote locations (requests flagged `remote`).
pub allow_remote: bool,
pub video_time: VideoTime,
/// Limit for one ffmpeg/ffprobe run.
pub tool_timeout: Duration,
}
impl Default for Config {
fn default() -> Self {
Self {
workers: std::thread::available_parallelism().map_or(2, |n| n.get().clamp(1, 4)),
max_file_size: 64 << 20,
allow_remote: false,
video_time: VideoTime::Percent(10.0),
tool_timeout: Duration::from_secs(15),
}
}
}
/// Result of a request, delivered once.
#[derive(Debug, PartialEq, Eq)]
pub enum Outcome {
/// The PNG in the cache.
Ready(PathBuf),
/// No thumbnail, and that is expected.
Skipped(Skip),
/// Generation failed; recorded in `fail/` until the file changes.
Failed(String),
Cancelled,
}
pub struct Request {
/// Absolute path.
pub path: PathBuf,
pub size: ThumbSize,
pub priority: Priority,
/// The file is on a remote location (see [`Config::allow_remote`]).
pub remote: bool,
/// Runs on a worker thread; hand the result to the UI thread from there.
pub done: Box<dyn FnOnce(Outcome) + Send>,
}
/// Cancels a request that has not finished; dropping it does not cancel.
#[derive(Clone)]
pub struct Ticket(Arc<AtomicBool>);
impl Ticket {
/// A queued request is dropped (callback gets `Cancelled`); a running ffmpeg is killed.
pub fn cancel(&self) {
self.0.store(true, Ordering::Relaxed);
}
}
struct Job {
priority: Priority,
seq: u64,
req: Request,
cancel: Arc<AtomicBool>,
}
impl PartialEq for Job {
fn eq(&self, other: &Self) -> bool {
self.seq == other.seq
}
}
impl Eq for Job {}
impl PartialOrd for Job {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Job {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.priority
.cmp(&other.priority)
.then(other.seq.cmp(&self.seq))
}
}
#[derive(Default)]
struct Queue {
heap: BinaryHeap<Job>,
next_seq: u64,
closed: bool,
}
struct Shared {
queue: Mutex<Queue>,
wake: Condvar,
config: Config,
}
/// Thumbnail service; workers stop when it is dropped (running jobs finish first).
pub struct Thumbnailer {
shared: Arc<Shared>,
}
impl Thumbnailer {
pub fn new(config: Config) -> Self {
let shared = Arc::new(Shared {
queue: Mutex::default(),
wake: Condvar::new(),
config,
});
for _ in 0..shared.config.workers.max(1) {
let shared = shared.clone();
std::thread::spawn(move || worker(&shared));
}
Self { shared }
}
pub fn request(&self, req: Request) -> Ticket {
let cancel = Arc::new(AtomicBool::new(false));
let mut queue = self.shared.queue.lock().unwrap();
let seq = queue.next_seq;
queue.next_seq += 1;
queue.heap.push(Job {
priority: req.priority,
seq,
req,
cancel: cancel.clone(),
});
drop(queue);
self.shared.wake.notify_one();
Ticket(cancel)
}
}
impl Drop for Thumbnailer {
fn drop(&mut self) {
self.shared.queue.lock().unwrap().closed = true;
self.shared.wake.notify_all();
}
}
fn worker(shared: &Shared) {
loop {
let job = {
let mut queue = shared.queue.lock().unwrap();
loop {
if queue.closed {
return;
}
if let Some(job) = queue.heap.pop() {
break job;
}
queue = shared.wake.wait(queue).unwrap();
}
};
let outcome = process(&job, &shared.config);
(job.req.done)(outcome);
}
}
fn process(job: &Job, config: &Config) -> Outcome {
let Request {
path, size, remote, ..
} = &job.req;
if job.cancel.load(Ordering::Relaxed) {
return Outcome::Cancelled;
}
if *remote && !config.allow_remote {
return Outcome::Skipped(Skip::Remote);
}
if cache::in_cache(path) {
return Outcome::Skipped(Skip::InCache);
}
let Some(bounded) = generate::supported(path) else {
return Outcome::Skipped(Skip::Unsupported);
};
let meta = match std::fs::metadata(path) {
Ok(m) if m.is_file() => m,
Ok(_) => return Outcome::Skipped(Skip::Unsupported),
Err(e) => return Outcome::Failed(e.to_string()),
};
let mtime = cache::mtime_secs(&meta);
if let Some(ready) = cache::valid(path, *size, mtime) {
return Outcome::Ready(ready);
}
if cache::known_failure(path, mtime) {
return Outcome::Skipped(Skip::KnownFailure);
}
if bounded && meta.len() > config.max_file_size {
return Outcome::Skipped(Skip::TooLarge);
}
let settings = Settings {
video_time: config.video_time,
tool_timeout: config.tool_timeout,
};
match generate::generate(path, size.pixels(), &settings, &job.cancel) {
Ok(img) => match cache::store(path, *size, &meta, &img) {
Ok(dest) => Outcome::Ready(dest),
Err(e) => Outcome::Failed(e.to_string()),
},
Err(GenError::Cancelled) => Outcome::Cancelled,
// No cover, or ffmpeg missing: not a failure of the file, so nothing is recorded.
Err(GenError::Unsupported) => Outcome::Skipped(Skip::Unsupported),
Err(GenError::Failed(reason)) => {
cache::store_failure(path, &meta);
Outcome::Failed(reason)
}
}
}