perf(thumbnails): scaled JPEG decode and continuous worker batching
Major speedups for large-folder thumbnail generation: - JPEGs decode through mozjpeg at the smallest DCT scale covering 320px instead of full resolution, with catch_unwind and a fallback to the image crate for anything mozjpeg rejects. EXIF orientation preserved in both paths. - RGB8 pipeline end to end (no RGBA round-trip) and CatmullRom resize in place of Lanczos3. - Video posters grab the seeked frame directly instead of running the ffmpeg thumbnail filter (which decoded ~100 frames), with decode threads capped at 2 per process. - Workers only sleep when the queue is empty rather than 250ms after every batch. Image batches commit before videos start, and videos run sequentially off the rayon pool (blocking ffmpeg waits were starving image decode) with per-item commits so progress keeps moving through slow stretches.
This commit is contained in:
+124
-12
@@ -31,29 +31,26 @@ pub fn generate_image_thumbnail(image_path: &Path, cache_dir: &Path) -> Result<G
|
||||
});
|
||||
}
|
||||
|
||||
let reader = image::ImageReader::open(image_path)?.with_guessed_format()?;
|
||||
let mut decoder = reader.into_decoder()?;
|
||||
let orientation = decoder.orientation()?;
|
||||
let mut img = image::DynamicImage::from_decoder(decoder)?;
|
||||
img.apply_orientation(orientation);
|
||||
let img = decode_for_thumbnail(image_path)?;
|
||||
|
||||
let src = image::DynamicImage::ImageRgba8(img.into_rgba8());
|
||||
// RGB8 throughout: JPEG output has no alpha, so decoding/resizing RGBA
|
||||
// only to flatten at encode time wastes a third of the bandwidth.
|
||||
let src = image::DynamicImage::ImageRgb8(img.into_rgb8());
|
||||
let (dst_width, dst_height) = fit_dimensions(src.width(), src.height(), THUMB_SIZE);
|
||||
|
||||
let mut dst = fir::images::Image::new(dst_width, dst_height, src.pixel_type().unwrap());
|
||||
let mut resizer = fir::Resizer::new();
|
||||
let options = fir::ResizeOptions::new()
|
||||
.resize_alg(fir::ResizeAlg::Convolution(fir::FilterType::Lanczos3));
|
||||
.resize_alg(fir::ResizeAlg::Convolution(fir::FilterType::CatmullRom));
|
||||
resizer.resize(&src, &mut dst, Some(&options))?;
|
||||
|
||||
let thumb = image::RgbaImage::from_raw(dst_width, dst_height, dst.buffer().to_vec())
|
||||
let thumb = image::RgbImage::from_raw(dst_width, dst_height, dst.buffer().to_vec())
|
||||
.ok_or_else(|| anyhow!("failed to construct resized thumbnail buffer"))?;
|
||||
|
||||
if let Some(parent) = out_path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
|
||||
let thumb = image::DynamicImage::ImageRgba8(thumb).into_rgb8();
|
||||
let mut output_file = std::fs::File::create(&out_path)?;
|
||||
let mut encoder = JpegEncoder::new_with_quality(&mut output_file, 82);
|
||||
encoder.encode_image(&thumb)?;
|
||||
@@ -64,6 +61,80 @@ pub fn generate_image_thumbnail(image_path: &Path, cache_dir: &Path) -> Result<G
|
||||
})
|
||||
}
|
||||
|
||||
/// Decodes an image for thumbnailing, with EXIF orientation already applied.
|
||||
///
|
||||
/// JPEGs take a fast path that decodes at reduced resolution (DCT scaling),
|
||||
/// which skips most of the IDCT/upsampling work for large photos. Anything
|
||||
/// that path can't handle falls back to the `image` crate.
|
||||
fn decode_for_thumbnail(image_path: &Path) -> Result<image::DynamicImage> {
|
||||
if is_jpeg(image_path) {
|
||||
if let Some(img) = decode_jpeg_scaled(image_path) {
|
||||
return Ok(img);
|
||||
}
|
||||
}
|
||||
|
||||
let reader = image::ImageReader::open(image_path)?.with_guessed_format()?;
|
||||
let mut decoder = reader.into_decoder()?;
|
||||
let orientation = decoder.orientation()?;
|
||||
let mut img = image::DynamicImage::from_decoder(decoder)?;
|
||||
img.apply_orientation(orientation);
|
||||
Ok(img)
|
||||
}
|
||||
|
||||
fn is_jpeg(path: &Path) -> bool {
|
||||
path.extension()
|
||||
.and_then(|ext| ext.to_str())
|
||||
.is_some_and(|ext| ext.eq_ignore_ascii_case("jpg") || ext.eq_ignore_ascii_case("jpeg"))
|
||||
}
|
||||
|
||||
/// Decodes a JPEG at the smallest DCT scale that still covers `THUMB_SIZE`.
|
||||
/// Returns `None` on any failure (corrupt file, CMYK without conversion
|
||||
/// support, etc.) so the caller can fall back to the generic decoder.
|
||||
/// mozjpeg reports errors by panicking, hence the `catch_unwind`.
|
||||
fn decode_jpeg_scaled(image_path: &Path) -> Option<image::DynamicImage> {
|
||||
let path = image_path.to_path_buf();
|
||||
let decoded = std::panic::catch_unwind(move || -> std::io::Result<(Vec<u8>, u32, u32)> {
|
||||
let mut decompress = mozjpeg::Decompress::new_path(&path)?;
|
||||
let (width, height) = decompress.size();
|
||||
decompress.scale(scale_numerator(width.max(height)));
|
||||
let mut started = decompress.rgb()?;
|
||||
let (out_width, out_height) = (started.width() as u32, started.height() as u32);
|
||||
let pixels = started.read_scanlines::<u8>()?;
|
||||
started.finish()?;
|
||||
Ok((pixels, out_width, out_height))
|
||||
})
|
||||
.ok()?
|
||||
.ok()?;
|
||||
|
||||
let (pixels, width, height) = decoded;
|
||||
let buffer = image::RgbImage::from_raw(width, height, pixels)?;
|
||||
let mut img = image::DynamicImage::ImageRgb8(buffer);
|
||||
if let Some(orientation) = exif_orientation(image_path) {
|
||||
img.apply_orientation(orientation);
|
||||
}
|
||||
Some(img)
|
||||
}
|
||||
|
||||
/// Smallest numerator (of /8) that keeps the longest side at or above
|
||||
/// `THUMB_SIZE`, so the subsequent resize never upscales.
|
||||
fn scale_numerator(max_dimension: usize) -> u8 {
|
||||
for numerator in 1..=8u8 {
|
||||
if max_dimension * numerator as usize / 8 >= THUMB_SIZE as usize {
|
||||
return numerator;
|
||||
}
|
||||
}
|
||||
8
|
||||
}
|
||||
|
||||
fn exif_orientation(path: &Path) -> Option<image::metadata::Orientation> {
|
||||
let file = std::fs::File::open(path).ok()?;
|
||||
let mut reader = std::io::BufReader::new(file);
|
||||
let exif = exif::Reader::new().read_from_container(&mut reader).ok()?;
|
||||
let field = exif.get_field(exif::Tag::Orientation, exif::In::PRIMARY)?;
|
||||
let value = field.value.get_uint(0)?;
|
||||
image::metadata::Orientation::from_exif(value as u8)
|
||||
}
|
||||
|
||||
pub fn generate_video_thumbnail(
|
||||
tools: &MediaTools,
|
||||
video_path: &Path,
|
||||
@@ -88,6 +159,8 @@ pub fn generate_video_thumbnail(
|
||||
let attempts: [&[&str]; 3] = [
|
||||
&[
|
||||
"-y",
|
||||
"-threads",
|
||||
"2",
|
||||
"-ss",
|
||||
"00:00:00.000",
|
||||
"-i",
|
||||
@@ -95,13 +168,15 @@ pub fn generate_video_thumbnail(
|
||||
"-frames:v",
|
||||
"1",
|
||||
"-vf",
|
||||
"thumbnail,scale=320:-1:force_original_aspect_ratio=decrease",
|
||||
"scale=320:-1:force_original_aspect_ratio=decrease",
|
||||
"-q:v",
|
||||
"4",
|
||||
&output_path,
|
||||
],
|
||||
&[
|
||||
"-y",
|
||||
"-threads",
|
||||
"2",
|
||||
"-ss",
|
||||
"00:00:00.250",
|
||||
"-i",
|
||||
@@ -109,19 +184,21 @@ pub fn generate_video_thumbnail(
|
||||
"-frames:v",
|
||||
"1",
|
||||
"-vf",
|
||||
"thumbnail,scale=320:-1:force_original_aspect_ratio=decrease",
|
||||
"scale=320:-1:force_original_aspect_ratio=decrease",
|
||||
"-q:v",
|
||||
"4",
|
||||
&output_path,
|
||||
],
|
||||
&[
|
||||
"-y",
|
||||
"-threads",
|
||||
"2",
|
||||
"-i",
|
||||
path_str.as_ref(),
|
||||
"-frames:v",
|
||||
"1",
|
||||
"-vf",
|
||||
"thumbnail,scale=320:-1:force_original_aspect_ratio=decrease",
|
||||
"scale=320:-1:force_original_aspect_ratio=decrease",
|
||||
"-q:v",
|
||||
"4",
|
||||
&output_path,
|
||||
@@ -165,6 +242,41 @@ fn hash_path(s: &str) -> String {
|
||||
format!("{:016x}", xxhash_rust::xxh3::xxh3_64(s.as_bytes()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn scale_numerator_picks_smallest_sufficient() {
|
||||
assert_eq!(scale_numerator(6000), 1);
|
||||
assert_eq!(scale_numerator(640), 4);
|
||||
assert_eq!(scale_numerator(320), 8);
|
||||
assert_eq!(scale_numerator(100), 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jpeg_fast_path_decodes_at_reduced_resolution() {
|
||||
let dir = std::env::temp_dir().join("phokus-thumb-test");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let src_path = dir.join("large.jpg");
|
||||
let img =
|
||||
image::RgbImage::from_fn(1600, 1200, |x, _| image::Rgb([(x % 256) as u8, 64, 128]));
|
||||
img.save(&src_path).unwrap();
|
||||
|
||||
// 1600 max dim -> numerator 2 -> 400x300 decode output
|
||||
let decoded = decode_jpeg_scaled(&src_path).expect("fast path should handle plain JPEG");
|
||||
assert_eq!((decoded.width(), decoded.height()), (400, 300));
|
||||
|
||||
let cache = dir.join("cache");
|
||||
let _ = std::fs::remove_file(thumb_path(&cache, &src_path.to_string_lossy()));
|
||||
let result = generate_image_thumbnail(&src_path, &cache).unwrap();
|
||||
assert_eq!(result.width, Some(1600));
|
||||
assert_eq!(result.height, Some(1200));
|
||||
let (thumb_w, thumb_h) = image::image_dimensions(&result.path).unwrap();
|
||||
assert_eq!((thumb_w, thumb_h), (320, 240));
|
||||
}
|
||||
}
|
||||
|
||||
fn fit_dimensions(width: u32, height: u32, max_size: u32) -> (u32, u32) {
|
||||
if width <= max_size && height <= max_size {
|
||||
return (width.max(1), height.max(1));
|
||||
|
||||
Reference in New Issue
Block a user