Tunal/crates/tunal-thumbs/src/generate.rs

275 lines
8.1 KiB
Rust

//! 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)?)
}