forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust376.5 MiBaeb8f71Tahinli3 months ago588 commits

lib.rs560 lines, 20.1 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 /// Largest total bytes accepted across every frame of one decode call.
124 ///
125 /// A single frame can pass [`Limits::check_bytes`] on its own and still
126 /// be a bomb once an animation's frame count multiplies it — GIF and
127 /// WebP both composite onto a full canvas per frame, so a file with many
128 /// small-looking frames can retain gigabytes nothing ever checked one
129 /// buffer at a time. [`AllocBudget`] enforces this across a decode call.
130 pub max_total_alloc: usize,
131}
132
133impl Default for Limits {
134 fn default() -> Self {
135 Limits {
136 max_pixels: 1 << 28,
137 max_alloc: 1 << 30,
138 max_total_alloc: 1 << 32,
139 }
140 }
141}
142
143impl Limits {
144 /// Check a header's dimensions before they size anything.
145 pub fn check(&self, width: u32, height: u32) -> Result<()> {
146 if width == 0 || height == 0 {
147 return Err(Error::corrupt(format!("{width}x{height} image")));
148 }
149 let pixels = u64::from(width) * u64::from(height);
150 if pixels > self.max_pixels {
151 return Err(Error::unsupported(
152 format!("{width}x{height} image"),
153 format!("{pixels} pixels is past the {} limit", self.max_pixels),
154 ));
155 }
156 Ok(())
157 }
158
159 /// Check a byte count computed from header-declared fields (a frame's
160 /// `width * height * bpp`, a palette size, a chunk length) before it
161 /// sizes a single allocation. `what` names the buffer for the error.
162 pub fn check_bytes(&self, what: &str, bytes: Option<usize>) -> Result<usize> {
163 let bytes =
164 bytes.ok_or_else(|| Error::corrupt(format!("{what}: size overflows usize")))?;
165 if bytes > self.max_alloc {
166 return Err(Error::unsupported(
167 what.to_string(),
168 format!("{bytes} bytes past the {} allocation limit", self.max_alloc),
169 ));
170 }
171 Ok(bytes)
172 }
173}
174
175/// Accumulates bytes spent across every frame of one decode call and refuses
176/// once the running total crosses [`Limits::max_total_alloc`] — the guard
177/// for `frame_count x canvas`, which [`Limits::check_bytes`] alone never
178/// sees since it only ever looks at one buffer at a time.
179#[derive(Debug, Default)]
180pub struct AllocBudget(usize);
181
182impl AllocBudget {
183 /// Spend `bytes` from the budget, refusing once the running total passes
184 /// `limits.max_total_alloc`.
185 pub fn spend(&mut self, limits: &Limits, what: &str, bytes: usize) -> Result<()> {
186 self.0 = self
187 .0
188 .checked_add(bytes)
189 .ok_or_else(|| Error::corrupt(format!("{what}: total size overflows usize")))?;
190 if self.0 > limits.max_total_alloc {
191 return Err(Error::unsupported(
192 what.to_string(),
193 format!(
194 "{} total decoded bytes past the {} limit",
195 self.0, limits.max_total_alloc
196 ),
197 ));
198 }
199 Ok(())
200 }
201}
202
203/// What a file said about its own pixels, parsed but not applied.
204#[derive(Debug, Clone, Copy, Default, PartialEq)]
205pub struct Metadata {
206 /// PNG `gAMA`: the gamma the file was authored at.
207 pub gamma: Option<f64>,
208 /// PNG `sRGB`: rendering intent 0..=3, meaning the file is sRGB.
209 pub srgb_intent: Option<u8>,
210 /// EXIF orientation tag 1..=8, from a JPEG APP1 or a WebP `EXIF` chunk.
211 ///
212 /// Exposed, never applied — the same choice the incumbent `image` crate
213 /// makes, so a caller swapping between them sees the same pixels.
214 pub orientation: Option<u8>,
215}
216
217/// A decoded image's samples, in the file's own colour form.
218#[derive(Debug, Clone, PartialEq, Eq)]
219pub enum Pixels {
220 /// 8-bit grayscale.
221 L8(Vec<u8>),
222 /// 8-bit grayscale + alpha.
223 La8(Vec<u8>),
224 /// 8-bit R,G,B.
225 Rgb8(Vec<u8>),
226 /// 8-bit R,G,B,A.
227 Rgba8(Vec<u8>),
228 /// 16-bit grayscale.
229 L16(Vec<u16>),
230 /// 16-bit grayscale + alpha.
231 La16(Vec<u16>),
232 /// 16-bit R,G,B.
233 Rgb16(Vec<u16>),
234 /// 16-bit R,G,B,A.
235 Rgba16(Vec<u16>),
236}
237
238impl Pixels {
239 /// Samples per pixel.
240 pub fn channels(&self) -> usize {
241 match self {
242 Pixels::L8(_) | Pixels::L16(_) => 1,
243 Pixels::La8(_) | Pixels::La16(_) => 2,
244 Pixels::Rgb8(_) | Pixels::Rgb16(_) => 3,
245 Pixels::Rgba8(_) | Pixels::Rgba16(_) => 4,
246 }
247 }
248
249 /// Bits per sample: 8 or 16.
250 pub fn bit_depth(&self) -> u8 {
251 match self {
252 Pixels::L8(_) | Pixels::La8(_) | Pixels::Rgb8(_) | Pixels::Rgba8(_) => 8,
253 _ => 16,
254 }
255 }
256
257 /// True when the samples carry an alpha channel.
258 pub fn has_alpha(&self) -> bool {
259 matches!(
260 self,
261 Pixels::La8(_) | Pixels::Rgba8(_) | Pixels::La16(_) | Pixels::Rgba16(_)
262 )
263 }
264}
265
266/// A decoded still image.
267#[derive(Debug, Clone, PartialEq)]
268pub struct Image {
269 /// Width in pixels.
270 pub width: u32,
271 /// Height in pixels.
272 pub height: u32,
273 /// The samples.
274 pub pixels: Pixels,
275 /// What the file declared about them.
276 pub meta: Metadata,
277}
278
279/// Rounding-correct 16-bit sample down to 8 bits: `round(v * 255 / 65535)`.
280fn narrow(v: u16) -> u8 {
281 ((u32::from(v) + 128) / 257) as u8
282}
283
284/// 8-bit sample widened to 16: `v * 65535 / 255`, exact.
285fn widen(v: u8) -> u16 {
286 u16::from(v) * 257
287}
288
289impl Image {
290 /// `(width, height)`.
291 pub fn dimensions(&self) -> (u32, u32) {
292 (self.width, self.height)
293 }
294
295 /// Packed 8-bit R,G,B, dropping any alpha channel.
296 pub fn to_rgb8(&self) -> Vec<u8> {
297 let n = (self.width as usize) * (self.height as usize);
298 let mut out = Vec::with_capacity(n * 3);
299 match &self.pixels {
300 Pixels::L8(d) => d.iter().for_each(|&l| out.extend_from_slice(&[l, l, l])),
301 Pixels::La8(d) => d
302 .chunks_exact(2)
303 .for_each(|p| out.extend_from_slice(&[p[0], p[0], p[0]])),
304 Pixels::Rgb8(d) => out.extend_from_slice(d),
305 Pixels::Rgba8(d) => d
306 .chunks_exact(4)
307 .for_each(|p| out.extend_from_slice(&p[..3])),
308 Pixels::L16(d) => d.iter().for_each(|&l| {
309 let l = narrow(l);
310 out.extend_from_slice(&[l, l, l]);
311 }),
312 Pixels::La16(d) => d.chunks_exact(2).for_each(|p| {
313 let l = narrow(p[0]);
314 out.extend_from_slice(&[l, l, l]);
315 }),
316 Pixels::Rgb16(d) => d.iter().for_each(|&s| out.push(narrow(s))),
317 Pixels::Rgba16(d) => d
318 .chunks_exact(4)
319 .for_each(|p| out.extend(p[..3].iter().map(|&s| narrow(s)))),
320 }
321 out
322 }
323
324 /// Packed 8-bit R,G,B,A; opaque where the source had no alpha.
325 pub fn to_rgba8(&self) -> Vec<u8> {
326 let n = (self.width as usize) * (self.height as usize);
327 let mut out = Vec::with_capacity(n * 4);
328 match &self.pixels {
329 Pixels::L8(d) => d
330 .iter()
331 .for_each(|&l| out.extend_from_slice(&[l, l, l, 255])),
332 Pixels::La8(d) => d
333 .chunks_exact(2)
334 .for_each(|p| out.extend_from_slice(&[p[0], p[0], p[0], p[1]])),
335 Pixels::Rgb8(d) => d
336 .chunks_exact(3)
337 .for_each(|p| out.extend_from_slice(&[p[0], p[1], p[2], 255])),
338 Pixels::Rgba8(d) => out.extend_from_slice(d),
339 Pixels::L16(d) => d.iter().for_each(|&l| {
340 let l = narrow(l);
341 out.extend_from_slice(&[l, l, l, 255]);
342 }),
343 Pixels::La16(d) => d.chunks_exact(2).for_each(|p| {
344 let l = narrow(p[0]);
345 out.extend_from_slice(&[l, l, l, narrow(p[1])]);
346 }),
347 Pixels::Rgb16(d) => d.chunks_exact(3).for_each(|p| {
348 out.extend_from_slice(&[narrow(p[0]), narrow(p[1]), narrow(p[2]), 255]);
349 }),
350 Pixels::Rgba16(d) => d.iter().for_each(|&s| out.push(narrow(s))),
351 }
352 out
353 }
354
355 /// Packed 16-bit R,G,B — 8-bit sources widened exactly (`v * 257`).
356 pub fn to_rgb16(&self) -> Vec<u16> {
357 match &self.pixels {
358 Pixels::Rgb16(d) => d.clone(),
359 Pixels::Rgba16(d) => d.chunks_exact(4).flat_map(|p| p[..3].to_vec()).collect(),
360 Pixels::L16(d) => d.iter().flat_map(|&l| [l, l, l]).collect(),
361 Pixels::La16(d) => d.chunks_exact(2).flat_map(|p| [p[0], p[0], p[0]]).collect(),
362 _ => self.to_rgb8().into_iter().map(widen).collect(),
363 }
364 }
365
366 /// Packed 16-bit R,G,B,A; opaque where the source had no alpha.
367 pub fn to_rgba16(&self) -> Vec<u16> {
368 match &self.pixels {
369 Pixels::Rgba16(d) => d.clone(),
370 Pixels::Rgb16(d) => d
371 .chunks_exact(3)
372 .flat_map(|p| [p[0], p[1], p[2], u16::MAX])
373 .collect(),
374 Pixels::L16(d) => d.iter().flat_map(|&l| [l, l, l, u16::MAX]).collect(),
375 Pixels::La16(d) => d
376 .chunks_exact(2)
377 .flat_map(|p| [p[0], p[0], p[0], p[1]])
378 .collect(),
379 _ => self.to_rgba8().into_iter().map(widen).collect(),
380 }
381 }
382
383 /// The image as an [`ec_core::VideoFrame`], packed RGB8 or RGBA8.
384 ///
385 /// The natural bridge for a caller that composes stills and decoded video
386 /// in one pipeline: alpha survives when the file had it, rather than being
387 /// silently dropped on the way to a frame.
388 pub fn to_video_frame(&self) -> Result<VideoFrame> {
389 let (format, data) = if self.pixels.has_alpha() {
390 (PixelFormat::Rgba8, self.to_rgba8())
391 } else {
392 (PixelFormat::Rgb8, self.to_rgb8())
393 };
394 let stride = (self.width as usize) * if self.pixels.has_alpha() { 4 } else { 3 };
395 VideoFrame::try_new(
396 format,
397 self.width,
398 self.height,
399 vec![Plane::new(data, stride)],
400 )
401 }
402}
403
404/// Dimensions and format from a header alone — the whole file is not decoded.
405#[derive(Debug, Clone, Copy, PartialEq, Eq)]
406pub struct Info {
407 /// Which format the bytes are in.
408 pub format: ImageFormat,
409 /// Width in pixels.
410 pub width: u32,
411 /// Height in pixels.
412 pub height: u32,
413}
414
415/// Decode `data`, guessing the format from its leading bytes.
416pub fn decode(data: &[u8]) -> Result<Image> {
417 decode_with_limits(data, Limits::default())
418}
419
420/// [`decode`] with caller-chosen [`Limits`].
421pub fn decode_with_limits(data: &[u8], limits: Limits) -> Result<Image> {
422 match ImageFormat::guess(data) {
423 Some(ImageFormat::Png) => png::decode(data, limits),
424 Some(ImageFormat::Jpeg) => jpeg::decode(data, limits),
425 Some(ImageFormat::WebP) => webp::decode(data, limits),
426 Some(ImageFormat::Gif) => gif::decode(data, limits),
427 Some(ImageFormat::Bmp) => bmp::decode(data, limits),
428 None => Err(Error::unsupported(
429 "image",
430 "no PNG, JPEG, WebP, GIF or BMP signature at the start of the data",
431 )),
432 }
433}
434
435/// Dimensions from the header alone, without decoding the pixels.
436pub fn info(data: &[u8]) -> Result<Info> {
437 match ImageFormat::guess(data) {
438 Some(ImageFormat::Png) => png::info(data),
439 Some(ImageFormat::Jpeg) => jpeg::info(data),
440 Some(ImageFormat::WebP) => webp::info(data),
441 Some(ImageFormat::Gif) => gif::info(data),
442 Some(ImageFormat::Bmp) => bmp::info(data),
443 None => Err(Error::unsupported(
444 "image",
445 "no PNG, JPEG, WebP, GIF or BMP signature at the start of the data",
446 )),
447 }
448}
449
450/// One picture of an animation, already composited onto the canvas.
451///
452/// A frame is the whole canvas, not the sub-rectangle the file stored, because
453/// every consumer of an animation draws whole pictures.
454#[derive(Debug, Clone, PartialEq)]
455pub struct AnimationFrame {
456 /// The canvas at this point in the animation.
457 pub image: Image,
458 /// How long the frame is shown, in `delay_num / delay_den` seconds.
459 pub delay_num: u32,
460 /// The denominator of that delay; GIF counts hundredths of a second.
461 pub delay_den: u32,
462}
463
464/// Every frame of an animation, composited.
465///
466/// A format that cannot animate -- and a single-picture file in one that can
467/// -- returns exactly one frame, with a zero delay, so a caller that wants
468/// frames never needs to know which format it holds.
469pub fn decode_animation(data: &[u8]) -> Result<Vec<AnimationFrame>> {
470 match ImageFormat::guess(data) {
471 Some(ImageFormat::Gif) => gif::decode_animation(data, Limits::default()),
472 Some(ImageFormat::WebP) if webp::is_animated(data) => {
473 webp::decode_frames(data, Limits::default())
474 }
475 _ => Ok(vec![AnimationFrame {
476 image: decode(data)?,
477 delay_num: 0,
478 delay_den: 100,
479 }]),
480 }
481}
482
483/// Read and decode the file at `path`.
484pub fn open(path: impl AsRef<std::path::Path>) -> Result<Image> {
485 let data = std::fs::read(path).map_err(Error::Io)?;
486 decode(&data)
487}
488
489/// Read the file at `path` and report its header dimensions.
490pub fn open_info(path: impl AsRef<std::path::Path>) -> Result<Info> {
491 let data = std::fs::read(path).map_err(Error::Io)?;
492 info(&data)
493}
494
495#[cfg(test)]
496mod tests {
497 use super::*;
498
499 #[test]
500 fn guess_reads_signatures_not_extensions() {
501 assert_eq!(
502 ImageFormat::guess(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0]),
503 Some(ImageFormat::Png)
504 );
505 assert_eq!(
506 ImageFormat::guess(&[0xff, 0xd8, 0xff, 0xe0]),
507 Some(ImageFormat::Jpeg)
508 );
509 let mut webp = b"RIFF\0\0\0\0WEBPVP8 ".to_vec();
510 webp.push(0);
511 assert_eq!(ImageFormat::guess(&webp), Some(ImageFormat::WebP));
512 assert_eq!(ImageFormat::guess(b"RIFF\0\0\0\0WAVEfmt "), None);
513 assert_eq!(ImageFormat::guess(b""), None);
514 }
515
516 #[test]
517 fn sample_conversion_round_trips_through_eight_bits() {
518 for v in 0..=255u8 {
519 assert_eq!(narrow(widen(v)), v, "{v}");
520 }
521 assert_eq!(narrow(0), 0);
522 assert_eq!(narrow(u16::MAX), 255);
523 assert_eq!(narrow(32768), 128);
524 }
525
526 #[test]
527 fn limits_refuse_before_allocating() {
528 let limits = Limits::default();
529 assert!(limits.check(1920, 1080).is_ok());
530 assert!(limits.check(0, 10).is_err());
531 assert!(limits.check(100_000, 100_000).is_err());
532 }
533
534 #[test]
535 fn check_bytes_refuses_past_max_alloc_before_a_frame_size_carries_it() {
536 let limits = Limits::default();
537 assert!(limits.check_bytes("test", Some(1024)).is_ok());
538 assert!(limits.check_bytes("test", Some(limits.max_alloc + 1)).is_err());
539 assert!(limits.check_bytes("test", None).is_err());
540 }
541
542 #[test]
543 fn alloc_budget_refuses_once_repeated_spends_cross_the_total() {
544 // The class this guards: no single spend is ever over budget on its
545 // own, but a canvas cloned once per animation frame is.
546 let limits = Limits::default();
547 let mut budget = AllocBudget::default();
548 let per_frame = limits.max_total_alloc / 4;
549 for i in 0..4 {
550 assert!(
551 budget.spend(&limits, "frame", per_frame).is_ok(),
552 "frame {i} alone is within budget"
553 );
554 }
555 assert!(
556 budget.spend(&limits, "frame", per_frame).is_err(),
557 "a fifth frame the same size crosses the total"
558 );
559 }
560}