forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

png.rs631 lines, 20.5 KiBHistoryRawDownload
1//! PNG decoding (W3C PNG / RFC 2083) over [`ec_inflate`].
2//!
3//! Every critical chunk is honoured: `IHDR`, `PLTE`, `tRNS`, all five filter
4//! types, all five colour types at every legal bit depth (1/2/4/8/16) and both
5//! interlace methods. `gAMA` and `sRGB` are parsed into [`Metadata`]; other
6//! ancillary chunks are skipped by length, which is what "safe to ignore"
7//! means in a format whose chunk list keeps growing.
8//!
9//! Every chunk's CRC is verified. A PNG that fails its own checksum is
10//! [`Error::Corrupt`], because the alternative — decoding it anyway — turns a
11//! detectable bit flip into a picture nobody can tell is wrong.
12
13use crate::{Image, ImageFormat, Info, Limits, Metadata, Pixels};
14use ec_core::{Error, Result};
15
16const SIGNATURE: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
17
18/// Adam7: `(x_start, y_start, x_step, y_step)` per pass.
19const ADAM7: [(u32, u32, u32, u32); 7] = [
20 (0, 0, 8, 8),
21 (4, 0, 8, 8),
22 (0, 4, 4, 8),
23 (2, 0, 4, 4),
24 (0, 2, 2, 4),
25 (1, 0, 2, 2),
26 (0, 1, 1, 2),
27];
28
29/// IHDR, the only chunk that must come first.
30#[derive(Debug, Clone, Copy)]
31struct Header {
32 width: u32,
33 height: u32,
34 depth: u8,
35 color_type: u8,
36 interlaced: bool,
37}
38
39impl Header {
40 /// Samples per pixel for the colour type (palette indices count as one).
41 fn channels(&self) -> usize {
42 match self.color_type {
43 0 | 3 => 1,
44 2 => 3,
45 4 => 2,
46 _ => 4,
47 }
48 }
49
50 /// Bytes in one unfiltered scanline of `width` pixels.
51 fn row_bytes(&self, width: u32) -> usize {
52 let bits = (width as usize) * self.channels() * (self.depth as usize);
53 bits.div_ceil(8)
54 }
55
56 /// Filter unit: bytes per pixel, rounded up, at least one.
57 fn filter_step(&self) -> usize {
58 ((self.channels() * self.depth as usize) / 8).max(1)
59 }
60}
61
62/// CRC-32 (IEEE) as PNG specifies it, table built at compile time.
63const CRC_TABLE: [u32; 256] = {
64 let mut table = [0u32; 256];
65 let mut n = 0;
66 while n < 256 {
67 let mut c = n as u32;
68 let mut k = 0;
69 while k < 8 {
70 c = if c & 1 != 0 {
71 0xedb8_8320 ^ (c >> 1)
72 } else {
73 c >> 1
74 };
75 k += 1;
76 }
77 table[n] = c;
78 n += 1;
79 }
80 table
81};
82
83pub(crate) fn crc32(data: &[u8]) -> u32 {
84 let mut c = 0xffff_ffffu32;
85 for &b in data {
86 c = CRC_TABLE[((c ^ u32::from(b)) & 0xff) as usize] ^ (c >> 8);
87 }
88 c ^ 0xffff_ffff
89}
90
91fn be32(data: &[u8]) -> u32 {
92 u32::from_be_bytes([data[0], data[1], data[2], data[3]])
93}
94
95/// One chunk: type, payload, and the offset the next chunk starts at.
96struct Chunk<'a> {
97 kind: [u8; 4],
98 data: &'a [u8],
99 next: usize,
100}
101
102/// Read the chunk at `at`, verifying its CRC.
103fn chunk(data: &[u8], at: usize) -> Result<Chunk<'_>> {
104 let head = data
105 .get(at..at + 8)
106 .ok_or_else(|| Error::corrupt("PNG: truncated chunk header"))?;
107 let len = be32(head) as usize;
108 let kind = [head[4], head[5], head[6], head[7]];
109 // The length field is 31-bit by spec; a bigger one is a corrupt file, not
110 // a reason to try to address past the buffer.
111 if len > 0x7fff_ffff {
112 return Err(Error::corrupt(format!("PNG: chunk length {len}")));
113 }
114 let body = data
115 .get(at + 8..at + 8 + len)
116 .ok_or_else(|| Error::corrupt("PNG: truncated chunk data"))?;
117 let crc = data
118 .get(at + 8 + len..at + 12 + len)
119 .ok_or_else(|| Error::corrupt("PNG: truncated chunk CRC"))?;
120 let want = be32(crc);
121 let got = crc32(&data[at + 4..at + 8 + len]);
122 if want != got {
123 return Err(Error::corrupt(format!(
124 "PNG: {} chunk CRC {got:#010x}, file says {want:#010x}",
125 String::from_utf8_lossy(&kind)
126 )));
127 }
128 Ok(Chunk {
129 kind,
130 data: body,
131 next: at + 12 + len,
132 })
133}
134
135fn header(data: &[u8]) -> Result<Header> {
136 if !data.starts_with(&SIGNATURE) {
137 return Err(Error::corrupt("PNG: bad signature"));
138 }
139 let ihdr = chunk(data, 8)?;
140 if &ihdr.kind != b"IHDR" || ihdr.data.len() != 13 {
141 return Err(Error::corrupt("PNG: first chunk is not a 13-byte IHDR"));
142 }
143 let d = ihdr.data;
144 let header = Header {
145 width: be32(d),
146 height: be32(&d[4..]),
147 depth: d[8],
148 color_type: d[9],
149 interlaced: d[12] == 1,
150 };
151 let depths: &[u8] = match header.color_type {
152 0 => &[1, 2, 4, 8, 16],
153 3 => &[1, 2, 4, 8],
154 2 | 4 | 6 => &[8, 16],
155 other => {
156 return Err(Error::corrupt(format!("PNG: colour type {other}")));
157 }
158 };
159 if !depths.contains(&header.depth) {
160 return Err(Error::corrupt(format!(
161 "PNG: bit depth {} with colour type {}",
162 header.depth, header.color_type
163 )));
164 }
165 if d[10] != 0 {
166 return Err(Error::corrupt(format!("PNG: compression method {}", d[10])));
167 }
168 if d[11] != 0 {
169 return Err(Error::corrupt(format!("PNG: filter method {}", d[11])));
170 }
171 if d[12] > 1 {
172 return Err(Error::corrupt(format!("PNG: interlace method {}", d[12])));
173 }
174 Ok(header)
175}
176
177/// Dimensions from IHDR and EXIF orientation from `eXIf`, without decoding pixels.
178///
179/// The chunk list is walked by length, so the CRCs are not checked here; the
180/// decoder checks them. A chunk whose body runs past the end ends the walk.
181pub fn info(data: &[u8]) -> Result<Info> {
182 let h = header(data)?;
183 Ok(Info {
184 format: ImageFormat::Png,
185 width: h.width,
186 height: h.height,
187 orientation: exif_orientation(data),
188 })
189}
190
191/// The first valid orientation in an `eXIf` chunk, or 1.
192fn exif_orientation(data: &[u8]) -> u8 {
193 let mut at = 8;
194 while let Some(head) = data.get(at..at + 8) {
195 let len = be32(head) as usize;
196 let kind = &head[4..8];
197 let Some(body) = data.get(at + 8..at.saturating_add(8).saturating_add(len)) else {
198 break;
199 };
200 let found = if kind == b"eXIf" { crate::exif::tiff_orientation(body) } else { None };
201 if let Some(o) = found {
202 return o;
203 }
204 if kind == b"IEND" {
205 break;
206 }
207 at = at.saturating_add(12).saturating_add(len);
208 }
209 1
210}
211
212/// Decode a PNG.
213pub fn decode(data: &[u8], limits: Limits) -> Result<Image> {
214 let hdr = header(data)?;
215 limits.check(hdr.width, hdr.height)?;
216
217 let mut palette: Vec<[u8; 3]> = Vec::new();
218 let mut trns: Option<Vec<u8>> = None;
219 let mut meta = Metadata::default();
220 let mut idat: Vec<u8> = Vec::new();
221 let mut at = chunk(data, 8)?.next;
222 let mut saw_end = false;
223 while !saw_end {
224 let c = chunk(data, at)?;
225 at = c.next;
226 match &c.kind {
227 b"PLTE" => {
228 if c.data.len() % 3 != 0 || c.data.len() > 256 * 3 {
229 return Err(Error::corrupt(format!(
230 "PNG: PLTE of {} bytes",
231 c.data.len()
232 )));
233 }
234 palette = c.data.as_chunks::<3>().0.iter().map(|p| [p[0], p[1], p[2]]).collect();
235 }
236 b"tRNS" => trns = Some(c.data.to_vec()),
237 b"gAMA" if c.data.len() == 4 => {
238 meta.gamma = Some(f64::from(be32(c.data)) / 100_000.0);
239 }
240 b"sRGB" if c.data.len() == 1 => meta.srgb_intent = Some(c.data[0]),
241 b"eXIf" => {
242 if meta.orientation.is_none() {
243 meta.orientation = crate::exif::tiff_orientation(c.data);
244 }
245 }
246 b"IDAT" => idat.extend_from_slice(c.data),
247 b"IEND" => saw_end = true,
248 // Anything else is skipped by its own length: unknown ancillary
249 // chunks are exactly what the chunk layout exists to survive.
250 _ => {}
251 }
252 }
253 if idat.is_empty() {
254 return Err(Error::corrupt("PNG: no IDAT data"));
255 }
256 if hdr.color_type == 3 && palette.is_empty() {
257 return Err(Error::corrupt("PNG: palette image without a PLTE chunk"));
258 }
259
260 // Exactly how many bytes the passes need; a stream claiming more is
261 // truncated by the limit rather than believed.
262 let expected: usize = passes(&hdr)
263 .iter()
264 .map(|&(w, h)| {
265 if w == 0 || h == 0 {
266 0
267 } else {
268 (h as usize) * (hdr.row_bytes(w) + 1)
269 }
270 })
271 .sum();
272 if expected > limits.max_alloc {
273 return Err(Error::unsupported(
274 "PNG",
275 format!("{expected} bytes of pixel data is past the allocation limit"),
276 ));
277 }
278
279 let channels_out = out_channels(&hdr, &trns);
280 // The decoded picture is refused by name before the expansion below is sized.
281 let sample_bytes = if hdr.depth == 16 { 2 } else { 1 };
282 limits.check_output(hdr.width, hdr.height, channels_out * sample_bytes)?;
283 // The expansion buffer is 16-bit whatever the depth, so it can be twice the raw
284 // scanlines the check above saw; it is budgeted on its own size too.
285 let out_bytes = limits.check_bytes(
286 "PNG pixels",
287 (hdr.width as usize)
288 .checked_mul(hdr.height as usize)
289 .and_then(|p| p.checked_mul(channels_out))
290 .and_then(|s| s.checked_mul(2)),
291 )?;
292 let raw = ec_inflate::inflate_zlib(&idat, expected).map_err(Error::from)?;
293 if raw.len() < expected {
294 return Err(Error::corrupt(format!(
295 "PNG: {} bytes of scanlines, {expected} needed",
296 raw.len()
297 )));
298 }
299
300 // Samples are carried at 16 bits internally whatever the file's depth, so
301 // one expansion path serves every colour type; the narrowing back to 8
302 // happens once, at the end.
303 let mut out = vec![0u16; out_bytes / 2];
304 let mut offset = 0;
305 for (pass, &(pw, ph)) in passes(&hdr).iter().enumerate() {
306 if pw == 0 || ph == 0 {
307 continue;
308 }
309 let row_bytes = hdr.row_bytes(pw);
310 let step = hdr.filter_step();
311 let mut previous = vec![0u8; row_bytes];
312 let mut current = vec![0u8; row_bytes];
313 let (x0, y0, dx, dy) = if hdr.interlaced {
314 ADAM7[pass]
315 } else {
316 (0, 0, 1, 1)
317 };
318 for row in 0..ph {
319 let start = offset + (row as usize) * (row_bytes + 1);
320 let filter = raw[start];
321 current.copy_from_slice(&raw[start + 1..start + 1 + row_bytes]);
322 unfilter(filter, step, &previous, &mut current)?;
323 let y = y0 + row * dy;
324 expand_row(
325 &current,
326 pw,
327 &hdr,
328 &palette,
329 trns.as_deref(),
330 channels_out,
331 |px, sample| {
332 let x = x0 + px * dx;
333 let base = ((y as usize) * (hdr.width as usize) + x as usize) * channels_out;
334 out[base..base + channels_out].copy_from_slice(sample);
335 },
336 )?;
337 std::mem::swap(&mut previous, &mut current);
338 }
339 offset += (ph as usize) * (row_bytes + 1);
340 }
341
342 let pixels = if hdr.depth == 16 {
343 match channels_out {
344 1 => Pixels::L16(out),
345 2 => Pixels::La16(out),
346 3 => Pixels::Rgb16(out),
347 _ => Pixels::Rgba16(out),
348 }
349 } else {
350 let bytes: Vec<u8> = out.into_iter().map(|s| s as u8).collect();
351 match channels_out {
352 1 => Pixels::L8(bytes),
353 2 => Pixels::La8(bytes),
354 3 => Pixels::Rgb8(bytes),
355 _ => Pixels::Rgba8(bytes),
356 }
357 };
358 Ok(Image {
359 width: hdr.width,
360 height: hdr.height,
361 pixels,
362 meta,
363 })
364}
365
366/// Channels the decoded image ends up with: a palette becomes RGB(A), and a
367/// `tRNS` chunk adds the alpha channel the colour type lacks.
368fn out_channels(hdr: &Header, trns: &Option<Vec<u8>>) -> usize {
369 match hdr.color_type {
370 0 => 1 + usize::from(trns.is_some()),
371 2 => 3 + usize::from(trns.is_some()),
372 3 => 3 + usize::from(trns.is_some()),
373 4 => 2,
374 _ => 4,
375 }
376}
377
378/// `(width, height)` of each pass — one entry for a non-interlaced image.
379fn passes(hdr: &Header) -> Vec<(u32, u32)> {
380 if !hdr.interlaced {
381 return vec![(hdr.width, hdr.height)];
382 }
383 ADAM7
384 .iter()
385 .map(|&(x0, y0, dx, dy)| {
386 (
387 hdr.width.saturating_sub(x0).div_ceil(dx),
388 hdr.height.saturating_sub(y0).div_ceil(dy),
389 )
390 })
391 .collect()
392}
393
394/// Reverse one scanline's filter in place.
395fn unfilter(filter: u8, step: usize, prev: &[u8], row: &mut [u8]) -> Result<()> {
396 match filter {
397 0 => {}
398 1 => {
399 for i in step..row.len() {
400 row[i] = row[i].wrapping_add(row[i - step]);
401 }
402 }
403 2 => {
404 for i in 0..row.len() {
405 row[i] = row[i].wrapping_add(prev[i]);
406 }
407 }
408 3 => {
409 for i in 0..row.len() {
410 let left = if i >= step {
411 u16::from(row[i - step])
412 } else {
413 0
414 };
415 let up = u16::from(prev[i]);
416 row[i] = row[i].wrapping_add(((left + up) / 2) as u8);
417 }
418 }
419 4 => {
420 for i in 0..row.len() {
421 let (a, c) = if i >= step {
422 (i32::from(row[i - step]), i32::from(prev[i - step]))
423 } else {
424 (0, 0)
425 };
426 let b = i32::from(prev[i]);
427 let p = a + b - c;
428 let (pa, pb, pc) = ((p - a).abs(), (p - b).abs(), (p - c).abs());
429 let pred = if pa <= pb && pa <= pc {
430 a
431 } else if pb <= pc {
432 b
433 } else {
434 c
435 };
436 row[i] = row[i].wrapping_add(pred as u8);
437 }
438 }
439 other => return Err(Error::corrupt(format!("PNG: filter type {other}"))),
440 }
441 Ok(())
442}
443
444/// Pull one pixel's raw samples out of a packed scanline.
445fn raw_sample(row: &[u8], depth: u8, index: usize) -> u16 {
446 match depth {
447 16 => u16::from_be_bytes([row[index * 2], row[index * 2 + 1]]),
448 8 => u16::from(row[index]),
449 _ => {
450 let per_byte = 8 / depth as usize;
451 let byte = row[index / per_byte];
452 let shift = 8 - depth as usize * (index % per_byte + 1);
453 u16::from((byte >> shift) & ((1u16 << depth) - 1) as u8)
454 }
455 }
456}
457
458/// Expand one unfiltered scanline into per-pixel output samples.
459///
460/// `emit` places pixel `px` of this pass; interlacing is entirely the caller's
461/// business, which keeps one expansion path serving both layouts.
462fn expand_row(
463 row: &[u8],
464 width: u32,
465 hdr: &Header,
466 palette: &[[u8; 3]],
467 trns: Option<&[u8]>,
468 channels_out: usize,
469 mut emit: impl FnMut(u32, &[u16]),
470) -> Result<()> {
471 // Sub-8-bit greyscale is scaled to the full range, so a 1-bit "1" is white
472 // rather than a nearly black 1/255.
473 let max = ((1u32 << hdr.depth) - 1) as u16;
474 let scale = |v: u16| -> u16 {
475 if hdr.depth == 16 || hdr.depth == 8 {
476 v
477 } else {
478 ((u32::from(v) * 255) / u32::from(max)) as u16
479 }
480 };
481 let mut sample = [0u16; 4];
482 for px in 0..width {
483 let base = (px as usize) * hdr.channels();
484 match hdr.color_type {
485 0 => {
486 let g = raw_sample(row, hdr.depth, base);
487 sample[0] = scale(g);
488 if channels_out == 2 {
489 let key = trns
490 .and_then(|t| t.get(..2))
491 .map(|t| u16::from_be_bytes([t[0], t[1]]));
492 sample[1] = if Some(g) == key {
493 0
494 } else {
495 max_for(hdr.depth)
496 };
497 }
498 }
499 2 => {
500 for c in 0..3 {
501 sample[c] = raw_sample(row, hdr.depth, base + c);
502 }
503 if channels_out == 4 {
504 let key = trns.and_then(|t| t.get(..6)).map(|t| {
505 [
506 u16::from_be_bytes([t[0], t[1]]),
507 u16::from_be_bytes([t[2], t[3]]),
508 u16::from_be_bytes([t[4], t[5]]),
509 ]
510 });
511 sample[3] = if key == Some([sample[0], sample[1], sample[2]]) {
512 0
513 } else {
514 max_for(hdr.depth)
515 };
516 }
517 }
518 3 => {
519 let index = raw_sample(row, hdr.depth, base) as usize;
520 let entry = palette.get(index).ok_or_else(|| {
521 Error::corrupt(format!(
522 "PNG: palette index {index} in a {}-entry PLTE",
523 palette.len()
524 ))
525 })?;
526 sample[0] = u16::from(entry[0]);
527 sample[1] = u16::from(entry[1]);
528 sample[2] = u16::from(entry[2]);
529 if channels_out == 4 {
530 sample[3] = u16::from(trns.and_then(|t| t.get(index)).copied().unwrap_or(255));
531 }
532 }
533 4 => {
534 sample[0] = raw_sample(row, hdr.depth, base);
535 sample[1] = raw_sample(row, hdr.depth, base + 1);
536 }
537 _ => {
538 for c in 0..4 {
539 sample[c] = raw_sample(row, hdr.depth, base + c);
540 }
541 }
542 }
543 emit(px, &sample[..channels_out]);
544 }
545 Ok(())
546}
547
548/// Fully opaque, at the depth the output carries.
549fn max_for(depth: u8) -> u16 {
550 if depth == 16 { u16::MAX } else { 255 }
551}
552
553#[cfg(test)]
554mod tests {
555 use super::*;
556
557 #[test]
558 fn crc_matches_the_known_iend_value() {
559 // IEND is a fixed, empty chunk; its CRC is the same in every PNG ever
560 // written, which makes it the one checksum worth pinning by hand.
561 assert_eq!(crc32(b"IEND"), 0xae42_6082);
562 }
563
564 #[test]
565 fn paeth_prefers_the_nearest_predictor() {
566 let prev = [10u8, 200];
567 let mut row = [0u8, 0];
568 unfilter(4, 1, &prev, &mut row).unwrap();
569 assert_eq!(row, [10, 200]);
570 }
571
572 #[test]
573 fn adam7_pass_sizes_cover_every_pixel() {
574 for (w, h) in [(1u32, 1u32), (7, 5), (16, 16), (33, 17)] {
575 let hdr = Header {
576 width: w,
577 height: h,
578 depth: 8,
579 color_type: 2,
580 interlaced: true,
581 };
582 let total: u32 = passes(&hdr).iter().map(|&(pw, ph)| pw * ph).sum();
583 assert_eq!(total, w * h, "{w}x{h}");
584 }
585 }
586
587 /// A 1x1 white 8-bit greyscale PNG, built here rather than checked in: the
588 /// zlib payload is a single stored DEFLATE block, so no encoder is needed.
589 fn tiny_png() -> Vec<u8> {
590 fn push_chunk(out: &mut Vec<u8>, kind: &[u8; 4], body: &[u8]) {
591 out.extend_from_slice(&(body.len() as u32).to_be_bytes());
592 let start = out.len();
593 out.extend_from_slice(kind);
594 out.extend_from_slice(body);
595 let crc = crc32(&out[start..]);
596 out.extend_from_slice(&crc.to_be_bytes());
597 }
598 let scanline = [0u8, 0xff]; // filter None, one white sample
599 let mut zlib = vec![0x78, 0x01, 0x01, 0x02, 0x00, 0xfd, 0xff];
600 zlib.extend_from_slice(&scanline);
601 let (mut a, mut b) = (1u32, 0u32);
602 for &byte in &scanline {
603 a = (a + u32::from(byte)) % 65521;
604 b = (b + a) % 65521;
605 }
606 zlib.extend_from_slice(&((b << 16) | a).to_be_bytes());
607
608 let mut png = SIGNATURE.to_vec();
609 let mut ihdr = Vec::new();
610 ihdr.extend_from_slice(&1u32.to_be_bytes());
611 ihdr.extend_from_slice(&1u32.to_be_bytes());
612 ihdr.extend_from_slice(&[8, 0, 0, 0, 0]);
613 push_chunk(&mut png, b"IHDR", &ihdr);
614 push_chunk(&mut png, b"IDAT", &zlib);
615 push_chunk(&mut png, b"IEND", &[]);
616 png
617 }
618
619 #[test]
620 fn a_one_pixel_png_decodes_and_a_bad_crc_does_not() {
621 let png = tiny_png();
622 let img = decode(&png, Limits::default()).expect("the hand-built PNG");
623 assert_eq!(img.dimensions(), (1, 1));
624 assert_eq!(img.pixels, Pixels::L8(vec![255]));
625
626 let mut broken = png.clone();
627 let last = broken.len() - 1;
628 broken[last] ^= 0xff;
629 assert!(decode(&broken, Limits::default()).is_err(), "bad IEND CRC");
630 }
631}