xtap-compress 0.1.3

StarTAP多平台场景感知图像压缩引擎 / Multi-platform scene-aware image compression: chat/social/archive adaptive modes for JPEG/PNG/WebP. 星TAP实验室出品。
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
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,
    /// v4.3.1:WebP 输出(网络分发/网页内嵌更省体积,支持透明通道)
    WebP,
}

#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
pub enum ColorSpace {
    KeepOriginal,
    ConvertToSRGB,
}

/// App 产品版本号(唯一真源)。与 lib crate 的 `version = "0.1.1"` 是两套体系,
/// GUI 三处版本显示(关于页 / 状态栏 / 卡片标题)统一引用此常量,升版只改这里。
pub const APP_VERSION: &str = "v4.4.4";

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AppConfig {
    /// v4.4.0:配置版本号(用于自动迁移;旧配置缺失=1,当前=2)
    #[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,       // USM 锐化
    pub sharpening_radius: f32,        // 锐化半径 (默认 1.0)
    pub sharpening_amount: f32,        // 锐化强度 (默认 0.8)
    pub use_custom_quantization: bool, // 自定义量化表
    pub preserve_high_frequency: bool, // 保留高频细节
    // v4.2.0:用途 / 平台 / 画质模式(GUI 记忆 + 三方接口对齐)
    // usage_mode: "social"(社交分享) | "archive"(高清存档) | "custom"(自定义)
    // quality_mode: "perceptual"(小而美感知压缩) | "normal"(普通标准压缩)
    // platform: wechat/wechat-new/xiaohongshu/instagram/general
    // serde(default):旧版 config.toml 没有这三个字段,升级后仍能正常加载(配置记忆不丢)
    #[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,
    // v4.3.0:色彩子采样(照片 420 省 ~1/3 码率 / 截图文字 444 防模糊 / 422 平衡)
    #[serde(default = "default_subsampling")]
    pub subsampling: String,
    // v4.3.1:输出保结构(复刻源目录层级到 output_dir)/ 后缀可控(覆盖默认 _wx/_hd/_da,空串=无后缀)
    #[serde(default)]
    pub preserve_structure: bool,
    #[serde(default)]
    pub output_suffix: Option<String>,
    // v4.4.0:CAS 锐化强度(0=关闭;画质优先档默认 0.35,缩放比>1.3 时自动补偿降采样柔化)
    #[serde(default)]
    pub cas_strength: f32,
    // v4.4.1:GUI 自定义导出目录记忆(用户通过文件选择器指定的输出目录,None=默认原文件旁)
    #[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,
            // v4.4.0:默认社交分享 + 防二压画质优先 + 微信平台
            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,
    /// v4.2.0-exp 感知压缩选项:None = 完全走 v4.1.0 旧路径(GUI 恒为 None)
    pub perceptual: Option<PerceptualOptions>,
    // v4.3.0:色彩子采样(照片 420 / 截图 444 / 平衡 422)
    pub subsampling: String,
    // v4.3.1:保结构输出(复刻源目录层级到 output_dir)
    pub preserve_structure: bool,
    // v4.3.1:结构基准目录(输出相对此目录复刻层级;由调用方计算注入)
    pub structure_base: Option<PathBuf>,
    // v4.3.1:后缀可控(覆盖默认 _wx/_hd/_da;None=默认,空串=无后缀)
    pub output_suffix: Option<String>,
    // v4.4.0:CAS 锐化强度(0=关闭;感知模式已有 USM 时自动跳过防双重锐化)
    pub cas_strength: f32,
}

pub struct Processor {
    config: ProcessConfig,
}

impl Processor {
    pub fn new(config: ProcessConfig) -> Self {
        Self { config }
    }

    /// 纯路径计算:给定输入文件,返回将要生成的输出路径(不创建目录、不做任何 IO 写入)。
    /// 供上层「续跑跳过」幂等判断复用,与 process_image 内部逻辑严格同源。
    ///
    /// v4.3.1 增强:
    /// - `preserve_structure=true` 时,按 `structure_base` 复刻源目录相对层级到 output_dir(修 D2 拍平)。
    /// - `output_suffix` 可覆盖默认 `_wx/_hd/_da`;空串=无后缀。`keep_original_name` 优先级最高(无后缀)。
    /// - 支持 WebP 输出扩展名。
    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());

        // 保结构:把输入相对 structure_base 的父目录层级拼到输出目录后
        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))
        }
    }

    /// 透传路径:不支持的格式(如 SVG)原样复制到 output_dir(保持保结构层级、不改名不改扩展名)。
    /// 与 expected_output_path 仅在「不加后缀」上有区别,便于 passthrough 模式 1:1 映射源文件名。
    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)
    }

    /// v4.2.0-exp:处理并返回感知指标(perceptual=None 时指标恒为 None,行为同 v4.1.0)
    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());

        // 输出路径与 expected_output_path 严格同源;按最终输出路径的父目录建目录(兼容保结构子目录)
        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))
    }

    /// 返回当前感知压缩配置(None = 走 v4.1.0 旧路径),供 CLI/JSON 输出 metrics 元数据
    pub fn perceptual_config(&self) -> Option<&PerceptualOptions> {
        self.config.perceptual.as_ref()
    }

    /// 实际生效的体积预算(KB):感知模式 budget_kb 覆盖 target_kb
    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() {
                // max_dim == 0 表示「不缩放」(高清存档),跳过 sips -Z
                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");
            // max_dim == 0(不缩放)时 qlmanage 仍需尺寸参数 → 给超大值等效原尺寸
            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();
        // v4.3.1:提前判定源图是否含 alpha 通道(PNG/WebP 透明图)。JPEG 输出不支持透明,
        // 含 alpha 时把透明区域填白底(修 D4:透明 PNG→JPEG 丢透明变黑)。
        let src_has_alpha = img.color().has_alpha();
        let perceptual = self.config.perceptual.as_ref();
        let mut pm = PerceptualMetrics::default();

        // max_dim == 0 表示「不缩放,保持原图尺寸」(高清存档/投稿场景)
        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;

        // 转换为 DynamicImage 以便后续处理
        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 {
            // 降噪在「目标分辨率」上做(§3 防御性修正:超大图全分辨率降噪会卡死/爆内存,
            // 统一放降采样后;高质量重采样已抑制高频噪点,目标分辨率降噪足以满足分享/存档画质)
            // JPG 输入禁降噪(放大块效应);超过 4000px 的超大图直接跳过降噪(防冻结)
            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);
            // 保守参数(§9 保画质铁律):radius 随尺寸微调,amount 经掩码加权后有效强度更低
            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) {
            // v4.4.1:CAS 锐化补偿——不再用固定强度,改为调用自适应计算:
            // 根据原图内容(人像/风景/复杂度/噪点)+ 原图尺寸 + 缩放幅度综合决策。
            // 自适应性继承自旧版 smart_adaptive_sharpen,输出映射为 CAS strength。
            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 {
            // v4.1.0 旧路径:智能自适应锐化(行为不变)
            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();
                // 转换为 RGB 格式;JPEG 不支持透明 → 含 alpha 的源图先按白底合成(修 D4 透明丢失)
                let rgb_buf: Vec<u8> = if src_has_alpha {
                    flatten_rgba8_to_rgb(dynamic_img.to_rgba8())
                } else {
                    dynamic_img.to_rgb8().into_raw()
                };

                // 感知模式:budget_kb 覆盖 target_kb;质量上限 quality_ceil
                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};
                    // P1:mozjpeg-rs 替换 jpeg-encoder(BSD-3,纯 Rust,零 C 依赖)
                    // 默认 4:2:0 子采样(照片省 ~1/3 码率);截图/文字场景由 subsampling 字段切 4:4:4(P2 贯通)
                    let sub = match self.config.subsampling.as_str() {
                        "444" => Subsampling::S444,
                        "422" => Subsampling::S422,
                        _ => Subsampling::S420, // "420" 默认(照片省码率)
                    };
                    let mut encoder = Encoder::default()
                        .quality(quality)
                        .progressive(true)
                        .optimize_huffman(true)
                        .subsampling(sub);
                    // 感知模式:用 MS-SSIM 调优量化表(mozjpeg-rs 不支持外部自定义表注入,
                    // 原 jpeg-encoder 的 MsSsim/Csf 自定义表统一改用内置 MssimTuned,叠加 trellis 画质更优)
                    match quant_mode {
                        Some(perceptual::QuantMode::MsSsim) | Some(perceptual::QuantMode::Csf) => {
                            encoder = encoder.quant_tables(QuantTableIdx::MssimTuned);
                        }
                        _ => {} // 非感知模式:mozjpeg 默认 Annex-K 表(v4.1.0 行为等价)
                    }
                    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;

                // 感知指标:解码输出 JPG,与「降采样后参考帧」算 SSIM/PSNR
                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(),
    };

    // P4(升级 v4.3.0):保留所有 APP 段(marker 0xE0–0xEF),零元数据损失。
    // 覆盖 EXIF(APP1)、XMP(APP1)、ICC 色彩配置(APP2 ICC_PROFILE)、MPF(APP2)、
    // Adobe IRB(APP13)/Adobe(APP14) 等。v4.2.0 只取首个 APP1(0xE1) 会丢 XMP 与
    // 宽色域 ICC 配置(ICC 在 APP2),违背"保证原图色彩"。
    // 注意:DQT/DHT/SOF/SOS 等不在 0xE0–0xEF 范围,不会被重复插入。
    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;
    // 从位置 1 起依次插入每个 APP 段(保持原顺序:EXIF / XMP / ICC 均保留)
    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()
}

/// 用途驱动的三方统一配置构造(GUI / CLI / AI JSON 同一套语义)
///
/// - social:平台预设值(已写入 `custom_*`)→ 社交分享最优体积/画质
/// - archive:不缩放(0) + 最高画质(100) + 不限位(0) → 高清存档
/// - custom:完全按用户自定义参数(含 `--mode hd` 的 4096/95/5000 兼容)
///
/// 平台预设 / 不缩放策略 / sRGB 强制 已在调用方(`apply_usage_preset` / `to_app_config` /
/// json 路径)写入 `config.custom_*` 与 `config.color_space`,本函数只负责按 `usage_mode` 选材。
/// 感知压缩(perceptual)由 `quality_mode` 决定,调用方在返回后按需覆盖。
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:不缩放(0) + 视觉无损画质(95,同原版 HD) + 不限体积(0);ProcessMode::HD 仅决定输出后缀 "_hd"
        // 注意:不用 Q100 —— Q100 禁用量化几乎无压缩,输出会比源图更大,违背压缩工具语义
        "archive" => (ProcessMode::HD, 0, 95, 0),
        _ => {
            // custom:完整保留 v4.1.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(),
        // v4.3.1:保结构 / 后缀
        preserve_structure: config.preserve_structure,
        structure_base: None, // 由调用方(CLI/JSON 入口)计算注入
        output_suffix: config.output_suffix.clone(),
        // v4.4.0:CAS 锐化补偿
        cas_strength: config.cas_strength,
        // 摄影级优化
        enable_sharpening: config.enable_sharpening,
        sharpening_radius: config.sharpening_radius,
        sharpening_amount: config.sharpening_amount,
        perceptual: None,
    }
}

// ============================================================================
// 摄影级优化功能 - 智能自适应锐化
// ============================================================================

/// 检测像素是否为肤色(快速算法)
///
/// 使用简单但有效的肤色检测算法
/// 返回值:0.0-1.0,值越高越可能是肤色
pub(crate) fn is_skin_color(r: u8, g: u8, b: u8) -> f32 {
    // RGB 转 YCbCr 色彩空间
    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
    }
}

/// 检测图像中肤色区域比例
///
/// 返回值:0.0-1.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
}

/// 智能锐化决策:根据图像特征判断是否需要锐化
///
/// 避免重复锐化的策略:
/// 1. 检测高频能量(已锐化的图高频能量高)
/// 2. 检测平坦区域比例(磨皮人像平坦区域多)
/// 3. 检测噪点水平(高噪点图不锐化)
/// 4. 根据尺寸和内容类型决策
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);

    // 如果肤色比例较高(> 30%),很可能是人像照片
    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
}

/// 估算图像复杂度(0.0-1.0)
/// 简单场景(天空、纯色背景)返回低值,复杂场景(纹理、细节)返回高值
fn estimate_image_complexity(image: &image::DynamicImage) -> f32 {
    let rgba = image.to_rgba8();
    let (width, height) = rgba.dimensions();

    // 采样 100x100 网格快速估算
    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;
    }

    // 归一化到 0-1
    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);
    // 复杂度高于 0.7 说明细节丰富,可能已足够锐利
    complexity > 0.7
}

/// 估算噪点水平(0.0-1.0)
/// 高噪点照片(高 ISO)锐化会放大噪点
fn estimate_noise_level(image: &image::DynamicImage) -> f32 {
    let rgba = image.to_rgba8();
    let (width, height) = rgba.dimensions();

    // 在平坦区域检测噪点
    let mut noise_scores = Vec::new();

    // 采样 10x10 区域
    let step = 20;
    for y in (0..height).step_by(step) {
        for x in (0..width).step_by(step) {
            // 检查 3x3 邻域
            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;
    // 归一化:variance < 10 为低噪点,> 50 为高噪点
    (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)
}

/// v4.4.1:将旧版 smart_adaptive_sharpen 的决策矩阵映射为 CAS 强度。
/// 不搞 CAS vs USM 二选一——把"人像/风景/复杂度/原图尺寸/缩放比/噪点"的
/// 自适应逻辑保留,输出的是 CAS strength 而非 USM (radius, amount, threshold)。
/// 这样既享受 CAS 的无光晕天然优势,又保留了旧版的内容感知智慧。
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);

    // 小图不锐化(与旧版 should_apply_sharpening 一致)
    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;
    }
    // 低复杂度人像:旧版 should_apply_sharpening 直接跳过(皮肤已平滑,锐化
    // 反而突兀)。不延续这个门控等于给磨皮人像强行加锐。
    if is_portrait && complexity <= 0.5 {
        return 0.0;
    }
    // 中等尺寸 + 极低复杂度:内容本身没什么细节可锐,强锐反而出噪点
    if larger_dim < 2000 && complexity <= 0.3 {
        return 0.0;
    }

    // 根据内容类型 + 原图尺寸确定基础强度(沿用旧版 9 档映射换算到 CAS)
    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);

    // 不超过调用方指定的上限(用户可通过 --cas-strength 限制最大值)
    adaptive.min(max_cas)
}

// ============================================================================
// USM 锐化核心函数
// ============================================================================

/// USM (Unsharp Mask) 锐化实现(智能版)
///
/// 特性:
/// - 自动检测并避开肤色区域
/// - 根据图像内容调整锐化强度
///
/// 原理:
/// 1. 对原图进行高斯模糊得到模糊图
/// 2. 原图 - 模糊图 = 高频细节(边缘)
/// 3. 原图 + amount * 高频细节 = 锐化图
///
/// 参数:
/// - radius: 高斯模糊半径,控制锐化范围
/// - amount: 锐化强度,0.5-1.5 常用
/// - threshold: 阈值,避免锐化平滑区域(减少噪点)
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);

    // USM 锐化公式:output = original + amount * (original - blurred)
    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];
                }
            }

            // Alpha 通道保持不变
            out_pixel[3] = orig_pixel[3];

            output.put_pixel(x, y, out_pixel);
        }
    }

    image::DynamicImage::ImageRgba8(output)
}

/// 高斯模糊实现(优化版:可分离卷积)
///
/// 性能优化:
/// - 使用可分离卷积:O(n²) → O(2n)
/// - 先水平卷积,再垂直卷积
/// - 性能提升 10 倍以上
pub(crate) fn gaussian_blur(
    image: &ImageBuffer<Rgba<u8>, Vec<u8>>,
    sigma: f32,
) -> ImageBuffer<Rgba<u8>, Vec<u8>> {
    let (width, height) = image.dimensions();

    // 高斯核大小(基于 sigma)
    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);

    // Step 1: 水平卷积
    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);
        }
    }

    // Step 2: 垂直卷积
    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
}

// ============================================================================
// 智能色彩空间管理(保留供未来使用)
// ============================================================================

/// 智能色彩空间管理
///
/// 策略:
/// - 长边 ≤ 3000px:统一转 sRGB(网络分享标准)
/// - 长边 > 3000px:保持原色彩空间(专业用途)
/// - 检测 300dpi+ 高分辨率:保持原样(印刷级)
#[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;
    }

    // 网络分享级:统一转 sRGB
    if max_dim <= 3000 {
        // 简单转换:假设原图为 sRGB(大多数数码照片)
        // 注:完整实现需要 ICC Profile 管理
        return image;
    }

    // 中等尺寸:保持原样
    image
}

/// 检测图片是否为 300dpi 或更高分辨率
#[allow(dead_code)]
fn is_high_resolution_dpi(input_path: &Path) -> bool {
    // 尝试读取 EXIF 中的 DPI 信息
    if let Ok(file) = fs::File::open(input_path) {
        if let Ok(mmap) = unsafe { Mmap::map(&file) } {
            // 简单判断:如果文件很大且尺寸不大,可能是高 DPI
            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> {
    // 注意: 调用者(process_image)已做 path_self_healing,此处直接用输入路径,
    // 避免重复 stat 调用
    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))
}

/// v4.3.1(修 D4):把 RGBA 图像按白底合成转 RGB。
/// 用于 JPEG 等不支持透明的输出格式,避免透明区域变黑或丢失透明度信息。
/// alpha=255(不透明)时等价于直接取 RGB,不会产生色偏。
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() {
        // social(聊天场景)→ ProcessMode::WeChat + 平台预设写入 custom_*
        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() {
        // archive(高清存档)→ 不缩放(0) + 视觉无损(95) + 不限体积(0)
        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);
        // 默认输出格式 Jpeg → 任意输入最终 .jpg;archive 后缀 _hd
        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() {
        // 端到端:生成 1600x1200 图 → 1280 上限压缩 → 输出存在、尺寸符合、体积下降
        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() {
        // 后缀规则:WeChat→_wx / HD→_hd / Custom→_da;overwrite 时保持原名
        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"));
        // 默认输出格式 Jpeg → 输出扩展名 .jpg(与输出格式一致,非输入格式)
        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);
        // 输入大小写不一致:大小写敏感 FS(Linux/Win)走兜底,macOS(APFS 不敏感)首分支已命中
        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();
    }
}