forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

png.rs588 lines, 18.9 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
83fn 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 alone.
178pub fn info(data: &[u8]) -> Result<Info> {
179 let h = header(data)?;
180 Ok(Info {
181 format: ImageFormat::Png,
182 width: h.width,
183 height: h.height,
184 })
185}
186
187/// Decode a PNG.
188pub fn decode(data: &[u8], limits: Limits) -> Result<Image> {
189 let hdr = header(data)?;
190 limits.check(hdr.width, hdr.height)?;
191
192 let mut palette: Vec<[u8; 3]> = Vec::new();
193 let mut trns: Option<Vec<u8>> = None;
194 let mut meta = Metadata::default();
195 let mut idat: Vec<u8> = Vec::new();
196 let mut at = chunk(data, 8)?.next;
197 let mut saw_end = false;
198 while !saw_end {
199 let c = chunk(data, at)?;
200 at = c.next;
201 match &c.kind {
202 b"PLTE" => {
203 if c.data.len() % 3 != 0 || c.data.len() > 256 * 3 {
204 return Err(Error::corrupt(format!(
205 "PNG: PLTE of {} bytes",
206 c.data.len()
207 )));
208 }
209 palette = c.data.chunks_exact(3).map(|p| [p[0], p[1], p[2]]).collect();
210 }
211 b"tRNS" => trns = Some(c.data.to_vec()),
212 b"gAMA" if c.data.len() == 4 => {
213 meta.gamma = Some(f64::from(be32(c.data)) / 100_000.0);
214 }
215 b"sRGB" if c.data.len() == 1 => meta.srgb_intent = Some(c.data[0]),
216 b"IDAT" => idat.extend_from_slice(c.data),
217 b"IEND" => saw_end = true,
218 // Anything else is skipped by its own length: unknown ancillary
219 // chunks are exactly what the chunk layout exists to survive.
220 _ => {}
221 }
222 }
223 if idat.is_empty() {
224 return Err(Error::corrupt("PNG: no IDAT data"));
225 }
226 if hdr.color_type == 3 && palette.is_empty() {
227 return Err(Error::corrupt("PNG: palette image without a PLTE chunk"));
228 }
229
230 // Exactly how many bytes the passes need; a stream claiming more is
231 // truncated by the limit rather than believed.
232 let expected: usize = passes(&hdr)
233 .iter()
234 .map(|&(w, h)| {
235 if w == 0 || h == 0 {
236 0
237 } else {
238 (h as usize) * (hdr.row_bytes(w) + 1)
239 }
240 })
241 .sum();
242 if expected > limits.max_alloc {
243 return Err(Error::unsupported(
244 "PNG",
245 format!("{expected} bytes of pixel data is past the allocation limit"),
246 ));
247 }
248 let raw = ec_inflate::inflate_zlib(&idat, expected).map_err(Error::from)?;
249 if raw.len() < expected {
250 return Err(Error::corrupt(format!(
251 "PNG: {} bytes of scanlines, {expected} needed",
252 raw.len()
253 )));
254 }
255
256 // Samples are carried at 16 bits internally whatever the file's depth, so
257 // one expansion path serves every colour type; the narrowing back to 8
258 // happens once, at the end.
259 let channels_out = out_channels(&hdr, &trns);
260 let mut out = vec![0u16; (hdr.width as usize) * (hdr.height as usize) * channels_out];
261 let mut offset = 0;
262 for (pass, &(pw, ph)) in passes(&hdr).iter().enumerate() {
263 if pw == 0 || ph == 0 {
264 continue;
265 }
266 let row_bytes = hdr.row_bytes(pw);
267 let step = hdr.filter_step();
268 let mut previous = vec![0u8; row_bytes];
269 let mut current = vec![0u8; row_bytes];
270 let (x0, y0, dx, dy) = if hdr.interlaced {
271 ADAM7[pass]
272 } else {
273 (0, 0, 1, 1)
274 };
275 for row in 0..ph {
276 let start = offset + (row as usize) * (row_bytes + 1);
277 let filter = raw[start];
278 current.copy_from_slice(&raw[start + 1..start + 1 + row_bytes]);
279 unfilter(filter, step, &previous, &mut current)?;
280 let y = y0 + row * dy;
281 expand_row(
282 &current,
283 pw,
284 &hdr,
285 &palette,
286 trns.as_deref(),
287 channels_out,
288 |px, sample| {
289 let x = x0 + px * dx;
290 let base = ((y as usize) * (hdr.width as usize) + x as usize) * channels_out;
291 out[base..base + channels_out].copy_from_slice(sample);
292 },
293 )?;
294 std::mem::swap(&mut previous, &mut current);
295 }
296 offset += (ph as usize) * (row_bytes + 1);
297 }
298
299 let pixels = if hdr.depth == 16 {
300 match channels_out {
301 1 => Pixels::L16(out),
302 2 => Pixels::La16(out),
303 3 => Pixels::Rgb16(out),
304 _ => Pixels::Rgba16(out),
305 }
306 } else {
307 let bytes: Vec<u8> = out.into_iter().map(|s| s as u8).collect();
308 match channels_out {
309 1 => Pixels::L8(bytes),
310 2 => Pixels::La8(bytes),
311 3 => Pixels::Rgb8(bytes),
312 _ => Pixels::Rgba8(bytes),
313 }
314 };
315 Ok(Image {
316 width: hdr.width,
317 height: hdr.height,
318 pixels,
319 meta,
320 })
321}
322
323/// Channels the decoded image ends up with: a palette becomes RGB(A), and a
324/// `tRNS` chunk adds the alpha channel the colour type lacks.
325fn out_channels(hdr: &Header, trns: &Option<Vec<u8>>) -> usize {
326 match hdr.color_type {
327 0 => 1 + usize::from(trns.is_some()),
328 2 => 3 + usize::from(trns.is_some()),
329 3 => 3 + usize::from(trns.is_some()),
330 4 => 2,
331 _ => 4,
332 }
333}
334
335/// `(width, height)` of each pass — one entry for a non-interlaced image.
336fn passes(hdr: &Header) -> Vec<(u32, u32)> {
337 if !hdr.interlaced {
338 return vec![(hdr.width, hdr.height)];
339 }
340 ADAM7
341 .iter()
342 .map(|&(x0, y0, dx, dy)| {
343 (
344 hdr.width.saturating_sub(x0).div_ceil(dx),
345 hdr.height.saturating_sub(y0).div_ceil(dy),
346 )
347 })
348 .collect()
349}
350
351/// Reverse one scanline's filter in place.
352fn unfilter(filter: u8, step: usize, prev: &[u8], row: &mut [u8]) -> Result<()> {
353 match filter {
354 0 => {}
355 1 => {
356 for i in step..row.len() {
357 row[i] = row[i].wrapping_add(row[i - step]);
358 }
359 }
360 2 => {
361 for i in 0..row.len() {
362 row[i] = row[i].wrapping_add(prev[i]);
363 }
364 }
365 3 => {
366 for i in 0..row.len() {
367 let left = if i >= step {
368 u16::from(row[i - step])
369 } else {
370 0
371 };
372 let up = u16::from(prev[i]);
373 row[i] = row[i].wrapping_add(((left + up) / 2) as u8);
374 }
375 }
376 4 => {
377 for i in 0..row.len() {
378 let (a, c) = if i >= step {
379 (i32::from(row[i - step]), i32::from(prev[i - step]))
380 } else {
381 (0, 0)
382 };
383 let b = i32::from(prev[i]);
384 let p = a + b - c;
385 let (pa, pb, pc) = ((p - a).abs(), (p - b).abs(), (p - c).abs());
386 let pred = if pa <= pb && pa <= pc {
387 a
388 } else if pb <= pc {
389 b
390 } else {
391 c
392 };
393 row[i] = row[i].wrapping_add(pred as u8);
394 }
395 }
396 other => return Err(Error::corrupt(format!("PNG: filter type {other}"))),
397 }
398 Ok(())
399}
400
401/// Pull one pixel's raw samples out of a packed scanline.
402fn raw_sample(row: &[u8], depth: u8, index: usize) -> u16 {
403 match depth {
404 16 => u16::from_be_bytes([row[index * 2], row[index * 2 + 1]]),
405 8 => u16::from(row[index]),
406 _ => {
407 let per_byte = 8 / depth as usize;
408 let byte = row[index / per_byte];
409 let shift = 8 - depth as usize * (index % per_byte + 1);
410 u16::from((byte >> shift) & ((1u16 << depth) - 1) as u8)
411 }
412 }
413}
414
415/// Expand one unfiltered scanline into per-pixel output samples.
416///
417/// `emit` places pixel `px` of this pass; interlacing is entirely the caller's
418/// business, which keeps one expansion path serving both layouts.
419fn expand_row(
420 row: &[u8],
421 width: u32,
422 hdr: &Header,
423 palette: &[[u8; 3]],
424 trns: Option<&[u8]>,
425 channels_out: usize,
426 mut emit: impl FnMut(u32, &[u16]),
427) -> Result<()> {
428 // Sub-8-bit greyscale is scaled to the full range, so a 1-bit "1" is white
429 // rather than a nearly black 1/255.
430 let max = ((1u32 << hdr.depth) - 1) as u16;
431 let scale = |v: u16| -> u16 {
432 if hdr.depth == 16 || hdr.depth == 8 {
433 v
434 } else {
435 ((u32::from(v) * 255) / u32::from(max)) as u16
436 }
437 };
438 let mut sample = [0u16; 4];
439 for px in 0..width {
440 let base = (px as usize) * hdr.channels();
441 match hdr.color_type {
442 0 => {
443 let g = raw_sample(row, hdr.depth, base);
444 sample[0] = scale(g);
445 if channels_out == 2 {
446 let key = trns
447 .and_then(|t| t.get(..2))
448 .map(|t| u16::from_be_bytes([t[0], t[1]]));
449 sample[1] = if Some(g) == key {
450 0
451 } else {
452 max_for(hdr.depth)
453 };
454 }
455 }
456 2 => {
457 for c in 0..3 {
458 sample[c] = raw_sample(row, hdr.depth, base + c);
459 }
460 if channels_out == 4 {
461 let key = trns.and_then(|t| t.get(..6)).map(|t| {
462 [
463 u16::from_be_bytes([t[0], t[1]]),
464 u16::from_be_bytes([t[2], t[3]]),
465 u16::from_be_bytes([t[4], t[5]]),
466 ]
467 });
468 sample[3] = if key == Some([sample[0], sample[1], sample[2]]) {
469 0
470 } else {
471 max_for(hdr.depth)
472 };
473 }
474 }
475 3 => {
476 let index = raw_sample(row, hdr.depth, base) as usize;
477 let entry = palette.get(index).ok_or_else(|| {
478 Error::corrupt(format!(
479 "PNG: palette index {index} in a {}-entry PLTE",
480 palette.len()
481 ))
482 })?;
483 sample[0] = u16::from(entry[0]);
484 sample[1] = u16::from(entry[1]);
485 sample[2] = u16::from(entry[2]);
486 if channels_out == 4 {
487 sample[3] = u16::from(trns.and_then(|t| t.get(index)).copied().unwrap_or(255));
488 }
489 }
490 4 => {
491 sample[0] = raw_sample(row, hdr.depth, base);
492 sample[1] = raw_sample(row, hdr.depth, base + 1);
493 }
494 _ => {
495 for c in 0..4 {
496 sample[c] = raw_sample(row, hdr.depth, base + c);
497 }
498 }
499 }
500 emit(px, &sample[..channels_out]);
501 }
502 Ok(())
503}
504
505/// Fully opaque, at the depth the output carries.
506fn max_for(depth: u8) -> u16 {
507 if depth == 16 { u16::MAX } else { 255 }
508}
509
510#[cfg(test)]
511mod tests {
512 use super::*;
513
514 #[test]
515 fn crc_matches_the_known_iend_value() {
516 // IEND is a fixed, empty chunk; its CRC is the same in every PNG ever
517 // written, which makes it the one checksum worth pinning by hand.
518 assert_eq!(crc32(b"IEND"), 0xae42_6082);
519 }
520
521 #[test]
522 fn paeth_prefers_the_nearest_predictor() {
523 let prev = [10u8, 200];
524 let mut row = [0u8, 0];
525 unfilter(4, 1, &prev, &mut row).unwrap();
526 assert_eq!(row, [10, 200]);
527 }
528
529 #[test]
530 fn adam7_pass_sizes_cover_every_pixel() {
531 for (w, h) in [(1u32, 1u32), (7, 5), (16, 16), (33, 17)] {
532 let hdr = Header {
533 width: w,
534 height: h,
535 depth: 8,
536 color_type: 2,
537 interlaced: true,
538 };
539 let total: u32 = passes(&hdr).iter().map(|&(pw, ph)| pw * ph).sum();
540 assert_eq!(total, w * h, "{w}x{h}");
541 }
542 }
543
544 /// A 1x1 white 8-bit greyscale PNG, built here rather than checked in: the
545 /// zlib payload is a single stored DEFLATE block, so no encoder is needed.
546 fn tiny_png() -> Vec<u8> {
547 fn push_chunk(out: &mut Vec<u8>, kind: &[u8; 4], body: &[u8]) {
548 out.extend_from_slice(&(body.len() as u32).to_be_bytes());
549 let start = out.len();
550 out.extend_from_slice(kind);
551 out.extend_from_slice(body);
552 let crc = crc32(&out[start..]);
553 out.extend_from_slice(&crc.to_be_bytes());
554 }
555 let scanline = [0u8, 0xff]; // filter None, one white sample
556 let mut zlib = vec![0x78, 0x01, 0x01, 0x02, 0x00, 0xfd, 0xff];
557 zlib.extend_from_slice(&scanline);
558 let (mut a, mut b) = (1u32, 0u32);
559 for &byte in &scanline {
560 a = (a + u32::from(byte)) % 65521;
561 b = (b + a) % 65521;
562 }
563 zlib.extend_from_slice(&((b << 16) | a).to_be_bytes());
564
565 let mut png = SIGNATURE.to_vec();
566 let mut ihdr = Vec::new();
567 ihdr.extend_from_slice(&1u32.to_be_bytes());
568 ihdr.extend_from_slice(&1u32.to_be_bytes());
569 ihdr.extend_from_slice(&[8, 0, 0, 0, 0]);
570 push_chunk(&mut png, b"IHDR", &ihdr);
571 push_chunk(&mut png, b"IDAT", &zlib);
572 push_chunk(&mut png, b"IEND", &[]);
573 png
574 }
575
576 #[test]
577 fn a_one_pixel_png_decodes_and_a_bad_crc_does_not() {
578 let png = tiny_png();
579 let img = decode(&png, Limits::default()).expect("the hand-built PNG");
580 assert_eq!(img.dimensions(), (1, 1));
581 assert_eq!(img.pixels, Pixels::L8(vec![255]));
582
583 let mut broken = png.clone();
584 let last = broken.len() - 1;
585 broken[last] ^= 0xff;
586 assert!(decode(&broken, Limits::default()).is_err(), "bad IEND CRC");
587 }
588}