Skip to main content

smriti/services/
image_io.rs

1//! Format-aware image opening.
2//!
3//! Wraps `image::open` so:
4//!   - HEIC/HEIF (every modern iPhone photo) decodes through libheif
5//!     when the `heic` Cargo feature is enabled, fails clearly
6//!     otherwise.
7//!   - RAW (NEF / CR2 / ARW / DNG / ORF / RW2 / PEF / RWL / SRW via the
8//!     TIFF walker; CR3 and RAF via their own containers) decodes via the
9//!     camera's embedded full-res JPEG preview when the `raw` feature is
10//!     on (default).
11//!   - Everything else falls through to the `image` crate.
12//!
13//! Call this from any code path that previously did `image::open(...)`
14//! — thumbnail generation, face detection, brightness sampling.
15
16use std::path::Path;
17
18use image::DynamicImage;
19
20/// Formats that need conversion before display in the system WebView.
21pub fn needs_display_rendition(path: &Path) -> bool {
22    let ext = path
23        .extension()
24        .and_then(|value| value.to_str())
25        .unwrap_or("")
26        .to_ascii_lowercase();
27    is_raw_extension(&ext) || matches!(ext.as_str(), "raf" | "heic" | "heif" | "tif" | "tiff")
28}
29
30/// Open and decode an image. Returns a fully-decoded `DynamicImage`
31/// regardless of the on-disk format. HEIC/HEIF route through libheif
32/// when compiled in; RAW files route through `raw_preview` to extract
33/// the embedded full-res JPEG preview (the camera's intended
34/// rendering, much better than software-debayered output without
35/// proprietary colour profiles); everything else uses the `image`
36/// crate's native decoders.
37pub fn open_image(path: &Path) -> Result<DynamicImage, String> {
38    catch_decode(path, || open_image_unguarded(path))
39}
40
41/// Run a decoder, turning a panic inside it into an ordinary error.
42///
43/// Image, HEIC and RAW decoders are fed arbitrary files from users'
44/// drives; one malformed file must fail that file, not the job or the
45/// app. The panic hook still records the panic in the crash log.
46pub fn catch_decode<T>(
47    path: &Path,
48    decode: impl FnOnce() -> Result<T, String>,
49) -> Result<T, String> {
50    std::panic::catch_unwind(std::panic::AssertUnwindSafe(decode))
51        .unwrap_or_else(|_| Err(format!("decoder crashed on {}", path.display())))
52}
53
54fn open_image_unguarded(path: &Path) -> Result<DynamicImage, String> {
55    let ext = path
56        .extension()
57        .and_then(|e| e.to_str())
58        .map(|e| e.to_ascii_lowercase());
59
60    match ext.as_deref() {
61        Some("heic") | Some("heif") => decode_heic(path),
62        Some(e) if is_raw_extension(e) => decode_raw_via_preview(path),
63        _ => image::open(path).map_err(|e| e.to_string()),
64    }
65}
66
67/// Recognises every TIFF-based RAW we route through the embedded-JPEG
68/// path. Kept in sync with `scanner::SUPPORTED_EXTENSIONS` and
69/// `reindexer`'s extension allowlist — adding a new RAW extension
70/// means touching this list too.
71pub fn is_raw_extension(e: &str) -> bool {
72    matches!(
73        e,
74        "nef" | "cr2" | "cr3" | "arw" | "dng" | "orf" | "rw2" | "pef" | "rwl" | "srw" | "raf"
75    )
76}
77
78/// Bytes of the embedded JPEG preview for any supported RAW: CR3 and RAF
79/// have their own containers, everything else is TIFF-based.
80#[cfg(feature = "raw")]
81pub fn raw_preview_jpeg(path: &Path) -> Result<Option<Vec<u8>>, String> {
82    let ext = path
83        .extension()
84        .and_then(|e| e.to_str())
85        .map(|e| e.to_ascii_lowercase());
86    match ext.as_deref() {
87        Some("cr3") => crate::services::raw_containers::cr3_preview(path),
88        Some("raf") => crate::services::raw_containers::raf_preview(path),
89        _ => crate::services::raw_preview::extract_largest_preview(path),
90    }
91}
92
93#[cfg(feature = "raw")]
94fn decode_raw_via_preview(path: &Path) -> Result<DynamicImage, String> {
95    let jpeg_bytes = raw_preview_jpeg(path)
96        .map_err(|e| format!("RAW preview lookup failed for {}: {}", path.display(), e))?
97        .ok_or_else(|| {
98            format!(
99                "RAW has no embedded JPEG preview: {}. Full-RAW Bayer decode is not supported in this build.",
100                path.display()
101            )
102        })?;
103    image::load_from_memory(&jpeg_bytes).map_err(|e| {
104        format!(
105            "embedded JPEG preview in {} is invalid: {}",
106            path.display(),
107            e
108        )
109    })
110}
111
112#[cfg(not(feature = "raw"))]
113fn decode_raw_via_preview(path: &Path) -> Result<DynamicImage, String> {
114    Err(format!(
115        "RAW support not compiled in (rebuild with --features raw to decode {})",
116        path.display()
117    ))
118}
119
120#[cfg(feature = "heic")]
121fn decode_heic(path: &Path) -> Result<DynamicImage, String> {
122    use libheif_rs::{ColorSpace, HeifContext, LibHeif, RgbChroma};
123
124    let lib = LibHeif::new();
125    let ctx = HeifContext::read_from_file(
126        path.to_str()
127            .ok_or_else(|| format!("non-UTF8 HEIC path: {}", path.display()))?,
128    )
129    .map_err(|e| format!("HeifContext::read_from_file failed: {}", e))?;
130    let handle = ctx
131        .primary_image_handle()
132        .map_err(|e| format!("HEIC primary_image_handle: {}", e))?;
133    let img = lib
134        .decode(&handle, ColorSpace::Rgb(RgbChroma::Rgb), None)
135        .map_err(|e| format!("HEIC decode: {}", e))?;
136
137    let planes = img.planes();
138    let plane = planes
139        .interleaved
140        .ok_or_else(|| "HEIC: missing interleaved RGB plane".to_string())?;
141    let (w, h) = (plane.width as u32, plane.height as u32);
142    let stride = plane.stride;
143    let mut buf = Vec::with_capacity((w as usize) * (h as usize) * 3);
144    for y in 0..(h as usize) {
145        let row_start = y * stride;
146        let row_end = row_start + (w as usize) * 3;
147        if row_end > plane.data.len() {
148            return Err(format!(
149                "HEIC: RGB plane too short at row {} (need {}, have {})",
150                y,
151                row_end,
152                plane.data.len()
153            ));
154        }
155        buf.extend_from_slice(&plane.data[row_start..row_end]);
156    }
157    image::RgbImage::from_raw(w, h, buf)
158        .map(DynamicImage::ImageRgb8)
159        .ok_or_else(|| "HEIC: RGB buffer size mismatch".to_string())
160}
161
162#[cfg(not(feature = "heic"))]
163fn decode_heic(path: &Path) -> Result<DynamicImage, String> {
164    Err(format!(
165        "HEIC support not compiled in (rebuild with --features heic to decode {})",
166        path.display()
167    ))
168}