use std::io::Cursor;
use std::path::Path;
use anyhow::{anyhow, Context, Result};
use image::{DynamicImage, ImageDecoder, ImageReader, RgbImage};
use crate::catalog::JPEG_EXTS;
pub const THUMB_SIZE: u32 = 240;
pub const PREVIEW_SIZE: u32 = 2560;
const RAW_HEAD_BYTES: u64 = 8 << 20;
pub fn load(path: &Path, max_edge: u32) -> Result<RgbImage> {
let is_jpeg = path
.extension()
.is_some_and(|e| JPEG_EXTS.contains(&e.to_string_lossy().to_ascii_lowercase().as_str()));
let img = if is_jpeg {
decode_jpeg(&read(path, None)?)?
} else {
match decode_embedded(&read(path, Some(RAW_HEAD_BYTES))?) {
Ok(img) => img,
Err(_) => decode_embedded(&read(path, None)?)?,
}
};
let (w, h) = (img.width(), img.height());
let img = if w.max(h) > max_edge {
let scale = max_edge as f32 / w.max(h) as f32;
img.thumbnail((w as f32 * scale) as u32, (h as f32 * scale) as u32)
} else {
img
};
Ok(img.into_rgb8())
}
fn decode_jpeg(bytes: &[u8]) -> Result<DynamicImage> {
let mut decoder =
ImageReader::with_format(Cursor::new(bytes), image::ImageFormat::Jpeg).into_decoder()?;
let orientation = decoder
.orientation()
.unwrap_or(image::metadata::Orientation::NoTransforms);
let mut img = DynamicImage::from_decoder(decoder)?;
img.apply_orientation(orientation);
Ok(img)
}
fn read(path: &Path, limit: Option<u64>) -> Result<Vec<u8>> {
use std::io::Read;
let file = std::fs::File::open(path).with_context(|| format!("reading {}", path.display()))?;
let mut bytes = Vec::new();
match limit {
Some(n) => file.take(n).read_to_end(&mut bytes),
None => (&file).read_to_end(&mut bytes),
}
.with_context(|| format!("reading {}", path.display()))?;
Ok(bytes)
}
fn decode_embedded(bytes: &[u8]) -> Result<DynamicImage> {
let mut candidates = embedded_jpegs(bytes);
candidates.sort_by_key(|&(pixels, _)| std::cmp::Reverse(pixels));
candidates
.into_iter()
.find_map(|(_, c)| decode_jpeg(c).ok())
.ok_or_else(|| anyhow!("no embedded JPEG preview found"))
}
fn embedded_jpegs(bytes: &[u8]) -> Vec<(u64, &[u8])> {
const MAX_CANDIDATES: usize = 64;
let mut found = Vec::new();
let mut pos = 0;
while found.len() < MAX_CANDIDATES {
let Some(off) = find_soi(&bytes[pos..]) else {
break;
};
let start = pos + off;
pos = start + 2;
let candidate = &bytes[start..];
if let Ok((w, h)) =
ImageReader::with_format(Cursor::new(candidate), image::ImageFormat::Jpeg)
.into_dimensions()
{
found.push((u64::from(w) * u64::from(h), candidate));
}
}
found
}
fn find_soi(hay: &[u8]) -> Option<usize> {
hay.windows(3).position(|w| w == [0xFF, 0xD8, 0xFF])
}
#[cfg(test)]
mod tests {
use super::*;
use image::ImageEncoder;
fn jpeg_bytes(w: u32, h: u32) -> Vec<u8> {
let img = RgbImage::from_pixel(w, h, image::Rgb([10, 20, 30]));
let mut out = Vec::new();
image::codecs::jpeg::JpegEncoder::new(&mut out)
.write_image(&img, w, h, image::ExtendedColorType::Rgb8)
.unwrap();
out
}
#[test]
fn picks_largest_embedded_jpeg() {
let small = jpeg_bytes(16, 12);
let large = jpeg_bytes(64, 48);
let mut raw = b"FUJIFILMCCD-RAW 0201FF".to_vec();
raw.extend_from_slice(&small);
raw.extend_from_slice(&[0u8; 100]);
raw.extend_from_slice(&large);
raw.extend_from_slice(&[0u8; 100]);
let img = decode_embedded(&raw).unwrap();
assert_eq!((img.width(), img.height()), (64, 48));
}
#[test]
fn falls_back_when_largest_candidate_does_not_decode() {
let mut large = jpeg_bytes(64, 48);
let sof = large.windows(2).position(|w| w == [0xFF, 0xC0]).unwrap();
large[sof + 1] = 0xC3;
let mut raw = large;
raw.extend_from_slice(&[0u8; 64]);
raw.extend_from_slice(&jpeg_bytes(32, 24));
let img = decode_embedded(&raw).unwrap();
assert_eq!((img.width(), img.height()), (32, 24));
}
#[test]
fn load_downscales_to_max_edge() {
let dir = std::env::temp_dir();
let path = dir.join(format!("flowcull-decode-{}.jpg", std::process::id()));
std::fs::write(&path, jpeg_bytes(200, 100)).unwrap();
let img = load(&path, 50).unwrap();
assert_eq!((img.width(), img.height()), (50, 25));
std::fs::remove_file(&path).unwrap();
}
}
#[cfg(test)]
mod real_file_tests {
#[test]
#[ignore]
fn decodes_sample_file() {
let path = std::path::PathBuf::from(std::env::var("FLOWCULL_SAMPLE").unwrap());
let t = std::time::Instant::now();
let img = super::load(&path, super::PREVIEW_SIZE).unwrap();
println!(
"{}: {}x{} in {:?}",
path.display(),
img.width(),
img.height(),
t.elapsed()
);
let t = std::time::Instant::now();
let img = super::load(&path, super::THUMB_SIZE).unwrap();
println!(
"thumb {}x{} in {:?}",
img.width(),
img.height(),
t.elapsed()
);
}
}