forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB210dfc8Tahinli3 months ago835 commits

lib.rs578 lines, 20.9 KiBHistoryRawDownload
1//! Still-image decoding: PNG, JPEG, WebP, GIF, BMP and TIFF.
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;
38pub mod tiff;
39mod upsample;
40pub mod webp;
41
42use ec_core::{PixelFormat, Plane, VideoFrame};
43
44// The family's error taxonomy is this crate's too, and a caller that has to
45// name a decode failure needs it in scope.
46pub use ec_core::{Error, Result};
47
48/// The formats this crate decodes.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum ImageFormat {
51 /// Portable Network Graphics (W3C PNG, RFC 2083).
52 Png,
53 /// JFIF/EXIF JPEG (ITU-T T.81 baseline and progressive).
54 Jpeg,
55 /// WebP: a RIFF container over VP8 (lossy) or VP8L (lossless).
56 WebP,
57 /// GIF, still or animated (GIF87a and GIF89a).
58 Gif,
59 /// Windows BMP (device-independent bitmap).
60 Bmp,
61 /// TIFF, the tag-directory format.
62 Tiff,
63}
64
65impl ImageFormat {
66 /// The format whose signature `data` starts with, if any.
67 ///
68 /// This is what `with_guessed_format` means: content, not file extension.
69 pub fn guess(data: &[u8]) -> Option<ImageFormat> {
70 if data.starts_with(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]) {
71 Some(ImageFormat::Png)
72 } else if data.starts_with(&[0xff, 0xd8, 0xff]) {
73 Some(ImageFormat::Jpeg)
74 } else if data.len() >= 12 && data.starts_with(b"RIFF") && &data[8..12] == b"WEBP" {
75 Some(ImageFormat::WebP)
76 } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
77 Some(ImageFormat::Gif)
78 } else if is_bmp(data) {
79 Some(ImageFormat::Bmp)
80 } else if data.starts_with(b"II\x2a\x00")
81 || data.starts_with(b"MM\x00\x2a")
82 || data.starts_with(b"II\x2b\x00")
83 || data.starts_with(b"MM\x00\x2b")
84 {
85 // 42 is classic TIFF and 43 is BigTIFF; the second is recognised
86 // here so that the decoder can refuse it by name rather than
87 // leaving the file unidentified.
88 Some(ImageFormat::Tiff)
89 } else {
90 None
91 }
92 }
93
94 /// The usual lowercase extension, for diagnostics.
95 pub fn extension(&self) -> &'static str {
96 match self {
97 ImageFormat::Png => "png",
98 ImageFormat::Jpeg => "jpg",
99 ImageFormat::WebP => "webp",
100 ImageFormat::Gif => "gif",
101 ImageFormat::Bmp => "bmp",
102 ImageFormat::Tiff => "tiff",
103 }
104 }
105}
106
107/// Whether `data` opens like a BMP.
108///
109/// "BM" is two bytes, which half the files on a disk could start with by
110/// accident, so the guess also asks the file header to agree with itself: the
111/// declared info-header length must be one the format defines, and the pixel
112/// data must start after the headers.
113fn is_bmp(data: &[u8]) -> bool {
114 if !data.starts_with(b"BM") || data.len() < 18 {
115 return false;
116 }
117 let u32_at =
118 |at: usize| u32::from_le_bytes([data[at], data[at + 1], data[at + 2], data[at + 3]]);
119 let offset = u32_at(10) as usize;
120 let info_size = u32_at(14) as usize;
121 matches!(info_size, 12 | 16 | 40 | 52 | 56 | 64 | 108 | 124) && offset >= 14 + info_size
122}
123
124/// Bounds applied before any buffer is sized from a header field.
125///
126/// A three-byte dimension field can ask for a 68-gigapixel allocation; this is
127/// the trust boundary that says no first. The default admits everything the
128/// formats themselves can express up to 2^28 pixels — comfortably past 8K
129/// (33 Mpx) and far below what would exhaust a desktop.
130#[derive(Debug, Clone, Copy)]
131pub struct Limits {
132 /// Largest `width * height` accepted.
133 pub max_pixels: u64,
134 /// Largest single decompressed buffer accepted, in bytes.
135 pub max_alloc: usize,
136 /// Largest total bytes accepted across every frame of one decode call.
137 ///
138 /// A single frame can pass [`Limits::check_bytes`] on its own and still
139 /// be a bomb once a frame or segment count multiplies it — GIF and WebP
140 /// both composite onto a full canvas per frame, and a stripped or tiled
141 /// TIFF decompresses many segments per call, so a file whose parts each
142 /// look small on their own can still retain gigabytes nothing ever
143 /// checked one buffer at a time. [`AllocBudget`] enforces this across a
144 /// decode call.
145 pub max_total_alloc: usize,
146}
147
148impl Default for Limits {
149 fn default() -> Self {
150 Limits {
151 max_pixels: 1 << 28,
152 max_alloc: 1 << 30,
153 max_total_alloc: 1 << 32,
154 }
155 }
156}
157
158impl Limits {
159 /// Check a header's dimensions before they size anything.
160 pub fn check(&self, width: u32, height: u32) -> Result<()> {
161 if width == 0 || height == 0 {
162 return Err(Error::corrupt(format!("{width}x{height} image")));
163 }
164 let pixels = u64::from(width) * u64::from(height);
165 if pixels > self.max_pixels {
166 return Err(Error::unsupported(
167 format!("{width}x{height} image"),
168 format!("{pixels} pixels is past the {} limit", self.max_pixels),
169 ));
170 }
171 Ok(())
172 }
173
174 /// Check a byte count computed from header-declared fields (a frame's or
175 /// strip's `width * height * bpp`, a palette size, a chunk length) before it
176 /// sizes a single allocation. `what` names the buffer for the error.
177 pub fn check_bytes(&self, what: &str, bytes: Option<usize>) -> Result<usize> {
178 let bytes =
179 bytes.ok_or_else(|| Error::corrupt(format!("{what}: size overflows usize")))?;
180 if bytes > self.max_alloc {
181 return Err(Error::unsupported(
182 what.to_string(),
183 format!("{bytes} bytes past the {} allocation limit", self.max_alloc),
184 ));
185 }
186 Ok(bytes)
187 }
188}
189
190/// Accumulates bytes spent across every frame or segment of one decode call
191/// and refuses once the running total crosses [`Limits::max_total_alloc`] —
192/// the guard for `frame_count x canvas` or `segment_count x segment_size`,
193/// which [`Limits::check_bytes`] alone never sees since it only ever looks
194/// at one buffer at a time.
195#[derive(Debug, Default)]
196pub struct AllocBudget(usize);
197
198impl AllocBudget {
199 /// Spend `bytes` from the budget, refusing once the running total passes
200 /// `limits.max_total_alloc`.
201 pub fn spend(&mut self, limits: &Limits, what: &str, bytes: usize) -> Result<()> {
202 self.0 = self
203 .0
204 .checked_add(bytes)
205 .ok_or_else(|| Error::corrupt(format!("{what}: total size overflows usize")))?;
206 if self.0 > limits.max_total_alloc {
207 return Err(Error::unsupported(
208 what.to_string(),
209 format!(
210 "{} total decoded bytes past the {} limit",
211 self.0, limits.max_total_alloc
212 ),
213 ));
214 }
215 Ok(())
216 }
217}
218
219/// What a file said about its own pixels, parsed but not applied.
220#[derive(Debug, Clone, Copy, Default, PartialEq)]
221pub struct Metadata {
222 /// PNG `gAMA`: the gamma the file was authored at.
223 pub gamma: Option<f64>,
224 /// PNG `sRGB`: rendering intent 0..=3, meaning the file is sRGB.
225 pub srgb_intent: Option<u8>,
226 /// EXIF orientation tag 1..=8, from a JPEG APP1 or a WebP `EXIF` chunk.
227 ///
228 /// Exposed, never applied — the same choice the incumbent `image` crate
229 /// makes, so a caller swapping between them sees the same pixels.
230 pub orientation: Option<u8>,
231}
232
233/// A decoded image's samples, in the file's own colour form.
234#[derive(Debug, Clone, PartialEq, Eq)]
235pub enum Pixels {
236 /// 8-bit grayscale.
237 L8(Vec<u8>),
238 /// 8-bit grayscale + alpha.
239 La8(Vec<u8>),
240 /// 8-bit R,G,B.
241 Rgb8(Vec<u8>),
242 /// 8-bit R,G,B,A.
243 Rgba8(Vec<u8>),
244 /// 16-bit grayscale.
245 L16(Vec<u16>),
246 /// 16-bit grayscale + alpha.
247 La16(Vec<u16>),
248 /// 16-bit R,G,B.
249 Rgb16(Vec<u16>),
250 /// 16-bit R,G,B,A.
251 Rgba16(Vec<u16>),
252}
253
254impl Pixels {
255 /// Samples per pixel.
256 pub fn channels(&self) -> usize {
257 match self {
258 Pixels::L8(_) | Pixels::L16(_) => 1,
259 Pixels::La8(_) | Pixels::La16(_) => 2,
260 Pixels::Rgb8(_) | Pixels::Rgb16(_) => 3,
261 Pixels::Rgba8(_) | Pixels::Rgba16(_) => 4,
262 }
263 }
264
265 /// Bits per sample: 8 or 16.
266 pub fn bit_depth(&self) -> u8 {
267 match self {
268 Pixels::L8(_) | Pixels::La8(_) | Pixels::Rgb8(_) | Pixels::Rgba8(_) => 8,
269 _ => 16,
270 }
271 }
272
273 /// True when the samples carry an alpha channel.
274 pub fn has_alpha(&self) -> bool {
275 matches!(
276 self,
277 Pixels::La8(_) | Pixels::Rgba8(_) | Pixels::La16(_) | Pixels::Rgba16(_)
278 )
279 }
280}
281
282/// A decoded still image.
283#[derive(Debug, Clone, PartialEq)]
284pub struct Image {
285 /// Width in pixels.
286 pub width: u32,
287 /// Height in pixels.
288 pub height: u32,
289 /// The samples.
290 pub pixels: Pixels,
291 /// What the file declared about them.
292 pub meta: Metadata,
293}
294
295/// Rounding-correct 16-bit sample down to 8 bits: `round(v * 255 / 65535)`.
296fn narrow(v: u16) -> u8 {
297 ((u32::from(v) + 128) / 257) as u8
298}
299
300/// 8-bit sample widened to 16: `v * 65535 / 255`, exact.
301fn widen(v: u8) -> u16 {
302 u16::from(v) * 257
303}
304
305impl Image {
306 /// `(width, height)`.
307 pub fn dimensions(&self) -> (u32, u32) {
308 (self.width, self.height)
309 }
310
311 /// Packed 8-bit R,G,B, dropping any alpha channel.
312 pub fn to_rgb8(&self) -> Vec<u8> {
313 let n = (self.width as usize) * (self.height as usize);
314 let mut out = Vec::with_capacity(n * 3);
315 match &self.pixels {
316 Pixels::L8(d) => d.iter().for_each(|&l| out.extend_from_slice(&[l, l, l])),
317 Pixels::La8(d) => d
318 .chunks_exact(2)
319 .for_each(|p| out.extend_from_slice(&[p[0], p[0], p[0]])),
320 Pixels::Rgb8(d) => out.extend_from_slice(d),
321 Pixels::Rgba8(d) => d
322 .chunks_exact(4)
323 .for_each(|p| out.extend_from_slice(&p[..3])),
324 Pixels::L16(d) => d.iter().for_each(|&l| {
325 let l = narrow(l);
326 out.extend_from_slice(&[l, l, l]);
327 }),
328 Pixels::La16(d) => d.chunks_exact(2).for_each(|p| {
329 let l = narrow(p[0]);
330 out.extend_from_slice(&[l, l, l]);
331 }),
332 Pixels::Rgb16(d) => d.iter().for_each(|&s| out.push(narrow(s))),
333 Pixels::Rgba16(d) => d
334 .chunks_exact(4)
335 .for_each(|p| out.extend(p[..3].iter().map(|&s| narrow(s)))),
336 }
337 out
338 }
339
340 /// Packed 8-bit R,G,B,A; opaque where the source had no alpha.
341 pub fn to_rgba8(&self) -> Vec<u8> {
342 let n = (self.width as usize) * (self.height as usize);
343 let mut out = Vec::with_capacity(n * 4);
344 match &self.pixels {
345 Pixels::L8(d) => d
346 .iter()
347 .for_each(|&l| out.extend_from_slice(&[l, l, l, 255])),
348 Pixels::La8(d) => d
349 .chunks_exact(2)
350 .for_each(|p| out.extend_from_slice(&[p[0], p[0], p[0], p[1]])),
351 Pixels::Rgb8(d) => d
352 .chunks_exact(3)
353 .for_each(|p| out.extend_from_slice(&[p[0], p[1], p[2], 255])),
354 Pixels::Rgba8(d) => out.extend_from_slice(d),
355 Pixels::L16(d) => d.iter().for_each(|&l| {
356 let l = narrow(l);
357 out.extend_from_slice(&[l, l, l, 255]);
358 }),
359 Pixels::La16(d) => d.chunks_exact(2).for_each(|p| {
360 let l = narrow(p[0]);
361 out.extend_from_slice(&[l, l, l, narrow(p[1])]);
362 }),
363 Pixels::Rgb16(d) => d.chunks_exact(3).for_each(|p| {
364 out.extend_from_slice(&[narrow(p[0]), narrow(p[1]), narrow(p[2]), 255]);
365 }),
366 Pixels::Rgba16(d) => d.iter().for_each(|&s| out.push(narrow(s))),
367 }
368 out
369 }
370
371 /// Packed 16-bit R,G,B — 8-bit sources widened exactly (`v * 257`).
372 pub fn to_rgb16(&self) -> Vec<u16> {
373 match &self.pixels {
374 Pixels::Rgb16(d) => d.clone(),
375 Pixels::Rgba16(d) => d.chunks_exact(4).flat_map(|p| p[..3].to_vec()).collect(),
376 Pixels::L16(d) => d.iter().flat_map(|&l| [l, l, l]).collect(),
377 Pixels::La16(d) => d.chunks_exact(2).flat_map(|p| [p[0], p[0], p[0]]).collect(),
378 _ => self.to_rgb8().into_iter().map(widen).collect(),
379 }
380 }
381
382 /// Packed 16-bit R,G,B,A; opaque where the source had no alpha.
383 pub fn to_rgba16(&self) -> Vec<u16> {
384 match &self.pixels {
385 Pixels::Rgba16(d) => d.clone(),
386 Pixels::Rgb16(d) => d
387 .chunks_exact(3)
388 .flat_map(|p| [p[0], p[1], p[2], u16::MAX])
389 .collect(),
390 Pixels::L16(d) => d.iter().flat_map(|&l| [l, l, l, u16::MAX]).collect(),
391 Pixels::La16(d) => d
392 .chunks_exact(2)
393 .flat_map(|p| [p[0], p[0], p[0], p[1]])
394 .collect(),
395 _ => self.to_rgba8().into_iter().map(widen).collect(),
396 }
397 }
398
399 /// The image as an [`ec_core::VideoFrame`], packed RGB8 or RGBA8.
400 ///
401 /// The natural bridge for a caller that composes stills and decoded video
402 /// in one pipeline: alpha survives when the file had it, rather than being
403 /// silently dropped on the way to a frame.
404 pub fn to_video_frame(&self) -> Result<VideoFrame> {
405 let (format, data) = if self.pixels.has_alpha() {
406 (PixelFormat::Rgba8, self.to_rgba8())
407 } else {
408 (PixelFormat::Rgb8, self.to_rgb8())
409 };
410 let stride = (self.width as usize) * if self.pixels.has_alpha() { 4 } else { 3 };
411 VideoFrame::try_new(
412 format,
413 self.width,
414 self.height,
415 vec![Plane::new(data, stride)],
416 )
417 }
418}
419
420/// Dimensions and format from a header alone — the whole file is not decoded.
421#[derive(Debug, Clone, Copy, PartialEq, Eq)]
422pub struct Info {
423 /// Which format the bytes are in.
424 pub format: ImageFormat,
425 /// Width in pixels.
426 pub width: u32,
427 /// Height in pixels.
428 pub height: u32,
429}
430
431/// Decode `data`, guessing the format from its leading bytes.
432pub fn decode(data: &[u8]) -> Result<Image> {
433 decode_with_limits(data, Limits::default())
434}
435
436/// [`decode`] with caller-chosen [`Limits`].
437pub fn decode_with_limits(data: &[u8], limits: Limits) -> Result<Image> {
438 match ImageFormat::guess(data) {
439 Some(ImageFormat::Png) => png::decode(data, limits),
440 Some(ImageFormat::Jpeg) => jpeg::decode(data, limits),
441 Some(ImageFormat::WebP) => webp::decode(data, limits),
442 Some(ImageFormat::Gif) => gif::decode(data, limits),
443 Some(ImageFormat::Bmp) => bmp::decode(data, limits),
444 Some(ImageFormat::Tiff) => tiff::decode(data, limits),
445 None => Err(Error::unsupported(
446 "image",
447 "no PNG, JPEG, WebP, GIF, BMP or TIFF signature at the start of the data",
448 )),
449 }
450}
451
452/// Dimensions from the header alone, without decoding the pixels.
453pub fn info(data: &[u8]) -> Result<Info> {
454 match ImageFormat::guess(data) {
455 Some(ImageFormat::Png) => png::info(data),
456 Some(ImageFormat::Jpeg) => jpeg::info(data),
457 Some(ImageFormat::WebP) => webp::info(data),
458 Some(ImageFormat::Gif) => gif::info(data),
459 Some(ImageFormat::Bmp) => bmp::info(data),
460 Some(ImageFormat::Tiff) => tiff::info(data),
461 None => Err(Error::unsupported(
462 "image",
463 "no PNG, JPEG, WebP, GIF, BMP or TIFF signature at the start of the data",
464 )),
465 }
466}
467
468/// One picture of an animation, already composited onto the canvas.
469///
470/// A frame is the whole canvas, not the sub-rectangle the file stored, because
471/// every consumer of an animation draws whole pictures.
472#[derive(Debug, Clone, PartialEq)]
473pub struct AnimationFrame {
474 /// The canvas at this point in the animation.
475 pub image: Image,
476 /// How long the frame is shown, in `delay_num / delay_den` seconds.
477 pub delay_num: u32,
478 /// The denominator of that delay; GIF counts hundredths of a second.
479 pub delay_den: u32,
480}
481
482/// Every frame of an animation, composited.
483///
484/// A format that cannot animate -- and a single-picture file in one that can
485/// -- returns exactly one frame, with a zero delay, so a caller that wants
486/// frames never needs to know which format it holds.
487pub fn decode_animation(data: &[u8]) -> Result<Vec<AnimationFrame>> {
488 match ImageFormat::guess(data) {
489 Some(ImageFormat::Gif) => gif::decode_animation(data, Limits::default()),
490 Some(ImageFormat::WebP) if webp::is_animated(data) => {
491 webp::decode_frames(data, Limits::default())
492 }
493 _ => Ok(vec![AnimationFrame {
494 image: decode(data)?,
495 delay_num: 0,
496 delay_den: 100,
497 }]),
498 }
499}
500
501/// Read and decode the file at `path`.
502pub fn open(path: impl AsRef<std::path::Path>) -> Result<Image> {
503 let data = std::fs::read(path).map_err(Error::Io)?;
504 decode(&data)
505}
506
507/// Read the file at `path` and report its header dimensions.
508pub fn open_info(path: impl AsRef<std::path::Path>) -> Result<Info> {
509 let data = std::fs::read(path).map_err(Error::Io)?;
510 info(&data)
511}
512
513#[cfg(test)]
514mod tests {
515 use super::*;
516
517 #[test]
518 fn guess_reads_signatures_not_extensions() {
519 assert_eq!(
520 ImageFormat::guess(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0]),
521 Some(ImageFormat::Png)
522 );
523 assert_eq!(
524 ImageFormat::guess(&[0xff, 0xd8, 0xff, 0xe0]),
525 Some(ImageFormat::Jpeg)
526 );
527 let mut webp = b"RIFF\0\0\0\0WEBPVP8 ".to_vec();
528 webp.push(0);
529 assert_eq!(ImageFormat::guess(&webp), Some(ImageFormat::WebP));
530 assert_eq!(ImageFormat::guess(b"RIFF\0\0\0\0WAVEfmt "), None);
531 assert_eq!(ImageFormat::guess(b""), None);
532 }
533
534 #[test]
535 fn sample_conversion_round_trips_through_eight_bits() {
536 for v in 0..=255u8 {
537 assert_eq!(narrow(widen(v)), v, "{v}");
538 }
539 assert_eq!(narrow(0), 0);
540 assert_eq!(narrow(u16::MAX), 255);
541 assert_eq!(narrow(32768), 128);
542 }
543
544 #[test]
545 fn limits_refuse_before_allocating() {
546 let limits = Limits::default();
547 assert!(limits.check(1920, 1080).is_ok());
548 assert!(limits.check(0, 10).is_err());
549 assert!(limits.check(100_000, 100_000).is_err());
550 }
551
552 #[test]
553 fn check_bytes_refuses_past_max_alloc_before_a_frame_size_carries_it() {
554 let limits = Limits::default();
555 assert!(limits.check_bytes("test", Some(1024)).is_ok());
556 assert!(limits.check_bytes("test", Some(limits.max_alloc + 1)).is_err());
557 assert!(limits.check_bytes("test", None).is_err());
558 }
559
560 #[test]
561 fn alloc_budget_refuses_once_repeated_spends_cross_the_total() {
562 // The class this guards: no single spend is ever over budget on its
563 // own, but a canvas cloned once per animation frame is.
564 let limits = Limits::default();
565 let mut budget = AllocBudget::default();
566 let per_frame = limits.max_total_alloc / 4;
567 for i in 0..4 {
568 assert!(
569 budget.spend(&limits, "frame", per_frame).is_ok(),
570 "frame {i} alone is within budget"
571 );
572 }
573 assert!(
574 budget.spend(&limits, "frame", per_frame).is_err(),
575 "a fifth frame the same size crosses the total"
576 );
577 }
578}