forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBbb2f32fTahinli3 months ago423 commits

lib.rs415 lines, 14.2 KiBHistoryRawDownload
1//! Still-image decoding: PNG, JPEG and WebP.
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 jpeg;
35pub mod png;
36mod upsample;
37pub mod webp;
38
39use ec_core::{PixelFormat, Plane, VideoFrame};
40
41// The family's error taxonomy is this crate's too, and a caller that has to
42// name a decode failure needs it in scope.
43pub use ec_core::{Error, Result};
44
45/// The formats this crate decodes.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum ImageFormat {
48 /// Portable Network Graphics (W3C PNG, RFC 2083).
49 Png,
50 /// JFIF/EXIF JPEG (ITU-T T.81 baseline and progressive).
51 Jpeg,
52 /// WebP: a RIFF container over VP8 (lossy) or VP8L (lossless).
53 WebP,
54}
55
56impl ImageFormat {
57 /// The format whose signature `data` starts with, if any.
58 ///
59 /// This is what `with_guessed_format` means: content, not file extension.
60 pub fn guess(data: &[u8]) -> Option<ImageFormat> {
61 if data.starts_with(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]) {
62 Some(ImageFormat::Png)
63 } else if data.starts_with(&[0xff, 0xd8, 0xff]) {
64 Some(ImageFormat::Jpeg)
65 } else if data.len() >= 12 && data.starts_with(b"RIFF") && &data[8..12] == b"WEBP" {
66 Some(ImageFormat::WebP)
67 } else {
68 None
69 }
70 }
71
72 /// The usual lowercase extension, for diagnostics.
73 pub fn extension(&self) -> &'static str {
74 match self {
75 ImageFormat::Png => "png",
76 ImageFormat::Jpeg => "jpg",
77 ImageFormat::WebP => "webp",
78 }
79 }
80}
81
82/// Bounds applied before any buffer is sized from a header field.
83///
84/// A three-byte dimension field can ask for a 68-gigapixel allocation; this is
85/// the trust boundary that says no first. The default admits everything the
86/// formats themselves can express up to 2^28 pixels — comfortably past 8K
87/// (33 Mpx) and far below what would exhaust a desktop.
88#[derive(Debug, Clone, Copy)]
89pub struct Limits {
90 /// Largest `width * height` accepted.
91 pub max_pixels: u64,
92 /// Largest single decompressed buffer accepted, in bytes.
93 pub max_alloc: usize,
94}
95
96impl Default for Limits {
97 fn default() -> Self {
98 Limits {
99 max_pixels: 1 << 28,
100 max_alloc: 1 << 32,
101 }
102 }
103}
104
105impl Limits {
106 /// Check a header's dimensions before they size anything.
107 pub fn check(&self, width: u32, height: u32) -> Result<()> {
108 if width == 0 || height == 0 {
109 return Err(Error::corrupt(format!("{width}x{height} image")));
110 }
111 let pixels = u64::from(width) * u64::from(height);
112 if pixels > self.max_pixels {
113 return Err(Error::unsupported(
114 format!("{width}x{height} image"),
115 format!("{pixels} pixels is past the {} limit", self.max_pixels),
116 ));
117 }
118 Ok(())
119 }
120}
121
122/// What a file said about its own pixels, parsed but not applied.
123#[derive(Debug, Clone, Copy, Default, PartialEq)]
124pub struct Metadata {
125 /// PNG `gAMA`: the gamma the file was authored at.
126 pub gamma: Option<f64>,
127 /// PNG `sRGB`: rendering intent 0..=3, meaning the file is sRGB.
128 pub srgb_intent: Option<u8>,
129 /// EXIF orientation tag 1..=8, from a JPEG APP1 or a WebP `EXIF` chunk.
130 ///
131 /// Exposed, never applied — the same choice the incumbent `image` crate
132 /// makes, so a caller swapping between them sees the same pixels.
133 pub orientation: Option<u8>,
134}
135
136/// A decoded image's samples, in the file's own colour form.
137#[derive(Debug, Clone, PartialEq, Eq)]
138pub enum Pixels {
139 /// 8-bit grayscale.
140 L8(Vec<u8>),
141 /// 8-bit grayscale + alpha.
142 La8(Vec<u8>),
143 /// 8-bit R,G,B.
144 Rgb8(Vec<u8>),
145 /// 8-bit R,G,B,A.
146 Rgba8(Vec<u8>),
147 /// 16-bit grayscale.
148 L16(Vec<u16>),
149 /// 16-bit grayscale + alpha.
150 La16(Vec<u16>),
151 /// 16-bit R,G,B.
152 Rgb16(Vec<u16>),
153 /// 16-bit R,G,B,A.
154 Rgba16(Vec<u16>),
155}
156
157impl Pixels {
158 /// Samples per pixel.
159 pub fn channels(&self) -> usize {
160 match self {
161 Pixels::L8(_) | Pixels::L16(_) => 1,
162 Pixels::La8(_) | Pixels::La16(_) => 2,
163 Pixels::Rgb8(_) | Pixels::Rgb16(_) => 3,
164 Pixels::Rgba8(_) | Pixels::Rgba16(_) => 4,
165 }
166 }
167
168 /// Bits per sample: 8 or 16.
169 pub fn bit_depth(&self) -> u8 {
170 match self {
171 Pixels::L8(_) | Pixels::La8(_) | Pixels::Rgb8(_) | Pixels::Rgba8(_) => 8,
172 _ => 16,
173 }
174 }
175
176 /// True when the samples carry an alpha channel.
177 pub fn has_alpha(&self) -> bool {
178 matches!(
179 self,
180 Pixels::La8(_) | Pixels::Rgba8(_) | Pixels::La16(_) | Pixels::Rgba16(_)
181 )
182 }
183}
184
185/// A decoded still image.
186#[derive(Debug, Clone, PartialEq)]
187pub struct Image {
188 /// Width in pixels.
189 pub width: u32,
190 /// Height in pixels.
191 pub height: u32,
192 /// The samples.
193 pub pixels: Pixels,
194 /// What the file declared about them.
195 pub meta: Metadata,
196}
197
198/// Rounding-correct 16-bit sample down to 8 bits: `round(v * 255 / 65535)`.
199fn narrow(v: u16) -> u8 {
200 ((u32::from(v) + 128) / 257) as u8
201}
202
203/// 8-bit sample widened to 16: `v * 65535 / 255`, exact.
204fn widen(v: u8) -> u16 {
205 u16::from(v) * 257
206}
207
208impl Image {
209 /// `(width, height)`.
210 pub fn dimensions(&self) -> (u32, u32) {
211 (self.width, self.height)
212 }
213
214 /// Packed 8-bit R,G,B, dropping any alpha channel.
215 pub fn to_rgb8(&self) -> Vec<u8> {
216 let n = (self.width as usize) * (self.height as usize);
217 let mut out = Vec::with_capacity(n * 3);
218 match &self.pixels {
219 Pixels::L8(d) => d.iter().for_each(|&l| out.extend_from_slice(&[l, l, l])),
220 Pixels::La8(d) => d
221 .chunks_exact(2)
222 .for_each(|p| out.extend_from_slice(&[p[0], p[0], p[0]])),
223 Pixels::Rgb8(d) => out.extend_from_slice(d),
224 Pixels::Rgba8(d) => d
225 .chunks_exact(4)
226 .for_each(|p| out.extend_from_slice(&p[..3])),
227 Pixels::L16(d) => d.iter().for_each(|&l| {
228 let l = narrow(l);
229 out.extend_from_slice(&[l, l, l]);
230 }),
231 Pixels::La16(d) => d.chunks_exact(2).for_each(|p| {
232 let l = narrow(p[0]);
233 out.extend_from_slice(&[l, l, l]);
234 }),
235 Pixels::Rgb16(d) => d.iter().for_each(|&s| out.push(narrow(s))),
236 Pixels::Rgba16(d) => d
237 .chunks_exact(4)
238 .for_each(|p| out.extend(p[..3].iter().map(|&s| narrow(s)))),
239 }
240 out
241 }
242
243 /// Packed 8-bit R,G,B,A; opaque where the source had no alpha.
244 pub fn to_rgba8(&self) -> Vec<u8> {
245 let n = (self.width as usize) * (self.height as usize);
246 let mut out = Vec::with_capacity(n * 4);
247 match &self.pixels {
248 Pixels::L8(d) => d
249 .iter()
250 .for_each(|&l| out.extend_from_slice(&[l, l, l, 255])),
251 Pixels::La8(d) => d
252 .chunks_exact(2)
253 .for_each(|p| out.extend_from_slice(&[p[0], p[0], p[0], p[1]])),
254 Pixels::Rgb8(d) => d
255 .chunks_exact(3)
256 .for_each(|p| out.extend_from_slice(&[p[0], p[1], p[2], 255])),
257 Pixels::Rgba8(d) => out.extend_from_slice(d),
258 Pixels::L16(d) => d.iter().for_each(|&l| {
259 let l = narrow(l);
260 out.extend_from_slice(&[l, l, l, 255]);
261 }),
262 Pixels::La16(d) => d.chunks_exact(2).for_each(|p| {
263 let l = narrow(p[0]);
264 out.extend_from_slice(&[l, l, l, narrow(p[1])]);
265 }),
266 Pixels::Rgb16(d) => d.chunks_exact(3).for_each(|p| {
267 out.extend_from_slice(&[narrow(p[0]), narrow(p[1]), narrow(p[2]), 255]);
268 }),
269 Pixels::Rgba16(d) => d.iter().for_each(|&s| out.push(narrow(s))),
270 }
271 out
272 }
273
274 /// Packed 16-bit R,G,B — 8-bit sources widened exactly (`v * 257`).
275 pub fn to_rgb16(&self) -> Vec<u16> {
276 match &self.pixels {
277 Pixels::Rgb16(d) => d.clone(),
278 Pixels::Rgba16(d) => d.chunks_exact(4).flat_map(|p| p[..3].to_vec()).collect(),
279 Pixels::L16(d) => d.iter().flat_map(|&l| [l, l, l]).collect(),
280 Pixels::La16(d) => d.chunks_exact(2).flat_map(|p| [p[0], p[0], p[0]]).collect(),
281 _ => self.to_rgb8().into_iter().map(widen).collect(),
282 }
283 }
284
285 /// Packed 16-bit R,G,B,A; opaque where the source had no alpha.
286 pub fn to_rgba16(&self) -> Vec<u16> {
287 match &self.pixels {
288 Pixels::Rgba16(d) => d.clone(),
289 Pixels::Rgb16(d) => d
290 .chunks_exact(3)
291 .flat_map(|p| [p[0], p[1], p[2], u16::MAX])
292 .collect(),
293 Pixels::L16(d) => d.iter().flat_map(|&l| [l, l, l, u16::MAX]).collect(),
294 Pixels::La16(d) => d
295 .chunks_exact(2)
296 .flat_map(|p| [p[0], p[0], p[0], p[1]])
297 .collect(),
298 _ => self.to_rgba8().into_iter().map(widen).collect(),
299 }
300 }
301
302 /// The image as an [`ec_core::VideoFrame`], packed RGB8 or RGBA8.
303 ///
304 /// The natural bridge for a caller that composes stills and decoded video
305 /// in one pipeline: alpha survives when the file had it, rather than being
306 /// silently dropped on the way to a frame.
307 pub fn to_video_frame(&self) -> Result<VideoFrame> {
308 let (format, data) = if self.pixels.has_alpha() {
309 (PixelFormat::Rgba8, self.to_rgba8())
310 } else {
311 (PixelFormat::Rgb8, self.to_rgb8())
312 };
313 let stride = (self.width as usize) * if self.pixels.has_alpha() { 4 } else { 3 };
314 VideoFrame::try_new(
315 format,
316 self.width,
317 self.height,
318 vec![Plane::new(data, stride)],
319 )
320 }
321}
322
323/// Dimensions and format from a header alone — the whole file is not decoded.
324#[derive(Debug, Clone, Copy, PartialEq, Eq)]
325pub struct Info {
326 /// Which format the bytes are in.
327 pub format: ImageFormat,
328 /// Width in pixels.
329 pub width: u32,
330 /// Height in pixels.
331 pub height: u32,
332}
333
334/// Decode `data`, guessing the format from its leading bytes.
335pub fn decode(data: &[u8]) -> Result<Image> {
336 decode_with_limits(data, Limits::default())
337}
338
339/// [`decode`] with caller-chosen [`Limits`].
340pub fn decode_with_limits(data: &[u8], limits: Limits) -> Result<Image> {
341 match ImageFormat::guess(data) {
342 Some(ImageFormat::Png) => png::decode(data, limits),
343 Some(ImageFormat::Jpeg) => jpeg::decode(data, limits),
344 Some(ImageFormat::WebP) => webp::decode(data, limits),
345 None => Err(Error::unsupported(
346 "image",
347 "no PNG, JPEG or WebP signature at the start of the data",
348 )),
349 }
350}
351
352/// Dimensions from the header alone, without decoding the pixels.
353pub fn info(data: &[u8]) -> Result<Info> {
354 match ImageFormat::guess(data) {
355 Some(ImageFormat::Png) => png::info(data),
356 Some(ImageFormat::Jpeg) => jpeg::info(data),
357 Some(ImageFormat::WebP) => webp::info(data),
358 None => Err(Error::unsupported(
359 "image",
360 "no PNG, JPEG or WebP signature at the start of the data",
361 )),
362 }
363}
364
365/// Read and decode the file at `path`.
366pub fn open(path: impl AsRef<std::path::Path>) -> Result<Image> {
367 let data = std::fs::read(path).map_err(Error::Io)?;
368 decode(&data)
369}
370
371/// Read the file at `path` and report its header dimensions.
372pub fn open_info(path: impl AsRef<std::path::Path>) -> Result<Info> {
373 let data = std::fs::read(path).map_err(Error::Io)?;
374 info(&data)
375}
376
377#[cfg(test)]
378mod tests {
379 use super::*;
380
381 #[test]
382 fn guess_reads_signatures_not_extensions() {
383 assert_eq!(
384 ImageFormat::guess(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0]),
385 Some(ImageFormat::Png)
386 );
387 assert_eq!(
388 ImageFormat::guess(&[0xff, 0xd8, 0xff, 0xe0]),
389 Some(ImageFormat::Jpeg)
390 );
391 let mut webp = b"RIFF\0\0\0\0WEBPVP8 ".to_vec();
392 webp.push(0);
393 assert_eq!(ImageFormat::guess(&webp), Some(ImageFormat::WebP));
394 assert_eq!(ImageFormat::guess(b"RIFF\0\0\0\0WAVEfmt "), None);
395 assert_eq!(ImageFormat::guess(b""), None);
396 }
397
398 #[test]
399 fn sample_conversion_round_trips_through_eight_bits() {
400 for v in 0..=255u8 {
401 assert_eq!(narrow(widen(v)), v, "{v}");
402 }
403 assert_eq!(narrow(0), 0);
404 assert_eq!(narrow(u16::MAX), 255);
405 assert_eq!(narrow(32768), 128);
406 }
407
408 #[test]
409 fn limits_refuse_before_allocating() {
410 let limits = Limits::default();
411 assert!(limits.check(1920, 1080).is_ok());
412 assert!(limits.check(0, 10).is_err());
413 assert!(limits.check(100_000, 100_000).is_err());
414 }
415}