Skip to main content

resopt/
analysis.rs

1use crate::{
2    ImageDifference, ImageInfo, Policy, Resource, ResourceInventory,
3    analyze_image::{self, Context as ImageContext},
4    cache::Cache,
5    filesystem::{contained_file, hash, write_new},
6    image_backend,
7    resources::{bounded_read, inventory_with_options},
8    timings::{Phase, Timings},
9};
10use anyhow::{Context, Result, ensure};
11use serde::{Deserialize, Serialize};
12use std::{
13    collections::{BTreeMap, HashMap},
14    fs,
15    path::{Path, PathBuf},
16    sync::{
17        Arc, Condvar, Mutex, OnceLock,
18        atomic::{AtomicBool, AtomicUsize, Ordering},
19    },
20    time::Instant,
21};
22
23/// Candidate verdicts a user may accept after reviewing the actual result.
24/// Every other rejection is a hard failure that approval cannot bypass.
25pub(crate) const WARNINGS: [&str; 3] = [
26    "alpha_error_exceeds_policy",
27    "transparency_presence_changed",
28    "quality_below_policy",
29];
30
31#[derive(Debug, Clone, Serialize, Deserialize)]
32#[serde(default, deny_unknown_fields)]
33pub struct AnalysisOptions {
34    /// Encoder quality parameters for lossy candidates; not savings percentages.
35    pub qualities: Vec<u8>,
36    pub include_ignored: bool,
37    /// Parallel image workers; 0 selects the CPU count, capped at 8.
38    pub jobs: usize,
39    /// All sizes are included by default, unlike the legacy lossless plan.
40    pub min_input_bytes: u64,
41    pub min_savings_bytes: u64,
42    pub probe_only: bool,
43    /// Lossy HEIC may quantize alpha. 0 requires exact alpha samples.
44    pub max_alpha_error: f32,
45    /// Lowest SSIMULACRA2 score a lossy candidate may have and still be
46    /// recommended. Lower-scoring candidates are kept as reviewable warnings.
47    pub min_score: f64,
48    /// Largest decoded image analyzed; each pixel costs 16 bytes per decode.
49    pub max_pixels: usize,
50    /// oxipng effort for the lossless PNG candidate.
51    pub png_level: u8,
52    /// Allow lossless PNG color-type, bit-depth and palette reductions.
53    pub png_reductions: bool,
54    /// Compare WebP candidates for loose files and Android resources. On by
55    /// default; asset-catalog renditions never receive WebP.
56    pub webp: bool,
57    /// Compare lossy PNG candidates (palette quantization) for PNG sources.
58    /// The file stays a PNG, so names, references and decoders are unaffected.
59    pub lossy_png: bool,
60    /// Also try HEIC at encoder quality 100. Apple's encoder has no lossless
61    /// mode, so this is its closest setting: still lossy, and labelled so.
62    pub heic_near_lossless: bool,
63    /// Overrides the `minSdk` detected from Gradle files.
64    pub android_min_sdk: Option<u32>,
65    /// Persistent result cache directory. `None` disables the cache; the CLI
66    /// passes the per-user cache directory unless `--no-cache` is given.
67    pub cache_dir: Option<PathBuf>,
68}
69impl Default for AnalysisOptions {
70    fn default() -> Self {
71        Self {
72            qualities: vec![75, 85, 95],
73            include_ignored: false,
74            jobs: 0,
75            min_input_bytes: 0,
76            min_savings_bytes: 1,
77            probe_only: false,
78            max_alpha_error: 1.0 / 255.0 + 0.000001,
79            min_score: 80.0,
80            max_pixels: image_backend::DEFAULT_MAX_PIXELS,
81            png_level: Policy::default().png_level,
82            png_reductions: false,
83            webp: true,
84            lossy_png: true,
85            heic_near_lossless: true,
86            android_min_sdk: None,
87            cache_dir: None,
88        }
89    }
90}
91impl AnalysisOptions {
92    pub(crate) fn validate(&self) -> Result<()> {
93        ensure!(
94            self.max_alpha_error.is_finite() && (0.0..=1.0).contains(&self.max_alpha_error),
95            "max_alpha_error must be 0..=1"
96        );
97        ensure!(
98            self.min_score.is_finite() && (0.0..=100.0).contains(&self.min_score),
99            "min_score must be 0..=100"
100        );
101        ensure!(
102            self.jobs <= 16,
103            "jobs must be 0..=16 (0 selects automatically)"
104        );
105        ensure!(
106            self.android_min_sdk.is_none_or(|v| (1..=99).contains(&v)),
107            "android_min_sdk must be 1..=99"
108        );
109        ensure!(
110            (1..=image_backend::MAX_PIXELS_LIMIT).contains(&self.max_pixels),
111            "max_pixels must be 1..={}",
112            image_backend::MAX_PIXELS_LIMIT
113        );
114        self.png_policy().validate()?;
115        ensure!(
116            !self.qualities.is_empty()
117                && self.qualities.len() <= 8
118                && self.qualities.iter().all(|q| (1..=100).contains(q)),
119            "qualities must contain 1..=8 values in 1..=100"
120        );
121        let mut qualities = self.qualities.clone();
122        qualities.sort_unstable();
123        qualities.dedup();
124        ensure!(
125            qualities.len() == self.qualities.len(),
126            "duplicate quality values"
127        );
128        Ok(())
129    }
130
131    pub(crate) fn png_policy(&self) -> Policy {
132        Policy {
133            png_level: self.png_level,
134            reductions: self.png_reductions,
135            ..Policy::default()
136        }
137    }
138
139    pub(crate) fn worker_count(&self) -> usize {
140        if self.jobs > 0 {
141            return self.jobs;
142        }
143        std::thread::available_parallelism()
144            .map_or(2, |n| n.get())
145            .clamp(1, 8)
146    }
147}
148
149#[derive(Debug, Clone, Serialize, Deserialize)]
150pub struct ImageCandidate {
151    pub format: String,
152    pub quality: Option<u8>,
153    pub lossy: bool,
154    pub bytes: u64,
155    pub savings_bytes: u64,
156    pub valid: bool,
157    pub rejection: Option<String>,
158    pub difference: Option<ImageDifference>,
159    pub artifact: Option<PathBuf>,
160    pub preview: Option<PathBuf>,
161    /// SHA-256 of the artifact, checked again before it is applied.
162    #[serde(default, skip_serializing_if = "Option::is_none")]
163    pub sha256: Option<String>,
164    /// Every visual policy threshold this candidate misses. `rejection` holds
165    /// the first one; approval must cover all of them.
166    #[serde(default, skip_serializing_if = "Vec::is_empty")]
167    pub warnings: Vec<String>,
168    /// Facts the reviewer should know, e.g. metadata a conversion does not carry.
169    #[serde(default, skip_serializing_if = "Vec::is_empty")]
170    pub notes: Vec<String>,
171}
172
173impl ImageCandidate {
174    /// A structurally sound candidate that only misses a visual policy threshold.
175    pub(crate) fn is_warning(&self) -> bool {
176        !self.valid
177            && self.lossy
178            && self.artifact.is_some()
179            && self
180                .rejection
181                .as_deref()
182                .is_some_and(|r| WARNINGS.contains(&r))
183    }
184
185    /// Warning kinds that must be approved before this candidate is applied.
186    pub(crate) fn required_warnings(&self) -> Vec<String> {
187        if !self.is_warning() {
188            vec![]
189        } else if self.warnings.is_empty() {
190            // Reports written before `warnings` existed recorded one kind.
191            self.rejection.iter().cloned().collect()
192        } else {
193            self.warnings.clone()
194        }
195    }
196}
197
198#[derive(Debug, Clone, Serialize, Deserialize)]
199pub struct ResourceAnalysis {
200    pub resource: Resource,
201    pub sha256: Option<String>,
202    pub image: Option<ImageInfo>,
203    /// `candidates_available`, `inspected`, `excluded`, `unsupported`, `failed`
204    /// or `not_analyzed` (analysis was cancelled first).
205    pub status: String,
206    pub issues: Vec<String>,
207    pub candidates: Vec<ImageCandidate>,
208    /// A size winner among candidates that passed every policy check.
209    pub smallest_candidate: Option<usize>,
210    pub original_preview: Option<PathBuf>,
211    pub original_artifact: Option<PathBuf>,
212    /// Codec, duration and bitrate of audio/video files, when ffprobe is installed.
213    #[serde(default, skip_serializing_if = "Option::is_none")]
214    pub media: Option<crate::media::MediaInfo>,
215    /// Bounded ZIP contents; entries are never extracted into the project.
216    #[serde(default, skip_serializing_if = "Option::is_none")]
217    pub archive: Option<crate::archive::ArchiveInfo>,
218    #[serde(default, skip_serializing_if = "Option::is_none")]
219    pub vap: Option<crate::vap::VapInfo>,
220    #[serde(default, skip_serializing_if = "Option::is_none")]
221    pub pag: Option<crate::pag::PagInfo>,
222    /// Canvas, timing and size of an animation, when it could be parsed.
223    #[serde(default, skip_serializing_if = "Option::is_none")]
224    pub animation: Option<AnimationInfo>,
225    /// Scale-invariant fingerprint used to find duplicate and resized images.
226    #[serde(default, skip_serializing_if = "Option::is_none")]
227    pub fingerprint: Option<crate::similarity::Fingerprint>,
228}
229
230impl ResourceAnalysis {
231    pub(crate) fn new(resource: &Resource, status: &str) -> Self {
232        Self {
233            resource: resource.clone(),
234            sha256: None,
235            image: None,
236            status: status.into(),
237            issues: vec![],
238            candidates: vec![],
239            smallest_candidate: None,
240            original_preview: None,
241            original_artifact: None,
242            fingerprint: None,
243            media: None,
244            archive: None,
245            vap: None,
246            pag: None,
247            animation: None,
248        }
249    }
250
251    pub(crate) fn recommended_savings(&self) -> u64 {
252        self.smallest_candidate
253            .and_then(|i| self.candidates.get(i))
254            .filter(|c| c.valid && c.artifact.is_some())
255            .map_or(0, |c| c.savings_bytes)
256    }
257}
258
259#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
260pub struct AnimationInfo {
261    pub width: u32,
262    pub height: u32,
263    pub fps: u32,
264    pub frames: usize,
265    /// Frame shown as the thumbnail.
266    pub poster_frame: usize,
267}
268
269#[derive(Debug, Serialize, Deserialize)]
270pub struct AnalysisReport {
271    pub schema_version: u32,
272    pub root: PathBuf,
273    pub backend: String,
274    pub options: AnalysisOptions,
275    pub inventory: ResourceInventory,
276    pub resources: Vec<ResourceAnalysis>,
277    pub status_counts: BTreeMap<String, usize>,
278    /// Sum of recommended candidates only; warning candidates are excluded.
279    pub potential_source_bytes_saved: u64,
280    /// Images that show the same picture (identical, resized or near-duplicate),
281    /// excluding intended variants such as `@2x`/`@3x` or density folders.
282    #[serde(default, skip_serializing_if = "Vec::is_empty")]
283    pub similar_groups: Vec<crate::similarity::SimilarGroup>,
284    /// Analysis stopped early; unfinished resources are `not_analyzed`.
285    #[serde(default)]
286    pub cancelled: bool,
287    #[serde(default, skip_serializing_if = "Option::is_none")]
288    pub performance: Option<Performance>,
289}
290
291#[derive(Debug, Clone, Default, Serialize, Deserialize)]
292pub struct Performance {
293    pub wall_seconds: f64,
294    pub first_result_seconds: Option<f64>,
295    pub workers: usize,
296    pub cache_hits: usize,
297    pub duplicate_reuses: usize,
298    /// Seconds per phase summed over workers (CPU-side, not wall-clock).
299    pub phase_seconds: BTreeMap<String, f64>,
300}
301
302/// Cooperative cancellation shared with the caller.
303#[derive(Clone, Default)]
304pub struct AnalysisControl(Arc<AtomicBool>);
305impl AnalysisControl {
306    pub fn cancel(&self) {
307        self.0.store(true, Ordering::SeqCst);
308    }
309    pub fn is_cancelled(&self) -> bool {
310        self.0.load(Ordering::SeqCst)
311    }
312}
313
314/// Bounds decoded source pixels in flight to one maximum-size image, so adding
315/// workers speeds up ordinary assets without multiplying peak memory.
316pub(crate) struct PixelBudget {
317    capacity: usize,
318    available: Mutex<usize>,
319    released: Condvar,
320}
321pub(crate) struct PixelLease<'a>(&'a PixelBudget, usize);
322impl PixelBudget {
323    pub fn new(capacity: usize) -> Self {
324        Self {
325            capacity,
326            available: Mutex::new(capacity),
327            released: Condvar::new(),
328        }
329    }
330    pub fn acquire(&self, pixels: usize) -> PixelLease<'_> {
331        let wanted = pixels.clamp(1, self.capacity);
332        let mut available = self.available.lock().unwrap_or_else(|e| e.into_inner());
333        while *available < wanted {
334            available = self
335                .released
336                .wait(available)
337                .unwrap_or_else(|e| e.into_inner());
338        }
339        *available -= wanted;
340        PixelLease(self, wanted)
341    }
342}
343impl Drop for PixelLease<'_> {
344    fn drop(&mut self) {
345        *self.0.available.lock().unwrap_or_else(|e| e.into_inner()) += self.1;
346        self.0.released.notify_all();
347    }
348}
349
350/// Read-only analysis of all inventoried resources, with lossy candidates staged
351/// solely for review. This report is deliberately not an executable apply plan.
352pub fn analyze(
353    root: impl AsRef<Path>,
354    out: impl AsRef<Path>,
355    options: AnalysisOptions,
356) -> Result<AnalysisReport> {
357    analyze_with_progress(root, out, options, |_, _| {})
358}
359
360pub fn analyze_with_progress(
361    root: impl AsRef<Path>,
362    out: impl AsRef<Path>,
363    options: AnalysisOptions,
364    progress: impl Fn(usize, usize) + Sync,
365) -> Result<AnalysisReport> {
366    analyze_with_observer(
367        root,
368        out,
369        options,
370        &AnalysisControl::default(),
371        |_, _, done, total| progress(done, total),
372    )
373}
374
375type Shared = Arc<OnceLock<(usize, ResourceAnalysis)>>;
376
377pub(crate) fn analyze_with_observer(
378    root: impl AsRef<Path>,
379    out: impl AsRef<Path>,
380    options: AnalysisOptions,
381    control: &AnalysisControl,
382    progress: impl Fn(usize, &ResourceAnalysis, usize, usize) + Sync,
383) -> Result<AnalysisReport> {
384    let started = Instant::now();
385    options.validate()?;
386    if !options.probe_only && image_backend::image_backend_available() {
387        image_backend::check_encoders()?;
388    }
389    let timings = Timings::default();
390    let inventory = timings.time(Phase::Scan, || {
391        inventory_with_options(
392            root,
393            crate::ScanOptions {
394                include_ignored: options.include_ignored,
395            },
396        )
397    })?;
398    let out = out.as_ref();
399    let parent = fs::canonicalize(
400        out.parent()
401            .filter(|p| !p.as_os_str().is_empty())
402            .unwrap_or(Path::new(".")),
403    )?;
404    let out = parent.join(out.file_name().context("output directory has no name")?);
405    ensure!(
406        !out.starts_with(&inventory.root),
407        "analysis output must be outside the scanned project"
408    );
409    fs::create_dir(&out).context("analysis output must be a new directory")?;
410    for folder in ["candidates", "previews", "originals"] {
411        fs::create_dir(out.join(folder))?;
412    }
413    if inventory
414        .assets
415        .iter()
416        .any(|r| matches!(r.format.as_str(), "pag" | "tcmp4"))
417    {
418        crate::pag::write_runtime(&out)?;
419    }
420    let cache = options
421        .cache_dir
422        .as_ref()
423        .filter(|_| !options.probe_only)
424        .and_then(|directory| Cache::open(directory).ok());
425    let min_sdk = options
426        .android_min_sdk
427        .or(inventory.android_min_sdk.as_ref().map(|sdk| sdk.level));
428    let workers = options.worker_count();
429    let budget = PixelBudget::new(options.max_pixels);
430    let context = ImageContext {
431        root: &inventory.root,
432        out: &out,
433        options: &options,
434        min_sdk,
435        timings: &timings,
436        control,
437        budget: &budget,
438    };
439    let total = inventory.assets.len();
440    let complete = AtomicUsize::new(0);
441    let cache_hits = AtomicUsize::new(0);
442    let duplicate_reuses = AtomicUsize::new(0);
443    let first_result = OnceLock::new();
444    let in_flight: Mutex<HashMap<String, Shared>> = Mutex::new(HashMap::new());
445    let finish = |index: usize, result: ResourceAnalysis| {
446        if result.status == "candidates_available" {
447            first_result.get_or_init(|| started.elapsed().as_secs_f64());
448        }
449        let done = complete.fetch_add(1, Ordering::Relaxed) + 1;
450        progress(index, &result, done, total);
451        (index, result)
452    };
453
454    // Rows that need no image work are published first so the inventory is
455    // visible immediately; images follow largest-first because they hold most
456    // of the savings.
457    let (mut work, settled): (Vec<usize>, Vec<usize>) = (0..total).partition(|&index| {
458        let resource = &inventory.assets[index];
459        resource.support == "optimizable"
460            || matches!(
461                resource.format.as_str(),
462                "zip" | "mp4" | "vap" | "pag" | "tcmp4"
463            )
464            || (resource.kind == "image" && options.probe_only)
465            || (is_media(resource) && crate::media::ffprobe_available())
466    });
467    work.sort_by_key(|&index| std::cmp::Reverse(inventory.assets[index].bytes));
468    let mut indexed: Vec<(usize, ResourceAnalysis)> = settled
469        .into_iter()
470        .map(|index| finish(index, settled_row(&inventory.assets[index])))
471        .collect();
472
473    let analyze_one = |index: usize| -> ResourceAnalysis {
474        let resource = &inventory.assets[index];
475        if control.is_cancelled() {
476            return ResourceAnalysis::new(resource, "not_analyzed");
477        }
478        if is_media(resource) && resource.format != "mp4" {
479            // Inspection only: spawning ffprobe runs on the worker pool so it
480            // never delays image results.
481            let mut row = settled_row(resource);
482            if let Ok(path) = contained_file(&inventory.root, &resource.path) {
483                row.media = timings.time(Phase::Decode, || crate::media::probe(&path));
484            }
485            return row;
486        }
487        let read = timings.time(Phase::Hash, || {
488            contained_file(&inventory.root, &resource.path)
489                .and_then(|path| bounded_read(&path))
490                .map(|bytes| {
491                    let digest = hash(&bytes);
492                    (bytes, digest)
493                })
494        });
495        let (bytes, digest) = match read {
496            Ok(read) => read,
497            Err(error) => {
498                let mut failed = ResourceAnalysis::new(resource, "failed");
499                failed.issues.push(format!("{error:#}"));
500                return failed;
501            }
502        };
503        if matches!(resource.format.as_str(), "pag" | "tcmp4") {
504            let mut row = ResourceAnalysis::new(resource, "inspected");
505            row.sha256 = Some(digest);
506            match crate::pag::inspect(&bytes) {
507                Ok(info) => {
508                    row.resource.kind = "animation".into();
509                    row.resource.format = "pag".into();
510                    let artifact = PathBuf::from(format!("originals/{index}.pag"));
511                    match write_new(&out.join(&artifact), &bytes) {
512                        Ok(()) => row.original_artifact = Some(artifact),
513                        Err(error) => row.issues.push(format!("preview_unavailable: {error:#}")),
514                    }
515                    row.pag = Some(info);
516                }
517                Err(error) => {
518                    row.status = "failed".into();
519                    row.issues.push(format!("{error:#}"));
520                }
521            }
522            return row;
523        }
524        if matches!(resource.format.as_str(), "mp4" | "vap") {
525            let mut row = settled_row(resource);
526            row.sha256 = Some(digest);
527            match crate::vap::inspect(&bytes) {
528                Ok(Some(info)) => {
529                    row.issues.clear();
530                    row.status = "inspected".into();
531                    row.resource.kind = "animation".into();
532                    row.resource.format = "vap".into();
533                    let artifact = PathBuf::from(format!("originals/{index}.mp4"));
534                    match write_new(&out.join(&artifact), &bytes) {
535                        Ok(()) => row.original_artifact = Some(artifact),
536                        Err(error) => row.issues.push(format!("preview_unavailable: {error:#}")),
537                    }
538                    row.vap = Some(info);
539                }
540                Ok(None) => {
541                    if let Ok(path) = contained_file(&inventory.root, &resource.path) {
542                        row.media = crate::media::probe(&path);
543                    }
544                }
545                Err(error) => {
546                    row.status = "failed".into();
547                    row.issues.push(format!("{error:#}"));
548                }
549            }
550            return row;
551        }
552        // Archive previews have their own entry paths; do not reuse image-cache manifests.
553        if resource.format == "zip" {
554            return crate::archive::analyze(&context, resource, index, &bytes, &digest);
555        }
556        let compute = |own_index: usize| {
557            #[cfg(target_os = "macos")]
558            {
559                objc2::rc::autoreleasepool(|_| {
560                    analyze_image::analyze(&context, resource, own_index, &bytes, &digest)
561                })
562            }
563            #[cfg(not(target_os = "macos"))]
564            {
565                analyze_image::analyze(&context, resource, own_index, &bytes, &digest)
566            }
567        };
568        if options.probe_only {
569            return compute(index);
570        }
571        let key = match Cache::key(
572            &digest,
573            &analyze_image::policy_key(resource, min_sdk),
574            &options,
575        ) {
576            Ok(key) => key,
577            Err(_) => return compute(index),
578        };
579        // Identical content under an identical policy is analyzed once per run.
580        let slot = in_flight
581            .lock()
582            .unwrap_or_else(|e| e.into_inner())
583            .entry(key.clone())
584            .or_default()
585            .clone();
586        let mut computed_here = false;
587        let (owner, shared) = slot.get_or_init(|| {
588            computed_here = true;
589            if let Some(cache) = &cache
590                && let Some(mut hit) = timings.time(Phase::Cache, || cache.load(&key, &out, index))
591                && restore_original_artifact(&mut hit, &out, index, &bytes, resource).is_ok()
592            {
593                cache_hits.fetch_add(1, Ordering::Relaxed);
594                hit.resource = resource.clone();
595                return (index, hit);
596            }
597            let result = compute(index);
598            if let Some(cache) = &cache
599                && matches!(result.status.as_str(), "candidates_available" | "inspected")
600            {
601                let _ = timings.time(Phase::Cache, || cache.store(&key, &result, &out, index));
602            }
603            (index, result)
604        });
605        if computed_here || *owner == index {
606            return shared.clone();
607        }
608        if matches!(shared.status.as_str(), "failed" | "not_analyzed") {
609            return compute(index);
610        }
611        duplicate_reuses.fetch_add(1, Ordering::Relaxed);
612        let mut reused = shared.clone();
613        reused.resource = resource.clone();
614        reused
615    };
616    // Plain threads pulling from a shared queue, not a rayon pool: oxipng uses
617    // rayon internally, and a rayon worker that waits on nested work runs other
618    // queued tasks on the same stack. With a task already holding a pixel lease
619    // or initializing a shared duplicate slot, that re-entrancy deadlocked.
620    let next = AtomicUsize::new(0);
621    let finished = Mutex::new(Vec::with_capacity(work.len()));
622    std::thread::scope(|scope| {
623        for _ in 0..workers.min(work.len()).max(1) {
624            scope.spawn(|| {
625                while let Some(&index) = work.get(next.fetch_add(1, Ordering::Relaxed)) {
626                    let done = finish(index, analyze_one(index));
627                    finished
628                        .lock()
629                        .unwrap_or_else(|e| e.into_inner())
630                        .push(done);
631                }
632            });
633        }
634    });
635    indexed.extend(finished.into_inner().unwrap_or_else(|e| e.into_inner()));
636    indexed.sort_by_key(|(index, _)| *index);
637    let resources: Vec<_> = indexed.into_iter().map(|(_, result)| result).collect();
638    let mut status_counts = BTreeMap::new();
639    let mut savings = 0;
640    for resource in &resources {
641        *status_counts.entry(resource.status.clone()).or_insert(0) += 1;
642        savings += resource.recommended_savings();
643    }
644    if let Some(cache) = &cache {
645        let _ = cache.prune(crate::cache::DEFAULT_MAX_BYTES);
646    }
647    let similar_groups = crate::similarity::group(&resources);
648    // Fingerprints exist for grouping (and the cache); the report keeps the groups.
649    let resources: Vec<_> = resources
650        .into_iter()
651        .map(|resource| ResourceAnalysis {
652            fingerprint: None,
653            ..resource
654        })
655        .collect();
656    let mut report = AnalysisReport {
657        schema_version: 2,
658        root: inventory.root.clone(),
659        backend: if image_backend::image_backend_available() {
660            "Apple ImageIO + CoreGraphics sRGB float comparison; bundled oxipng and libwebp"
661        } else {
662            "Portable PNG and WebP (bundled oxipng and libwebp); JPEG/HEIC require macOS"
663        }
664        .into(),
665        options,
666        inventory,
667        resources,
668        status_counts,
669        potential_source_bytes_saved: savings,
670        similar_groups,
671        cancelled: control.is_cancelled(),
672        performance: None,
673    };
674    let html = timings.time(Phase::Report, || crate::report::render_html(&report))?;
675    report.performance = Some(Performance {
676        wall_seconds: started.elapsed().as_secs_f64(),
677        first_result_seconds: first_result.get().copied(),
678        workers,
679        cache_hits: cache_hits.load(Ordering::Relaxed),
680        duplicate_reuses: duplicate_reuses.load(Ordering::Relaxed),
681        phase_seconds: timings.snapshot(),
682    });
683    write_new(&out.join("analysis.json"), &serde_json::to_vec(&report)?)?;
684    write_new(&out.join("report.html"), html.as_bytes())?;
685    Ok(report)
686}
687
688fn is_media(resource: &Resource) -> bool {
689    matches!(resource.kind.as_str(), "audio" | "video") && resource.conversion_exclusion.is_none()
690}
691
692/// Inventory rows that need no decoding.
693fn settled_row(resource: &Resource) -> ResourceAnalysis {
694    if let Some(reason) = &resource.conversion_exclusion {
695        let mut row = ResourceAnalysis::new(resource, "excluded");
696        row.issues.push(reason.clone());
697        return row;
698    }
699    let mut row = ResourceAnalysis::new(resource, "unsupported");
700    if is_media(resource) && !crate::media::ffprobe_available() {
701        row.issues.push("ffprobe_not_installed".into());
702    }
703    row.issues.push(if resource.kind == "image" {
704        format!("{}_decoding_requires_macos_imageio", resource.format)
705    } else {
706        format!("{}_optimization_backend_not_implemented", resource.kind)
707    });
708    row
709}
710
711/// Cached entries omit the original artifact because it is the source itself.
712fn restore_original_artifact(
713    hit: &mut ResourceAnalysis,
714    out: &Path,
715    index: usize,
716    bytes: &[u8],
717    resource: &Resource,
718) -> Result<()> {
719    if hit.status == "candidates_available" {
720        let artifact = PathBuf::from(format!("originals/{index}.{}", resource.format));
721        crate::filesystem::write_artifact(&out.join(&artifact), bytes)?;
722        hit.original_artifact = Some(artifact);
723    }
724    Ok(())
725}
726
727#[cfg(test)]
728mod tests {
729    use super::*;
730
731    #[test]
732    fn pixel_budget_serializes_oversized_work_without_deadlock() {
733        let budget = PixelBudget::new(100);
734        let peak = AtomicUsize::new(0);
735        let current = AtomicUsize::new(0);
736        std::thread::scope(|scope| {
737            for _ in 0..6 {
738                scope.spawn(|| {
739                    // Requests above capacity are clamped instead of waiting forever.
740                    let _lease = budget.acquire(1_000);
741                    let now = current.fetch_add(1, Ordering::SeqCst) + 1;
742                    peak.fetch_max(now, Ordering::SeqCst);
743                    std::thread::sleep(std::time::Duration::from_millis(5));
744                    current.fetch_sub(1, Ordering::SeqCst);
745                });
746            }
747        });
748        assert_eq!(peak.load(Ordering::SeqCst), 1);
749        let _a = budget.acquire(60);
750        let _b = budget.acquire(40);
751    }
752
753    #[test]
754    fn options_reject_out_of_range_policy_values() {
755        for options in [
756            AnalysisOptions {
757                min_score: 101.0,
758                ..Default::default()
759            },
760            AnalysisOptions {
761                min_score: f64::NAN,
762                ..Default::default()
763            },
764            AnalysisOptions {
765                jobs: 17,
766                ..Default::default()
767            },
768            AnalysisOptions {
769                android_min_sdk: Some(0),
770                ..Default::default()
771            },
772        ] {
773            assert!(options.validate().is_err());
774        }
775        assert!(AnalysisOptions::default().validate().is_ok());
776        assert!((1..=8).contains(&AnalysisOptions::default().worker_count()));
777    }
778}