forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB463079bTahinli3 months ago578 commits

lib.rs481 lines, 16.8 KiBHistoryRawDownload
1//! Still-image decoding: PNG, JPEG, WebP, GIF and BMP.
2//!
3//! One entry point — [`decode`] over bytes, [`open`] over a path — guesses the
4//! format from the leading bytes and hands back an [`Image`]: dimensions, a
5//! [`Pixels`] buffer in the file's own colour form, and the [`Metadata`] the
6//! file declared about it (gamma, sRGB intent, EXIF orientation).
7//!
8//! Contracts worth knowing before implementing against this crate:
9//!
10//! - Metadata is *parsed and exposed, never applied*. A JPEG that says it was
11//! shot sideways decodes to the pixels as stored, with
12//! [`Metadata::orientation`] set; a PNG's gamma is reported, not rendered.
13//! Rotating or gamma-correcting behind the caller's back would make a
14//! round-trip through this crate lossy in a way no caller asked for.
15//! - Sample depth survives: a 16-bit PNG decodes to a 16-bit [`Pixels`]
16//! variant. [`Image::to_rgb8`] and friends convert on demand.
17//! - Refusals are [`ec_core::Error::Unsupported`] naming *what* and *why* —
18//! an animated WebP and a CMYK JPEG each say so rather than producing a
19//! plausible-looking wrong picture.
20//! - Truncated or corrupt input is an error, never a panic and never an
21//! unbounded allocation: [`Limits`] bounds pixel count before any buffer is
22//! sized from header fields.
23//!
24//! No async, no unsafe, no external dependencies beyond the family's own
25//! [`ec_core`] and [`ec_inflate`].
26
27#![forbid(unsafe_code)]
28#![warn(missing_docs)]
29// Coefficient positions, macroblock columns and prediction samples are indices
30// in every specification these decoders implement; iterating them by index is
31// what keeps the code readable against the text it comes from.
32#![allow(clippy::needless_range_loop)]
33
34pub mod bmp;
35pub mod gif;
36pub mod jpeg;
37pub mod png;
38mod upsample;
39pub mod webp;
40
41use ec_core::{PixelFormat, Plane, VideoFrame};
42
43// The family's error taxonomy is this crate's too, and a caller that has to
44// name a decode failure needs it in scope.
45pub use ec_core::{Error, Result};
46
47/// The formats this crate decodes.
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub enum ImageFormat {
50 /// Portable Network Graphics (W3C PNG, RFC 2083).
51 Png,
52 /// JFIF/EXIF JPEG (ITU-T T.81 baseline and progressive).
53 Jpeg,
54 /// WebP: a RIFF container over VP8 (lossy) or VP8L (lossless).
55 WebP,
56 /// GIF, still or animated (GIF87a and GIF89a).
57 Gif,
58 /// Windows BMP (device-independent bitmap).
59 Bmp,
60}
61
62impl ImageFormat {
63 /// The format whose signature `data` starts with, if any.
64 ///
65 /// This is what `with_guessed_format` means: content, not file extension.
66 pub fn guess(data: &[u8]) -> Option<ImageFormat> {
67 if data.starts_with(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]) {
68 Some(ImageFormat::Png)
69 } else if data.starts_with(&[0xff, 0xd8, 0xff]) {
70 Some(ImageFormat::Jpeg)
71 } else if data.len() >= 12 && data.starts_with(b"RIFF") && &data[8..12] == b"WEBP" {
72 Some(ImageFormat::WebP)
73 } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
74 Some(ImageFormat::Gif)
75 } else if is_bmp(data) {
76 Some(ImageFormat::Bmp)
77 } else {
78 None
79 }
80 }
81
82 /// The usual lowercase extension, for diagnostics.
83 pub fn extension(&self) -> &'static str {
84 match self {
85 ImageFormat::Png => "png",
86 ImageFormat::Jpeg => "jpg",
87 ImageFormat::WebP => "webp",
88 ImageFormat::Gif => "gif",
89 ImageFormat::Bmp => "bmp",
90 }
91 }
92}
93
94/// Whether `data` opens like a BMP.
95///
96/// "BM" is two bytes, which half the files on a disk could start with by
97/// accident, so the guess also asks the file header to agree with itself: the
98/// declared info-header length must be one the format defines, and the pixel
99/// data must start after the headers.
100fn is_bmp(data: &[u8]) -> bool {
101 if !data.starts_with(b"BM") || data.len() < 18 {
102 return false;
103 }
104 let u32_at =
105 |at: usize| u32::from_le_bytes([data[at], data[at + 1], data[at + 2], data[at + 3]]);
106 let offset = u32_at(10) as usize;
107 let info_size = u32_at(14) as usize;
108 matches!(info_size, 12 | 16 | 40 | 52 | 56 | 64 | 108 | 124) && offset >= 14 + info_size
109}
110
111/// Bounds applied before any buffer is sized from a header field.
112///
113/// A three-byte dimension field can ask for a 68-gigapixel allocation; this is
114/// the trust boundary that says no first. The default admits everything the
115/// formats themselves can express up to 2^28 pixels — comfortably past 8K
116/// (33 Mpx) and far below what would exhaust a desktop.
117#[derive(Debug, Clone, Copy)]
118pub struct Limits {
119 /// Largest `width * height` accepted.
120 pub max_pixels: u64,
121 /// Largest single decompressed buffer accepted, in bytes.
122 pub max_alloc: usize,
123}
124
125impl Default for Limits {
126 fn default() -> Self {
127 Limits {
128 max_pixels: 1 << 28,
129 max_alloc: 1 << 32,
130 }
131 }
132}
133
134impl Limits {
135 /// Check a header's dimensions before they size anything.
136 pub fn check(&self, width: u32, height: u32) -> Result<()> {
137 if width == 0 || height == 0 {
138 return Err(Error::corrupt(format!("{width}x{height} image")));
139 }
140 let pixels = u64::from(width) * u64::from(height);
141 if pixels > self.max_pixels {
142 return Err(Error::unsupported(
143 format!("{width}x{height} image"),
144 format!("{pixels} pixels is past the {} limit", self.max_pixels),
145 ));
146 }
147 Ok(())
148 }
149}
150
151/// What a file said about its own pixels, parsed but not applied.
152#[derive(Debug, Clone, Copy, Default, PartialEq)]
153pub struct Metadata {
154 /// PNG `gAMA`: the gamma the file was authored at.
155 pub gamma: Option<f64>,
156 /// PNG `sRGB`: rendering intent 0..=3, meaning the file is sRGB.
157 pub srgb_intent: Option<u8>,
158 /// EXIF orientation tag 1..=8, from a JPEG APP1 or a WebP `EXIF` chunk.
159 ///
160 /// Exposed, never applied — the same choice the incumbent `image` crate
161 /// makes, so a caller swapping between them sees the same pixels.
162 pub orientation: Option<u8>,
163}
164
165/// A decoded image's samples, in the file's own colour form.
166#[derive(Debug, Clone, PartialEq, Eq)]
167pub enum Pixels {
168 /// 8-bit grayscale.
169 L8(Vec<u8>),
170 /// 8-bit grayscale + alpha.
171 La8(Vec<u8>),
172 /// 8-bit R,G,B.
173 Rgb8(Vec<u8>),
174 /// 8-bit R,G,B,A.
175 Rgba8(Vec<u8>),
176 /// 16-bit grayscale.
177 L16(Vec<u16>),
178 /// 16-bit grayscale + alpha.
179 La16(Vec<u16>),
180 /// 16-bit R,G,B.
181 Rgb16(Vec<u16>),
182 /// 16-bit R,G,B,A.
183 Rgba16(Vec<u16>),
184}
185
186impl Pixels {
187 /// Samples per pixel.
188 pub fn channels(&self) -> usize {
189 match self {
190 Pixels::L8(_) | Pixels::L16(_) => 1,
191 Pixels::La8(_) | Pixels::La16(_) => 2,
192 Pixels::Rgb8(_) | Pixels::Rgb16(_) => 3,
193 Pixels::Rgba8(_) | Pixels::Rgba16(_) => 4,
194 }
195 }
196
197 /// Bits per sample: 8 or 16.
198 pub fn bit_depth(&self) -> u8 {
199 match self {
200 Pixels::L8(_) | Pixels::La8(_) | Pixels::Rgb8(_) | Pixels::Rgba8(_) => 8,
201 _ => 16,
202 }
203 }
204
205 /// True when the samples carry an alpha channel.
206 pub fn has_alpha(&self) -> bool {
207 matches!(
208 self,
209 Pixels::La8(_) | Pixels::Rgba8(_) | Pixels::La16(_) | Pixels::Rgba16(_)
210 )
211 }
212}
213
214/// A decoded still image.
215#[derive(Debug, Clone, PartialEq)]
216pub struct Image {
217 /// Width in pixels.
218 pub width: u32,
219 /// Height in pixels.
220 pub height: u32,
221 /// The samples.
222 pub pixels: Pixels,
223 /// What the file declared about them.
224 pub meta: Metadata,
225}
226
227/// Rounding-correct 16-bit sample down to 8 bits: `round(v * 255 / 65535)`.
228fn narrow(v: u16) -> u8 {
229 ((u32::from(v) + 128) / 257) as u8
230}
231
232/// 8-bit sample widened to 16: `v * 65535 / 255`, exact.
233fn widen(v: u8) -> u16 {
234 u16::from(v) * 257
235}
236
237impl Image {
238 /// `(width, height)`.
239 pub fn dimensions(&self) -> (u32, u32) {
240 (self.width, self.height)
241 }
242
243 /// Packed 8-bit R,G,B, dropping any alpha channel.
244 pub fn to_rgb8(&self) -> Vec<u8> {
245 let n = (self.width as usize) * (self.height as usize);
246 let mut out = Vec::with_capacity(n * 3);
247 match &self.pixels {
248 Pixels::L8(d) => d.iter().for_each(|&l| out.extend_from_slice(&[l, l, l])),
249 Pixels::La8(d) => d
250 .chunks_exact(2)
251 .for_each(|p| out.extend_from_slice(&[p[0], p[0], p[0]])),
252 Pixels::Rgb8(d) => out.extend_from_slice(d),
253 Pixels::Rgba8(d) => d
254 .chunks_exact(4)
255 .for_each(|p| out.extend_from_slice(&p[..3])),
256 Pixels::L16(d) => d.iter().for_each(|&l| {
257 let l = narrow(l);
258 out.extend_from_slice(&[l, l, l]);
259 }),
260 Pixels::La16(d) => d.chunks_exact(2).for_each(|p| {
261 let l = narrow(p[0]);
262 out.extend_from_slice(&[l, l, l]);
263 }),
264 Pixels::Rgb16(d) => d.iter().for_each(|&s| out.push(narrow(s))),
265 Pixels::Rgba16(d) => d
266 .chunks_exact(4)
267 .for_each(|p| out.extend(p[..3].iter().map(|&s| narrow(s)))),
268 }
269 out
270 }
271
272 /// Packed 8-bit R,G,B,A; opaque where the source had no alpha.
273 pub fn to_rgba8(&self) -> Vec<u8> {
274 let n = (self.width as usize) * (self.height as usize);
275 let mut out = Vec::with_capacity(n * 4);
276 match &self.pixels {
277 Pixels::L8(d) => d
278 .iter()
279 .for_each(|&l| out.extend_from_slice(&[l, l, l, 255])),
280 Pixels::La8(d) => d
281 .chunks_exact(2)
282 .for_each(|p| out.extend_from_slice(&[p[0], p[0], p[0], p[1]])),
283 Pixels::Rgb8(d) => d
284 .chunks_exact(3)
285 .for_each(|p| out.extend_from_slice(&[p[0], p[1], p[2], 255])),
286 Pixels::Rgba8(d) => out.extend_from_slice(d),
287 Pixels::L16(d) => d.iter().for_each(|&l| {
288 let l = narrow(l);
289 out.extend_from_slice(&[l, l, l, 255]);
290 }),
291 Pixels::La16(d) => d.chunks_exact(2).for_each(|p| {
292 let l = narrow(p[0]);
293 out.extend_from_slice(&[l, l, l, narrow(p[1])]);
294 }),
295 Pixels::Rgb16(d) => d.chunks_exact(3).for_each(|p| {
296 out.extend_from_slice(&[narrow(p[0]), narrow(p[1]), narrow(p[2]), 255]);
297 }),
298 Pixels::Rgba16(d) => d.iter().for_each(|&s| out.push(narrow(s))),
299 }
300 out
301 }
302
303 /// Packed 16-bit R,G,B — 8-bit sources widened exactly (`v * 257`).
304 pub fn to_rgb16(&self) -> Vec<u16> {
305 match &self.pixels {
306 Pixels::Rgb16(d) => d.clone(),
307 Pixels::Rgba16(d) => d.chunks_exact(4).flat_map(|p| p[..3].to_vec()).collect(),
308 Pixels::L16(d) => d.iter().flat_map(|&l| [l, l, l]).collect(),
309 Pixels::La16(d) => d.chunks_exact(2).flat_map(|p| [p[0], p[0], p[0]]).collect(),
310 _ => self.to_rgb8().into_iter().map(widen).collect(),
311 }
312 }
313
314 /// Packed 16-bit R,G,B,A; opaque where the source had no alpha.
315 pub fn to_rgba16(&self) -> Vec<u16> {
316 match &self.pixels {
317 Pixels::Rgba16(d) => d.clone(),
318 Pixels::Rgb16(d) => d
319 .chunks_exact(3)
320 .flat_map(|p| [p[0], p[1], p[2], u16::MAX])
321 .collect(),
322 Pixels::L16(d) => d.iter().flat_map(|&l| [l, l, l, u16::MAX]).collect(),
323 Pixels::La16(d) => d
324 .chunks_exact(2)
325 .flat_map(|p| [p[0], p[0], p[0], p[1]])
326 .collect(),
327 _ => self.to_rgba8().into_iter().map(widen).collect(),
328 }
329 }
330
331 /// The image as an [`ec_core::VideoFrame`], packed RGB8 or RGBA8.
332 ///
333 /// The natural bridge for a caller that composes stills and decoded video
334 /// in one pipeline: alpha survives when the file had it, rather than being
335 /// silently dropped on the way to a frame.
336 pub fn to_video_frame(&self) -> Result<VideoFrame> {
337 let (format, data) = if self.pixels.has_alpha() {
338 (PixelFormat::Rgba8, self.to_rgba8())
339 } else {
340 (PixelFormat::Rgb8, self.to_rgb8())
341 };
342 let stride = (self.width as usize) * if self.pixels.has_alpha() { 4 } else { 3 };
343 VideoFrame::try_new(
344 format,
345 self.width,
346 self.height,
347 vec![Plane::new(data, stride)],
348 )
349 }
350}
351
352/// Dimensions and format from a header alone — the whole file is not decoded.
353#[derive(Debug, Clone, Copy, PartialEq, Eq)]
354pub struct Info {
355 /// Which format the bytes are in.
356 pub format: ImageFormat,
357 /// Width in pixels.
358 pub width: u32,
359 /// Height in pixels.
360 pub height: u32,
361}
362
363/// Decode `data`, guessing the format from its leading bytes.
364pub fn decode(data: &[u8]) -> Result<Image> {
365 decode_with_limits(data, Limits::default())
366}
367
368/// [`decode`] with caller-chosen [`Limits`].
369pub fn decode_with_limits(data: &[u8], limits: Limits) -> Result<Image> {
370 match ImageFormat::guess(data) {
371 Some(ImageFormat::Png) => png::decode(data, limits),
372 Some(ImageFormat::Jpeg) => jpeg::decode(data, limits),
373 Some(ImageFormat::WebP) => webp::decode(data, limits),
374 Some(ImageFormat::Gif) => gif::decode(data, limits),
375 Some(ImageFormat::Bmp) => bmp::decode(data, limits),
376 None => Err(Error::unsupported(
377 "image",
378 "no PNG, JPEG, WebP, GIF or BMP signature at the start of the data",
379 )),
380 }
381}
382
383/// Dimensions from the header alone, without decoding the pixels.
384pub fn info(data: &[u8]) -> Result<Info> {
385 match ImageFormat::guess(data) {
386 Some(ImageFormat::Png) => png::info(data),
387 Some(ImageFormat::Jpeg) => jpeg::info(data),
388 Some(ImageFormat::WebP) => webp::info(data),
389 Some(ImageFormat::Gif) => gif::info(data),
390 Some(ImageFormat::Bmp) => bmp::info(data),
391 None => Err(Error::unsupported(
392 "image",
393 "no PNG, JPEG, WebP, GIF or BMP signature at the start of the data",
394 )),
395 }
396}
397
398/// One picture of an animation, already composited onto the canvas.
399///
400/// A frame is the whole canvas, not the sub-rectangle the file stored, because
401/// every consumer of an animation draws whole pictures.
402#[derive(Debug, Clone, PartialEq)]
403pub struct AnimationFrame {
404 /// The canvas at this point in the animation.
405 pub image: Image,
406 /// How long the frame is shown, in `delay_num / delay_den` seconds.
407 pub delay_num: u32,
408 /// The denominator of that delay; GIF counts hundredths of a second.
409 pub delay_den: u32,
410}
411
412/// Every frame of an animation, composited.
413///
414/// A format that cannot animate -- and a single-picture file in one that can
415/// -- returns exactly one frame, with a zero delay, so a caller that wants
416/// frames never needs to know which format it holds.
417pub fn decode_animation(data: &[u8]) -> Result<Vec<AnimationFrame>> {
418 match ImageFormat::guess(data) {
419 Some(ImageFormat::Gif) => gif::decode_animation(data, Limits::default()),
420 Some(ImageFormat::WebP) if webp::is_animated(data) => {
421 webp::decode_frames(data, Limits::default())
422 }
423 _ => Ok(vec![AnimationFrame {
424 image: decode(data)?,
425 delay_num: 0,
426 delay_den: 100,
427 }]),
428 }
429}
430
431/// Read and decode the file at `path`.
432pub fn open(path: impl AsRef<std::path::Path>) -> Result<Image> {
433 let data = std::fs::read(path).map_err(Error::Io)?;
434 decode(&data)
435}
436
437/// Read the file at `path` and report its header dimensions.
438pub fn open_info(path: impl AsRef<std::path::Path>) -> Result<Info> {
439 let data = std::fs::read(path).map_err(Error::Io)?;
440 info(&data)
441}
442
443#[cfg(test)]
444mod tests {
445 use super::*;
446
447 #[test]
448 fn guess_reads_signatures_not_extensions() {
449 assert_eq!(
450 ImageFormat::guess(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0]),
451 Some(ImageFormat::Png)
452 );
453 assert_eq!(
454 ImageFormat::guess(&[0xff, 0xd8, 0xff, 0xe0]),
455 Some(ImageFormat::Jpeg)
456 );
457 let mut webp = b"RIFF\0\0\0\0WEBPVP8 ".to_vec();
458 webp.push(0);
459 assert_eq!(ImageFormat::guess(&webp), Some(ImageFormat::WebP));
460 assert_eq!(ImageFormat::guess(b"RIFF\0\0\0\0WAVEfmt "), None);
461 assert_eq!(ImageFormat::guess(b""), None);
462 }
463
464 #[test]
465 fn sample_conversion_round_trips_through_eight_bits() {
466 for v in 0..=255u8 {
467 assert_eq!(narrow(widen(v)), v, "{v}");
468 }
469 assert_eq!(narrow(0), 0);
470 assert_eq!(narrow(u16::MAX), 255);
471 assert_eq!(narrow(32768), 128);
472 }
473
474 #[test]
475 fn limits_refuse_before_allocating() {
476 let limits = Limits::default();
477 assert!(limits.check(1920, 1080).is_ok());
478 assert!(limits.check(0, 10).is_err());
479 assert!(limits.check(100_000, 100_000).is_err());
480 }
481}