pub mod cas;
pub mod perceptual;
use anyhow::Result;
use bytes::Bytes;
use fast_image_resize as fr;
use image::GenericImageView;
use img_parts::jpeg::Jpeg;
use memmap2::Mmap;
use perceptual::{FocusMode, PerceptualMetrics, PerceptualOptions};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};
#[cfg(target_os = "macos")]
use std::sync::atomic::{AtomicUsize, Ordering};
use image::ImageBuffer;
use image::Rgba;
#[cfg(target_os = "macos")]
static SIPS_CONCURRENCY: AtomicUsize = AtomicUsize::new(0);
#[cfg(target_os = "macos")]
const MAX_SIPS_CONCURRENCY: usize = 4;
#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
pub enum ProcessMode {
WeChat,
HD,
Custom,
}
#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
pub enum OutputFormat {
Jpeg,
KeepOriginal,
WebP,
}
#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
pub enum ColorSpace {
KeepOriginal,
ConvertToSRGB,
}
pub const APP_VERSION: &str = "v4.4.4";
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AppConfig {
#[serde(default = "default_config_version")]
pub config_version: u32,
pub mode: ProcessMode,
pub custom_max_dim: u32,
pub custom_quality: u8,
pub custom_target_kb: u32,
pub overwrite: bool,
pub keep_original_name: bool,
pub output_format: OutputFormat,
pub color_space: ColorSpace,
pub enable_sharpening: bool, pub sharpening_radius: f32, pub sharpening_amount: f32, pub use_custom_quantization: bool, pub preserve_high_frequency: bool, #[serde(default = "default_usage_mode")]
pub usage_mode: String,
#[serde(default = "default_quality_mode")]
pub quality_mode: String,
#[serde(default = "default_platform")]
pub platform: String,
#[serde(default = "default_subsampling")]
pub subsampling: String,
#[serde(default)]
pub preserve_structure: bool,
#[serde(default)]
pub output_suffix: Option<String>,
#[serde(default)]
pub cas_strength: f32,
#[serde(default)]
pub custom_output_dir: Option<String>,
}
fn default_usage_mode() -> String {
"social".to_string()
}
fn default_config_version() -> u32 {
1
}
fn default_quality_mode() -> String {
"max".to_string()
}
fn default_platform() -> String {
"wechat".to_string()
}
fn default_subsampling() -> String {
"420".to_string()
}
impl Default for AppConfig {
fn default() -> Self {
Self {
config_version: 2,
mode: ProcessMode::Custom,
custom_max_dim: 3000,
custom_quality: 85,
custom_target_kb: 0,
overwrite: false,
keep_original_name: false,
output_format: OutputFormat::Jpeg,
color_space: ColorSpace::KeepOriginal,
enable_sharpening: false,
sharpening_radius: 1.0,
sharpening_amount: 0.8,
use_custom_quantization: false,
preserve_high_frequency: false,
usage_mode: "social".to_string(),
quality_mode: "max".to_string(),
platform: "wechat".to_string(),
subsampling: "420".to_string(),
preserve_structure: false,
output_suffix: None,
cas_strength: 0.0,
custom_output_dir: None,
}
}
}
#[derive(Clone, Debug)]
pub struct ProcessConfig {
pub mode: ProcessMode,
pub max_dim: u32,
pub quality: u8,
pub target_kb: u32,
pub output_dir: Option<PathBuf>,
pub overwrite: bool,
pub keep_original_name: bool,
pub output_format: OutputFormat,
pub color_space: ColorSpace,
pub enable_sharpening: bool,
pub sharpening_radius: f32,
pub sharpening_amount: f32,
pub perceptual: Option<PerceptualOptions>,
pub subsampling: String,
pub preserve_structure: bool,
pub structure_base: Option<PathBuf>,
pub output_suffix: Option<String>,
pub cas_strength: f32,
}
pub struct Processor {
config: ProcessConfig,
}
impl Processor {
pub fn new(config: ProcessConfig) -> Self {
Self { config }
}
pub fn expected_output_path(&self, input_path: &Path) -> PathBuf {
let healed_path = path_self_healing(input_path);
let file_stem = healed_path
.file_stem()
.unwrap_or_default()
.to_string_lossy()
.to_string();
let extension = healed_path
.extension()
.and_then(|e| e.to_str())
.unwrap_or("")
.to_lowercase();
let output_ext = match self.config.output_format {
OutputFormat::Jpeg => "jpg",
OutputFormat::WebP => "webp",
OutputFormat::KeepOriginal => match extension.as_str() {
"png" => "png",
"webp" => "webp",
_ => "jpg",
},
};
let base_out = self
.config
.output_dir
.clone()
.unwrap_or_else(|| healed_path.parent().unwrap_or(Path::new(".")).to_path_buf());
let rel_parent = if self.config.preserve_structure {
self.config
.structure_base
.as_ref()
.and_then(|b| {
healed_path
.parent()
.unwrap_or(Path::new("."))
.strip_prefix(b)
.ok()
})
.unwrap_or_else(|| Path::new(""))
} else {
Path::new("")
};
let out_dir = base_out.join(rel_parent);
let suffix = if self.config.keep_original_name {
String::new()
} else if let Some(s) = &self.config.output_suffix {
if s.is_empty() {
String::new()
} else {
format!("_{}", s)
}
} else {
match self.config.mode {
ProcessMode::WeChat => "_wx".to_string(),
ProcessMode::HD => "_hd".to_string(),
_ => "_da".to_string(),
}
};
if self.config.overwrite {
healed_path.to_path_buf()
} else if self.config.keep_original_name {
out_dir.join(format!("{}.{}", file_stem, output_ext))
} else {
out_dir.join(format!("{}{}.{}", file_stem, suffix, output_ext))
}
}
pub fn passthrough_path(&self, input_path: &Path) -> PathBuf {
let healed_path = path_self_healing(input_path);
let base_out = self
.config
.output_dir
.clone()
.unwrap_or_else(|| healed_path.parent().unwrap_or(Path::new(".")).to_path_buf());
let rel_parent = if self.config.preserve_structure {
self.config
.structure_base
.as_ref()
.and_then(|b| {
healed_path
.parent()
.unwrap_or(Path::new("."))
.strip_prefix(b)
.ok()
})
.unwrap_or_else(|| Path::new(""))
} else {
Path::new("")
};
let out_dir = base_out.join(rel_parent);
let name = healed_path
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string();
out_dir.join(name)
}
pub fn process_image(&self, input_path: &Path) -> Result<PathBuf> {
self.process_image_with_metrics(input_path).map(|(p, _)| p)
}
pub fn process_image_with_metrics(
&self,
input_path: &Path,
) -> Result<(PathBuf, Option<PerceptualMetrics>)> {
let healed_path = path_self_healing(input_path);
let file_name_os = healed_path
.file_name()
.unwrap_or_default()
.to_string_lossy();
if file_name_os.starts_with("._") {
return Err(anyhow::anyhow!("跳过系统隐藏文件"));
}
let extension = healed_path
.extension()
.and_then(|e| e.to_str())
.unwrap_or("")
.to_lowercase();
let raw_extensions = [
"dng", "cr2", "cr3", "nef", "arw", "orf", "raf", "rw2", "pef", "srw", "3fr",
];
let is_raw = raw_extensions.contains(&extension.as_str());
let output_path = self.expected_output_path(&healed_path);
if let Some(parent) = output_path.parent() {
fs::create_dir_all(parent)?;
}
let metrics: Option<PerceptualMetrics>;
#[cfg(target_os = "macos")]
{
let file_stem = healed_path.file_stem().unwrap().to_string_lossy();
if is_raw {
self.process_raw(&healed_path, &output_path, &file_stem, &file_name_os)?;
metrics = None;
} else {
metrics = self.process_normal(&healed_path, &output_path, &extension)?;
}
}
#[cfg(not(target_os = "macos"))]
if is_raw {
return Err(anyhow::anyhow!(
"RAW 格式 ({}) 仅在 macOS 系统上支持。请先在 Mac 上处理,或转成 JPG/PNG 后使用。",
extension
));
} else {
metrics = self.process_normal(&healed_path, &output_path, &extension)?;
}
Ok((output_path, metrics))
}
pub fn perceptual_config(&self) -> Option<&PerceptualOptions> {
self.config.perceptual.as_ref()
}
pub fn effective_target_kb(&self) -> u32 {
match &self.config.perceptual {
Some(p) => p.budget_kb.unwrap_or(self.config.target_kb),
None => self.config.target_kb,
}
}
#[cfg(target_os = "macos")]
fn process_raw(
&self,
input_path: &Path,
output_path: &Path,
file_stem: &str,
file_name: &str,
) -> Result<()> {
while SIPS_CONCURRENCY.load(Ordering::SeqCst) >= MAX_SIPS_CONCURRENCY {
std::thread::sleep(std::time::Duration::from_millis(100));
}
SIPS_CONCURRENCY.fetch_add(1, Ordering::SeqCst);
let input_path_abs =
fs::canonicalize(input_path).unwrap_or_else(|_| input_path.to_path_buf());
let result = (|| -> Result<()> {
let mut preview_cmd = std::process::Command::new("sips");
preview_cmd
.arg("-e")
.arg("preview")
.arg(&input_path_abs)
.arg("--out")
.arg(output_path);
let _ = preview_cmd.output();
if output_path.exists() {
if self.config.max_dim > 0 {
if let Ok(img) = image::open(output_path) {
let (w, h) = img.dimensions();
if w > self.config.max_dim || h > self.config.max_dim {
let mut resize_cmd = std::process::Command::new("sips");
resize_cmd.arg("-Z").arg(self.config.max_dim.to_string());
resize_cmd.arg(output_path);
let _ = resize_cmd.output();
}
}
}
return Ok(());
}
let mut cmd = std::process::Command::new("sips");
cmd.arg("-s").arg("format").arg("jpeg");
let quality = self.config.quality;
cmd.arg("-s").arg("formatOptions").arg(quality.to_string());
if self.config.max_dim > 0 {
cmd.arg("-Z").arg(self.config.max_dim.to_string());
}
cmd.arg(&input_path_abs).arg("--out").arg(output_path);
let mut child = cmd.spawn()?;
let timeout = std::time::Duration::from_secs(30);
let start = std::time::Instant::now();
let status = loop {
match child.try_wait()? {
Some(status) => break status,
None => {
if start.elapsed() > timeout {
let _ = child.kill();
break std::process::ExitStatus::default();
}
std::thread::sleep(std::time::Duration::from_millis(100));
}
}
};
if status.success() && output_path.exists() {
return Ok(());
}
let temp_dir = std::env::temp_dir().join("rust_compressor_ql");
let _ = fs::create_dir_all(&temp_dir);
let mut ql_cmd = std::process::Command::new("qlmanage");
ql_cmd.arg("-t").arg("-s");
if self.config.max_dim > 0 {
ql_cmd.arg(self.config.max_dim.to_string());
} else {
ql_cmd.arg("20000");
}
ql_cmd.arg("-o").arg(&temp_dir).arg(&input_path_abs);
if let Ok(mut child) = ql_cmd.spawn() {
let start = std::time::Instant::now();
loop {
if let Ok(Some(_)) = child.try_wait() {
break;
}
if start.elapsed().as_secs() > 30 {
let _ = child.kill();
break;
}
std::thread::sleep(std::time::Duration::from_millis(100));
}
}
let ql_file_1 = temp_dir.join(format!("{}.png", file_stem));
let ql_file_2 = temp_dir.join(format!("{}.png", file_name));
let ql_file = if ql_file_1.exists() {
Some(ql_file_1)
} else if ql_file_2.exists() {
Some(ql_file_2)
} else {
None
};
if let Some(path) = ql_file {
let mut conv_cmd = std::process::Command::new("sips");
conv_cmd
.arg("-s")
.arg("format")
.arg("jpeg")
.arg(&path)
.arg("--out")
.arg(output_path);
let _ = conv_cmd.output();
let _ = fs::remove_file(path);
if output_path.exists() {
return Ok(());
}
}
Err(anyhow::anyhow!("该机型 RAW 暂不支持"))
})();
SIPS_CONCURRENCY.fetch_sub(1, Ordering::SeqCst);
result?;
Ok(())
}
fn process_normal(
&self,
input_path: &Path,
output_path: &Path,
extension: &str,
) -> Result<Option<PerceptualMetrics>> {
let img = load_image_safe(input_path)?;
let (width, height) = img.dimensions();
let src_has_alpha = img.color().has_alpha();
let perceptual = self.config.perceptual.as_ref();
let mut pm = PerceptualMetrics::default();
let scale = if self.config.max_dim > 0
&& (width > self.config.max_dim || height > self.config.max_dim)
{
let ratio_w = self.config.max_dim as f32 / width as f32;
let ratio_h = self.config.max_dim as f32 / height as f32;
ratio_w.min(ratio_h)
} else {
1.0
};
let new_width = (width as f32 * scale) as u32;
let new_height = (height as f32 * scale) as u32;
let img_rgba = img.to_rgba8();
let t_down = std::time::Instant::now();
let src_image = fr::images::Image::from_vec_u8(
width,
height,
img_rgba.into_raw(),
fr::PixelType::U8x4,
)?;
let mut dst_image = fr::images::Image::new(new_width, new_height, fr::PixelType::U8x4);
let mut resizer = fr::Resizer::new();
resizer.resize(&src_image, &mut dst_image, None)?;
let rgba_buf = dst_image.buffer();
pm.downscale_ms = t_down.elapsed().as_millis() as u64;
let mut dynamic_img = image::DynamicImage::ImageRgba8(
image::ImageBuffer::from_raw(new_width, new_height, rgba_buf.to_vec())
.ok_or_else(|| anyhow::anyhow!("Failed to create image buffer"))?,
);
let reference_gray = perceptual.map(|_| perceptual::to_gray(&dynamic_img));
if let Some(p) = perceptual {
let is_jpeg_input = matches!(extension, "jpg" | "jpeg");
if p.denoise_strength > 0 && !is_jpeg_input && new_width.max(new_height) <= 4000 {
let t = std::time::Instant::now();
dynamic_img = image::DynamicImage::ImageRgba8(perceptual::bilateral_denoise(
&dynamic_img.to_rgba8(),
p.denoise_strength,
));
pm.denoise_ms = t.elapsed().as_millis() as u64;
pm.denoise_applied = true;
}
let t = std::time::Instant::now();
let rgba_now = dynamic_img.to_rgba8();
let mask = match p.focus_mode {
FocusMode::Auto => perceptual::saliency_mask(&rgba_now),
FocusMode::Center => perceptual::center_mask(new_width, new_height),
};
let larger = new_width.max(new_height);
let (radius, amount, threshold) = if larger < 1500 {
(0.7, 0.55, 6)
} else if larger < 3000 {
(0.9, 0.7, 5)
} else {
(1.1, 0.8, 4)
};
dynamic_img =
perceptual::masked_usm_sharpen(&dynamic_img, &mask, radius, amount, threshold);
pm.sharpen_ms = t.elapsed().as_millis() as u64;
} else if self.config.cas_strength > 0.0 && scale < (1.0 / 1.3) {
let t = std::time::Instant::now();
let adaptive_strength =
compute_adaptive_cas_strength(&dynamic_img, scale, self.config.cas_strength);
if adaptive_strength > 0.0 {
dynamic_img = cas::cas_sharpen(&dynamic_img, adaptive_strength);
}
pm.sharpen_ms = t.elapsed().as_millis() as u64;
} else if self.config.enable_sharpening {
dynamic_img = smart_adaptive_sharpen(&dynamic_img, new_width.max(new_height));
}
let mut result_data;
use std::io::Cursor;
let output_ext = match self.config.output_format {
OutputFormat::Jpeg => "jpg",
OutputFormat::WebP => "webp",
OutputFormat::KeepOriginal => match extension {
"png" => "png",
"webp" => "webp",
_ => "jpg",
},
};
match output_ext {
"png" => {
use image::codecs::png::{CompressionType, FilterType, PngEncoder};
let mut cursor = Cursor::new(Vec::new());
let encoder = PngEncoder::new_with_quality(
&mut cursor,
CompressionType::Best,
FilterType::Adaptive,
);
dynamic_img.write_with_encoder(encoder)?;
result_data = cursor.into_inner();
}
"webp" => {
let mut cursor = Cursor::new(Vec::new());
dynamic_img.write_to(&mut cursor, image::ImageFormat::WebP)?;
result_data = cursor.into_inner();
}
_ => {
let t_encode = std::time::Instant::now();
let rgb_buf: Vec<u8> = if src_has_alpha {
flatten_rgba8_to_rgb(dynamic_img.to_rgba8())
} else {
dynamic_img.to_rgb8().into_raw()
};
let effective_target_kb = match perceptual {
Some(p) => p.budget_kb.unwrap_or(self.config.target_kb),
None => self.config.target_kb,
};
let limit_bytes = if effective_target_kb > 0 {
Some((effective_target_kb as usize) * 1024)
} else {
None
};
let quant_mode = perceptual.map(|p| p.quant_mode);
let encode_jpeg = |quality: u8| -> Result<Vec<u8>, anyhow::Error> {
use mozjpeg_rs::{Encoder, QuantTableIdx, Subsampling};
let sub = match self.config.subsampling.as_str() {
"444" => Subsampling::S444,
"422" => Subsampling::S422,
_ => Subsampling::S420, };
let mut encoder = Encoder::default()
.quality(quality)
.progressive(true)
.optimize_huffman(true)
.subsampling(sub);
match quant_mode {
Some(perceptual::QuantMode::MsSsim) | Some(perceptual::QuantMode::Csf) => {
encoder = encoder.quant_tables(QuantTableIdx::MssimTuned);
}
_ => {} }
encoder
.encode_rgb(&rgb_buf, new_width, new_height)
.map_err(|e| anyhow::anyhow!("JPEG encoding failed: {}", e))
};
if let Some(limit) = limit_bytes {
let current_q = match perceptual {
Some(p) => self.config.quality.min(p.quality_ceil),
None => self.config.quality,
};
pm.final_quality = current_q;
let data = encode_jpeg(current_q)?;
if data.len() <= limit {
result_data = data;
} else {
let mut low = 1;
let mut high = current_q - 1;
let mut best_data = Vec::new();
while low <= high {
let mid = (low + high) / 2;
if mid == 0 {
break;
}
if let Ok(data) = encode_jpeg(mid) {
if data.len() <= limit {
best_data = data;
pm.final_quality = mid;
low = mid + 1;
} else {
if mid == 0 {
break;
}
high = mid - 1;
}
} else {
break;
}
}
if !best_data.is_empty() {
result_data = best_data;
} else {
result_data = encode_jpeg(1)?;
pm.final_quality = 1;
}
}
} else {
let q = match perceptual {
Some(p) => self.config.quality.min(p.quality_ceil),
None => self.config.quality,
};
pm.final_quality = q;
result_data = encode_jpeg(q)?;
}
pm.encode_ms = t_encode.elapsed().as_millis() as u64;
if let (Some(_), Some((ref_gray, gw, gh))) = (perceptual, reference_gray.as_ref()) {
if let Ok(decoded) = image::load_from_memory(&result_data) {
let (out_gray, ow, oh) = perceptual::to_gray(&decoded);
if ow == *gw && oh == *gh {
pm.ssim_vs_source =
perceptual::ssim_gray(ref_gray, &out_gray, *gw, *gh);
pm.psnr_vs_source = perceptual::psnr_gray(ref_gray, &out_gray);
}
}
}
if extension == "jpg" || extension == "jpeg" {
result_data = preserve_exif_safe(input_path, &result_data);
}
}
}
fs::write(output_path, result_data)?;
Ok(perceptual.map(|_| pm))
}
}
fn preserve_exif_safe(input_path: &Path, result_data: &[u8]) -> Vec<u8> {
let input_file = match fs::File::open(input_path) {
Ok(file) => file,
Err(_) => return result_data.to_vec(),
};
let input_mmap = match unsafe { Mmap::map(&input_file) } {
Ok(mmap) => mmap,
Err(_) => return result_data.to_vec(),
};
if input_mmap.len() > 100 * 1024 * 1024 {
return result_data.to_vec();
}
let input_jpeg = match Jpeg::from_bytes(Bytes::copy_from_slice(&input_mmap)) {
Ok(jpeg) => jpeg,
Err(_) => return result_data.to_vec(),
};
let meta_segments: Vec<_> = input_jpeg
.segments()
.iter()
.filter(|s| (0xE0..=0xEF).contains(&s.marker()))
.cloned()
.collect();
if meta_segments.is_empty() {
return result_data.to_vec();
}
drop(input_mmap);
drop(input_file);
let output_jpeg = match Jpeg::from_bytes(Bytes::copy_from_slice(result_data)) {
Ok(jpeg) => jpeg,
Err(_) => return result_data.to_vec(),
};
let mut output_jpeg = output_jpeg;
let mut insert_pos = 1;
for seg in &meta_segments {
output_jpeg.segments_mut().insert(insert_pos, seg.clone());
insert_pos += 1;
}
output_jpeg.encoder().bytes().to_vec()
}
pub fn app_config_to_process_config(
config: &AppConfig,
output_dir: Option<PathBuf>,
) -> ProcessConfig {
let (mode, max_dim, quality, target_kb) = match config.usage_mode.as_str() {
"social" => (
ProcessMode::WeChat,
config.custom_max_dim,
config.custom_quality,
config.custom_target_kb,
),
"archive" => (ProcessMode::HD, 0, 95, 0),
_ => {
match config.mode {
ProcessMode::HD => (ProcessMode::HD, 4096, 95, 5000),
ProcessMode::WeChat => (ProcessMode::WeChat, 2048, 95, 900),
ProcessMode::Custom => (
ProcessMode::Custom,
config.custom_max_dim,
config.custom_quality,
config.custom_target_kb,
),
}
}
};
ProcessConfig {
mode,
max_dim,
quality,
target_kb,
output_dir,
overwrite: config.overwrite,
keep_original_name: config.keep_original_name,
output_format: config.output_format,
color_space: config.color_space,
subsampling: config.subsampling.clone(),
preserve_structure: config.preserve_structure,
structure_base: None, output_suffix: config.output_suffix.clone(),
cas_strength: config.cas_strength,
enable_sharpening: config.enable_sharpening,
sharpening_radius: config.sharpening_radius,
sharpening_amount: config.sharpening_amount,
perceptual: None,
}
}
pub(crate) fn is_skin_color(r: u8, g: u8, b: u8) -> f32 {
let _y = 0.299 * r as f32 + 0.587 * g as f32 + 0.114 * b as f32;
let cb = -0.1687 * r as f32 - 0.3313 * g as f32 + 0.5 * b as f32 + 128.0;
let cr = 0.5 * r as f32 - 0.4187 * g as f32 - 0.0813 * b as f32 + 128.0;
let cb_min = 77.0;
let cb_max = 127.0;
let cr_min = 133.0;
let cr_max = 173.0;
if cb >= cb_min && cb <= cb_max && cr >= cr_min && cr <= cr_max {
let cb_score = 1.0 - ((cb - (cb_min + cb_max) / 2.0) / ((cb_max - cb_min) / 2.0)).abs();
let cr_score = 1.0 - ((cr - (cr_min + cr_max) / 2.0) / ((cr_max - cr_min) / 2.0)).abs();
(cb_score * cr_score).clamp(0.0, 1.0)
} else {
0.0
}
}
pub(crate) fn estimate_skin_ratio(image: &image::DynamicImage) -> f32 {
let rgba = image.to_rgba8();
let (width, height) = rgba.dimensions();
let sample_step = 20;
let mut skin_count = 0;
let mut total_count = 0;
for y in (0..height).step_by(sample_step as usize) {
for x in (0..width).step_by(sample_step as usize) {
let pixel = rgba.get_pixel(x, y);
let skin_score = is_skin_color(pixel[0], pixel[1], pixel[2]);
if skin_score > 0.3 {
skin_count += 1;
}
total_count += 1;
}
}
if total_count == 0 {
return 0.0;
}
skin_count as f32 / total_count as f32
}
fn should_apply_sharpening(image: &image::DynamicImage, _max_dim: u32) -> bool {
let (width, height) = image.dimensions();
let larger_dim = width.max(height);
if larger_dim < 800 {
return false;
}
let skin_ratio = estimate_skin_ratio(image);
if skin_ratio > 0.3 {
return estimate_image_complexity(image) > 0.5;
}
if larger_dim < 2000 {
return estimate_image_complexity(image) > 0.3;
}
if larger_dim >= 2000 {
if is_already_sharp_enough(image) {
return false;
}
if estimate_noise_level(image) > 0.6 {
return false;
}
return true;
}
true
}
fn estimate_image_complexity(image: &image::DynamicImage) -> f32 {
let rgba = image.to_rgba8();
let (width, height) = rgba.dimensions();
let sample_w = (width / 100).max(1);
let sample_h = (height / 100).max(1);
let mut complexity_sum = 0.0f32;
let mut count = 0;
for y in (0..height).step_by(sample_h as usize) {
for x in (0..width).step_by(sample_w as usize) {
let pixel = rgba.get_pixel(x, y);
let mut neighbors = Vec::new();
if x > 0 {
neighbors.push(rgba.get_pixel(x - 1, y));
}
if x < width - 1 {
neighbors.push(rgba.get_pixel(x + 1, y));
}
if y > 0 {
neighbors.push(rgba.get_pixel(x, y - 1));
}
if y < height - 1 {
neighbors.push(rgba.get_pixel(x, y + 1));
}
if !neighbors.is_empty() {
let variance = neighbors
.iter()
.map(|n| {
((pixel[0] as i16 - n[0] as i16).abs() as f32
+ (pixel[1] as i16 - n[1] as i16).abs() as f32
+ (pixel[2] as i16 - n[2] as i16).abs() as f32)
/ 3.0
})
.sum::<f32>()
/ neighbors.len() as f32;
complexity_sum += variance;
count += 1;
}
}
}
if count == 0 {
return 0.0;
}
let avg_complexity = complexity_sum / count as f32;
(avg_complexity / 50.0).clamp(0.0, 1.0)
}
fn is_already_sharp_enough(image: &image::DynamicImage) -> bool {
let complexity = estimate_image_complexity(image);
complexity > 0.7
}
fn estimate_noise_level(image: &image::DynamicImage) -> f32 {
let rgba = image.to_rgba8();
let (width, height) = rgba.dimensions();
let mut noise_scores = Vec::new();
let step = 20;
for y in (0..height).step_by(step) {
for x in (0..width).step_by(step) {
let mut region_pixels = Vec::new();
for dy in 0..3.min(height - y) {
for dx in 0..3.min(width - x) {
region_pixels.push(rgba.get_pixel(x + dx, y + dy));
}
}
if region_pixels.len() >= 4 {
let mean_r = region_pixels.iter().map(|p| p[0] as f32).sum::<f32>()
/ region_pixels.len() as f32;
let variance = region_pixels
.iter()
.map(|p| (p[0] as f32 - mean_r).powi(2))
.sum::<f32>()
/ region_pixels.len() as f32;
if variance < 100.0 {
noise_scores.push(variance);
}
}
}
}
if noise_scores.is_empty() {
return 0.0;
}
let avg_noise = noise_scores.iter().sum::<f32>() / noise_scores.len() as f32;
(avg_noise / 50.0).min(1.0)
}
fn smart_adaptive_sharpen(image: &image::DynamicImage, max_dim: u32) -> image::DynamicImage {
if !should_apply_sharpening(image, max_dim) {
return image.clone();
}
let (width, height) = image.dimensions();
let larger_dim = width.max(height);
let skin_ratio = estimate_skin_ratio(image);
let is_portrait = skin_ratio > 0.3;
let complexity = estimate_image_complexity(image);
let (radius, mut amount, threshold) = if is_portrait {
if larger_dim < 2000 {
(0.6, 0.3, 15) } else if larger_dim < 4000 {
(0.8, 0.4, 12) } else {
(1.0, 0.5, 10) }
} else {
if larger_dim < 2000 {
if complexity > 0.5 {
(0.8, 0.6, 10) } else {
(0.6, 0.4, 15) }
} else if larger_dim < 4000 {
if complexity > 0.5 {
(1.0, 0.8, 6) } else {
(0.8, 0.6, 8) }
} else if complexity > 0.5 {
(1.5, 1.0, 4) } else {
(1.2, 0.8, 5) }
};
if larger_dim < 1500 {
amount *= 0.7;
}
apply_usm_sharpen(image, radius, amount, threshold)
}
fn compute_adaptive_cas_strength(image: &image::DynamicImage, scale: f32, max_cas: f32) -> f32 {
let (width, height) = image.dimensions();
let larger_dim = width.max(height);
if larger_dim < 800 {
return 0.0;
}
let skin_ratio = estimate_skin_ratio(image);
let complexity = estimate_image_complexity(image);
let noise = estimate_noise_level(image);
let is_portrait = skin_ratio > 0.3;
if noise > 0.6 {
return 0.0;
}
if is_already_sharp_enough(image) {
return 0.0;
}
if is_portrait && complexity <= 0.5 {
return 0.0;
}
if larger_dim < 2000 && complexity <= 0.3 {
return 0.0;
}
let base: f32 = if is_portrait {
if larger_dim < 2000 {
0.08
} else if larger_dim < 4000 {
0.14
} else {
0.22
}
} else {
if complexity > 0.5 {
if larger_dim < 2000 {
0.18
} else if larger_dim < 4000 {
0.30
} else {
0.44
}
} else if larger_dim < 2000 {
0.12
} else if larger_dim < 4000 {
0.22
} else {
0.34
}
};
let scale_factor = ((1.0 - scale) / 0.9).clamp(0.0, 1.0).powf(0.5);
let size_penalty = if larger_dim < 1500 { 0.6 } else { 1.0 };
let noise_penalty = if noise > 0.4 { 0.75 } else { 1.0 };
let adaptive = (base * scale_factor * size_penalty * noise_penalty).clamp(0.0, 0.5);
adaptive.min(max_cas)
}
fn apply_usm_sharpen(
image: &image::DynamicImage,
radius: f32,
amount: f32,
threshold: u8,
) -> image::DynamicImage {
let rgba = image.to_rgba8();
let (width, height) = rgba.dimensions();
let sigma = radius;
let blurred = gaussian_blur(&rgba, sigma);
let skin_ratio = estimate_skin_ratio(image);
let is_portrait = skin_ratio > 0.3;
let mut output = ImageBuffer::new(width, height);
for y in 0..height {
for x in 0..width {
let orig_pixel = rgba.get_pixel(x, y);
let blur_pixel = blurred.get_pixel(x, y);
let mut out_pixel = Rgba([0u8; 4]);
let skin_score = is_skin_color(orig_pixel[0], orig_pixel[1], orig_pixel[2]);
let skin_factor = if is_portrait && skin_score > 0.3 {
1.0 - skin_score * 0.8
} else {
1.0
};
for c in 0..3 {
let diff = orig_pixel[c] as i16 - blur_pixel[c] as i16;
if diff.abs() > threshold as i16 {
let effective_amount = amount * skin_factor;
let sharpened = orig_pixel[c] as i32 + (effective_amount * diff as f32) as i32;
out_pixel[c] = sharpened.clamp(0, 255) as u8;
} else {
out_pixel[c] = orig_pixel[c];
}
}
out_pixel[3] = orig_pixel[3];
output.put_pixel(x, y, out_pixel);
}
}
image::DynamicImage::ImageRgba8(output)
}
pub(crate) fn gaussian_blur(
image: &ImageBuffer<Rgba<u8>, Vec<u8>>,
sigma: f32,
) -> ImageBuffer<Rgba<u8>, Vec<u8>> {
let (width, height) = image.dimensions();
let kernel_size = ((sigma * 6.0) as usize).max(3) | 1; let half_kernel = kernel_size / 2;
let kernel = generate_1d_gaussian_kernel(kernel_size, sigma);
let mut temp = ImageBuffer::new(width, height);
for y in 0..height {
for x in 0..width {
let mut pixel = Rgba([0u8; 4]);
for c in 0..4 {
let mut sum = 0.0f32;
let mut weight_sum = 0.0f32;
for (kx, &weight) in kernel.iter().enumerate() {
let px = (x as i32 + kx as i32 - half_kernel as i32).clamp(0, width as i32 - 1)
as u32;
let sample_pixel = image.get_pixel(px, y);
sum += sample_pixel[c] as f32 * weight;
weight_sum += weight;
}
pixel[c] = (sum / weight_sum).clamp(0.0, 255.0) as u8;
}
temp.put_pixel(x, y, pixel);
}
}
let mut output = ImageBuffer::new(width, height);
for y in 0..height {
for x in 0..width {
let mut pixel = Rgba([0u8; 4]);
for c in 0..4 {
let mut sum = 0.0f32;
let mut weight_sum = 0.0f32;
for (ky, &weight) in kernel.iter().enumerate() {
let py = (y as i32 + ky as i32 - half_kernel as i32).clamp(0, height as i32 - 1)
as u32;
let sample_pixel = temp.get_pixel(x, py);
sum += sample_pixel[c] as f32 * weight;
weight_sum += weight;
}
pixel[c] = (sum / weight_sum).clamp(0.0, 255.0) as u8;
}
output.put_pixel(x, y, pixel);
}
}
output
}
fn generate_1d_gaussian_kernel(size: usize, sigma: f32) -> Vec<f32> {
let mut kernel = vec![0.0f32; size];
let half = (size / 2) as f32;
let two_sigma_sq = 2.0 * sigma * sigma;
let mut sum = 0.0f32;
for (x, val) in kernel.iter_mut().enumerate() {
let dx = x as f32 - half;
let value = (-dx * dx / two_sigma_sq).exp();
*val = value;
sum += value;
}
for val in kernel.iter_mut() {
*val /= sum;
}
kernel
}
#[allow(dead_code)]
fn manage_color_space(
image: image::DynamicImage,
max_dim: u32,
has_300dpi: bool,
) -> image::DynamicImage {
if has_300dpi || max_dim > 4000 {
return image;
}
if max_dim <= 3000 {
return image;
}
image
}
#[allow(dead_code)]
fn is_high_resolution_dpi(input_path: &Path) -> bool {
if let Ok(file) = fs::File::open(input_path) {
if let Ok(mmap) = unsafe { Mmap::map(&file) } {
if mmap.len() > 5 * 1024 * 1024 {
return true;
}
}
}
false
}
pub fn path_self_healing(input_path: &Path) -> PathBuf {
let path_str = input_path.to_string_lossy();
if input_path.exists() && input_path.is_file() {
return input_path.to_path_buf();
}
if let Some(file_name) = input_path.file_name().and_then(|n| n.to_str()) {
if let Some(parent) = input_path.parent() {
if parent.exists() {
if let Ok(entries) = fs::read_dir(parent) {
for entry in entries.flatten() {
if let Some(name) = entry.file_name().to_str() {
if name.eq_ignore_ascii_case(file_name) {
let candidate = entry.path();
if candidate.is_file() {
return candidate;
}
}
}
}
}
}
if let Ok(entries) = fs::read_dir(parent) {
for entry in entries.flatten() {
if let Some(name) = entry.file_name().to_str() {
if name.to_lowercase() == file_name.to_lowercase() {
let candidate = entry.path();
if candidate.is_file() {
return candidate;
}
}
}
}
}
}
}
let normalized = path_str.replace("\\", "/");
if normalized != path_str {
let alt_path = Path::new(&normalized);
if alt_path.exists() && alt_path.is_file() {
return alt_path.to_path_buf();
}
}
input_path.to_path_buf()
}
fn load_image_safe(input_path: &Path) -> Result<image::DynamicImage> {
if let Ok(img) = load_image_mmap(input_path) {
return Ok(img);
}
image::open(input_path).map_err(|e| anyhow::anyhow!("Failed to load image: {}", e))
}
fn load_image_mmap(input_path: &Path) -> Result<image::DynamicImage> {
let file = fs::File::open(input_path)?;
let file_size = file.metadata()?.len();
if file_size > 200 * 1024 * 1024 {
let mmap = unsafe { Mmap::map(&file)? };
return image::load_from_memory(&mmap)
.map_err(|e| anyhow::anyhow!("Failed to decode with mmap: {}", e));
}
drop(file);
let bytes = fs::read(input_path)?;
image::load_from_memory(&bytes)
.map_err(|e| anyhow::anyhow!("Failed to decode from memory: {}", e))
}
fn flatten_rgba8_to_rgb(img: image::RgbaImage) -> Vec<u8> {
let (w, h) = img.dimensions();
let mut out = Vec::with_capacity((w * h * 3) as usize);
for p in img.pixels() {
let [r, g, b, a] = p.0;
let alpha = a as f32 / 255.0;
let inv = 1.0 - alpha;
out.push((r as f32 * alpha + 255.0 * inv) as u8);
out.push((g as f32 * alpha + 255.0 * inv) as u8);
out.push((b as f32 * alpha + 255.0 * inv) as u8);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
fn tmp_dir(tag: &str) -> PathBuf {
let d =
std::env::temp_dir().join(format!("xtap_compress_test_{}_{}", tag, std::process::id()));
let _ = fs::remove_dir_all(&d);
fs::create_dir_all(&d).unwrap();
d
}
fn make_test_image(path: &Path, w: u32, h: u32) {
let mut img = image::RgbaImage::new(w, h);
for (x, y, px) in img.enumerate_pixels_mut() {
let r = (x as f32 / w as f32 * 255.0) as u8;
let g = (y as f32 / h as f32 * 255.0) as u8;
let b = ((x + y) as f32 / (w + h) as f32 * 255.0) as u8;
*px = image::Rgba([r, g, b, 255]);
}
img.save(path).unwrap();
}
#[test]
fn test_app_config_social_maps_to_wechat() {
let cfg = AppConfig {
usage_mode: "social".to_string(),
custom_max_dim: 1280,
custom_quality: 90,
custom_target_kb: 300,
..Default::default()
};
let pc = app_config_to_process_config(&cfg, None);
assert_eq!(pc.mode, ProcessMode::WeChat);
assert_eq!(pc.max_dim, 1280);
assert_eq!(pc.quality, 90);
assert_eq!(pc.target_kb, 300);
assert_eq!(pc.subsampling, "420");
let p = Processor::new(pc);
let out = p.expected_output_path(Path::new("photo.jpg"));
assert!(out.to_string_lossy().ends_with("_wx.jpg"));
}
#[test]
fn test_app_config_archive_no_downscale() {
let cfg = AppConfig {
usage_mode: "archive".to_string(),
..Default::default()
};
let pc = app_config_to_process_config(&cfg, None);
assert_eq!(pc.mode, ProcessMode::HD);
assert_eq!(pc.max_dim, 0, "archive 不应缩放");
assert_eq!(pc.quality, 95);
assert_eq!(pc.target_kb, 0);
let out = Processor::new(pc).expected_output_path(Path::new("photo.png"));
assert!(out.to_string_lossy().ends_with("_hd.jpg"));
}
#[test]
fn test_process_image_compresses_and_scales() {
let dir = tmp_dir("e2e");
let src = dir.join("src.png");
make_test_image(&src, 1600, 1200);
let cfg = AppConfig::default();
let mut pc = app_config_to_process_config(&cfg, Some(dir.join("out")));
pc.max_dim = 1280;
pc.quality = 80;
pc.overwrite = false;
pc.keep_original_name = true;
let processor = Processor::new(pc);
let out = processor.process_image(&src).unwrap();
assert!(out.exists(), "输出文件应存在");
let img = image::open(&out).unwrap();
assert!(
img.width() <= 1280 && img.height() <= 1280,
"应缩放至 1280 内,实际 {}x{}",
img.width(),
img.height()
);
assert!(
fs::metadata(&out).unwrap().len() < fs::metadata(&src).unwrap().len(),
"压缩后体积应小于原图"
);
fs::remove_dir_all(&dir).ok();
}
#[test]
fn test_expected_output_path_suffix_rules() {
let base = ProcessConfig {
mode: ProcessMode::Custom,
max_dim: 2000,
quality: 85,
target_kb: 0,
output_dir: None,
overwrite: false,
keep_original_name: false,
output_format: OutputFormat::Jpeg,
color_space: ColorSpace::KeepOriginal,
enable_sharpening: false,
sharpening_radius: 1.0,
sharpening_amount: 0.8,
perceptual: None,
subsampling: "420".to_string(),
preserve_structure: false,
structure_base: None,
output_suffix: None,
cas_strength: 0.0,
};
let wx = Processor::new(ProcessConfig {
mode: ProcessMode::WeChat,
..base.clone()
})
.expected_output_path(Path::new("a.JPG"));
assert!(
wx.to_string_lossy().ends_with("_wx.jpg"),
"大小写扩展名应归一 + 后缀 _wx,实际 {}",
wx.display()
);
let hd = Processor::new(ProcessConfig {
mode: ProcessMode::HD,
..base.clone()
})
.expected_output_path(Path::new("a.png"));
assert!(hd.to_string_lossy().ends_with("_hd.jpg"));
let da = Processor::new(ProcessConfig {
mode: ProcessMode::Custom,
..base.clone()
})
.expected_output_path(Path::new("a.webp"));
assert!(
da.to_string_lossy().ends_with("_da.jpg"),
"Custom 默认后缀 _da,实际 {}",
da.display()
);
let ow = Processor::new(ProcessConfig {
overwrite: true,
..base
})
.expected_output_path(Path::new("b.jpg"));
assert!(ow.to_string_lossy().ends_with("b.jpg"));
}
#[test]
fn test_path_self_healing_case_insensitive() {
let dir = tmp_dir("heal");
let real = dir.join("Photo.PNG");
make_test_image(&real, 64, 64);
let healed = path_self_healing(&dir.join("photo.png"));
assert!(healed.exists(), "healed 路径必须存在: {}", healed.display());
assert_eq!(
fs::canonicalize(&healed).unwrap(),
fs::canonicalize(&real).unwrap(),
"healed 与真实文件应为同一文件"
);
fs::remove_dir_all(&dir).ok();
}
}