forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

png_encode.rs166 lines, 5.3 KiBHistoryRawDownload
1//! PNG encoding for 8-bit RGB and RGBA: one `IDAT`, adaptive per-row filters.
2//!
3//! Each scanline is filtered with whichever of the five PNG filters has the
4//! smallest sum of absolute residuals (the standard heuristic). The filtered
5//! rows are deflated with [`ec_inflate::deflate_zlib`], so the output is
6//! smaller than stored blocks but larger than zlib's dynamic-Huffman output.
7//! Every chunk gets its CRC, and the output decodes through [`crate::png::decode`].
8
9use crate::png::crc32;
10use ec_core::{Error, Result};
11
12const SIGNATURE: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
13/// PNG's chunk length field is a 31-bit unsigned integer.
14const MAX_CHUNK: usize = 0x7fff_ffff;
15
16/// Encode packed 8-bit R,G,B (`width * height * 3` bytes) as a PNG file.
17pub fn encode_rgb8(width: u32, height: u32, pixels: &[u8]) -> Result<Vec<u8>> {
18 encode(width, height, pixels, 3, 2)
19}
20
21/// Encode packed 8-bit R,G,B,A (`width * height * 4` bytes) as a PNG file.
22pub fn encode_rgba8(width: u32, height: u32, pixels: &[u8]) -> Result<Vec<u8>> {
23 encode(width, height, pixels, 4, 6)
24}
25
26fn encode(
27 width: u32,
28 height: u32,
29 pixels: &[u8],
30 channels: usize,
31 color_type: u8,
32) -> Result<Vec<u8>> {
33 if width == 0 || height == 0 || width > MAX_CHUNK as u32 || height > MAX_CHUNK as u32 {
34 return Err(Error::unsupported(
35 "PNG encode",
36 format!("{width}x{height} is not a PNG-sized image"),
37 ));
38 }
39 let row = (width as usize) * channels;
40 let expected = row
41 .checked_mul(height as usize)
42 .ok_or_else(|| Error::unsupported("PNG encode", "image size overflows"))?;
43 if pixels.len() != expected {
44 return Err(Error::unsupported(
45 "PNG encode",
46 format!(
47 "{} bytes of pixels for {width}x{height} (need {expected})",
48 pixels.len()
49 ),
50 ));
51 }
52
53 let zero = vec![0u8; row];
54 let mut raw = Vec::with_capacity((row + 1) * height as usize);
55 let mut best = Vec::with_capacity(row);
56 let mut trial = Vec::with_capacity(row);
57 for y in 0..height as usize {
58 let cur = &pixels[y * row..(y + 1) * row];
59 let prev = if y == 0 {
60 &zero[..]
61 } else {
62 &pixels[(y - 1) * row..y * row]
63 };
64 let mut best_kind = 0u8;
65 let mut best_score = u64::MAX;
66 for kind in 0..5u8 {
67 trial.clear();
68 filter_row(kind, cur, prev, channels, &mut trial);
69 let score: u64 = trial
70 .iter()
71 .map(|&b| u64::from((b as i8).unsigned_abs()))
72 .sum();
73 if score < best_score {
74 best_score = score;
75 best_kind = kind;
76 std::mem::swap(&mut best, &mut trial);
77 }
78 }
79 raw.push(best_kind);
80 raw.extend_from_slice(&best);
81 }
82
83 let idat = ec_inflate::deflate_zlib(&raw);
84 if idat.len() > MAX_CHUNK {
85 return Err(Error::unsupported(
86 "PNG encode",
87 "compressed data exceeds one IDAT chunk",
88 ));
89 }
90 let mut ihdr = Vec::with_capacity(13);
91 ihdr.extend_from_slice(&width.to_be_bytes());
92 ihdr.extend_from_slice(&height.to_be_bytes());
93 ihdr.extend_from_slice(&[8, color_type, 0, 0, 0]);
94
95 let mut out = Vec::with_capacity(idat.len() + 64);
96 out.extend_from_slice(&SIGNATURE);
97 put_chunk(&mut out, b"IHDR", &ihdr);
98 put_chunk(&mut out, b"IDAT", &idat);
99 put_chunk(&mut out, b"IEND", &[]);
100 Ok(out)
101}
102
103fn put_chunk(out: &mut Vec<u8>, kind: &[u8; 4], body: &[u8]) {
104 out.extend_from_slice(&(body.len() as u32).to_be_bytes());
105 let start = out.len();
106 out.extend_from_slice(kind);
107 out.extend_from_slice(body);
108 let crc = crc32(&out[start..]);
109 out.extend_from_slice(&crc.to_be_bytes());
110}
111
112/// Apply PNG filter `kind` (0..=4, RFC 2083 section 6) to one scanline.
113fn filter_row(kind: u8, cur: &[u8], prev: &[u8], bpp: usize, out: &mut Vec<u8>) {
114 for i in 0..cur.len() {
115 let a = if i >= bpp { cur[i - bpp] } else { 0 };
116 let b = prev[i];
117 let c = if i >= bpp { prev[i - bpp] } else { 0 };
118 let predictor = match kind {
119 0 => 0,
120 1 => a,
121 2 => b,
122 3 => ((u16::from(a) + u16::from(b)) / 2) as u8,
123 _ => paeth(a, b, c),
124 };
125 out.push(cur[i].wrapping_sub(predictor));
126 }
127}
128
129fn paeth(a: u8, b: u8, c: u8) -> u8 {
130 let (ia, ib, ic) = (i16::from(a), i16::from(b), i16::from(c));
131 let p = ia + ib - ic;
132 let (pa, pb, pc) = ((p - ia).abs(), (p - ib).abs(), (p - ic).abs());
133 if pa <= pb && pa <= pc {
134 a
135 } else if pb <= pc {
136 b
137 } else {
138 c
139 }
140}
141
142#[cfg(test)]
143mod tests {
144 use super::*;
145
146 #[test]
147 fn paeth_picks_the_nearest_neighbour_with_ties_to_a_then_b() {
148 assert_eq!(paeth(10, 20, 10), 20);
149 assert_eq!(paeth(10, 10, 10), 10);
150 assert_eq!(paeth(0, 0, 255), 0);
151 }
152
153 #[test]
154 fn a_flat_image_round_trips() {
155 let px = vec![7u8; 5 * 3 * 3];
156 let png = encode_rgb8(5, 3, &px).unwrap();
157 let img = crate::decode(&png).unwrap();
158 assert_eq!(img.to_rgb8(), px);
159 }
160
161 #[test]
162 fn a_size_mismatch_is_refused() {
163 assert!(encode_rgb8(2, 2, &[0; 11]).is_err());
164 assert!(encode_rgba8(0, 2, &[]).is_err());
165 }
166}