Skip to main content

smriti/services/
thumbnail.rs

1//! Thumbnail generation and caching service
2//!
3//! Follows a modified freedesktop.org thumbnail spec:
4//! - Thumbnails stored on the drive itself for portability
5//! - Named by the indexed file fingerprint
6//! - Stored as JPEG for smaller size
7//! - Three thumbnail sizes and a source-resolution display rendition
8//!
9//! Decode strategy:
10//! 1. Reuse an adequate embedded EXIF thumbnail
11//! 2. Fall back to bounded full decode when no adequate embedded preview exists
12//! 3. Per-image timeout to prevent stuck queue from corrupt/huge images
13//! 4. Priority-aware concurrency so visible cells beat background prewarm
14
15use std::num::NonZeroUsize;
16use std::path::{Path, PathBuf};
17use std::sync::{Arc, Condvar, Mutex, RwLock};
18use std::time::{Duration, Instant};
19use std::{fs::File, io::BufReader};
20
21use exif::{In, Reader as ExifReader, Tag};
22use lru::LruCache;
23
24use image::codecs::jpeg::JpegEncoder;
25use image::imageops::FilterType;
26use image::{DynamicImage, GenericImageView, ImageReader};
27
28use crate::services::image_utils::apply_exif_orientation;
29
30/// Maximum time allowed for a single thumbnail generation before giving up.
31const THUMBNAIL_TIMEOUT: Duration = Duration::from_secs(10);
32
33// A timed-out native decoder cannot be force-killed safely. Keep the real
34// decoder slot owned by the spawned thread so repeated timeouts cannot create
35// an unbounded pile of abandoned workers. The slot is released only when the
36// decoder thread actually exits.
37static DECODER_LIMITER: std::sync::OnceLock<Arc<ConcurrencyLimiter>> = std::sync::OnceLock::new();
38
39/// Thumbnail size variants
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
41pub enum ThumbnailSize {
42    Small,    // 260 px (timeline grid)
43    Medium,   // 430 px (detail preview)
44    Large,    // 860 px (larger preview)
45    Original, // Browser-compatible rendition at decoded source resolution.
46}
47
48impl ThumbnailSize {
49    pub fn pixels(&self) -> u32 {
50        match self {
51            ThumbnailSize::Small => 260,
52            ThumbnailSize::Medium => 430,
53            ThumbnailSize::Large => 860,
54            ThumbnailSize::Original => u32::MAX,
55        }
56    }
57
58    pub fn dir_name(&self) -> &'static str {
59        match self {
60            ThumbnailSize::Small => "small",
61            ThumbnailSize::Medium => "medium",
62            ThumbnailSize::Large => "large",
63            ThumbnailSize::Original => "original",
64        }
65    }
66}
67
68/// Cached thumbnail entry.
69///
70/// Access recency is tracked by the enclosing `LruCache` — no explicit
71/// `last_accessed` field. Previously the struct carried an `Instant`
72/// that was set on insert but never bumped on access, so the "LRU"
73/// eviction was effectively FIFO.
74#[derive(Debug, Clone)]
75pub struct ThumbnailEntry {
76    pub path: PathBuf,
77    pub file_size: u64,
78}
79
80/// Maximum number of entries the in-memory cache tracks. Serves as a
81/// backstop against unbounded metadata growth — actual eviction
82/// typically fires from the byte-budget check in `evict_if_needed`
83/// well before the count limit is hit. 10k is plenty for any visible
84/// scrolling window even on huge libraries.
85const CACHE_ENTRY_CAPACITY: usize = 10_000;
86
87/// Concurrent background (prewarm) decodes: half the cores, between 1 and
88/// 3, so at least one of the 4 decode permits stays free for thumbnails the
89/// user is looking at.
90fn background_permits() -> usize {
91    std::thread::available_parallelism()
92        .map(|n| n.get() / 2)
93        .unwrap_or(1)
94        .clamp(1, 3)
95}
96
97/// Blocking concurrency limiter. Callers wait on a condvar until a
98/// permit is free instead of failing fast. The previous `try_acquire`
99/// returned an error when the queue was full — under prewarm load that
100/// surfaced as "Too many concurrent thumbnail generations" for every
101/// foreground IPC request, which the UI reported as a missing thumbnail.
102struct ConcurrencyLimiter {
103    max: usize,
104    max_background: usize,
105    state: Mutex<LimiterState>,
106    cv: Condvar,
107}
108
109#[derive(Debug, Default)]
110struct LimiterState {
111    foreground_active: usize,
112    background_active: usize,
113    foreground_waiting: usize,
114}
115
116#[derive(Debug, Clone, Copy)]
117enum GenerationPriority {
118    Foreground,
119    Background,
120}
121
122impl ConcurrencyLimiter {
123    fn new(max: usize, max_background: usize) -> Self {
124        Self {
125            max,
126            max_background,
127            state: Mutex::new(LimiterState::default()),
128            cv: Condvar::new(),
129        }
130    }
131
132    /// Block until a permit is available, then claim it. Safe to call
133    /// from a `spawn_blocking` worker — Tokio has hundreds of blocking
134    /// threads and parking one is fine.
135    fn acquire(self: &Arc<Self>, priority: GenerationPriority) -> ConcurrencyPermit {
136        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
137        if matches!(priority, GenerationPriority::Foreground) {
138            state.foreground_waiting += 1;
139        }
140
141        loop {
142            let active = state.foreground_active + state.background_active;
143            let can_acquire = match priority {
144                GenerationPriority::Foreground => active < self.max,
145                GenerationPriority::Background => {
146                    active < self.max
147                        && state.background_active < self.max_background
148                        && state.foreground_waiting == 0
149                }
150            };
151
152            if can_acquire {
153                match priority {
154                    GenerationPriority::Foreground => {
155                        state.foreground_waiting = state.foreground_waiting.saturating_sub(1);
156                        state.foreground_active += 1;
157                    }
158                    GenerationPriority::Background => {
159                        state.background_active += 1;
160                    }
161                }
162                break;
163            }
164
165            state = self.cv.wait(state).unwrap_or_else(|e| e.into_inner());
166        }
167
168        ConcurrencyPermit {
169            limiter: self.clone(),
170            priority,
171        }
172    }
173
174    /// Deadline-aware admission for foreground requests. A stuck native
175    /// decoder must not make every later visible request wait forever.
176    fn acquire_for(
177        self: &Arc<Self>,
178        priority: GenerationPriority,
179        timeout: Duration,
180    ) -> Option<ConcurrencyPermit> {
181        let deadline = Instant::now() + timeout;
182        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
183        if matches!(priority, GenerationPriority::Foreground) {
184            state.foreground_waiting += 1;
185        }
186        loop {
187            let active = state.foreground_active + state.background_active;
188            let can_acquire = match priority {
189                GenerationPriority::Foreground => active < self.max,
190                GenerationPriority::Background => {
191                    active < self.max
192                        && state.background_active < self.max_background
193                        && state.foreground_waiting == 0
194                }
195            };
196            if can_acquire {
197                if matches!(priority, GenerationPriority::Foreground) {
198                    state.foreground_waiting = state.foreground_waiting.saturating_sub(1);
199                    state.foreground_active += 1;
200                } else {
201                    state.background_active += 1;
202                }
203                return Some(ConcurrencyPermit {
204                    limiter: self.clone(),
205                    priority,
206                });
207            }
208            let remaining = deadline.saturating_duration_since(Instant::now());
209            if remaining.is_zero() {
210                if matches!(priority, GenerationPriority::Foreground) {
211                    state.foreground_waiting = state.foreground_waiting.saturating_sub(1);
212                }
213                return None;
214            }
215            let (next, timed_out) = self
216                .cv
217                .wait_timeout(state, remaining)
218                .unwrap_or_else(|e| e.into_inner());
219            state = next;
220            if timed_out.timed_out() {
221                if matches!(priority, GenerationPriority::Foreground) {
222                    state.foreground_waiting = state.foreground_waiting.saturating_sub(1);
223                }
224                return None;
225            }
226        }
227    }
228
229    /// Release a permit and wake one waiter.
230    fn release(&self, priority: GenerationPriority) {
231        {
232            let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
233            match priority {
234                GenerationPriority::Foreground => {
235                    state.foreground_active = state.foreground_active.saturating_sub(1);
236                }
237                GenerationPriority::Background => {
238                    state.background_active = state.background_active.saturating_sub(1);
239                }
240            }
241        }
242        self.cv.notify_all();
243    }
244}
245
246struct ConcurrencyPermit {
247    limiter: Arc<ConcurrencyLimiter>,
248    priority: GenerationPriority,
249}
250
251impl Drop for ConcurrencyPermit {
252    fn drop(&mut self) {
253        self.limiter.release(self.priority);
254    }
255}
256
257struct GenerationDeduper {
258    active: Mutex<std::collections::HashSet<String>>,
259    cv: Condvar,
260}
261
262impl GenerationDeduper {
263    fn new() -> Self {
264        Self {
265            active: Mutex::new(std::collections::HashSet::new()),
266            cv: Condvar::new(),
267        }
268    }
269
270    fn enter(self: &Arc<Self>, key: String) -> GenerationGuard {
271        let mut active = self.active.lock().unwrap_or_else(|e| e.into_inner());
272        while active.contains(&key) {
273            active = self.cv.wait(active).unwrap_or_else(|e| e.into_inner());
274        }
275        active.insert(key.clone());
276        GenerationGuard {
277            deduper: self.clone(),
278            key,
279        }
280    }
281
282    fn leave(&self, key: &str) {
283        {
284            let mut active = self.active.lock().unwrap_or_else(|e| e.into_inner());
285            active.remove(key);
286        }
287        self.cv.notify_all();
288    }
289}
290
291struct GenerationGuard {
292    deduper: Arc<GenerationDeduper>,
293    key: String,
294}
295
296impl Drop for GenerationGuard {
297    fn drop(&mut self) {
298        self.deduper.leave(&self.key);
299    }
300}
301
302/// Thumbnail service with LRU cache management
303pub struct ThumbnailService {
304    /// Root path of the drive. The cache folder is looked up from it each
305    /// time (see `cache_location`), so moving the caches to or from this
306    /// computer takes effect without reopening the library.
307    drive_root: PathBuf,
308
309    /// In-memory cache of thumbnail paths. Switched from
310    /// `HashMap + last_accessed Instant` to `LruCache` so eviction is
311    /// O(1) via `pop_lru()` instead of O(n) sort-by-timestamp, and so
312    /// access recency is tracked correctly (the old field was set on
313    /// insert and never updated).
314    cache: Arc<RwLock<LruCache<(String, ThumbnailSize), ThumbnailEntry>>>,
315
316    /// Maximum cache size in bytes
317    max_cache_bytes: u64,
318
319    /// Current cache size in bytes
320    current_cache_bytes: Arc<RwLock<u64>>,
321    // Serialize inventory with publication, not with image decoding or cache hits.
322    accounting: Mutex<()>,
323    /// Serialize directory sweeps so concurrent generators cannot evict from
324    /// stale byte snapshots or race one another's removals.
325    eviction: Mutex<()>,
326
327    /// Concurrency limiter for generation (std::sync for blocking context)
328    generation_limiter: Arc<ConcurrencyLimiter>,
329
330    /// Hash+size keys currently being generated. Duplicate requests wait
331    /// for the first decode and then reuse its output from disk.
332    generating: Arc<GenerationDeduper>,
333}
334
335impl ThumbnailService {
336    /// Create a new thumbnail service for a drive
337    pub fn new<P: AsRef<Path>>(drive_root: P, max_cache_gb: f64) -> std::io::Result<Self> {
338        let drive_root = drive_root.as_ref().to_path_buf();
339        let cache_dir = crate::services::cache_location::thumbnails_dir(&drive_root);
340
341        // Create cache directories for each size
342        for size in [
343            ThumbnailSize::Small,
344            ThumbnailSize::Medium,
345            ThumbnailSize::Large,
346            ThumbnailSize::Original,
347        ] {
348            std::fs::create_dir_all(cache_dir.join(size.dir_name()))?;
349        }
350
351        let max_cache_bytes = (max_cache_gb * 1024.0 * 1024.0 * 1024.0) as u64;
352
353        let capacity = NonZeroUsize::new(CACHE_ENTRY_CAPACITY)
354            .expect("CACHE_ENTRY_CAPACITY is a non-zero compile-time constant");
355
356        Ok(Self {
357            drive_root,
358            cache: Arc::new(RwLock::new(LruCache::new(capacity))),
359            max_cache_bytes,
360            current_cache_bytes: Arc::new(RwLock::new(0)),
361            accounting: Mutex::new(()),
362            eviction: Mutex::new(()),
363            // Cap concurrent decodes at 4. Each large JPEG holds ~50–80 MB
364            // of decoded RGB while resizing — at 8-wide we saw OOM on
365            // mid-spec laptops. 4 keeps the working set under ~320 MB.
366            generation_limiter: Arc::new(ConcurrencyLimiter::new(4, background_permits())),
367            generating: Arc::new(GenerationDeduper::new()),
368        })
369    }
370
371    /// Generate a thumbnail synchronously with a timeout guard.
372    ///
373    /// Call this from a background task (spawn_blocking) after get_thumbnail returns Pending.
374    pub fn generate_thumbnail(
375        &self,
376        photo_path: &Path,
377        file_hash: &str,
378        orientation: i32,
379        size: ThumbnailSize,
380    ) -> Result<PathBuf, String> {
381        self.generate_thumbnail_with_priority(
382            photo_path,
383            file_hash,
384            orientation,
385            size,
386            GenerationPriority::Foreground,
387            false,
388        )
389    }
390
391    pub fn generate_thumbnail_background(
392        &self,
393        photo_path: &Path,
394        file_hash: &str,
395        orientation: i32,
396        size: ThumbnailSize,
397    ) -> Result<PathBuf, String> {
398        self.generate_thumbnail_with_priority(
399            photo_path,
400            file_hash,
401            orientation,
402            size,
403            GenerationPriority::Background,
404            false,
405        )
406    }
407
408    /// Generate background thumbnails for a batch on a few scoped worker
409    /// threads (one per background permit), returning results in input
410    /// order. `None` marks items skipped because `cancel` was set.
411    ///
412    /// Dedicated threads, not Rayon: workers park on the limiter while
413    /// foreground requests run, and parking Rayon's global pool would
414    /// stall face detection and other parallel work sharing it.
415    pub fn generate_background_batch(
416        &self,
417        items: &[(PathBuf, String, i32)],
418        size: ThumbnailSize,
419        force: bool,
420        cancel: &std::sync::atomic::AtomicBool,
421    ) -> Vec<Option<Result<PathBuf, String>>> {
422        use std::sync::atomic::{AtomicUsize, Ordering};
423        let results: Vec<Mutex<Option<Result<PathBuf, String>>>> =
424            items.iter().map(|_| Mutex::new(None)).collect();
425        let next = AtomicUsize::new(0);
426        let workers = background_permits().min(items.len()).max(1);
427        std::thread::scope(|scope| {
428            for _ in 0..workers {
429                scope.spawn(|| loop {
430                    if cancel.load(Ordering::Relaxed) {
431                        break;
432                    }
433                    let index = next.fetch_add(1, Ordering::Relaxed);
434                    let Some((path, hash, orientation)) = items.get(index) else {
435                        break;
436                    };
437                    let result = if force {
438                        self.generate_thumbnail_background_forced(path, hash, *orientation, size)
439                    } else {
440                        self.generate_thumbnail_background(path, hash, *orientation, size)
441                    };
442                    *results[index].lock().unwrap_or_else(|e| e.into_inner()) = Some(result);
443                });
444            }
445        });
446        results
447            .into_iter()
448            .map(|slot| slot.into_inner().unwrap_or_else(|e| e.into_inner()))
449            .collect()
450    }
451
452    /// Background generation that ignores an existing adequate thumbnail —
453    /// used by "regenerate thumbnails" so quality upgrades actually happen
454    /// even though the old (adequate) rendition is still on disk.
455    pub fn generate_thumbnail_background_forced(
456        &self,
457        photo_path: &Path,
458        file_hash: &str,
459        orientation: i32,
460        size: ThumbnailSize,
461    ) -> Result<PathBuf, String> {
462        self.generate_thumbnail_with_priority(
463            photo_path,
464            file_hash,
465            orientation,
466            size,
467            GenerationPriority::Background,
468            true,
469        )
470    }
471
472    fn generate_thumbnail_with_priority(
473        &self,
474        photo_path: &Path,
475        file_hash: &str,
476        orientation: i32,
477        size: ThumbnailSize,
478        priority: GenerationPriority,
479        force: bool,
480    ) -> Result<PathBuf, String> {
481        let thumb_path = self.thumbnail_path(file_hash, size);
482        if !force && self.try_existing_thumbnail(file_hash, size, &thumb_path) {
483            return Ok(thumb_path);
484        }
485
486        let key = format!("{}:{file_hash}", size.dir_name());
487        let _generation = self.generating.enter(key);
488        if !force && self.try_existing_thumbnail(file_hash, size, &thumb_path) {
489            return Ok(thumb_path);
490        }
491
492        let _permit = self.generation_limiter.acquire(priority);
493        let start = Instant::now();
494        self.generate_thumbnail_inner(photo_path, file_hash, orientation, size, start, force)
495    }
496
497    /// Inner thumbnail generation (separated for clean permit release)
498    fn generate_thumbnail_inner(
499        &self,
500        photo_path: &Path,
501        file_hash: &str,
502        orientation: i32,
503        size: ThumbnailSize,
504        start: Instant,
505        force: bool,
506    ) -> Result<PathBuf, String> {
507        // Check if existing thumbnail is adequate quality (not a tiny EXIF extract)
508        let thumb_path = self.thumbnail_path(file_hash, size);
509        if !force && self.try_existing_thumbnail(file_hash, size, &thumb_path) {
510            return Ok(thumb_path);
511        }
512
513        // Keep any old rendition until the replacement is fully encoded.
514
515        // Create the hash subdirectory if it doesn't exist
516        if let Some(parent) = thumb_path.parent() {
517            std::fs::create_dir_all(parent)
518                .map_err(|e| format!("Failed to create thumbnail subdirectory: {}", e))?;
519        }
520
521        // Check timeout before expensive decode
522        if start.elapsed() > THUMBNAIL_TIMEOUT {
523            return Err("Thumbnail generation timed out before decode".to_string());
524        }
525
526        // Strategy 2: Decode with downscale hint for large JPEGs.
527        // The decode runs on a worker thread with a hard timeout: a
528        // `decode()` stuck on a disconnected USB drive would otherwise
529        // hold the limiter permit and the dedupe entry forever, hanging
530        // every requester of that thumbnail. The abandoned thread is
531        // bounded (one per timeout, distinct keys only — the deduper
532        // serializes same-key requests) and its result is dropped.
533        let img = Self::decode_with_timeout(photo_path, size)?;
534        let img = apply_exif_orientation(img, orientation);
535
536        // Check timeout after decode
537        if start.elapsed() > THUMBNAIL_TIMEOUT {
538            return Err("Thumbnail generation timed out after decode".to_string());
539        }
540
541        // Generate thumbnail
542        let thumb = if size == ThumbnailSize::Original {
543            img
544        } else {
545            self.create_thumbnail(&img, size)
546        };
547
548        // Lanczos3 on a huge source can outlive the budget on its own;
549        // fail before paying for the encode as well.
550        if start.elapsed() > THUMBNAIL_TIMEOUT {
551            return Err("Thumbnail generation timed out after resize".to_string());
552        }
553
554        // Save as JPEG. Lower quality at the small end where artifacts
555        // are invisible to the eye anyway, kept high for the viewer-size
556        // Large where compression shows.
557        let quality = match size {
558            ThumbnailSize::Small => 78,
559            ThumbnailSize::Medium => 83,
560            ThumbnailSize::Large => 88,
561            ThumbnailSize::Original => 95,
562        };
563        let mut out =
564            tempfile::NamedTempFile::new_in(thumb_path.parent().expect("cache directory"))
565                .map_err(|e| format!("Failed to create thumbnail file: {}", e))?;
566        let mut encoder = JpegEncoder::new_with_quality(&mut out, quality);
567        encoder
568            .encode_image(&thumb)
569            .map_err(|e| format!("Failed to encode thumbnail: {}", e))?;
570        {
571            // Keep the publication/accounting critical section short. Disk
572            // inventory and eviction can be expensive and must not hold
573            // other generators behind this lock.
574            let _accounting = self
575                .accounting
576                .lock()
577                .unwrap_or_else(|error| error.into_inner());
578            let replaced_bytes = std::fs::metadata(&thumb_path).map(|m| m.len()).unwrap_or(0);
579            out.persist(&thumb_path)
580                .map_err(|e| format!("Failed to publish thumbnail: {e}"))?;
581            if let Ok(mut current) = self.current_cache_bytes.write() {
582                *current = current.saturating_sub(replaced_bytes);
583            }
584        }
585        self.add_to_cache(file_hash, size, &thumb_path);
586        self.track_cache_size(&thumb_path);
587        self.evict_if_needed(Some(&thumb_path));
588
589        Ok(thumb_path)
590    }
591
592    fn try_existing_thumbnail(
593        &self,
594        file_hash: &str,
595        size: ThumbnailSize,
596        thumb_path: &Path,
597    ) -> bool {
598        if !thumb_path.exists() {
599            return false;
600        }
601        let file_size = std::fs::metadata(thumb_path).map(|m| m.len()).unwrap_or(0);
602        if file_size == 0 {
603            return false;
604        }
605        // Most generated thumbnails are >5KB. For simple images (solid
606        // colors, screenshots, graphics), valid JPEGs can be smaller, so
607        // fall back to a cheap dimension check before treating them as stale
608        // tiny EXIF extracts from older cache versions.
609        if file_size <= 5000 && !Self::thumbnail_dimensions_are_adequate(thumb_path, size) {
610            return false;
611        }
612        self.add_to_cache(file_hash, size, thumb_path);
613        true
614    }
615
616    fn thumbnail_dimensions_are_adequate(thumb_path: &Path, size: ThumbnailSize) -> bool {
617        ImageReader::open(thumb_path)
618            .ok()
619            .and_then(|r| r.with_guessed_format().ok())
620            .and_then(|r| r.into_dimensions().ok())
621            .map(|(width, height)| {
622                (size == ThumbnailSize::Original && width > 0 && height > 0)
623                    || width.max(height) >= size.pixels()
624            })
625            .unwrap_or(false)
626    }
627
628    /// Decode an image with fast downscaling for large files.
629    ///
630    /// For JPEGs, the underlying libjpeg can decode at 1/2, 1/4, or 1/8 scale
631    /// natively — much faster than decoding full resolution then resizing.
632    /// HEIC/HEIF route through `services::image_io::open_image` (libheif).
633    fn decode_image_fast(
634        photo_path: &Path,
635        target_size: ThumbnailSize,
636    ) -> Result<DynamicImage, String> {
637        // Route HEIC/HEIF through the format-aware wrapper. The
638        // `image` crate's reader doesn't recognise these formats so we
639        // can't use its guessed-format path; fall back to a full decode
640        // via libheif. For JPEG/PNG/etc, the existing fast path with
641        // alloc limits stays in effect.
642        let ext = photo_path
643            .extension()
644            .and_then(|e| e.to_str())
645            .map(|e| e.to_ascii_lowercase());
646        if matches!(ext.as_deref(), Some("heic") | Some("heif"))
647            || ext
648                .as_deref()
649                .is_some_and(crate::services::image_io::is_raw_extension)
650        {
651            return crate::services::image_io::open_image(photo_path);
652        }
653
654        if matches!(ext.as_deref(), Some("jpg") | Some("jpeg")) {
655            if let Some(img) = Self::decode_embedded_jpeg_thumbnail(photo_path, target_size) {
656                return Ok(img);
657            }
658        }
659
660        let reader =
661            ImageReader::open(photo_path).map_err(|e| format!("Failed to open image: {}", e))?;
662
663        // Use with_guessed_format for proper format detection
664        let reader = reader
665            .with_guessed_format()
666            .map_err(|e| format!("Failed to guess image format: {}", e))?;
667
668        // Memory limit for the decode. The old 200 MB cap silently rejected
669        // large panoramas (~80 Mpx needs ~240 MB as RGB8), and because a failed
670        // thumbnail leaves `thumbnailed = FALSE` the pending-thumbnail banner
671        // could never clear — it just re-ran a pass that failed identically.
672        // 384 MB admits those while still refusing genuinely pathological files.
673        let mut limits = image::Limits::default();
674        limits.max_alloc = Some(384 * 1024 * 1024);
675
676        let mut reader = reader;
677        reader.limits(limits);
678
679        let img = reader
680            .decode()
681            .map_err(|e| format!("Failed to decode image: {}", e))?;
682
683        Ok(img)
684    }
685
686    /// Decode on a worker thread, giving up after the thumbnail timeout.
687    ///
688    /// A blocked read (network drive gone, yanked USB) has no async
689    /// cancellation path in std, so the abandoned thread may finish the
690    /// decode into the void later — that is accepted: it holds no permit
691    /// and no dedupe entry, and the receiver ignores the late result.
692    fn decode_with_timeout(
693        photo_path: &Path,
694        target_size: ThumbnailSize,
695    ) -> Result<DynamicImage, String> {
696        let decoder_permit = DECODER_LIMITER
697            .get_or_init(|| Arc::new(ConcurrencyLimiter::new(8, 8)))
698            .acquire_for(GenerationPriority::Foreground, THUMBNAIL_TIMEOUT)
699            .ok_or_else(|| "thumbnail decoder admission timed out; retry shortly".to_string())?;
700        let (tx, rx) = std::sync::mpsc::channel::<Result<DynamicImage, String>>();
701        let path = photo_path.to_path_buf();
702        std::thread::spawn(move || {
703            let _decoder_permit = decoder_permit;
704            let _ = tx.send(crate::services::image_io::catch_decode(&path, || {
705                Self::decode_image_fast(&path, target_size)
706            }));
707        });
708        match rx.recv_timeout(THUMBNAIL_TIMEOUT) {
709            Ok(result) => result,
710            Err(_) => Err(format!(
711                "decode timed out after {}s (source unreadable?)",
712                THUMBNAIL_TIMEOUT.as_secs()
713            )),
714        }
715    }
716
717    fn decode_embedded_jpeg_thumbnail(
718        photo_path: &Path,
719        target_size: ThumbnailSize,
720    ) -> Option<DynamicImage> {
721        let file = File::open(photo_path).ok()?;
722        let mut reader = BufReader::new(file);
723        let exif = ExifReader::new().read_from_container(&mut reader).ok()?;
724        let offset = exif
725            .get_field(Tag::JPEGInterchangeFormat, In::THUMBNAIL)
726            .and_then(|f| f.value.get_uint(0))? as usize;
727        let len = exif
728            .get_field(Tag::JPEGInterchangeFormatLength, In::THUMBNAIL)
729            .and_then(|f| f.value.get_uint(0))? as usize;
730        let end = offset.checked_add(len)?;
731        let bytes = exif.buf().get(offset..end)?;
732        let img = crate::services::image_io::catch_decode(photo_path, || {
733            image::load_from_memory(bytes).map_err(|e| e.to_string())
734        })
735        .ok()?;
736        let (width, height) = img.dimensions();
737        if width.max(height) < target_size.pixels() {
738            return None;
739        }
740        Some(img)
741    }
742
743    /// Track cache size after adding a thumbnail
744    fn track_cache_size(&self, thumb_path: &Path) {
745        let file_size = std::fs::metadata(thumb_path).map(|m| m.len()).unwrap_or(0);
746        if let Ok(mut current) = self.current_cache_bytes.write() {
747            *current += file_size;
748        }
749    }
750
751    /// Create a thumbnail from an image, maintaining aspect ratio.
752    ///
753    /// Filter choice trades quality for speed:
754    /// - Small (grid): `Triangle` prioritizes inexpensive resampling.
755    /// - Medium: `CatmullRom` keeps edges crisp without Lanczos3's cost.
756    /// - Large (viewer): `Lanczos3` — the user is going to look at this.
757    fn create_thumbnail(&self, img: &DynamicImage, size: ThumbnailSize) -> DynamicImage {
758        if size == ThumbnailSize::Original {
759            return img.clone();
760        }
761        let max_dim = size.pixels();
762        let (width, height) = img.dimensions();
763
764        // Calculate new dimensions maintaining aspect ratio
765        let (new_width, new_height) = if width > height {
766            let ratio = max_dim as f64 / width as f64;
767            (max_dim, (height as f64 * ratio) as u32)
768        } else {
769            let ratio = max_dim as f64 / height as f64;
770            ((width as f64 * ratio) as u32, max_dim)
771        };
772
773        let filter = match size {
774            ThumbnailSize::Small => FilterType::Triangle,
775            ThumbnailSize::Medium => FilterType::CatmullRom,
776            ThumbnailSize::Large => FilterType::Lanczos3,
777            ThumbnailSize::Original => unreachable!("originals are not resized"),
778        };
779        img.resize(new_width, new_height, filter)
780    }
781
782    /// The thumbnail cache folder: in the library, or on this computer.
783    fn cache_dir(&self) -> PathBuf {
784        crate::services::cache_location::thumbnails_dir(&self.drive_root)
785    }
786
787    /// Forget remembered thumbnail locations, after the cache folder moved.
788    pub fn forget_cached_paths(&self) {
789        if let Ok(mut cache) = self.cache.write() {
790            cache.clear();
791        }
792    }
793
794    /// Get the path where a thumbnail should be stored.
795    /// Includes a version segment so quality upgrades trigger regeneration.
796    fn thumbnail_path(&self, file_hash: &str, size: ThumbnailSize) -> PathBuf {
797        // Use first 2 chars of hash as subdirectory (like git)
798        let subdir = &file_hash[..2.min(file_hash.len())];
799
800        self.cache_dir()
801            .join(size.dir_name())
802            .join("v2")
803            .join(subdir)
804            .join(format!("{}.jpg", file_hash))
805    }
806
807    /// Add a thumbnail to the in-memory cache
808    fn add_to_cache(&self, file_hash: &str, size: ThumbnailSize, path: &Path) {
809        let file_size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
810
811        let entry = ThumbnailEntry {
812            path: path.to_path_buf(),
813            file_size,
814        };
815
816        if let Ok(mut cache) = self.cache.write() {
817            cache.put((file_hash.to_string(), size), entry);
818        }
819    }
820
821    /// Evict oldest thumbnails until we're back under 80% of the
822    /// byte budget. LruCache's `pop_lru` gives O(1) access to the
823    /// oldest entry, vs. the previous O(n log n) sort of every
824    /// thumbnail by timestamp.
825    fn evict_if_needed(&self, protected: Option<&Path>) {
826        let _eviction_guard = match self.eviction.lock() {
827            Ok(guard) => guard,
828            Err(_) => return,
829        };
830        let current = match self.current_cache_bytes.read() {
831            Ok(v) => *v,
832            Err(_) => return,
833        };
834
835        if current <= self.max_cache_bytes {
836            return;
837        }
838
839        let target = self.max_cache_bytes * 80 / 100;
840        let mut freed = 0u64;
841
842        // The bounded LRU is only a hot-path index, not a disk inventory.
843        // Evict untracked files first so older cache entries cannot escape
844        // the byte budget after falling out of the in-memory index.
845        let tracked: std::collections::HashSet<PathBuf> = self
846            .cache
847            .read()
848            .map(|cache| cache.iter().map(|(_, entry)| entry.path.clone()).collect())
849            .unwrap_or_default();
850        for size in [
851            ThumbnailSize::Small,
852            ThumbnailSize::Medium,
853            ThumbnailSize::Large,
854            ThumbnailSize::Original,
855        ] {
856            for entry in walkdir::WalkDir::new(self.cache_dir().join(size.dir_name()).join("v2"))
857                .follow_links(false)
858                .follow_root_links(false)
859                .into_iter()
860                .filter_map(Result::ok)
861            {
862                if current.saturating_sub(freed) <= target {
863                    break;
864                }
865                let path = entry.path();
866                if !entry.file_type().is_file()
867                    || path.extension().is_none_or(|ext| ext != "jpg")
868                    || tracked.contains(path)
869                    || protected == Some(path)
870                {
871                    continue;
872                }
873                if let Ok(metadata) = entry.metadata() {
874                    if std::fs::remove_file(path).is_ok() {
875                        freed += metadata.len();
876                    }
877                }
878            }
879        }
880
881        // Pop oldest entries one at a time until we're under target.
882        // The cache lock is held only for the pop; file deletion
883        // happens without it.
884        loop {
885            if current.saturating_sub(freed) <= target {
886                break;
887            }
888            let popped = {
889                let mut cache = match self.cache.write() {
890                    Ok(c) => c,
891                    Err(_) => break,
892                };
893                cache.pop_lru()
894            };
895
896            let Some((key, entry)) = popped else { break };
897            if protected == Some(entry.path.as_path()) {
898                if let Ok(mut cache) = self.cache.write() {
899                    cache.put(key, entry);
900                }
901                break;
902            }
903
904            if std::fs::remove_file(&entry.path).is_ok() {
905                freed += entry.file_size;
906            }
907
908            if current.saturating_sub(freed) <= target {
909                break;
910            }
911        }
912
913        if let Ok(mut current) = self.current_cache_bytes.write() {
914            *current = current.saturating_sub(freed);
915        }
916
917        tracing::info!("Evicted {} bytes from thumbnail cache", freed);
918    }
919
920    /// Scan existing thumbnails on disk and populate cache
921    pub fn load_existing_thumbnails(&self) -> std::io::Result<()> {
922        self.load_existing_thumbnails_until(&std::sync::atomic::AtomicBool::new(false))
923    }
924
925    pub fn load_existing_thumbnails_until(
926        &self,
927        cancel: &std::sync::atomic::AtomicBool,
928    ) -> std::io::Result<()> {
929        // The accounting lock is deliberately *not* held across the walk
930        // below. It is held for the duration of a publish, so holding it
931        // across a full directory scan of the cache (on a slow external
932        // drive, thousands of stats) stalled every thumbnail being written
933        // at the time — which is what made the app appear to freeze while
934        // thumbnails were being produced.
935        let mut total_size = 0u64;
936
937        for size in [
938            ThumbnailSize::Small,
939            ThumbnailSize::Medium,
940            ThumbnailSize::Large,
941            ThumbnailSize::Original,
942        ] {
943            let size_dir = self.cache_dir().join(size.dir_name()).join("v2");
944
945            if !size_dir.exists() {
946                continue;
947            }
948
949            for subdir_entry in std::fs::read_dir(&size_dir)? {
950                let subdir_entry = subdir_entry?;
951                if !subdir_entry.file_type()?.is_dir() {
952                    continue;
953                }
954
955                for file_entry in std::fs::read_dir(subdir_entry.path())? {
956                    if cancel.load(std::sync::atomic::Ordering::Relaxed) {
957                        return Ok(());
958                    }
959                    let file_entry = file_entry?;
960                    if !file_entry.file_type()?.is_file() {
961                        continue;
962                    }
963                    let path = file_entry.path();
964
965                    if path.extension().map(|e| e == "jpg").unwrap_or(false) {
966                        if let Some(stem) = path.file_stem() {
967                            let hash = stem.to_string_lossy().to_string();
968                            let file_size = file_entry.metadata()?.len();
969
970                            total_size += file_size;
971
972                            let entry = ThumbnailEntry {
973                                path: path.clone(),
974                                file_size,
975                            };
976
977                            if let Ok(mut cache) = self.cache.write() {
978                                cache.put((hash, size), entry);
979                            }
980                        }
981                    }
982                }
983            }
984        }
985
986        {
987            let _accounting = self
988                .accounting
989                .lock()
990                .unwrap_or_else(|error| error.into_inner());
991            if let Ok(mut current) = self.current_cache_bytes.write() {
992                *current = total_size;
993            }
994        }
995        self.evict_if_needed(None);
996
997        let count = self.cache.read().map(|c| c.len()).unwrap_or(0);
998        tracing::info!(
999            "Loaded {} existing thumbnails ({} MB)",
1000            count,
1001            total_size / 1024 / 1024
1002        );
1003
1004        Ok(())
1005    }
1006}
1007
1008#[cfg(test)]
1009mod tests {
1010    use super::*;
1011
1012    #[test]
1013    fn inventory_evicts_untracked_files_and_restarts_with_exact_accounting() {
1014        let dir = tempfile::tempdir().unwrap();
1015        let mut service = ThumbnailService::new(dir.path(), 1.0).unwrap();
1016        let folder = service.cache_dir().join("small/v2/ab");
1017        std::fs::create_dir_all(&folder).unwrap();
1018        for i in 0..CACHE_ENTRY_CAPACITY + 5 {
1019            std::fs::write(folder.join(format!("ab{i:08x}.jpg")), [1u8]).unwrap();
1020        }
1021        service.load_existing_thumbnails().unwrap();
1022        assert_eq!(service.cache.read().unwrap().len(), CACHE_ENTRY_CAPACITY);
1023        // Remove memory tracking to reproduce the worst case: all disk
1024        // entries have fallen out of the bounded LRU.
1025        service.cache.write().unwrap().clear();
1026        service.max_cache_bytes = 10;
1027        service.evict_if_needed(None);
1028        let remaining = std::fs::read_dir(&folder).unwrap().count() as u64;
1029        assert!(remaining <= 8);
1030        assert_eq!(*service.current_cache_bytes.read().unwrap(), remaining);
1031        service.load_existing_thumbnails().unwrap();
1032        assert_eq!(*service.current_cache_bytes.read().unwrap(), remaining);
1033    }
1034
1035    #[test]
1036    fn repeated_inventory_does_not_double_count_published_renditions() {
1037        let dir = tempfile::tempdir().unwrap();
1038        let source = dir.path().join("source.png");
1039        DynamicImage::new_rgb8(48, 32).save(&source).unwrap();
1040        let service = ThumbnailService::new(dir.path(), 1.0).unwrap();
1041        let path = service
1042            .generate_thumbnail(&source, "abcdef12", 1, ThumbnailSize::Original)
1043            .unwrap();
1044        let size = std::fs::metadata(path).unwrap().len();
1045        service.load_existing_thumbnails().unwrap();
1046        service.load_existing_thumbnails().unwrap();
1047        assert_eq!(*service.current_cache_bytes.read().unwrap(), size);
1048    }
1049    use tempfile::tempdir;
1050
1051    #[test]
1052    fn test_thumbnail_path_generation() {
1053        let temp = tempdir().unwrap();
1054        let service = ThumbnailService::new(temp.path(), 1.0).unwrap();
1055
1056        let path = service.thumbnail_path("abcdef123456", ThumbnailSize::Medium);
1057
1058        assert!(path.to_string_lossy().contains("medium"));
1059        assert!(path.to_string_lossy().contains("ab")); // subdir
1060        assert!(path.to_string_lossy().contains("abcdef123456.jpg"));
1061    }
1062
1063    #[test]
1064    fn test_thumbnail_sizes() {
1065        assert_eq!(ThumbnailSize::Small.pixels(), 260);
1066        assert_eq!(ThumbnailSize::Medium.pixels(), 430);
1067        assert_eq!(ThumbnailSize::Large.pixels(), 860);
1068    }
1069
1070    #[test]
1071    fn test_cache_directories_created() {
1072        let temp = tempdir().unwrap();
1073        let _service = ThumbnailService::new(temp.path(), 1.0).unwrap();
1074
1075        assert!(temp.path().join(".photovault/thumbnails/small").exists());
1076        assert!(temp.path().join(".photovault/thumbnails/medium").exists());
1077        assert!(temp.path().join(".photovault/thumbnails/large").exists());
1078    }
1079
1080    #[test]
1081    fn small_but_dimensionally_valid_thumbnail_is_reused() {
1082        let temp = tempdir().unwrap();
1083        let service = ThumbnailService::new(temp.path(), 1.0).unwrap();
1084        let path = service.thumbnail_path("abcdef123456", ThumbnailSize::Small);
1085        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1086        DynamicImage::new_rgb8(ThumbnailSize::Small.pixels(), ThumbnailSize::Small.pixels())
1087            .save(&path)
1088            .unwrap();
1089
1090        assert!(std::fs::metadata(&path).unwrap().len() <= 5000);
1091        assert!(service.try_existing_thumbnail("abcdef123456", ThumbnailSize::Small, &path));
1092    }
1093
1094    #[test]
1095    fn test_generation_deduper_serializes_same_key() {
1096        let deduper = Arc::new(GenerationDeduper::new());
1097        let first = deduper.enter("medium:abc".into());
1098        let (tx, rx) = std::sync::mpsc::channel();
1099        let deduper_for_thread = deduper.clone();
1100
1101        let handle = std::thread::spawn(move || {
1102            let _second = deduper_for_thread.enter("medium:abc".into());
1103            tx.send(()).unwrap();
1104        });
1105
1106        assert!(rx.recv_timeout(Duration::from_millis(50)).is_err());
1107        drop(first);
1108        assert!(rx.recv_timeout(Duration::from_secs(1)).is_ok());
1109        handle.join().unwrap();
1110    }
1111
1112    #[test]
1113    fn test_concurrency_limiter_blocks_until_release() {
1114        use std::sync::Arc;
1115        use std::thread;
1116        use std::time::Duration;
1117
1118        let limiter = Arc::new(ConcurrencyLimiter::new(1, 1));
1119        let permit = limiter.acquire(GenerationPriority::Foreground);
1120
1121        // Second acquire should block. Spawn a thread that waits on
1122        // it, then release from the main thread after a short delay
1123        // and confirm the thread woke up.
1124        let l = limiter.clone();
1125        let started = Arc::new(std::sync::atomic::AtomicBool::new(false));
1126        let s = started.clone();
1127        let handle = thread::spawn(move || {
1128            l.acquire(GenerationPriority::Foreground);
1129            s.store(true, std::sync::atomic::Ordering::Release);
1130        });
1131
1132        thread::sleep(Duration::from_millis(20));
1133        assert!(!started.load(std::sync::atomic::Ordering::Acquire));
1134
1135        drop(permit);
1136        handle.join().unwrap();
1137        assert!(started.load(std::sync::atomic::Ordering::Acquire));
1138    }
1139
1140    #[test]
1141    fn test_background_generation_is_capped() {
1142        use std::sync::mpsc;
1143        use std::sync::Arc;
1144        use std::thread;
1145        use std::time::Duration;
1146
1147        let limiter = Arc::new(ConcurrencyLimiter::new(4, 1));
1148        let permit = limiter.acquire(GenerationPriority::Background);
1149
1150        let (tx, rx) = mpsc::channel();
1151        let l = limiter.clone();
1152        let handle = thread::spawn(move || {
1153            let _permit = l.acquire(GenerationPriority::Background);
1154            tx.send(()).unwrap();
1155        });
1156
1157        thread::sleep(Duration::from_millis(20));
1158        assert!(rx.try_recv().is_err());
1159
1160        drop(permit);
1161        rx.recv_timeout(Duration::from_secs(1)).unwrap();
1162        handle.join().unwrap();
1163    }
1164
1165    #[test]
1166    fn test_waiting_foreground_generation_preempts_background() {
1167        use std::sync::mpsc;
1168        use std::sync::Arc;
1169        use std::thread;
1170        use std::time::Duration;
1171
1172        let limiter = Arc::new(ConcurrencyLimiter::new(1, 1));
1173        let permit = limiter.acquire(GenerationPriority::Background);
1174
1175        let (tx, rx) = mpsc::channel();
1176        let l = limiter.clone();
1177        let tx_foreground = tx.clone();
1178        let foreground = thread::spawn(move || {
1179            let _permit = l.acquire(GenerationPriority::Foreground);
1180            tx_foreground.send("foreground").unwrap();
1181        });
1182
1183        // Synchronize on the admission state itself instead of guessing how
1184        // long the spawned waiter needs to reach the condition variable.
1185        let deadline = std::time::Instant::now() + Duration::from_secs(1);
1186        loop {
1187            if limiter.state.lock().unwrap().foreground_waiting == 1 {
1188                break;
1189            }
1190            assert!(
1191                std::time::Instant::now() < deadline,
1192                "foreground waiter did not enter admission"
1193            );
1194            thread::yield_now();
1195        }
1196
1197        let l = limiter.clone();
1198        let background = thread::spawn(move || {
1199            let _permit = l.acquire(GenerationPriority::Background);
1200            tx.send("background").unwrap();
1201        });
1202
1203        assert!(rx.try_recv().is_err());
1204
1205        drop(permit);
1206        assert_eq!(
1207            rx.recv_timeout(Duration::from_secs(1)).unwrap(),
1208            "foreground"
1209        );
1210        assert_eq!(
1211            rx.recv_timeout(Duration::from_secs(1)).unwrap(),
1212            "background"
1213        );
1214
1215        foreground.join().unwrap();
1216        background.join().unwrap();
1217    }
1218}