forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB2b1c4a3Tahinli3 months ago487 commits

lib.rs440 lines, 14.8 KiBHistoryRawDownload
1//! Compatibility shim carrying the `image` name and version, over
2//! [`ec_image`].
3//!
4//! Only the surface a caller in this family actually consumes is here. edith's
5//! engine uses exactly:
6//!
7//! ```text
8//! image::ImageReader::open(path)?.with_guessed_format()?.decode()?.to_rgb8()
9//! image::ImageReader::open(path)?.with_guessed_format()?.into_dimensions()?
10//! image::open(path)?.to_rgb8().get_pixel(x, y).0 (engine test suite)
11//! ```
12//!
13//! so `ImageReader`, `DynamicImage` and the three 8-bit buffer types are the
14//! whole shim. Anything else the upstream crate exposes is deliberately
15//! absent, so a new use shows up as a compile error rather than as silently
16//! different behaviour.
17//!
18//! **Not covered, deliberately:** the *app* crate's `RgbaImage::from_raw` /
19//! `Frame::new` pair feeds `gpui::RenderImage`, which is typed against the
20//! real `image` crate gpui itself depends on. Those two call sites cannot be
21//! served by a shim — a `[patch.crates-io]` swap would retype gpui's own
22//! dependency as well. The engine must therefore take this crate by rename
23//! (`image = { package = "ec-image-shim", path = ... }`) or the app must keep
24//! the real crate; the swap is not a blanket patch. See the S40 report.
25//!
26//! Behaviour differences from `image` 0.25.10, all consequences of the decoder
27//! underneath and none of them reached by the surface above:
28//!
29//! - Only PNG, JPEG and WebP decode — the formats edith's `is_image` admits.
30//! - EXIF orientation is parsed and exposed, not applied, exactly as upstream.
31//! - JPEG samples may differ from upstream's by up to 4 counts of 255, an
32//! IDCT-rounding difference the format explicitly permits; PNG and lossless
33//! WebP are pixel-exact.
34
35#![forbid(unsafe_code)]
36#![warn(missing_docs)]
37
38use std::fmt;
39use std::path::Path;
40
41/// Failure of a decode, as `image::ImageError`.
42#[derive(Debug)]
43pub enum ImageError {
44 /// The bytes are not a valid image of their format.
45 Decoding(String),
46 /// The format, or something in it, is not supported.
47 Unsupported(String),
48 /// Underlying I/O failure.
49 IoError(std::io::Error),
50}
51
52impl fmt::Display for ImageError {
53 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54 match self {
55 ImageError::Decoding(m) => write!(f, "Format error decoding image: {m}"),
56 ImageError::Unsupported(m) => write!(f, "The image format is not supported: {m}"),
57 ImageError::IoError(e) => write!(f, "{e}"),
58 }
59 }
60}
61
62impl std::error::Error for ImageError {
63 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
64 match self {
65 ImageError::IoError(e) => Some(e),
66 _ => None,
67 }
68 }
69}
70
71impl From<std::io::Error> for ImageError {
72 fn from(e: std::io::Error) -> ImageError {
73 ImageError::IoError(e)
74 }
75}
76
77impl From<ec_image::Error> for ImageError {
78 fn from(e: ec_image::Error) -> ImageError {
79 match e {
80 ec_image::Error::Io(e) => ImageError::IoError(e),
81 ec_image::Error::Unsupported { what, why } => {
82 ImageError::Unsupported(format!("{what}: {why}"))
83 }
84 other => ImageError::Decoding(other.to_string()),
85 }
86 }
87}
88
89/// The result of a decode, as `image::ImageResult`.
90pub type ImageResult<T> = Result<T, ImageError>;
91
92/// The formats this build decodes.
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub enum ImageFormat {
95 /// PNG.
96 Png,
97 /// JPEG.
98 Jpeg,
99 /// WebP.
100 WebP,
101}
102
103/// One 8-bit greyscale pixel.
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub struct Luma(pub [u8; 1]);
106/// One 8-bit R,G,B pixel.
107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108pub struct Rgb(pub [u8; 3]);
109/// One 8-bit R,G,B,A pixel.
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
111pub struct Rgba(pub [u8; 4]);
112
113/// Generates the three concrete buffer types the surface uses. Upstream has
114/// one generic `ImageBuffer`; three concrete types cover every consumed call
115/// without dragging a pixel-trait hierarchy in behind them.
116macro_rules! buffer {
117 ($name:ident, $pixel:ident, $channels:expr, $doc:literal) => {
118 #[doc = $doc]
119 #[derive(Debug, Clone, PartialEq, Eq)]
120 pub struct $name {
121 width: u32,
122 height: u32,
123 data: Vec<u8>,
124 }
125
126 impl $name {
127 /// A buffer over `data`, or `None` when it is not
128 #[doc = concat!(stringify!($channels), " bytes per pixel.")]
129 pub fn from_raw(width: u32, height: u32, data: Vec<u8>) -> Option<$name> {
130 let needed = (width as usize)
131 .checked_mul(height as usize)?
132 .checked_mul($channels)?;
133 (data.len() >= needed).then_some($name {
134 width,
135 height,
136 data,
137 })
138 }
139
140 /// `(width, height)`.
141 pub fn dimensions(&self) -> (u32, u32) {
142 (self.width, self.height)
143 }
144
145 /// Width in pixels.
146 pub fn width(&self) -> u32 {
147 self.width
148 }
149
150 /// Height in pixels.
151 pub fn height(&self) -> u32 {
152 self.height
153 }
154
155 /// The pixel at `(x, y)`; panics when it is outside the image, as
156 /// upstream's does.
157 pub fn get_pixel(&self, x: u32, y: u32) -> $pixel {
158 assert!(
159 x < self.width && y < self.height,
160 "({x}, {y}) is outside a {}x{} image",
161 self.width,
162 self.height
163 );
164 let at = ((y as usize) * (self.width as usize) + x as usize) * $channels;
165 let mut pixel = [0u8; $channels];
166 pixel.copy_from_slice(&self.data[at..at + $channels]);
167 $pixel(pixel)
168 }
169
170 /// The samples, packed.
171 pub fn as_raw(&self) -> &Vec<u8> {
172 &self.data
173 }
174
175 /// The samples, taken by value.
176 pub fn into_raw(self) -> Vec<u8> {
177 self.data
178 }
179
180 /// The samples as a slice.
181 pub fn into_vec(self) -> Vec<u8> {
182 self.data
183 }
184 }
185
186 impl std::ops::Deref for $name {
187 type Target = [u8];
188 fn deref(&self) -> &[u8] {
189 &self.data
190 }
191 }
192 };
193}
194
195buffer!(GrayImage, Luma, 1, "An 8-bit greyscale image buffer.");
196buffer!(RgbImage, Rgb, 3, "An 8-bit RGB image buffer.");
197buffer!(RgbaImage, Rgba, 4, "An 8-bit RGBA image buffer.");
198
199/// A decoded image of whichever colour form its file carried.
200#[derive(Debug, Clone, PartialEq)]
201pub enum DynamicImage {
202 /// 8-bit greyscale.
203 ImageLuma8(GrayImage),
204 /// 8-bit RGB.
205 ImageRgb8(RgbImage),
206 /// 8-bit RGBA.
207 ImageRgba8(RgbaImage),
208}
209
210impl DynamicImage {
211 fn from_decoded(image: ec_image::Image) -> DynamicImage {
212 let (w, h) = (image.width, image.height);
213 match &image.pixels {
214 ec_image::Pixels::L8(data) => DynamicImage::ImageLuma8(
215 GrayImage::from_raw(w, h, data.clone()).expect("plane sized by the decoder"),
216 ),
217 ec_image::Pixels::Rgb8(data) => DynamicImage::ImageRgb8(
218 RgbImage::from_raw(w, h, data.clone()).expect("plane sized by the decoder"),
219 ),
220 _ if image.pixels.has_alpha() => DynamicImage::ImageRgba8(
221 RgbaImage::from_raw(w, h, image.to_rgba8()).expect("plane sized by the decoder"),
222 ),
223 _ => DynamicImage::ImageRgb8(
224 RgbImage::from_raw(w, h, image.to_rgb8()).expect("plane sized by the decoder"),
225 ),
226 }
227 }
228
229 /// `(width, height)`.
230 pub fn dimensions(&self) -> (u32, u32) {
231 match self {
232 DynamicImage::ImageLuma8(b) => b.dimensions(),
233 DynamicImage::ImageRgb8(b) => b.dimensions(),
234 DynamicImage::ImageRgba8(b) => b.dimensions(),
235 }
236 }
237
238 /// Width in pixels.
239 pub fn width(&self) -> u32 {
240 self.dimensions().0
241 }
242
243 /// Height in pixels.
244 pub fn height(&self) -> u32 {
245 self.dimensions().1
246 }
247
248 /// The image as 8-bit RGB, dropping any alpha channel.
249 pub fn to_rgb8(&self) -> RgbImage {
250 let (w, h) = self.dimensions();
251 let data = match self {
252 DynamicImage::ImageRgb8(b) => return b.clone(),
253 DynamicImage::ImageLuma8(b) => b.data.iter().flat_map(|&l| [l, l, l]).collect(),
254 DynamicImage::ImageRgba8(b) => b
255 .data
256 .chunks_exact(4)
257 .flat_map(|p| p[..3].to_vec())
258 .collect(),
259 };
260 RgbImage::from_raw(w, h, data).expect("converted plane")
261 }
262
263 /// The image as 8-bit RGBA; opaque where the source had no alpha.
264 pub fn to_rgba8(&self) -> RgbaImage {
265 let (w, h) = self.dimensions();
266 let data = match self {
267 DynamicImage::ImageRgba8(b) => return b.clone(),
268 DynamicImage::ImageLuma8(b) => b.data.iter().flat_map(|&l| [l, l, l, 255]).collect(),
269 DynamicImage::ImageRgb8(b) => b
270 .data
271 .chunks_exact(3)
272 .flat_map(|p| [p[0], p[1], p[2], 255])
273 .collect(),
274 };
275 RgbaImage::from_raw(w, h, data).expect("converted plane")
276 }
277
278 /// The image as 8-bit greyscale, by the same luma weights upstream uses.
279 pub fn to_luma8(&self) -> GrayImage {
280 let (w, h) = self.dimensions();
281 let data = match self {
282 DynamicImage::ImageLuma8(b) => return b.clone(),
283 _ => self
284 .to_rgb8()
285 .data
286 .chunks_exact(3)
287 .map(|p| {
288 let luma =
289 2126 * u32::from(p[0]) + 7152 * u32::from(p[1]) + 722 * u32::from(p[2]);
290 ((luma + 5000) / 10000).min(255) as u8
291 })
292 .collect(),
293 };
294 GrayImage::from_raw(w, h, data).expect("converted plane")
295 }
296}
297
298/// A decoder that guesses its format from the bytes, as `image::ImageReader`.
299///
300/// Upstream is generic over any `BufRead + Seek`; this reads the whole file
301/// once, because every caller in this family hands it a path and then decodes
302/// the whole picture anyway.
303#[derive(Debug)]
304pub struct ImageReader {
305 data: Vec<u8>,
306 format: Option<ImageFormat>,
307}
308
309impl ImageReader {
310 /// Open `path` for decoding. The format is not guessed yet.
311 pub fn open(path: impl AsRef<Path>) -> std::io::Result<ImageReader> {
312 Ok(ImageReader {
313 data: std::fs::read(path)?,
314 format: None,
315 })
316 }
317
318 /// A reader over bytes already in memory.
319 pub fn new(data: Vec<u8>) -> ImageReader {
320 ImageReader { data, format: None }
321 }
322
323 /// Guess the format from the leading bytes.
324 ///
325 /// Upstream returns an I/O error here because it may have to read; an
326 /// unrecognised signature is not an error at this point in either crate —
327 /// it surfaces at `decode`.
328 pub fn with_guessed_format(mut self) -> std::io::Result<ImageReader> {
329 self.format = ec_image::ImageFormat::guess(&self.data).map(|f| match f {
330 ec_image::ImageFormat::Png => ImageFormat::Png,
331 ec_image::ImageFormat::Jpeg => ImageFormat::Jpeg,
332 ec_image::ImageFormat::WebP => ImageFormat::WebP,
333 });
334 Ok(self)
335 }
336
337 /// The format, once guessed or set.
338 pub fn format(&self) -> Option<ImageFormat> {
339 self.format
340 }
341
342 /// Decode the whole picture.
343 pub fn decode(self) -> ImageResult<DynamicImage> {
344 Ok(DynamicImage::from_decoded(ec_image::decode(&self.data)?))
345 }
346
347 /// The dimensions from the header alone, without decoding the pixels.
348 pub fn into_dimensions(self) -> ImageResult<(u32, u32)> {
349 let info = ec_image::info(&self.data)?;
350 Ok((info.width, info.height))
351 }
352}
353
354/// Decode the file at `path`.
355pub fn open(path: impl AsRef<Path>) -> ImageResult<DynamicImage> {
356 let data = std::fs::read(path)?;
357 load_from_memory(&data)
358}
359
360/// Decode bytes already in memory.
361pub fn load_from_memory(data: &[u8]) -> ImageResult<DynamicImage> {
362 Ok(DynamicImage::from_decoded(ec_image::decode(data)?))
363}
364
365#[cfg(test)]
366mod tests {
367 use super::*;
368 use std::path::PathBuf;
369
370 fn fixtures() -> PathBuf {
371 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/stills")
372 }
373
374 /// The exact sequence edith's engine performs, start to finish.
375 #[test]
376 fn the_engine_call_sequence_works() {
377 let path = fixtures().join("rgb8.png");
378 if !path.exists() {
379 eprintln!("skipped: fixtures/stills not generated");
380 return;
381 }
382 let reader = ImageReader::open(&path).expect("open");
383 let rgb = reader
384 .with_guessed_format()
385 .expect("guess")
386 .decode()
387 .map_err(|e| format!("{}: {e}", path.display()))
388 .expect("decode")
389 .to_rgb8();
390 let (width, height) = rgb.dimensions();
391 assert_eq!((width, height), (320, 240));
392 assert_eq!(rgb.len(), 320 * 240 * 3, "Deref reaches the samples");
393
394 let dimensions = ImageReader::open(&path)
395 .unwrap()
396 .with_guessed_format()
397 .unwrap()
398 .into_dimensions()
399 .expect("dimensions");
400 assert_eq!(dimensions, (320, 240));
401
402 let pixel = open(&path).expect("open").to_rgb8().get_pixel(7, 9).0;
403 assert_eq!(pixel.len(), 3);
404 }
405
406 #[test]
407 fn a_missing_file_is_an_io_error_the_caller_can_propagate() {
408 let err = ImageReader::open(fixtures().join("nope.png")).unwrap_err();
409 assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
410 let err: ImageError = err.into();
411 assert!(matches!(err, ImageError::IoError(_)), "{err}");
412 }
413
414 #[test]
415 fn a_file_that_is_not_an_image_fails_at_decode_not_at_guess() {
416 let reader = ImageReader::new(b"not a picture at all".to_vec())
417 .with_guessed_format()
418 .expect("guessing never fails on unknown bytes");
419 assert_eq!(reader.format(), None);
420 assert!(matches!(reader.decode(), Err(ImageError::Unsupported(_))));
421 }
422
423 #[test]
424 fn alpha_survives_and_grey_stays_grey() {
425 let dir = fixtures();
426 if !dir.join("rgba8.png").exists() {
427 eprintln!("skipped: fixtures/stills not generated");
428 return;
429 }
430 let rgba = open(dir.join("rgba8.png")).unwrap();
431 assert!(matches!(rgba, DynamicImage::ImageRgba8(_)));
432 let grey = open(dir.join("gray8.png")).unwrap();
433 assert!(matches!(grey, DynamicImage::ImageLuma8(_)));
434 // to_rgb8 of a grey image repeats the luma into all three channels.
435 let rgb = grey.to_rgb8();
436 let p = rgb.get_pixel(3, 3).0;
437 assert_eq!(p[0], p[1]);
438 assert_eq!(p[1], p[2]);
439 }
440}