smriti/services/
image_io.rs1use std::path::Path;
17
18use image::DynamicImage;
19
20pub 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
30pub fn open_image(path: &Path) -> Result<DynamicImage, String> {
38 catch_decode(path, || open_image_unguarded(path))
39}
40
41pub 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
67pub 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#[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}