forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9448d3cTahinli2 months ago3799 commits

lib.rs488 lines, 16.4 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#[cfg(feature = "gpui")]
42pub mod gpui;
43// The names gpui writes as `image::...`; upstream has them at the crate root,
44// so the feature's module is flattened into it.
45#[cfg(feature = "gpui")]
46pub use gpui::{
47 AnimationDecoder, Delay, Frame, Frames, ImageDecoder, codecs, guess_format,
48 load_from_memory_with_format,
49};
50/// Upstream's one generic buffer type. Every caller behind the `gpui` feature
51/// instantiates it at RGBA8, so that is what the name means here.
52#[cfg(feature = "gpui")]
53pub type ImageBuffer = RgbaImage;
54
55/// Failure of a decode, as `image::ImageError`.
56#[derive(Debug)]
57pub enum ImageError {
58 /// The bytes are not a valid image of their format.
59 Decoding(String),
60 /// The format, or something in it, is not supported.
61 Unsupported(String),
62 /// Underlying I/O failure.
63 IoError(std::io::Error),
64}
65
66impl fmt::Display for ImageError {
67 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68 match self {
69 ImageError::Decoding(m) => write!(f, "Format error decoding image: {m}"),
70 ImageError::Unsupported(m) => write!(f, "The image format is not supported: {m}"),
71 ImageError::IoError(e) => write!(f, "{e}"),
72 }
73 }
74}
75
76impl std::error::Error for ImageError {
77 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
78 match self {
79 ImageError::IoError(e) => Some(e),
80 _ => None,
81 }
82 }
83}
84
85impl From<std::io::Error> for ImageError {
86 fn from(e: std::io::Error) -> ImageError {
87 ImageError::IoError(e)
88 }
89}
90
91impl From<ec_image::Error> for ImageError {
92 fn from(e: ec_image::Error) -> ImageError {
93 match e {
94 ec_image::Error::Io(e) => ImageError::IoError(e),
95 ec_image::Error::Unsupported { what, why } => {
96 ImageError::Unsupported(format!("{what}: {why}"))
97 }
98 other => ImageError::Decoding(other.to_string()),
99 }
100 }
101}
102
103/// The result of a decode, as `image::ImageResult`.
104pub type ImageResult<T> = Result<T, ImageError>;
105
106/// The formats this build decodes.
107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108pub enum ImageFormat {
109 /// PNG.
110 Png,
111 /// JPEG.
112 Jpeg,
113 /// WebP.
114 WebP,
115 /// GIF.
116 #[cfg(feature = "gpui")]
117 Gif,
118 /// Windows bitmap.
119 #[cfg(feature = "gpui")]
120 Bmp,
121 /// TIFF.
122 #[cfg(feature = "gpui")]
123 Tiff,
124}
125
126/// One 8-bit greyscale pixel.
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128pub struct Luma(pub [u8; 1]);
129/// One 8-bit R,G,B pixel.
130#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131pub struct Rgb(pub [u8; 3]);
132/// One 8-bit R,G,B,A pixel.
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub struct Rgba(pub [u8; 4]);
135
136/// Generates the three concrete buffer types the surface uses. Upstream has
137/// one generic `ImageBuffer`; three concrete types cover every consumed call
138/// without dragging a pixel-trait hierarchy in behind them.
139macro_rules! buffer {
140 ($name:ident, $pixel:ident, $channels:expr, $doc:literal) => {
141 #[doc = $doc]
142 #[derive(Debug, Clone, PartialEq, Eq)]
143 pub struct $name {
144 width: u32,
145 height: u32,
146 data: Vec<u8>,
147 }
148
149 impl $name {
150 /// A buffer over `data`, or `None` when it is not
151 #[doc = concat!(stringify!($channels), " bytes per pixel.")]
152 pub fn from_raw(width: u32, height: u32, data: Vec<u8>) -> Option<$name> {
153 let needed = (width as usize)
154 .checked_mul(height as usize)?
155 .checked_mul($channels)?;
156 (data.len() >= needed).then_some($name {
157 width,
158 height,
159 data,
160 })
161 }
162
163 /// `(width, height)`.
164 pub fn dimensions(&self) -> (u32, u32) {
165 (self.width, self.height)
166 }
167
168 /// Width in pixels.
169 pub fn width(&self) -> u32 {
170 self.width
171 }
172
173 /// Height in pixels.
174 pub fn height(&self) -> u32 {
175 self.height
176 }
177
178 /// The pixel at `(x, y)`; panics when it is outside the image, as
179 /// upstream's does.
180 pub fn get_pixel(&self, x: u32, y: u32) -> $pixel {
181 assert!(
182 x < self.width && y < self.height,
183 "({x}, {y}) is outside a {}x{} image",
184 self.width,
185 self.height
186 );
187 let at = ((y as usize) * (self.width as usize) + x as usize) * $channels;
188 let mut pixel = [0u8; $channels];
189 pixel.copy_from_slice(&self.data[at..at + $channels]);
190 $pixel(pixel)
191 }
192
193 /// The samples, packed.
194 pub fn as_raw(&self) -> &Vec<u8> {
195 &self.data
196 }
197
198 /// The samples, taken by value.
199 pub fn into_raw(self) -> Vec<u8> {
200 self.data
201 }
202
203 /// The samples as a slice.
204 pub fn into_vec(self) -> Vec<u8> {
205 self.data
206 }
207 }
208
209 impl std::ops::Deref for $name {
210 type Target = [u8];
211 fn deref(&self) -> &[u8] {
212 &self.data
213 }
214 }
215
216 impl std::ops::DerefMut for $name {
217 fn deref_mut(&mut self) -> &mut [u8] {
218 &mut self.data
219 }
220 }
221 };
222}
223
224buffer!(GrayImage, Luma, 1, "An 8-bit greyscale image buffer.");
225buffer!(RgbImage, Rgb, 3, "An 8-bit RGB image buffer.");
226buffer!(RgbaImage, Rgba, 4, "An 8-bit RGBA image buffer.");
227
228/// A decoded image of whichever colour form its file carried.
229#[derive(Debug, Clone, PartialEq)]
230pub enum DynamicImage {
231 /// 8-bit greyscale.
232 ImageLuma8(GrayImage),
233 /// 8-bit RGB.
234 ImageRgb8(RgbImage),
235 /// 8-bit RGBA.
236 ImageRgba8(RgbaImage),
237}
238
239impl DynamicImage {
240 fn from_decoded(image: ec_image::Image) -> DynamicImage {
241 let (w, h) = (image.width, image.height);
242 match &image.pixels {
243 ec_image::Pixels::L8(data) => DynamicImage::ImageLuma8(
244 GrayImage::from_raw(w, h, data.clone()).expect("plane sized by the decoder"),
245 ),
246 ec_image::Pixels::Rgb8(data) => DynamicImage::ImageRgb8(
247 RgbImage::from_raw(w, h, data.clone()).expect("plane sized by the decoder"),
248 ),
249 _ if image.pixels.has_alpha() => DynamicImage::ImageRgba8(
250 RgbaImage::from_raw(w, h, image.to_rgba8()).expect("plane sized by the decoder"),
251 ),
252 _ => DynamicImage::ImageRgb8(
253 RgbImage::from_raw(w, h, image.to_rgb8()).expect("plane sized by the decoder"),
254 ),
255 }
256 }
257
258 /// `(width, height)`.
259 pub fn dimensions(&self) -> (u32, u32) {
260 match self {
261 DynamicImage::ImageLuma8(b) => b.dimensions(),
262 DynamicImage::ImageRgb8(b) => b.dimensions(),
263 DynamicImage::ImageRgba8(b) => b.dimensions(),
264 }
265 }
266
267 /// Width in pixels.
268 pub fn width(&self) -> u32 {
269 self.dimensions().0
270 }
271
272 /// Height in pixels.
273 pub fn height(&self) -> u32 {
274 self.dimensions().1
275 }
276
277 /// The image as 8-bit RGB, dropping any alpha channel.
278 pub fn to_rgb8(&self) -> RgbImage {
279 let (w, h) = self.dimensions();
280 let data = match self {
281 DynamicImage::ImageRgb8(b) => return b.clone(),
282 DynamicImage::ImageLuma8(b) => b.data.iter().flat_map(|&l| [l, l, l]).collect(),
283 DynamicImage::ImageRgba8(b) => b
284 .data
285 .chunks_exact(4)
286 .flat_map(|p| p[..3].to_vec())
287 .collect(),
288 };
289 RgbImage::from_raw(w, h, data).expect("converted plane")
290 }
291
292 /// The image as 8-bit RGBA; opaque where the source had no alpha.
293 pub fn to_rgba8(&self) -> RgbaImage {
294 let (w, h) = self.dimensions();
295 let data = match self {
296 DynamicImage::ImageRgba8(b) => return b.clone(),
297 DynamicImage::ImageLuma8(b) => b.data.iter().flat_map(|&l| [l, l, l, 255]).collect(),
298 DynamicImage::ImageRgb8(b) => b
299 .data
300 .chunks_exact(3)
301 .flat_map(|p| [p[0], p[1], p[2], 255])
302 .collect(),
303 };
304 RgbaImage::from_raw(w, h, data).expect("converted plane")
305 }
306
307 /// The image as 8-bit greyscale, by the same luma weights upstream uses.
308 pub fn to_luma8(&self) -> GrayImage {
309 let (w, h) = self.dimensions();
310 let data = match self {
311 DynamicImage::ImageLuma8(b) => return b.clone(),
312 _ => self
313 .to_rgb8()
314 .data
315 .chunks_exact(3)
316 .map(|p| {
317 let luma =
318 2126 * u32::from(p[0]) + 7152 * u32::from(p[1]) + 722 * u32::from(p[2]);
319 ((luma + 5000) / 10000).min(255) as u8
320 })
321 .collect(),
322 };
323 GrayImage::from_raw(w, h, data).expect("converted plane")
324 }
325}
326
327/// A decoder that guesses its format from the bytes, as `image::ImageReader`.
328///
329/// Upstream is generic over any `BufRead + Seek`; this reads the whole file
330/// once, because every caller in this family hands it a path and then decodes
331/// the whole picture anyway.
332#[derive(Debug)]
333pub struct ImageReader {
334 data: Vec<u8>,
335 format: Option<ImageFormat>,
336}
337
338impl ImageReader {
339 /// Open `path` for decoding. The format is not guessed yet.
340 pub fn open(path: impl AsRef<Path>) -> std::io::Result<ImageReader> {
341 Ok(ImageReader {
342 data: std::fs::read(path)?,
343 format: None,
344 })
345 }
346
347 /// A reader over bytes already in memory.
348 pub fn new(data: Vec<u8>) -> ImageReader {
349 ImageReader { data, format: None }
350 }
351
352 /// Guess the format from the leading bytes.
353 ///
354 /// Upstream returns an I/O error here because it may have to read; an
355 /// unrecognised signature is not an error at this point in either crate —
356 /// it surfaces at `decode`.
357 pub fn with_guessed_format(mut self) -> std::io::Result<ImageReader> {
358 self.format = format_of(&self.data);
359 Ok(self)
360 }
361
362 /// The format, once guessed or set.
363 pub fn format(&self) -> Option<ImageFormat> {
364 self.format
365 }
366
367 /// Decode the whole picture.
368 pub fn decode(self) -> ImageResult<DynamicImage> {
369 Ok(DynamicImage::from_decoded(ec_image::decode(&self.data)?))
370 }
371
372 /// The dimensions from the header alone, without decoding the pixels.
373 pub fn into_dimensions(self) -> ImageResult<(u32, u32)> {
374 let info = ec_image::info(&self.data)?;
375 Ok((info.width, info.height))
376 }
377}
378
379/// The format `data`'s leading bytes name, if this build decodes it.
380fn format_of(data: &[u8]) -> Option<ImageFormat> {
381 match ec_image::ImageFormat::guess(data)? {
382 ec_image::ImageFormat::Png => Some(ImageFormat::Png),
383 ec_image::ImageFormat::Jpeg => Some(ImageFormat::Jpeg),
384 ec_image::ImageFormat::WebP => Some(ImageFormat::WebP),
385 // Only the gpui half of this shim names the formats gpui asks for; a
386 // build without it has no variant to answer with.
387 #[cfg(feature = "gpui")]
388 ec_image::ImageFormat::Gif => Some(ImageFormat::Gif),
389 #[cfg(not(feature = "gpui"))]
390 ec_image::ImageFormat::Gif => None,
391 #[cfg(feature = "gpui")]
392 ec_image::ImageFormat::Bmp => Some(ImageFormat::Bmp),
393 #[cfg(not(feature = "gpui"))]
394 ec_image::ImageFormat::Bmp => None,
395 #[cfg(feature = "gpui")]
396 ec_image::ImageFormat::Tiff => Some(ImageFormat::Tiff),
397 #[cfg(not(feature = "gpui"))]
398 ec_image::ImageFormat::Tiff => None,
399 }
400}
401
402/// Decode the file at `path`.
403pub fn open(path: impl AsRef<Path>) -> ImageResult<DynamicImage> {
404 let data = std::fs::read(path)?;
405 load_from_memory(&data)
406}
407
408/// Decode bytes already in memory.
409pub fn load_from_memory(data: &[u8]) -> ImageResult<DynamicImage> {
410 Ok(DynamicImage::from_decoded(ec_image::decode(data)?))
411}
412
413#[cfg(test)]
414mod tests {
415 use super::*;
416 use std::path::PathBuf;
417
418 fn fixtures() -> PathBuf {
419 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/stills")
420 }
421
422 /// The exact sequence edith's engine performs, start to finish.
423 #[test]
424 fn the_engine_call_sequence_works() {
425 let path = fixtures().join("rgb8.png");
426 if !path.exists() {
427 eprintln!("skipped: fixtures/stills not generated");
428 return;
429 }
430 let reader = ImageReader::open(&path).expect("open");
431 let rgb = reader
432 .with_guessed_format()
433 .expect("guess")
434 .decode()
435 .map_err(|e| format!("{}: {e}", path.display()))
436 .expect("decode")
437 .to_rgb8();
438 let (width, height) = rgb.dimensions();
439 assert_eq!((width, height), (320, 240));
440 assert_eq!(rgb.len(), 320 * 240 * 3, "Deref reaches the samples");
441
442 let dimensions = ImageReader::open(&path)
443 .unwrap()
444 .with_guessed_format()
445 .unwrap()
446 .into_dimensions()
447 .expect("dimensions");
448 assert_eq!(dimensions, (320, 240));
449
450 let pixel = open(&path).expect("open").to_rgb8().get_pixel(7, 9).0;
451 assert_eq!(pixel.len(), 3);
452 }
453
454 #[test]
455 fn a_missing_file_is_an_io_error_the_caller_can_propagate() {
456 let err = ImageReader::open(fixtures().join("nope.png")).unwrap_err();
457 assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
458 let err: ImageError = err.into();
459 assert!(matches!(err, ImageError::IoError(_)), "{err}");
460 }
461
462 #[test]
463 fn a_file_that_is_not_an_image_fails_at_decode_not_at_guess() {
464 let reader = ImageReader::new(b"not a picture at all".to_vec())
465 .with_guessed_format()
466 .expect("guessing never fails on unknown bytes");
467 assert_eq!(reader.format(), None);
468 assert!(matches!(reader.decode(), Err(ImageError::Unsupported(_))));
469 }
470
471 #[test]
472 fn alpha_survives_and_grey_stays_grey() {
473 let dir = fixtures();
474 if !dir.join("rgba8.png").exists() {
475 eprintln!("skipped: fixtures/stills not generated");
476 return;
477 }
478 let rgba = open(dir.join("rgba8.png")).unwrap();
479 assert!(matches!(rgba, DynamicImage::ImageRgba8(_)));
480 let grey = open(dir.join("gray8.png")).unwrap();
481 assert!(matches!(grey, DynamicImage::ImageLuma8(_)));
482 // to_rgb8 of a grey image repeats the luma into all three channels.
483 let rgb = grey.to_rgb8();
484 let p = rgb.get_pixel(3, 3).0;
485 assert_eq!(p[0], p[1]);
486 assert_eq!(p[1], p[2]);
487 }
488}