Skip to main content

xtap_compress/
lib.rs

1pub mod cas;
2pub mod perceptual;
3
4use anyhow::Result;
5use bytes::Bytes;
6use fast_image_resize as fr;
7use image::GenericImageView;
8use img_parts::jpeg::Jpeg;
9use memmap2::Mmap;
10use perceptual::{FocusMode, PerceptualMetrics, PerceptualOptions};
11use serde::{Deserialize, Serialize};
12use std::fs;
13use std::path::{Path, PathBuf};
14#[cfg(target_os = "macos")]
15use std::sync::atomic::{AtomicUsize, Ordering};
16
17// 摄影级优化导入
18use image::ImageBuffer;
19use image::Rgba;
20
21#[cfg(target_os = "macos")]
22static SIPS_CONCURRENCY: AtomicUsize = AtomicUsize::new(0);
23#[cfg(target_os = "macos")]
24const MAX_SIPS_CONCURRENCY: usize = 4;
25
26#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
27pub enum ProcessMode {
28    WeChat,
29    HD,
30    Custom,
31}
32
33#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
34pub enum OutputFormat {
35    Jpeg,
36    KeepOriginal,
37    /// v4.3.1:WebP 输出(网络分发/网页内嵌更省体积,支持透明通道)
38    WebP,
39}
40
41#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
42pub enum ColorSpace {
43    KeepOriginal,
44    ConvertToSRGB,
45}
46
47/// App 产品版本号(唯一真源)。与 lib crate 的 `version = "0.1.1"` 是两套体系,
48/// GUI 三处版本显示(关于页 / 状态栏 / 卡片标题)统一引用此常量,升版只改这里。
49pub const APP_VERSION: &str = "v4.4.4";
50
51#[derive(Clone, Debug, Serialize, Deserialize)]
52pub struct AppConfig {
53    /// v4.4.0:配置版本号(用于自动迁移;旧配置缺失=1,当前=2)
54    #[serde(default = "default_config_version")]
55    pub config_version: u32,
56    pub mode: ProcessMode,
57    pub custom_max_dim: u32,
58    pub custom_quality: u8,
59    pub custom_target_kb: u32,
60    pub overwrite: bool,
61    pub keep_original_name: bool,
62    pub output_format: OutputFormat,
63    pub color_space: ColorSpace,
64    // 摄影级优化选项
65    pub enable_sharpening: bool,       // USM 锐化
66    pub sharpening_radius: f32,        // 锐化半径 (默认 1.0)
67    pub sharpening_amount: f32,        // 锐化强度 (默认 0.8)
68    pub use_custom_quantization: bool, // 自定义量化表
69    pub preserve_high_frequency: bool, // 保留高频细节
70    // v4.2.0:用途 / 平台 / 画质模式(GUI 记忆 + 三方接口对齐)
71    // usage_mode: "social"(社交分享) | "archive"(高清存档) | "custom"(自定义)
72    // quality_mode: "perceptual"(小而美感知压缩) | "normal"(普通标准压缩)
73    // platform: wechat/wechat-new/xiaohongshu/instagram/general
74    // serde(default):旧版 config.toml 没有这三个字段,升级后仍能正常加载(配置记忆不丢)
75    #[serde(default = "default_usage_mode")]
76    pub usage_mode: String,
77    #[serde(default = "default_quality_mode")]
78    pub quality_mode: String,
79    #[serde(default = "default_platform")]
80    pub platform: String,
81    // v4.3.0:色彩子采样(照片 420 省 ~1/3 码率 / 截图文字 444 防模糊 / 422 平衡)
82    #[serde(default = "default_subsampling")]
83    pub subsampling: String,
84    // v4.3.1:输出保结构(复刻源目录层级到 output_dir)/ 后缀可控(覆盖默认 _wx/_hd/_da,空串=无后缀)
85    #[serde(default)]
86    pub preserve_structure: bool,
87    #[serde(default)]
88    pub output_suffix: Option<String>,
89    // v4.4.0:CAS 锐化强度(0=关闭;画质优先档默认 0.35,缩放比>1.3 时自动补偿降采样柔化)
90    #[serde(default)]
91    pub cas_strength: f32,
92    // v4.4.1:GUI 自定义导出目录记忆(用户通过文件选择器指定的输出目录,None=默认原文件旁)
93    #[serde(default)]
94    pub custom_output_dir: Option<String>,
95}
96
97fn default_usage_mode() -> String {
98    "social".to_string()
99}
100fn default_config_version() -> u32 {
101    1
102}
103fn default_quality_mode() -> String {
104    "max".to_string()
105}
106fn default_platform() -> String {
107    "wechat".to_string()
108}
109
110fn default_subsampling() -> String {
111    "420".to_string()
112}
113
114impl Default for AppConfig {
115    fn default() -> Self {
116        Self {
117            config_version: 2,
118            mode: ProcessMode::Custom,
119            custom_max_dim: 3000,
120            custom_quality: 85,
121            custom_target_kb: 0,
122            overwrite: false,
123            keep_original_name: false,
124            output_format: OutputFormat::Jpeg,
125            color_space: ColorSpace::KeepOriginal,
126            // 摄影级优化默认关闭(保持原有行为)
127            enable_sharpening: false,
128            sharpening_radius: 1.0,
129            sharpening_amount: 0.8,
130            use_custom_quantization: false,
131            preserve_high_frequency: false,
132            // v4.4.0:默认社交分享 + 防二压画质优先 + 微信平台
133            usage_mode: "social".to_string(),
134            quality_mode: "max".to_string(),
135            platform: "wechat".to_string(),
136            subsampling: "420".to_string(),
137            preserve_structure: false,
138            output_suffix: None,
139            cas_strength: 0.0,
140            custom_output_dir: None,
141        }
142    }
143}
144
145#[derive(Clone, Debug)]
146pub struct ProcessConfig {
147    pub mode: ProcessMode,
148    pub max_dim: u32,
149    pub quality: u8,
150    pub target_kb: u32,
151    pub output_dir: Option<PathBuf>,
152    pub overwrite: bool,
153    pub keep_original_name: bool,
154    pub output_format: OutputFormat,
155    pub color_space: ColorSpace,
156    // 摄影级优化
157    pub enable_sharpening: bool,
158    pub sharpening_radius: f32,
159    pub sharpening_amount: f32,
160    /// v4.2.0-exp 感知压缩选项:None = 完全走 v4.1.0 旧路径(GUI 恒为 None)
161    pub perceptual: Option<PerceptualOptions>,
162    // v4.3.0:色彩子采样(照片 420 / 截图 444 / 平衡 422)
163    pub subsampling: String,
164    // v4.3.1:保结构输出(复刻源目录层级到 output_dir)
165    pub preserve_structure: bool,
166    // v4.3.1:结构基准目录(输出相对此目录复刻层级;由调用方计算注入)
167    pub structure_base: Option<PathBuf>,
168    // v4.3.1:后缀可控(覆盖默认 _wx/_hd/_da;None=默认,空串=无后缀)
169    pub output_suffix: Option<String>,
170    // v4.4.0:CAS 锐化强度(0=关闭;感知模式已有 USM 时自动跳过防双重锐化)
171    pub cas_strength: f32,
172}
173
174pub struct Processor {
175    config: ProcessConfig,
176}
177
178impl Processor {
179    pub fn new(config: ProcessConfig) -> Self {
180        Self { config }
181    }
182
183    /// 纯路径计算:给定输入文件,返回将要生成的输出路径(不创建目录、不做任何 IO 写入)。
184    /// 供上层「续跑跳过」幂等判断复用,与 process_image 内部逻辑严格同源。
185    ///
186    /// v4.3.1 增强:
187    /// - `preserve_structure=true` 时,按 `structure_base` 复刻源目录相对层级到 output_dir(修 D2 拍平)。
188    /// - `output_suffix` 可覆盖默认 `_wx/_hd/_da`;空串=无后缀。`keep_original_name` 优先级最高(无后缀)。
189    /// - 支持 WebP 输出扩展名。
190    pub fn expected_output_path(&self, input_path: &Path) -> PathBuf {
191        let healed_path = path_self_healing(input_path);
192        let file_stem = healed_path
193            .file_stem()
194            .unwrap_or_default()
195            .to_string_lossy()
196            .to_string();
197        let extension = healed_path
198            .extension()
199            .and_then(|e| e.to_str())
200            .unwrap_or("")
201            .to_lowercase();
202
203        let output_ext = match self.config.output_format {
204            OutputFormat::Jpeg => "jpg",
205            OutputFormat::WebP => "webp",
206            OutputFormat::KeepOriginal => match extension.as_str() {
207                "png" => "png",
208                "webp" => "webp",
209                _ => "jpg",
210            },
211        };
212
213        let base_out = self
214            .config
215            .output_dir
216            .clone()
217            .unwrap_or_else(|| healed_path.parent().unwrap_or(Path::new(".")).to_path_buf());
218
219        // 保结构:把输入相对 structure_base 的父目录层级拼到输出目录后
220        let rel_parent = if self.config.preserve_structure {
221            self.config
222                .structure_base
223                .as_ref()
224                .and_then(|b| {
225                    healed_path
226                        .parent()
227                        .unwrap_or(Path::new("."))
228                        .strip_prefix(b)
229                        .ok()
230                })
231                .unwrap_or_else(|| Path::new(""))
232        } else {
233            Path::new("")
234        };
235        let out_dir = base_out.join(rel_parent);
236
237        let suffix = if self.config.keep_original_name {
238            String::new()
239        } else if let Some(s) = &self.config.output_suffix {
240            if s.is_empty() {
241                String::new()
242            } else {
243                format!("_{}", s)
244            }
245        } else {
246            match self.config.mode {
247                ProcessMode::WeChat => "_wx".to_string(),
248                ProcessMode::HD => "_hd".to_string(),
249                _ => "_da".to_string(),
250            }
251        };
252
253        if self.config.overwrite {
254            healed_path.to_path_buf()
255        } else if self.config.keep_original_name {
256            out_dir.join(format!("{}.{}", file_stem, output_ext))
257        } else {
258            out_dir.join(format!("{}{}.{}", file_stem, suffix, output_ext))
259        }
260    }
261
262    /// 透传路径:不支持的格式(如 SVG)原样复制到 output_dir(保持保结构层级、不改名不改扩展名)。
263    /// 与 expected_output_path 仅在「不加后缀」上有区别,便于 passthrough 模式 1:1 映射源文件名。
264    pub fn passthrough_path(&self, input_path: &Path) -> PathBuf {
265        let healed_path = path_self_healing(input_path);
266        let base_out = self
267            .config
268            .output_dir
269            .clone()
270            .unwrap_or_else(|| healed_path.parent().unwrap_or(Path::new(".")).to_path_buf());
271        let rel_parent = if self.config.preserve_structure {
272            self.config
273                .structure_base
274                .as_ref()
275                .and_then(|b| {
276                    healed_path
277                        .parent()
278                        .unwrap_or(Path::new("."))
279                        .strip_prefix(b)
280                        .ok()
281                })
282                .unwrap_or_else(|| Path::new(""))
283        } else {
284            Path::new("")
285        };
286        let out_dir = base_out.join(rel_parent);
287        let name = healed_path
288            .file_name()
289            .unwrap_or_default()
290            .to_string_lossy()
291            .to_string();
292        out_dir.join(name)
293    }
294
295    pub fn process_image(&self, input_path: &Path) -> Result<PathBuf> {
296        self.process_image_with_metrics(input_path).map(|(p, _)| p)
297    }
298
299    /// v4.2.0-exp:处理并返回感知指标(perceptual=None 时指标恒为 None,行为同 v4.1.0)
300    pub fn process_image_with_metrics(
301        &self,
302        input_path: &Path,
303    ) -> Result<(PathBuf, Option<PerceptualMetrics>)> {
304        let healed_path = path_self_healing(input_path);
305        let file_name_os = healed_path
306            .file_name()
307            .unwrap_or_default()
308            .to_string_lossy();
309        if file_name_os.starts_with("._") {
310            return Err(anyhow::anyhow!("跳过系统隐藏文件"));
311        }
312
313        let extension = healed_path
314            .extension()
315            .and_then(|e| e.to_str())
316            .unwrap_or("")
317            .to_lowercase();
318
319        let raw_extensions = [
320            "dng", "cr2", "cr3", "nef", "arw", "orf", "raf", "rw2", "pef", "srw", "3fr",
321        ];
322        let is_raw = raw_extensions.contains(&extension.as_str());
323
324        // 输出路径与 expected_output_path 严格同源;按最终输出路径的父目录建目录(兼容保结构子目录)
325        let output_path = self.expected_output_path(&healed_path);
326        if let Some(parent) = output_path.parent() {
327            fs::create_dir_all(parent)?;
328        }
329
330        let metrics: Option<PerceptualMetrics>;
331
332        #[cfg(target_os = "macos")]
333        {
334            let file_stem = healed_path.file_stem().unwrap().to_string_lossy();
335            if is_raw {
336                self.process_raw(&healed_path, &output_path, &file_stem, &file_name_os)?;
337                metrics = None;
338            } else {
339                metrics = self.process_normal(&healed_path, &output_path, &extension)?;
340            }
341        }
342
343        #[cfg(not(target_os = "macos"))]
344        if is_raw {
345            return Err(anyhow::anyhow!(
346                "RAW 格式 ({}) 仅在 macOS 系统上支持。请先在 Mac 上处理,或转成 JPG/PNG 后使用。",
347                extension
348            ));
349        } else {
350            metrics = self.process_normal(&healed_path, &output_path, &extension)?;
351        }
352
353        Ok((output_path, metrics))
354    }
355
356    /// 返回当前感知压缩配置(None = 走 v4.1.0 旧路径),供 CLI/JSON 输出 metrics 元数据
357    pub fn perceptual_config(&self) -> Option<&PerceptualOptions> {
358        self.config.perceptual.as_ref()
359    }
360
361    /// 实际生效的体积预算(KB):感知模式 budget_kb 覆盖 target_kb
362    pub fn effective_target_kb(&self) -> u32 {
363        match &self.config.perceptual {
364            Some(p) => p.budget_kb.unwrap_or(self.config.target_kb),
365            None => self.config.target_kb,
366        }
367    }
368
369    #[cfg(target_os = "macos")]
370    fn process_raw(
371        &self,
372        input_path: &Path,
373        output_path: &Path,
374        file_stem: &str,
375        file_name: &str,
376    ) -> Result<()> {
377        while SIPS_CONCURRENCY.load(Ordering::SeqCst) >= MAX_SIPS_CONCURRENCY {
378            std::thread::sleep(std::time::Duration::from_millis(100));
379        }
380        SIPS_CONCURRENCY.fetch_add(1, Ordering::SeqCst);
381
382        let input_path_abs =
383            fs::canonicalize(input_path).unwrap_or_else(|_| input_path.to_path_buf());
384        let result = (|| -> Result<()> {
385            let mut preview_cmd = std::process::Command::new("sips");
386            preview_cmd
387                .arg("-e")
388                .arg("preview")
389                .arg(&input_path_abs)
390                .arg("--out")
391                .arg(output_path);
392
393            let _ = preview_cmd.output();
394            if output_path.exists() {
395                // max_dim == 0 表示「不缩放」(高清存档),跳过 sips -Z
396                if self.config.max_dim > 0 {
397                    if let Ok(img) = image::open(output_path) {
398                        let (w, h) = img.dimensions();
399                        if w > self.config.max_dim || h > self.config.max_dim {
400                            let mut resize_cmd = std::process::Command::new("sips");
401                            resize_cmd.arg("-Z").arg(self.config.max_dim.to_string());
402                            resize_cmd.arg(output_path);
403                            let _ = resize_cmd.output();
404                        }
405                    }
406                }
407                return Ok(());
408            }
409
410            let mut cmd = std::process::Command::new("sips");
411            cmd.arg("-s").arg("format").arg("jpeg");
412            let quality = self.config.quality;
413            cmd.arg("-s").arg("formatOptions").arg(quality.to_string());
414            if self.config.max_dim > 0 {
415                cmd.arg("-Z").arg(self.config.max_dim.to_string());
416            }
417            cmd.arg(&input_path_abs).arg("--out").arg(output_path);
418
419            let mut child = cmd.spawn()?;
420            let timeout = std::time::Duration::from_secs(30);
421            let start = std::time::Instant::now();
422
423            let status = loop {
424                match child.try_wait()? {
425                    Some(status) => break status,
426                    None => {
427                        if start.elapsed() > timeout {
428                            let _ = child.kill();
429                            break std::process::ExitStatus::default();
430                        }
431                        std::thread::sleep(std::time::Duration::from_millis(100));
432                    }
433                }
434            };
435
436            if status.success() && output_path.exists() {
437                return Ok(());
438            }
439
440            let temp_dir = std::env::temp_dir().join("rust_compressor_ql");
441            let _ = fs::create_dir_all(&temp_dir);
442            let mut ql_cmd = std::process::Command::new("qlmanage");
443            ql_cmd.arg("-t").arg("-s");
444            // max_dim == 0(不缩放)时 qlmanage 仍需尺寸参数 → 给超大值等效原尺寸
445            if self.config.max_dim > 0 {
446                ql_cmd.arg(self.config.max_dim.to_string());
447            } else {
448                ql_cmd.arg("20000");
449            }
450            ql_cmd.arg("-o").arg(&temp_dir).arg(&input_path_abs);
451
452            if let Ok(mut child) = ql_cmd.spawn() {
453                let start = std::time::Instant::now();
454                loop {
455                    if let Ok(Some(_)) = child.try_wait() {
456                        break;
457                    }
458                    if start.elapsed().as_secs() > 30 {
459                        let _ = child.kill();
460                        break;
461                    }
462                    std::thread::sleep(std::time::Duration::from_millis(100));
463                }
464            }
465
466            let ql_file_1 = temp_dir.join(format!("{}.png", file_stem));
467            let ql_file_2 = temp_dir.join(format!("{}.png", file_name));
468            let ql_file = if ql_file_1.exists() {
469                Some(ql_file_1)
470            } else if ql_file_2.exists() {
471                Some(ql_file_2)
472            } else {
473                None
474            };
475
476            if let Some(path) = ql_file {
477                let mut conv_cmd = std::process::Command::new("sips");
478                conv_cmd
479                    .arg("-s")
480                    .arg("format")
481                    .arg("jpeg")
482                    .arg(&path)
483                    .arg("--out")
484                    .arg(output_path);
485                let _ = conv_cmd.output();
486                let _ = fs::remove_file(path);
487                if output_path.exists() {
488                    return Ok(());
489                }
490            }
491
492            Err(anyhow::anyhow!("该机型 RAW 暂不支持"))
493        })();
494
495        SIPS_CONCURRENCY.fetch_sub(1, Ordering::SeqCst);
496        result?;
497        Ok(())
498    }
499
500    fn process_normal(
501        &self,
502        input_path: &Path,
503        output_path: &Path,
504        extension: &str,
505    ) -> Result<Option<PerceptualMetrics>> {
506        let img = load_image_safe(input_path)?;
507        let (width, height) = img.dimensions();
508        // v4.3.1:提前判定源图是否含 alpha 通道(PNG/WebP 透明图)。JPEG 输出不支持透明,
509        // 含 alpha 时把透明区域填白底(修 D4:透明 PNG→JPEG 丢透明变黑)。
510        let src_has_alpha = img.color().has_alpha();
511        let perceptual = self.config.perceptual.as_ref();
512        let mut pm = PerceptualMetrics::default();
513
514        // max_dim == 0 表示「不缩放,保持原图尺寸」(高清存档/投稿场景)
515        let scale = if self.config.max_dim > 0
516            && (width > self.config.max_dim || height > self.config.max_dim)
517        {
518            let ratio_w = self.config.max_dim as f32 / width as f32;
519            let ratio_h = self.config.max_dim as f32 / height as f32;
520            ratio_w.min(ratio_h)
521        } else {
522            1.0
523        };
524
525        let new_width = (width as f32 * scale) as u32;
526        let new_height = (height as f32 * scale) as u32;
527
528        let img_rgba = img.to_rgba8();
529
530        let t_down = std::time::Instant::now();
531        let src_image = fr::images::Image::from_vec_u8(
532            width,
533            height,
534            img_rgba.into_raw(),
535            fr::PixelType::U8x4,
536        )?;
537
538        let mut dst_image = fr::images::Image::new(new_width, new_height, fr::PixelType::U8x4);
539
540        let mut resizer = fr::Resizer::new();
541        resizer.resize(&src_image, &mut dst_image, None)?;
542
543        let rgba_buf = dst_image.buffer();
544        pm.downscale_ms = t_down.elapsed().as_millis() as u64;
545
546        // 转换为 DynamicImage 以便后续处理
547        let mut dynamic_img = image::DynamicImage::ImageRgba8(
548            image::ImageBuffer::from_raw(new_width, new_height, rgba_buf.to_vec())
549                .ok_or_else(|| anyhow::anyhow!("Failed to create image buffer"))?,
550        );
551
552        // 感知指标参考帧:降采样后、锐化编码前的灰度图
553        let reference_gray = perceptual.map(|_| perceptual::to_gray(&dynamic_img));
554
555        if let Some(p) = perceptual {
556            // 降噪在「目标分辨率」上做(§3 防御性修正:超大图全分辨率降噪会卡死/爆内存,
557            // 统一放降采样后;高质量重采样已抑制高频噪点,目标分辨率降噪足以满足分享/存档画质)
558            // JPG 输入禁降噪(放大块效应);超过 4000px 的超大图直接跳过降噪(防冻结)
559            let is_jpeg_input = matches!(extension, "jpg" | "jpeg");
560            if p.denoise_strength > 0 && !is_jpeg_input && new_width.max(new_height) <= 4000 {
561                let t = std::time::Instant::now();
562                dynamic_img = image::DynamicImage::ImageRgba8(perceptual::bilateral_denoise(
563                    &dynamic_img.to_rgba8(),
564                    p.denoise_strength,
565                ));
566                pm.denoise_ms = t.elapsed().as_millis() as u64;
567                pm.denoise_applied = true;
568            }
569            // 锐化在目标分辨率上做、且是编码前最后一步
570            let t = std::time::Instant::now();
571            let rgba_now = dynamic_img.to_rgba8();
572            let mask = match p.focus_mode {
573                FocusMode::Auto => perceptual::saliency_mask(&rgba_now),
574                FocusMode::Center => perceptual::center_mask(new_width, new_height),
575            };
576            let larger = new_width.max(new_height);
577            // 保守参数(§9 保画质铁律):radius 随尺寸微调,amount 经掩码加权后有效强度更低
578            let (radius, amount, threshold) = if larger < 1500 {
579                (0.7, 0.55, 6)
580            } else if larger < 3000 {
581                (0.9, 0.7, 5)
582            } else {
583                (1.1, 0.8, 4)
584            };
585            dynamic_img =
586                perceptual::masked_usm_sharpen(&dynamic_img, &mask, radius, amount, threshold);
587            pm.sharpen_ms = t.elapsed().as_millis() as u64;
588        } else if self.config.cas_strength > 0.0 && scale < (1.0 / 1.3) {
589            // v4.4.1:CAS 锐化补偿——不再用固定强度,改为调用自适应计算:
590            // 根据原图内容(人像/风景/复杂度/噪点)+ 原图尺寸 + 缩放幅度综合决策。
591            // 自适应性继承自旧版 smart_adaptive_sharpen,输出映射为 CAS strength。
592            let t = std::time::Instant::now();
593            let adaptive_strength =
594                compute_adaptive_cas_strength(&dynamic_img, scale, self.config.cas_strength);
595            if adaptive_strength > 0.0 {
596                dynamic_img = cas::cas_sharpen(&dynamic_img, adaptive_strength);
597            }
598            pm.sharpen_ms = t.elapsed().as_millis() as u64;
599        } else if self.config.enable_sharpening {
600            // v4.1.0 旧路径:智能自适应锐化(行为不变)
601            dynamic_img = smart_adaptive_sharpen(&dynamic_img, new_width.max(new_height));
602        }
603
604        let mut result_data;
605        use std::io::Cursor;
606
607        let output_ext = match self.config.output_format {
608            OutputFormat::Jpeg => "jpg",
609            OutputFormat::WebP => "webp",
610            OutputFormat::KeepOriginal => match extension {
611                "png" => "png",
612                "webp" => "webp",
613                _ => "jpg",
614            },
615        };
616
617        match output_ext {
618            "png" => {
619                use image::codecs::png::{CompressionType, FilterType, PngEncoder};
620                let mut cursor = Cursor::new(Vec::new());
621                let encoder = PngEncoder::new_with_quality(
622                    &mut cursor,
623                    CompressionType::Best,
624                    FilterType::Adaptive,
625                );
626                dynamic_img.write_with_encoder(encoder)?;
627                result_data = cursor.into_inner();
628            }
629            "webp" => {
630                let mut cursor = Cursor::new(Vec::new());
631                dynamic_img.write_to(&mut cursor, image::ImageFormat::WebP)?;
632                result_data = cursor.into_inner();
633            }
634            _ => {
635                let t_encode = std::time::Instant::now();
636                // 转换为 RGB 格式;JPEG 不支持透明 → 含 alpha 的源图先按白底合成(修 D4 透明丢失)
637                let rgb_buf: Vec<u8> = if src_has_alpha {
638                    flatten_rgba8_to_rgb(dynamic_img.to_rgba8())
639                } else {
640                    dynamic_img.to_rgb8().into_raw()
641                };
642
643                // 感知模式:budget_kb 覆盖 target_kb;质量上限 quality_ceil
644                let effective_target_kb = match perceptual {
645                    Some(p) => p.budget_kb.unwrap_or(self.config.target_kb),
646                    None => self.config.target_kb,
647                };
648                let limit_bytes = if effective_target_kb > 0 {
649                    Some((effective_target_kb as usize) * 1024)
650                } else {
651                    None
652                };
653
654                let quant_mode = perceptual.map(|p| p.quant_mode);
655                let encode_jpeg = |quality: u8| -> Result<Vec<u8>, anyhow::Error> {
656                    use mozjpeg_rs::{Encoder, QuantTableIdx, Subsampling};
657                    // P1:mozjpeg-rs 替换 jpeg-encoder(BSD-3,纯 Rust,零 C 依赖)
658                    // 默认 4:2:0 子采样(照片省 ~1/3 码率);截图/文字场景由 subsampling 字段切 4:4:4(P2 贯通)
659                    let sub = match self.config.subsampling.as_str() {
660                        "444" => Subsampling::S444,
661                        "422" => Subsampling::S422,
662                        _ => Subsampling::S420, // "420" 默认(照片省码率)
663                    };
664                    let mut encoder = Encoder::default()
665                        .quality(quality)
666                        .progressive(true)
667                        .optimize_huffman(true)
668                        .subsampling(sub);
669                    // 感知模式:用 MS-SSIM 调优量化表(mozjpeg-rs 不支持外部自定义表注入,
670                    // 原 jpeg-encoder 的 MsSsim/Csf 自定义表统一改用内置 MssimTuned,叠加 trellis 画质更优)
671                    match quant_mode {
672                        Some(perceptual::QuantMode::MsSsim) | Some(perceptual::QuantMode::Csf) => {
673                            encoder = encoder.quant_tables(QuantTableIdx::MssimTuned);
674                        }
675                        _ => {} // 非感知模式:mozjpeg 默认 Annex-K 表(v4.1.0 行为等价)
676                    }
677                    encoder
678                        .encode_rgb(&rgb_buf, new_width, new_height)
679                        .map_err(|e| anyhow::anyhow!("JPEG encoding failed: {}", e))
680                };
681
682                if let Some(limit) = limit_bytes {
683                    let current_q = match perceptual {
684                        Some(p) => self.config.quality.min(p.quality_ceil),
685                        None => self.config.quality,
686                    };
687                    pm.final_quality = current_q;
688                    let data = encode_jpeg(current_q)?;
689
690                    if data.len() <= limit {
691                        result_data = data;
692                    } else {
693                        let mut low = 1;
694                        let mut high = current_q - 1;
695                        let mut best_data = Vec::new();
696
697                        while low <= high {
698                            let mid = (low + high) / 2;
699                            if mid == 0 {
700                                break;
701                            }
702
703                            if let Ok(data) = encode_jpeg(mid) {
704                                if data.len() <= limit {
705                                    best_data = data;
706                                    pm.final_quality = mid;
707                                    low = mid + 1;
708                                } else {
709                                    if mid == 0 {
710                                        break;
711                                    }
712                                    high = mid - 1;
713                                }
714                            } else {
715                                break;
716                            }
717                        }
718
719                        if !best_data.is_empty() {
720                            result_data = best_data;
721                        } else {
722                            result_data = encode_jpeg(1)?;
723                            pm.final_quality = 1;
724                        }
725                    }
726                } else {
727                    let q = match perceptual {
728                        Some(p) => self.config.quality.min(p.quality_ceil),
729                        None => self.config.quality,
730                    };
731                    pm.final_quality = q;
732                    result_data = encode_jpeg(q)?;
733                }
734                pm.encode_ms = t_encode.elapsed().as_millis() as u64;
735
736                // 感知指标:解码输出 JPG,与「降采样后参考帧」算 SSIM/PSNR
737                if let (Some(_), Some((ref_gray, gw, gh))) = (perceptual, reference_gray.as_ref()) {
738                    if let Ok(decoded) = image::load_from_memory(&result_data) {
739                        let (out_gray, ow, oh) = perceptual::to_gray(&decoded);
740                        if ow == *gw && oh == *gh {
741                            pm.ssim_vs_source =
742                                perceptual::ssim_gray(ref_gray, &out_gray, *gw, *gh);
743                            pm.psnr_vs_source = perceptual::psnr_gray(ref_gray, &out_gray);
744                        }
745                    }
746                }
747
748                if extension == "jpg" || extension == "jpeg" {
749                    result_data = preserve_exif_safe(input_path, &result_data);
750                }
751            }
752        }
753
754        fs::write(output_path, result_data)?;
755        Ok(perceptual.map(|_| pm))
756    }
757}
758
759fn preserve_exif_safe(input_path: &Path, result_data: &[u8]) -> Vec<u8> {
760    let input_file = match fs::File::open(input_path) {
761        Ok(file) => file,
762        Err(_) => return result_data.to_vec(),
763    };
764
765    let input_mmap = match unsafe { Mmap::map(&input_file) } {
766        Ok(mmap) => mmap,
767        Err(_) => return result_data.to_vec(),
768    };
769
770    if input_mmap.len() > 100 * 1024 * 1024 {
771        return result_data.to_vec();
772    }
773
774    let input_jpeg = match Jpeg::from_bytes(Bytes::copy_from_slice(&input_mmap)) {
775        Ok(jpeg) => jpeg,
776        Err(_) => return result_data.to_vec(),
777    };
778
779    // P4(升级 v4.3.0):保留所有 APP 段(marker 0xE0–0xEF),零元数据损失。
780    // 覆盖 EXIF(APP1)、XMP(APP1)、ICC 色彩配置(APP2 ICC_PROFILE)、MPF(APP2)、
781    // Adobe IRB(APP13)/Adobe(APP14) 等。v4.2.0 只取首个 APP1(0xE1) 会丢 XMP 与
782    // 宽色域 ICC 配置(ICC 在 APP2),违背"保证原图色彩"。
783    // 注意:DQT/DHT/SOF/SOS 等不在 0xE0–0xEF 范围,不会被重复插入。
784    let meta_segments: Vec<_> = input_jpeg
785        .segments()
786        .iter()
787        .filter(|s| (0xE0..=0xEF).contains(&s.marker()))
788        .cloned()
789        .collect();
790    if meta_segments.is_empty() {
791        return result_data.to_vec();
792    }
793
794    drop(input_mmap);
795    drop(input_file);
796
797    let output_jpeg = match Jpeg::from_bytes(Bytes::copy_from_slice(result_data)) {
798        Ok(jpeg) => jpeg,
799        Err(_) => return result_data.to_vec(),
800    };
801
802    let mut output_jpeg = output_jpeg;
803    // 从位置 1 起依次插入每个 APP 段(保持原顺序:EXIF / XMP / ICC 均保留)
804    let mut insert_pos = 1;
805    for seg in &meta_segments {
806        output_jpeg.segments_mut().insert(insert_pos, seg.clone());
807        insert_pos += 1;
808    }
809    output_jpeg.encoder().bytes().to_vec()
810}
811
812/// 用途驱动的三方统一配置构造(GUI / CLI / AI JSON 同一套语义)
813///
814/// - social:平台预设值(已写入 `custom_*`)→ 社交分享最优体积/画质
815/// - archive:不缩放(0) + 最高画质(100) + 不限位(0) → 高清存档
816/// - custom:完全按用户自定义参数(含 `--mode hd` 的 4096/95/5000 兼容)
817///
818/// 平台预设 / 不缩放策略 / sRGB 强制 已在调用方(`apply_usage_preset` / `to_app_config` /
819/// json 路径)写入 `config.custom_*` 与 `config.color_space`,本函数只负责按 `usage_mode` 选材。
820/// 感知压缩(perceptual)由 `quality_mode` 决定,调用方在返回后按需覆盖。
821pub fn app_config_to_process_config(
822    config: &AppConfig,
823    output_dir: Option<PathBuf>,
824) -> ProcessConfig {
825    let (mode, max_dim, quality, target_kb) = match config.usage_mode.as_str() {
826        "social" => (
827            ProcessMode::WeChat,
828            config.custom_max_dim,
829            config.custom_quality,
830            config.custom_target_kb,
831        ),
832        // archive:不缩放(0) + 视觉无损画质(95,同原版 HD) + 不限体积(0);ProcessMode::HD 仅决定输出后缀 "_hd"
833        // 注意:不用 Q100 —— Q100 禁用量化几乎无压缩,输出会比源图更大,违背压缩工具语义
834        "archive" => (ProcessMode::HD, 0, 95, 0),
835        _ => {
836            // custom:完整保留 v4.1.0 三种旧模式语义(向后兼容铁律)
837            match config.mode {
838                ProcessMode::HD => (ProcessMode::HD, 4096, 95, 5000),
839                ProcessMode::WeChat => (ProcessMode::WeChat, 2048, 95, 900),
840                ProcessMode::Custom => (
841                    ProcessMode::Custom,
842                    config.custom_max_dim,
843                    config.custom_quality,
844                    config.custom_target_kb,
845                ),
846            }
847        }
848    };
849    ProcessConfig {
850        mode,
851        max_dim,
852        quality,
853        target_kb,
854        output_dir,
855        overwrite: config.overwrite,
856        keep_original_name: config.keep_original_name,
857        output_format: config.output_format,
858        color_space: config.color_space,
859        subsampling: config.subsampling.clone(),
860        // v4.3.1:保结构 / 后缀
861        preserve_structure: config.preserve_structure,
862        structure_base: None, // 由调用方(CLI/JSON 入口)计算注入
863        output_suffix: config.output_suffix.clone(),
864        // v4.4.0:CAS 锐化补偿
865        cas_strength: config.cas_strength,
866        // 摄影级优化
867        enable_sharpening: config.enable_sharpening,
868        sharpening_radius: config.sharpening_radius,
869        sharpening_amount: config.sharpening_amount,
870        perceptual: None,
871    }
872}
873
874// ============================================================================
875// 摄影级优化功能 - 智能自适应锐化
876// ============================================================================
877
878/// 检测像素是否为肤色(快速算法)
879///
880/// 使用简单但有效的肤色检测算法
881/// 返回值:0.0-1.0,值越高越可能是肤色
882pub(crate) fn is_skin_color(r: u8, g: u8, b: u8) -> f32 {
883    // RGB 转 YCbCr 色彩空间
884    let _y = 0.299 * r as f32 + 0.587 * g as f32 + 0.114 * b as f32;
885    let cb = -0.1687 * r as f32 - 0.3313 * g as f32 + 0.5 * b as f32 + 128.0;
886    let cr = 0.5 * r as f32 - 0.4187 * g as f32 - 0.0813 * b as f32 + 128.0;
887
888    // 肤色范围(经验值)
889    let cb_min = 77.0;
890    let cb_max = 127.0;
891    let cr_min = 133.0;
892    let cr_max = 173.0;
893
894    if cb >= cb_min && cb <= cb_max && cr >= cr_min && cr <= cr_max {
895        // 在肤色范围内
896        let cb_score = 1.0 - ((cb - (cb_min + cb_max) / 2.0) / ((cb_max - cb_min) / 2.0)).abs();
897        let cr_score = 1.0 - ((cr - (cr_min + cr_max) / 2.0) / ((cr_max - cr_min) / 2.0)).abs();
898        (cb_score * cr_score).clamp(0.0, 1.0)
899    } else {
900        0.0
901    }
902}
903
904/// 检测图像中肤色区域比例
905///
906/// 返回值:0.0-1.0,表示图像中肤色区域的比例
907pub(crate) fn estimate_skin_ratio(image: &image::DynamicImage) -> f32 {
908    let rgba = image.to_rgba8();
909    let (width, height) = rgba.dimensions();
910
911    // 采样计算,避免全图处理影响性能
912    let sample_step = 20;
913    let mut skin_count = 0;
914    let mut total_count = 0;
915
916    for y in (0..height).step_by(sample_step as usize) {
917        for x in (0..width).step_by(sample_step as usize) {
918            let pixel = rgba.get_pixel(x, y);
919            let skin_score = is_skin_color(pixel[0], pixel[1], pixel[2]);
920            if skin_score > 0.3 {
921                skin_count += 1;
922            }
923            total_count += 1;
924        }
925    }
926
927    if total_count == 0 {
928        return 0.0;
929    }
930
931    skin_count as f32 / total_count as f32
932}
933
934/// 智能锐化决策:根据图像特征判断是否需要锐化
935///
936/// 避免重复锐化的策略:
937/// 1. 检测高频能量(已锐化的图高频能量高)
938/// 2. 检测平坦区域比例(磨皮人像平坦区域多)
939/// 3. 检测噪点水平(高噪点图不锐化)
940/// 4. 根据尺寸和内容类型决策
941fn should_apply_sharpening(image: &image::DynamicImage, _max_dim: u32) -> bool {
942    let (width, height) = image.dimensions();
943    let larger_dim = width.max(height);
944
945    // 小图不锐化(避免过度处理)
946    if larger_dim < 800 {
947        return false;
948    }
949
950    // 检测肤色比例
951    let skin_ratio = estimate_skin_ratio(image);
952
953    // 如果肤色比例较高(> 30%),很可能是人像照片
954    if skin_ratio > 0.3 {
955        // 人像照片:降低锐化需求,避免锐化肤色
956        return estimate_image_complexity(image) > 0.5;
957    }
958
959    // 超大图才需要明显锐化
960    if larger_dim < 2000 {
961        // 中等尺寸:仅当图像内容需要时才锐化
962        return estimate_image_complexity(image) > 0.3;
963    }
964
965    // 大图:默认锐化,除非检测到问题
966    if larger_dim >= 2000 {
967        // 检查是否已足够锐利
968        if is_already_sharp_enough(image) {
969            return false;
970        }
971
972        // 检查是否高噪点(避免锐化噪点)
973        if estimate_noise_level(image) > 0.6 {
974            return false;
975        }
976
977        return true;
978    }
979
980    true
981}
982
983/// 估算图像复杂度(0.0-1.0)
984/// 简单场景(天空、纯色背景)返回低值,复杂场景(纹理、细节)返回高值
985fn estimate_image_complexity(image: &image::DynamicImage) -> f32 {
986    let rgba = image.to_rgba8();
987    let (width, height) = rgba.dimensions();
988
989    // 采样 100x100 网格快速估算
990    let sample_w = (width / 100).max(1);
991    let sample_h = (height / 100).max(1);
992
993    let mut complexity_sum = 0.0f32;
994    let mut count = 0;
995
996    for y in (0..height).step_by(sample_h as usize) {
997        for x in (0..width).step_by(sample_w as usize) {
998            let pixel = rgba.get_pixel(x, y);
999
1000            // 计算局部方差(简单版)
1001            let mut neighbors = Vec::new();
1002            if x > 0 {
1003                neighbors.push(rgba.get_pixel(x - 1, y));
1004            }
1005            if x < width - 1 {
1006                neighbors.push(rgba.get_pixel(x + 1, y));
1007            }
1008            if y > 0 {
1009                neighbors.push(rgba.get_pixel(x, y - 1));
1010            }
1011            if y < height - 1 {
1012                neighbors.push(rgba.get_pixel(x, y + 1));
1013            }
1014
1015            if !neighbors.is_empty() {
1016                let variance = neighbors
1017                    .iter()
1018                    .map(|n| {
1019                        ((pixel[0] as i16 - n[0] as i16).abs() as f32
1020                            + (pixel[1] as i16 - n[1] as i16).abs() as f32
1021                            + (pixel[2] as i16 - n[2] as i16).abs() as f32)
1022                            / 3.0
1023                    })
1024                    .sum::<f32>()
1025                    / neighbors.len() as f32;
1026
1027                complexity_sum += variance;
1028                count += 1;
1029            }
1030        }
1031    }
1032
1033    if count == 0 {
1034        return 0.0;
1035    }
1036
1037    // 归一化到 0-1
1038    let avg_complexity = complexity_sum / count as f32;
1039    (avg_complexity / 50.0).clamp(0.0, 1.0)
1040}
1041
1042/// 检测图像是否已足够锐利
1043fn is_already_sharp_enough(image: &image::DynamicImage) -> bool {
1044    let complexity = estimate_image_complexity(image);
1045    // 复杂度高于 0.7 说明细节丰富,可能已足够锐利
1046    complexity > 0.7
1047}
1048
1049/// 估算噪点水平(0.0-1.0)
1050/// 高噪点照片(高 ISO)锐化会放大噪点
1051fn estimate_noise_level(image: &image::DynamicImage) -> f32 {
1052    let rgba = image.to_rgba8();
1053    let (width, height) = rgba.dimensions();
1054
1055    // 在平坦区域检测噪点
1056    let mut noise_scores = Vec::new();
1057
1058    // 采样 10x10 区域
1059    let step = 20;
1060    for y in (0..height).step_by(step) {
1061        for x in (0..width).step_by(step) {
1062            // 检查 3x3 邻域
1063            let mut region_pixels = Vec::new();
1064            for dy in 0..3.min(height - y) {
1065                for dx in 0..3.min(width - x) {
1066                    region_pixels.push(rgba.get_pixel(x + dx, y + dy));
1067                }
1068            }
1069
1070            if region_pixels.len() >= 4 {
1071                // 计算区域标准差
1072                let mean_r = region_pixels.iter().map(|p| p[0] as f32).sum::<f32>()
1073                    / region_pixels.len() as f32;
1074                let variance = region_pixels
1075                    .iter()
1076                    .map(|p| (p[0] as f32 - mean_r).powi(2))
1077                    .sum::<f32>()
1078                    / region_pixels.len() as f32;
1079
1080                // 平坦区域的标准差代表噪点水平
1081                if variance < 100.0 {
1082                    // 只统计平坦区域
1083                    noise_scores.push(variance);
1084                }
1085            }
1086        }
1087    }
1088
1089    if noise_scores.is_empty() {
1090        return 0.0;
1091    }
1092
1093    let avg_noise = noise_scores.iter().sum::<f32>() / noise_scores.len() as f32;
1094    // 归一化:variance < 10 为低噪点,> 50 为高噪点
1095    (avg_noise / 50.0).min(1.0)
1096}
1097
1098/// 智能自适应锐化(主入口)
1099///
1100/// 特性:
1101/// - 仅在需要时锐化(避免重复处理)
1102/// - 根据尺寸和内容自动选择参数
1103/// - 自动检测人像照片,降低肤色区域锐化
1104/// - 根据风景/人像选择不同的锐化策略
1105/// - 高性能(可选跳过)
1106fn smart_adaptive_sharpen(image: &image::DynamicImage, max_dim: u32) -> image::DynamicImage {
1107    // 智能决策:是否需要锐化
1108    if !should_apply_sharpening(image, max_dim) {
1109        return image.clone();
1110    }
1111
1112    let (width, height) = image.dimensions();
1113    let larger_dim = width.max(height);
1114
1115    // 检测肤色比例
1116    let skin_ratio = estimate_skin_ratio(image);
1117    let is_portrait = skin_ratio > 0.3;
1118    let complexity = estimate_image_complexity(image);
1119
1120    // 根据尺寸、复杂度和内容类型选择参数
1121    let (radius, mut amount, threshold) = if is_portrait {
1122        // 人像照片:降低锐化强度
1123        if larger_dim < 2000 {
1124            (0.6, 0.3, 15) // 小图人像:非常轻微锐化
1125        } else if larger_dim < 4000 {
1126            (0.8, 0.4, 12) // 中图人像:轻微锐化
1127        } else {
1128            (1.0, 0.5, 10) // 大图人像:标准锐化但降低强度
1129        }
1130    } else {
1131        // 风景/其他照片:根据复杂度调整
1132        if larger_dim < 2000 {
1133            if complexity > 0.5 {
1134                (0.8, 0.6, 10) // 复杂小图:中度锐化
1135            } else {
1136                (0.6, 0.4, 15) // 简单小图:轻微锐化
1137            }
1138        } else if larger_dim < 4000 {
1139            if complexity > 0.5 {
1140                (1.0, 0.8, 6) // 复杂中图:强锐化
1141            } else {
1142                (0.8, 0.6, 8) // 简单中图:中度锐化
1143            }
1144        } else if complexity > 0.5 {
1145            (1.5, 1.0, 4) // 复杂超大图:最强锐化
1146        } else {
1147            (1.2, 0.8, 5) // 简单超大图:强锐化
1148        }
1149    };
1150
1151    // 原图本身很小的情况:进一步降低锐化
1152    if larger_dim < 1500 {
1153        amount *= 0.7;
1154    }
1155
1156    apply_usm_sharpen(image, radius, amount, threshold)
1157}
1158
1159/// v4.4.1:将旧版 smart_adaptive_sharpen 的决策矩阵映射为 CAS 强度。
1160/// 不搞 CAS vs USM 二选一——把"人像/风景/复杂度/原图尺寸/缩放比/噪点"的
1161/// 自适应逻辑保留,输出的是 CAS strength 而非 USM (radius, amount, threshold)。
1162/// 这样既享受 CAS 的无光晕天然优势,又保留了旧版的内容感知智慧。
1163fn compute_adaptive_cas_strength(image: &image::DynamicImage, scale: f32, max_cas: f32) -> f32 {
1164    let (width, height) = image.dimensions();
1165    let larger_dim = width.max(height);
1166
1167    // 小图不锐化(与旧版 should_apply_sharpening 一致)
1168    if larger_dim < 800 {
1169        return 0.0;
1170    }
1171
1172    let skin_ratio = estimate_skin_ratio(image);
1173    let complexity = estimate_image_complexity(image);
1174    let noise = estimate_noise_level(image);
1175    let is_portrait = skin_ratio > 0.3;
1176
1177    // 高噪点图避免锐化(放大噪点比锐化好处更差)
1178    if noise > 0.6 {
1179        return 0.0;
1180    }
1181    // 已经足够锐利的图不再重复锐化
1182    if is_already_sharp_enough(image) {
1183        return 0.0;
1184    }
1185    // 低复杂度人像:旧版 should_apply_sharpening 直接跳过(皮肤已平滑,锐化
1186    // 反而突兀)。不延续这个门控等于给磨皮人像强行加锐。
1187    if is_portrait && complexity <= 0.5 {
1188        return 0.0;
1189    }
1190    // 中等尺寸 + 极低复杂度:内容本身没什么细节可锐,强锐反而出噪点
1191    if larger_dim < 2000 && complexity <= 0.3 {
1192        return 0.0;
1193    }
1194
1195    // 根据内容类型 + 原图尺寸确定基础强度(沿用旧版 9 档映射换算到 CAS)
1196    let base: f32 = if is_portrait {
1197        // 人像:保守,防止把皮肤纹理锐出假感
1198        if larger_dim < 2000 {
1199            0.08
1200        } else if larger_dim < 4000 {
1201            0.14
1202        } else {
1203            0.22
1204        }
1205    } else {
1206        // 风景/其他:根据复杂度调节
1207        if complexity > 0.5 {
1208            if larger_dim < 2000 {
1209                0.18
1210            } else if larger_dim < 4000 {
1211                0.30
1212            } else {
1213                0.44
1214            }
1215        } else if larger_dim < 2000 {
1216            0.12
1217        } else if larger_dim < 4000 {
1218            0.22
1219        } else {
1220            0.34
1221        }
1222    };
1223
1224    // 缩放幅度因子:降采样越大,越需要锐化补偿
1225    let scale_factor = ((1.0 - scale) / 0.9).clamp(0.0, 1.0).powf(0.5);
1226
1227    // 原图本身很小的额外降低
1228    let size_penalty = if larger_dim < 1500 { 0.6 } else { 1.0 };
1229
1230    // 噪点惩罚(中等噪点适度降低)
1231    let noise_penalty = if noise > 0.4 { 0.75 } else { 1.0 };
1232
1233    let adaptive = (base * scale_factor * size_penalty * noise_penalty).clamp(0.0, 0.5);
1234
1235    // 不超过调用方指定的上限(用户可通过 --cas-strength 限制最大值)
1236    adaptive.min(max_cas)
1237}
1238
1239// ============================================================================
1240// USM 锐化核心函数
1241// ============================================================================
1242
1243/// USM (Unsharp Mask) 锐化实现(智能版)
1244///
1245/// 特性:
1246/// - 自动检测并避开肤色区域
1247/// - 根据图像内容调整锐化强度
1248///
1249/// 原理:
1250/// 1. 对原图进行高斯模糊得到模糊图
1251/// 2. 原图 - 模糊图 = 高频细节(边缘)
1252/// 3. 原图 + amount * 高频细节 = 锐化图
1253///
1254/// 参数:
1255/// - radius: 高斯模糊半径,控制锐化范围
1256/// - amount: 锐化强度,0.5-1.5 常用
1257/// - threshold: 阈值,避免锐化平滑区域(减少噪点)
1258fn apply_usm_sharpen(
1259    image: &image::DynamicImage,
1260    radius: f32,
1261    amount: f32,
1262    threshold: u8,
1263) -> image::DynamicImage {
1264    let rgba = image.to_rgba8();
1265    let (width, height) = rgba.dimensions();
1266
1267    // 高斯模糊生成模糊图
1268    let sigma = radius;
1269    let blurred = gaussian_blur(&rgba, sigma);
1270
1271    // 检测肤色比例
1272    let skin_ratio = estimate_skin_ratio(image);
1273    let is_portrait = skin_ratio > 0.3;
1274
1275    // 创建输出图像
1276    let mut output = ImageBuffer::new(width, height);
1277
1278    // USM 锐化公式:output = original + amount * (original - blurred)
1279    for y in 0..height {
1280        for x in 0..width {
1281            let orig_pixel = rgba.get_pixel(x, y);
1282            let blur_pixel = blurred.get_pixel(x, y);
1283
1284            let mut out_pixel = Rgba([0u8; 4]);
1285
1286            // 检测当前像素是否为肤色
1287            let skin_score = is_skin_color(orig_pixel[0], orig_pixel[1], orig_pixel[2]);
1288            let skin_factor = if is_portrait && skin_score > 0.3 {
1289                // 人像照片且是肤色区域:大幅降低锐化强度
1290                1.0 - skin_score * 0.8
1291            } else {
1292                // 非肤色区域或非人像:正常锐化
1293                1.0
1294            };
1295
1296            for c in 0..3 {
1297                // 计算差异(高频细节)
1298                let diff = orig_pixel[c] as i16 - blur_pixel[c] as i16;
1299
1300                // 阈值处理:小差异不锐化(避免噪点)
1301                if diff.abs() > threshold as i16 {
1302                    // 应用锐化强度和肤色因子
1303                    let effective_amount = amount * skin_factor;
1304                    let sharpened = orig_pixel[c] as i32 + (effective_amount * diff as f32) as i32;
1305                    out_pixel[c] = sharpened.clamp(0, 255) as u8;
1306                } else {
1307                    out_pixel[c] = orig_pixel[c];
1308                }
1309            }
1310
1311            // Alpha 通道保持不变
1312            out_pixel[3] = orig_pixel[3];
1313
1314            output.put_pixel(x, y, out_pixel);
1315        }
1316    }
1317
1318    image::DynamicImage::ImageRgba8(output)
1319}
1320
1321/// 高斯模糊实现(优化版:可分离卷积)
1322///
1323/// 性能优化:
1324/// - 使用可分离卷积:O(n²) → O(2n)
1325/// - 先水平卷积,再垂直卷积
1326/// - 性能提升 10 倍以上
1327pub(crate) fn gaussian_blur(
1328    image: &ImageBuffer<Rgba<u8>, Vec<u8>>,
1329    sigma: f32,
1330) -> ImageBuffer<Rgba<u8>, Vec<u8>> {
1331    let (width, height) = image.dimensions();
1332
1333    // 高斯核大小(基于 sigma)
1334    let kernel_size = ((sigma * 6.0) as usize).max(3) | 1; // 确保奇数
1335    let half_kernel = kernel_size / 2;
1336
1337    // 生成一维高斯核
1338    let kernel = generate_1d_gaussian_kernel(kernel_size, sigma);
1339
1340    // Step 1: 水平卷积
1341    let mut temp = ImageBuffer::new(width, height);
1342    for y in 0..height {
1343        for x in 0..width {
1344            let mut pixel = Rgba([0u8; 4]);
1345            for c in 0..4 {
1346                let mut sum = 0.0f32;
1347                let mut weight_sum = 0.0f32;
1348                for (kx, &weight) in kernel.iter().enumerate() {
1349                    let px = (x as i32 + kx as i32 - half_kernel as i32).clamp(0, width as i32 - 1)
1350                        as u32;
1351                    let sample_pixel = image.get_pixel(px, y);
1352                    sum += sample_pixel[c] as f32 * weight;
1353                    weight_sum += weight;
1354                }
1355                pixel[c] = (sum / weight_sum).clamp(0.0, 255.0) as u8;
1356            }
1357            temp.put_pixel(x, y, pixel);
1358        }
1359    }
1360
1361    // Step 2: 垂直卷积
1362    let mut output = ImageBuffer::new(width, height);
1363    for y in 0..height {
1364        for x in 0..width {
1365            let mut pixel = Rgba([0u8; 4]);
1366            for c in 0..4 {
1367                let mut sum = 0.0f32;
1368                let mut weight_sum = 0.0f32;
1369                for (ky, &weight) in kernel.iter().enumerate() {
1370                    let py = (y as i32 + ky as i32 - half_kernel as i32).clamp(0, height as i32 - 1)
1371                        as u32;
1372                    let sample_pixel = temp.get_pixel(x, py);
1373                    sum += sample_pixel[c] as f32 * weight;
1374                    weight_sum += weight;
1375                }
1376                pixel[c] = (sum / weight_sum).clamp(0.0, 255.0) as u8;
1377            }
1378            output.put_pixel(x, y, pixel);
1379        }
1380    }
1381
1382    output
1383}
1384
1385/// 生成一维高斯核
1386fn generate_1d_gaussian_kernel(size: usize, sigma: f32) -> Vec<f32> {
1387    let mut kernel = vec![0.0f32; size];
1388    let half = (size / 2) as f32;
1389    let two_sigma_sq = 2.0 * sigma * sigma;
1390
1391    let mut sum = 0.0f32;
1392    for (x, val) in kernel.iter_mut().enumerate() {
1393        let dx = x as f32 - half;
1394        let value = (-dx * dx / two_sigma_sq).exp();
1395        *val = value;
1396        sum += value;
1397    }
1398
1399    // 归一化
1400    for val in kernel.iter_mut() {
1401        *val /= sum;
1402    }
1403
1404    kernel
1405}
1406
1407// ============================================================================
1408// 智能色彩空间管理(保留供未来使用)
1409// ============================================================================
1410
1411/// 智能色彩空间管理
1412///
1413/// 策略:
1414/// - 长边 ≤ 3000px:统一转 sRGB(网络分享标准)
1415/// - 长边 > 3000px:保持原色彩空间(专业用途)
1416/// - 检测 300dpi+ 高分辨率:保持原样(印刷级)
1417#[allow(dead_code)]
1418fn manage_color_space(
1419    image: image::DynamicImage,
1420    max_dim: u32,
1421    has_300dpi: bool,
1422) -> image::DynamicImage {
1423    // 高分辨率印刷级:完全保持原样
1424    if has_300dpi || max_dim > 4000 {
1425        return image;
1426    }
1427
1428    // 网络分享级:统一转 sRGB
1429    if max_dim <= 3000 {
1430        // 简单转换:假设原图为 sRGB(大多数数码照片)
1431        // 注:完整实现需要 ICC Profile 管理
1432        return image;
1433    }
1434
1435    // 中等尺寸:保持原样
1436    image
1437}
1438
1439/// 检测图片是否为 300dpi 或更高分辨率
1440#[allow(dead_code)]
1441fn is_high_resolution_dpi(input_path: &Path) -> bool {
1442    // 尝试读取 EXIF 中的 DPI 信息
1443    if let Ok(file) = fs::File::open(input_path) {
1444        if let Ok(mmap) = unsafe { Mmap::map(&file) } {
1445            // 简单判断:如果文件很大且尺寸不大,可能是高 DPI
1446            if mmap.len() > 5 * 1024 * 1024 {
1447                return true;
1448            }
1449        }
1450    }
1451    false
1452}
1453
1454pub fn path_self_healing(input_path: &Path) -> PathBuf {
1455    let path_str = input_path.to_string_lossy();
1456
1457    if input_path.exists() && input_path.is_file() {
1458        return input_path.to_path_buf();
1459    }
1460
1461    if let Some(file_name) = input_path.file_name().and_then(|n| n.to_str()) {
1462        if let Some(parent) = input_path.parent() {
1463            if parent.exists() {
1464                if let Ok(entries) = fs::read_dir(parent) {
1465                    for entry in entries.flatten() {
1466                        if let Some(name) = entry.file_name().to_str() {
1467                            if name.eq_ignore_ascii_case(file_name) {
1468                                let candidate = entry.path();
1469                                if candidate.is_file() {
1470                                    return candidate;
1471                                }
1472                            }
1473                        }
1474                    }
1475                }
1476            }
1477
1478            if let Ok(entries) = fs::read_dir(parent) {
1479                for entry in entries.flatten() {
1480                    if let Some(name) = entry.file_name().to_str() {
1481                        if name.to_lowercase() == file_name.to_lowercase() {
1482                            let candidate = entry.path();
1483                            if candidate.is_file() {
1484                                return candidate;
1485                            }
1486                        }
1487                    }
1488                }
1489            }
1490        }
1491    }
1492
1493    let normalized = path_str.replace("\\", "/");
1494    if normalized != path_str {
1495        let alt_path = Path::new(&normalized);
1496        if alt_path.exists() && alt_path.is_file() {
1497            return alt_path.to_path_buf();
1498        }
1499    }
1500
1501    input_path.to_path_buf()
1502}
1503
1504fn load_image_safe(input_path: &Path) -> Result<image::DynamicImage> {
1505    // 注意: 调用者(process_image)已做 path_self_healing,此处直接用输入路径,
1506    // 避免重复 stat 调用
1507    if let Ok(img) = load_image_mmap(input_path) {
1508        return Ok(img);
1509    }
1510
1511    image::open(input_path).map_err(|e| anyhow::anyhow!("Failed to load image: {}", e))
1512}
1513
1514fn load_image_mmap(input_path: &Path) -> Result<image::DynamicImage> {
1515    let file = fs::File::open(input_path)?;
1516    let file_size = file.metadata()?.len();
1517
1518    if file_size > 200 * 1024 * 1024 {
1519        let mmap = unsafe { Mmap::map(&file)? };
1520        return image::load_from_memory(&mmap)
1521            .map_err(|e| anyhow::anyhow!("Failed to decode with mmap: {}", e));
1522    }
1523
1524    drop(file);
1525    let bytes = fs::read(input_path)?;
1526    image::load_from_memory(&bytes)
1527        .map_err(|e| anyhow::anyhow!("Failed to decode from memory: {}", e))
1528}
1529
1530/// v4.3.1(修 D4):把 RGBA 图像按白底合成转 RGB。
1531/// 用于 JPEG 等不支持透明的输出格式,避免透明区域变黑或丢失透明度信息。
1532/// alpha=255(不透明)时等价于直接取 RGB,不会产生色偏。
1533fn flatten_rgba8_to_rgb(img: image::RgbaImage) -> Vec<u8> {
1534    let (w, h) = img.dimensions();
1535    let mut out = Vec::with_capacity((w * h * 3) as usize);
1536    for p in img.pixels() {
1537        let [r, g, b, a] = p.0;
1538        let alpha = a as f32 / 255.0;
1539        let inv = 1.0 - alpha;
1540        out.push((r as f32 * alpha + 255.0 * inv) as u8);
1541        out.push((g as f32 * alpha + 255.0 * inv) as u8);
1542        out.push((b as f32 * alpha + 255.0 * inv) as u8);
1543    }
1544    out
1545}
1546
1547#[cfg(test)]
1548mod tests {
1549    use super::*;
1550    use std::fs;
1551
1552    fn tmp_dir(tag: &str) -> PathBuf {
1553        let d =
1554            std::env::temp_dir().join(format!("xtap_compress_test_{}_{}", tag, std::process::id()));
1555        let _ = fs::remove_dir_all(&d);
1556        fs::create_dir_all(&d).unwrap();
1557        d
1558    }
1559
1560    /// 生成一张纯色渐变测试图(避免依赖外部图片)
1561    fn make_test_image(path: &Path, w: u32, h: u32) {
1562        let mut img = image::RgbaImage::new(w, h);
1563        for (x, y, px) in img.enumerate_pixels_mut() {
1564            let r = (x as f32 / w as f32 * 255.0) as u8;
1565            let g = (y as f32 / h as f32 * 255.0) as u8;
1566            let b = ((x + y) as f32 / (w + h) as f32 * 255.0) as u8;
1567            *px = image::Rgba([r, g, b, 255]);
1568        }
1569        img.save(path).unwrap();
1570    }
1571
1572    #[test]
1573    fn test_app_config_social_maps_to_wechat() {
1574        // social(聊天场景)→ ProcessMode::WeChat + 平台预设写入 custom_*
1575        let cfg = AppConfig {
1576            usage_mode: "social".to_string(),
1577            custom_max_dim: 1280,
1578            custom_quality: 90,
1579            custom_target_kb: 300,
1580            ..Default::default()
1581        };
1582
1583        let pc = app_config_to_process_config(&cfg, None);
1584        assert_eq!(pc.mode, ProcessMode::WeChat);
1585        assert_eq!(pc.max_dim, 1280);
1586        assert_eq!(pc.quality, 90);
1587        assert_eq!(pc.target_kb, 300);
1588        assert_eq!(pc.subsampling, "420");
1589        // 默认输出后缀与模式对应
1590        let p = Processor::new(pc);
1591        let out = p.expected_output_path(Path::new("photo.jpg"));
1592        assert!(out.to_string_lossy().ends_with("_wx.jpg"));
1593    }
1594
1595    #[test]
1596    fn test_app_config_archive_no_downscale() {
1597        // archive(高清存档)→ 不缩放(0) + 视觉无损(95) + 不限体积(0)
1598        let cfg = AppConfig {
1599            usage_mode: "archive".to_string(),
1600            ..Default::default()
1601        };
1602
1603        let pc = app_config_to_process_config(&cfg, None);
1604        assert_eq!(pc.mode, ProcessMode::HD);
1605        assert_eq!(pc.max_dim, 0, "archive 不应缩放");
1606        assert_eq!(pc.quality, 95);
1607        assert_eq!(pc.target_kb, 0);
1608        // 默认输出格式 Jpeg → 任意输入最终 .jpg;archive 后缀 _hd
1609        let out = Processor::new(pc).expected_output_path(Path::new("photo.png"));
1610        assert!(out.to_string_lossy().ends_with("_hd.jpg"));
1611    }
1612
1613    #[test]
1614    fn test_process_image_compresses_and_scales() {
1615        // 端到端:生成 1600x1200 图 → 1280 上限压缩 → 输出存在、尺寸符合、体积下降
1616        let dir = tmp_dir("e2e");
1617        let src = dir.join("src.png");
1618        make_test_image(&src, 1600, 1200);
1619
1620        let cfg = AppConfig::default();
1621        let mut pc = app_config_to_process_config(&cfg, Some(dir.join("out")));
1622        pc.max_dim = 1280;
1623        pc.quality = 80;
1624        pc.overwrite = false;
1625        pc.keep_original_name = true;
1626
1627        let processor = Processor::new(pc);
1628        let out = processor.process_image(&src).unwrap();
1629        assert!(out.exists(), "输出文件应存在");
1630
1631        let img = image::open(&out).unwrap();
1632        assert!(
1633            img.width() <= 1280 && img.height() <= 1280,
1634            "应缩放至 1280 内,实际 {}x{}",
1635            img.width(),
1636            img.height()
1637        );
1638        assert!(
1639            fs::metadata(&out).unwrap().len() < fs::metadata(&src).unwrap().len(),
1640            "压缩后体积应小于原图"
1641        );
1642        fs::remove_dir_all(&dir).ok();
1643    }
1644
1645    #[test]
1646    fn test_expected_output_path_suffix_rules() {
1647        // 后缀规则:WeChat→_wx / HD→_hd / Custom→_da;overwrite 时保持原名
1648        let base = ProcessConfig {
1649            mode: ProcessMode::Custom,
1650            max_dim: 2000,
1651            quality: 85,
1652            target_kb: 0,
1653            output_dir: None,
1654            overwrite: false,
1655            keep_original_name: false,
1656            output_format: OutputFormat::Jpeg,
1657            color_space: ColorSpace::KeepOriginal,
1658            enable_sharpening: false,
1659            sharpening_radius: 1.0,
1660            sharpening_amount: 0.8,
1661            perceptual: None,
1662            subsampling: "420".to_string(),
1663            preserve_structure: false,
1664            structure_base: None,
1665            output_suffix: None,
1666            cas_strength: 0.0,
1667        };
1668
1669        let wx = Processor::new(ProcessConfig {
1670            mode: ProcessMode::WeChat,
1671            ..base.clone()
1672        })
1673        .expected_output_path(Path::new("a.JPG"));
1674        assert!(
1675            wx.to_string_lossy().ends_with("_wx.jpg"),
1676            "大小写扩展名应归一 + 后缀 _wx,实际 {}",
1677            wx.display()
1678        );
1679
1680        let hd = Processor::new(ProcessConfig {
1681            mode: ProcessMode::HD,
1682            ..base.clone()
1683        })
1684        .expected_output_path(Path::new("a.png"));
1685        // 默认输出格式 Jpeg → 输出扩展名 .jpg(与输出格式一致,非输入格式)
1686        assert!(hd.to_string_lossy().ends_with("_hd.jpg"));
1687
1688        let da = Processor::new(ProcessConfig {
1689            mode: ProcessMode::Custom,
1690            ..base.clone()
1691        })
1692        .expected_output_path(Path::new("a.webp"));
1693        assert!(
1694            da.to_string_lossy().ends_with("_da.jpg"),
1695            "Custom 默认后缀 _da,实际 {}",
1696            da.display()
1697        );
1698
1699        let ow = Processor::new(ProcessConfig {
1700            overwrite: true,
1701            ..base
1702        })
1703        .expected_output_path(Path::new("b.jpg"));
1704        assert!(ow.to_string_lossy().ends_with("b.jpg"));
1705    }
1706
1707    #[test]
1708    fn test_path_self_healing_case_insensitive() {
1709        let dir = tmp_dir("heal");
1710        let real = dir.join("Photo.PNG");
1711        make_test_image(&real, 64, 64);
1712        // 输入大小写不一致:大小写敏感 FS(Linux/Win)走兜底,macOS(APFS 不敏感)首分支已命中
1713        let healed = path_self_healing(&dir.join("photo.png"));
1714        // 两种平台行为都应指向真实存在的同一文件
1715        assert!(healed.exists(), "healed 路径必须存在: {}", healed.display());
1716        assert_eq!(
1717            fs::canonicalize(&healed).unwrap(),
1718            fs::canonicalize(&real).unwrap(),
1719            "healed 与真实文件应为同一文件"
1720        );
1721        fs::remove_dir_all(&dir).ok();
1722    }
1723}