1use crate::deflate::{zlib_compress, zlib_decompress};
13use lib_jsl_core::ErrorsJSL;
14use std::path::Path;
15
16#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct RasterImage {
19 pub width: usize,
20 pub height: usize,
21 pub channels: usize,
23 pub bit_depth: u8,
25 pub samples: Vec<u16>,
28}
29
30impl RasterImage {
31 pub fn new(width: usize, height: usize, channels: usize, bit_depth: u8, samples: Vec<u16>) -> Result<Self, ErrorsJSL> {
32 let image = RasterImage { width, height, channels, bit_depth, samples };
33 image.validate()?;
34 Ok(image)
35 }
36
37 fn validate(&self) -> Result<(), ErrorsJSL> {
38 if !(1..=4).contains(&self.channels) || !(self.bit_depth == 8 || self.bit_depth == 16) {
39 return Err(ErrorsJSL::InvalidInputRange("Images need 1 to 4 channels and 8- or 16-bit samples."));
40 }
41 if self.samples.len() != self.width * self.height * self.channels {
42 return Err(ErrorsJSL::IncompatibleArraySizes((self.samples.len(), self.width * self.height * self.channels)));
43 }
44 if self.bit_depth == 8 && self.samples.iter().any(|&s| s > 255) {
45 return Err(ErrorsJSL::InvalidInputRange("8-bit samples must be below 256."));
46 }
47 Ok(())
48 }
49
50 pub fn sample(&self, x: usize, y: usize, c: usize) -> u16 {
52 self.samples[(y * self.width + x) * self.channels + c]
53 }
54
55 pub fn to_u8(&self) -> Vec<u8> {
57 match self.bit_depth {
58 16 => self.samples.iter().map(|&s| (s >> 8) as u8).collect(),
59 _ => self.samples.iter().map(|&s| s as u8).collect(),
60 }
61 }
62}
63
64const SIGNATURE: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
65
66fn crc32_table() -> [u32; 256] {
67 let mut table = [0u32; 256];
68 for (n, entry) in table.iter_mut().enumerate() {
69 let mut c = n as u32;
70 for _ in 0..8 {
71 c = if c & 1 == 1 { 0xedb8_8320 ^ (c >> 1) } else { c >> 1 };
72 }
73 *entry = c;
74 }
75 table
76}
77
78pub(crate) fn crc32(parts: &[&[u8]]) -> u32 {
79 let table = crc32_table();
80 let mut c = 0xffff_ffffu32;
81 for part in parts {
82 for &b in *part {
83 c = table[((c ^ b as u32) & 0xff) as usize] ^ (c >> 8);
84 }
85 }
86 c ^ 0xffff_ffff
87}
88
89fn corrupt(message: &'static str) -> ErrorsJSL {
90 ErrorsJSL::RuntimeError(message)
91}
92
93fn paeth(a: u8, b: u8, c: u8) -> u8 {
95 let p = a as i16 + b as i16 - c as i16;
96 let (pa, pb, pc) = ((p - a as i16).abs(), (p - b as i16).abs(), (p - c as i16).abs());
97 if pa <= pb && pa <= pc {
98 a
99 } else if pb <= pc {
100 b
101 } else {
102 c
103 }
104}
105
106fn unfilter(data: &[u8], rows: usize, stride: usize, bpp: usize) -> Result<Vec<u8>, ErrorsJSL> {
108 if data.len() < rows * (stride + 1) {
109 return Err(corrupt("PNG image data is truncated."));
110 }
111 let mut out = vec![0u8; rows * stride];
112 for y in 0..rows {
113 let filter = data[y * (stride + 1)];
114 let line = &data[y * (stride + 1) + 1..(y + 1) * (stride + 1)];
115 let (done, current) = out.split_at_mut(y * stride);
116 let previous = if y > 0 { &done[(y - 1) * stride..] } else { &[][..] };
117 let current = &mut current[..stride];
118 for i in 0..stride {
119 let a = if i >= bpp { current[i - bpp] } else { 0 };
120 let b = if y > 0 { previous[i] } else { 0 };
121 let c = if y > 0 && i >= bpp { previous[i - bpp] } else { 0 };
122 let predictor = match filter {
123 0 => 0,
124 1 => a,
125 2 => b,
126 3 => ((a as u16 + b as u16) / 2) as u8,
127 4 => paeth(a, b, c),
128 _ => return Err(corrupt("Unknown PNG filter type.")),
129 };
130 current[i] = line[i].wrapping_add(predictor);
131 }
132 }
133 Ok(out)
134}
135fn unpack(row: &[u8], count: usize, depth: u8) -> Vec<u16> {
139 match depth {
140 16 => (0..count).map(|i| u16::from_be_bytes([row[2 * i], row[2 * i + 1]])).collect(),
141 8 => row[..count].iter().map(|&b| b as u16).collect(),
142 _ => {
143 let per_byte = 8 / depth as usize;
144 let mask = (1u16 << depth) - 1;
145 (0..count).map(|i| (row[i / per_byte] as u16 >> (8 - depth as usize * (i % per_byte + 1))) & mask).collect()
146 }
147 }
148}
149
150pub fn png_decode(data: &[u8]) -> Result<RasterImage, ErrorsJSL> {
152 if data.len() < 8 || data[..8] != SIGNATURE {
153 return Err(corrupt("Not a PNG file."));
154 }
155 let mut position = 8;
156 let (mut header, mut palette, mut transparency) = (None, None, None);
157 let mut compressed = Vec::new();
158 while position + 12 <= data.len() {
159 let length = u32::from_be_bytes(data[position..position + 4].try_into().expect("4 bytes")) as usize;
160 let kind = &data[position + 4..position + 8];
161 let end = position + 8 + length;
162 if end + 4 > data.len() {
163 return Err(corrupt("PNG chunk is truncated."));
164 }
165 let body = &data[position + 8..end];
166 let stored = u32::from_be_bytes(data[end..end + 4].try_into().expect("4 bytes"));
167 if crc32(&[kind, body]) != stored {
168 return Err(corrupt("PNG chunk CRC mismatch."));
169 }
170 match kind {
171 b"IHDR" => {
172 if body.len() != 13 {
173 return Err(corrupt("Bad IHDR chunk."));
174 }
175 header = Some(body.to_vec());
176 }
177 b"PLTE" => palette = Some(body.to_vec()),
178 b"tRNS" => transparency = Some(body.to_vec()),
179 b"IDAT" => compressed.extend_from_slice(body),
180 b"IEND" => break,
181 _ if kind[0] & 0x20 == 0 => return Err(corrupt("Unsupported critical PNG chunk.")),
182 _ => {}
183 }
184 position = end + 4;
185 }
186 let h = header.ok_or(corrupt("Missing IHDR chunk."))?;
187 let width = u32::from_be_bytes(h[0..4].try_into().expect("4 bytes")) as usize;
188 let height = u32::from_be_bytes(h[4..8].try_into().expect("4 bytes")) as usize;
189 let (depth, colour, interlace) = (h[8], h[9], h[12]);
190 let channels = match colour {
191 0 | 3 => 1,
192 2 => 3,
193 4 => 2,
194 6 => 4,
195 _ => return Err(corrupt("Unknown PNG colour type.")),
196 };
197 let depth_ok = match colour {
198 0 => [1, 2, 4, 8, 16].contains(&depth),
199 3 => [1, 2, 4, 8].contains(&depth),
200 _ => depth == 8 || depth == 16,
201 };
202 if !depth_ok || h[10] != 0 || h[11] != 0 || interlace > 1 || width == 0 || height == 0 {
203 return Err(corrupt("Unsupported PNG header."));
204 }
205 if width > i32::MAX as usize || height > i32::MAX as usize {
206 return Err(corrupt("PNG dimensions exceed 2^31 - 1."));
207 }
208 let raw = zlib_decompress(&compressed)?;
209 let bits_per_pixel = channels * depth as usize;
210 let bpp = bits_per_pixel.div_ceil(8);
211 let passes: Vec<(usize, usize, usize, usize)> =
212 if interlace == 1 { vec![(0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2)] } else { vec![(0, 0, 1, 1)] };
213 let needed = passes.iter().try_fold(0usize, |total, &(x0, y0, dx, dy)| {
215 let (pw, ph) = ((width.saturating_sub(x0)).div_ceil(dx), (height.saturating_sub(y0)).div_ceil(dy));
216 if pw == 0 || ph == 0 {
217 return Some(total);
218 }
219 let stride = pw.checked_mul(bits_per_pixel)?.div_ceil(8);
220 total.checked_add(ph.checked_mul(stride.checked_add(1)?)?)
221 });
222 if needed.is_none_or(|n| raw.len() < n) {
223 return Err(corrupt("PNG image data are shorter than the header implies."));
224 }
225 let mut samples = vec![0u16; width * height * channels];
227 let mut offset = 0;
228 for (x0, y0, dx, dy) in passes {
229 let (pw, ph) = ((width.saturating_sub(x0)).div_ceil(dx), (height.saturating_sub(y0)).div_ceil(dy));
230 if pw == 0 || ph == 0 {
231 continue;
232 }
233 let stride = (pw * bits_per_pixel).div_ceil(8);
234 let rows = unfilter(&raw[offset.min(raw.len())..], ph, stride, bpp)?;
235 offset += ph * (stride + 1);
236 for py in 0..ph {
237 let values = unpack(&rows[py * stride..(py + 1) * stride], pw * channels, depth);
238 for px in 0..pw {
239 let (x, y) = (x0 + px * dx, y0 + py * dy);
240 for c in 0..channels {
241 samples[(y * width + x) * channels + c] = values[px * channels + c];
242 }
243 }
244 }
245 }
246 if colour == 3 {
247 let palette = palette.ok_or(corrupt("Palette image without PLTE."))?;
248 let alpha = transparency.unwrap_or_default();
249 let out_channels = if alpha.is_empty() { 3 } else { 4 };
250 let mut expanded = Vec::with_capacity(width * height * out_channels);
251 for &index in &samples {
252 let i = index as usize;
253 if 3 * i + 2 >= palette.len() {
254 return Err(corrupt("Palette index out of range."));
255 }
256 expanded.extend(palette[3 * i..3 * i + 3].iter().map(|&v| v as u16));
257 if out_channels == 4 {
258 expanded.push(*alpha.get(i).unwrap_or(&255) as u16);
259 }
260 }
261 return RasterImage::new(width, height, out_channels, 8, expanded);
262 }
263 let out_depth = if depth == 16 { 16 } else { 8 };
264 if depth < 8 {
265 let scale = 255 / ((1u16 << depth) - 1);
266 samples.iter_mut().for_each(|s| *s *= scale);
267 }
268 RasterImage::new(width, height, channels, out_depth, samples)
269}
270
271pub fn png_encode(image: &RasterImage, level: u8) -> Result<Vec<u8>, ErrorsJSL> {
273 image.validate()?;
274 if image.width == 0 || image.height == 0 {
275 return Err(ErrorsJSL::InvalidInputRange("PNG images cannot be empty."));
276 }
277 let colour = match image.channels {
278 1 => 0u8,
279 2 => 4,
280 3 => 2,
281 _ => 6,
282 };
283 let bytes_per_sample = image.bit_depth as usize / 8;
284 let bpp = image.channels * bytes_per_sample;
285 let stride = image.width * bpp;
286 let packed: Vec<u8> = if image.bit_depth == 16 { image.samples.iter().flat_map(|s| s.to_be_bytes()).collect() } else { image.samples.iter().map(|&s| s as u8).collect() };
287 let mut filtered = Vec::with_capacity(image.height * (stride + 1));
288 let mut candidate = vec![0u8; stride];
289 for y in 0..image.height {
290 let row = &packed[y * stride..(y + 1) * stride];
291 let previous = if y > 0 { &packed[(y - 1) * stride..y * stride] } else { &[][..] };
292 let mut best: (u64, u8, Vec<u8>) = (u64::MAX, 0, Vec::new());
293 for filter in 0..5u8 {
294 for i in 0..stride {
295 let a = if i >= bpp { row[i - bpp] } else { 0 };
296 let b = if y > 0 { previous[i] } else { 0 };
297 let c = if y > 0 && i >= bpp { previous[i - bpp] } else { 0 };
298 let predictor = match filter {
299 0 => 0,
300 1 => a,
301 2 => b,
302 3 => ((a as u16 + b as u16) / 2) as u8,
303 _ => paeth(a, b, c),
304 };
305 candidate[i] = row[i].wrapping_sub(predictor);
306 }
307 let cost: u64 = candidate.iter().map(|&v| (v as i8).unsigned_abs() as u64).sum();
308 if cost < best.0 {
309 best = (cost, filter, candidate.clone());
310 }
311 }
312 filtered.push(best.1);
313 filtered.extend_from_slice(&best.2);
314 }
315 let mut out = SIGNATURE.to_vec();
316 let mut chunk = |kind: &[u8; 4], body: &[u8]| {
317 out.extend_from_slice(&(body.len() as u32).to_be_bytes());
318 out.extend_from_slice(kind);
319 out.extend_from_slice(body);
320 out.extend_from_slice(&crc32(&[kind, body]).to_be_bytes());
321 };
322 let mut header = Vec::with_capacity(13);
323 header.extend_from_slice(&(image.width as u32).to_be_bytes());
324 header.extend_from_slice(&(image.height as u32).to_be_bytes());
325 header.extend_from_slice(&[image.bit_depth, colour, 0, 0, 0]);
326 chunk(b"IHDR", &header);
327 chunk(b"IDAT", &zlib_compress(&filtered, level));
328 chunk(b"IEND", &[]);
329 Ok(out)
330}
331
332pub fn read_png_file(path: impl AsRef<Path>) -> Result<RasterImage, ErrorsJSL> {
334 let data = std::fs::read(path).map_err(|_| ErrorsJSL::RuntimeError("Could not read the PNG file."))?;
335 png_decode(&data)
336}
337
338pub fn write_png_file(path: impl AsRef<Path>, image: &RasterImage) -> Result<(), ErrorsJSL> {
340 std::fs::write(path, png_encode(image, 6)?).map_err(|_| ErrorsJSL::RuntimeError("Could not write the PNG file."))
341}
342
343#[cfg(test)]
344mod tests {
345 use super::*;
346
347 #[test]
348 fn a_header_promising_more_data_than_the_file_holds_is_an_error() {
349 let image = RasterImage::new(4, 4, 1, 8, vec![9; 16]).unwrap();
352 let mut bytes = png_encode(&image, 6).unwrap();
353 bytes[16..20].copy_from_slice(&0x7fff_ffffu32.to_be_bytes());
354 bytes[20..24].copy_from_slice(&0x7fff_ffffu32.to_be_bytes());
355 let crc = crc32(&[&bytes[12..16], &bytes[16..29]]);
356 bytes[29..33].copy_from_slice(&crc.to_be_bytes());
357 assert!(png_decode(&bytes).is_err());
358 }
359
360 const FILTERED_RGB: &[u8] = &[
363 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 4, 0, 0, 0, 3, 8, 2,
364 0, 0, 0, 59, 150, 57, 145, 0, 0, 0, 27, 73, 68, 65, 84, 120, 218, 99, 100, 96, 248, 111, 35,
365 119, 14, 130, 152, 68, 220, 190, 193, 17, 11, 136, 146, 131, 34, 0, 13, 139, 14, 135, 144,
366 81, 59, 57, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130,
367 ];
368 const ADAM7_GRAY: &[u8] = &[
370 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 10, 0, 0, 0, 9, 8, 0,
371 0, 0, 1, 89, 202, 210, 89, 0, 0, 0, 117, 73, 68, 65, 84, 120, 218, 99, 96, 176, 96, 200, 88,
372 192, 32, 195, 208, 194, 96, 18, 144, 195, 192, 167, 197, 224, 20, 199, 80, 54, 137, 65, 74,
373 195, 204, 37, 136, 193, 47, 38, 171, 162, 141, 129, 93, 84, 217, 208, 158, 65, 81, 223, 214,
374 59, 146, 193, 218, 51, 60, 181, 152, 33, 52, 185, 176, 190, 151, 33, 191, 182, 123, 230,
375 114, 6, 94, 17, 105, 37, 77, 3, 115, 59, 87, 31, 6, 117, 61, 83, 27, 103, 175, 192, 136,
376 248, 52, 6, 71, 15, 255, 176, 216, 148, 236, 162, 202, 6, 134, 232, 164, 204, 130, 242, 186,
377 214, 158, 201, 179, 0, 108, 97, 29, 92, 81, 53, 226, 176, 0, 0, 0, 0, 73, 69, 78, 68, 174,
378 66, 96, 130,
379 ];
380 const PALETTE_2BIT: &[u8] = &[
382 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 5, 0, 0, 0, 2, 2, 3,
383 0, 0, 0, 237, 4, 254, 206, 0, 0, 0, 12, 80, 76, 84, 69, 255, 0, 0, 0, 255, 0, 0, 0, 255, 9,
384 9, 9, 92, 113, 126, 134, 0, 0, 0, 3, 116, 82, 78, 83, 255, 128, 0, 127, 109, 104, 120, 0, 0,
385 0, 14, 73, 68, 65, 84, 120, 218, 99, 144, 118, 96, 120, 210, 0, 0, 3, 213, 1, 192, 188, 47,
386 210, 168, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130,
387 ];
388
389 #[test]
390 fn decodes_independently_encoded_images() {
391 let rgb = png_decode(FILTERED_RGB).unwrap();
392 assert_eq!((rgb.width, rgb.height, rgb.channels, rgb.bit_depth), (4, 3, 3, 8));
393 for y in 0..3 {
394 for x in 0..4 {
395 let want = [(x * 60 + y * 20) % 256, (x * 30 + y * 70) % 256, (255 - x * 50 - y * 10) % 256];
396 assert_eq!([rgb.sample(x, y, 0), rgb.sample(x, y, 1), rgb.sample(x, y, 2)], want.map(|v| v as u16), "({x}, {y})");
397 }
398 }
399 let gray = png_decode(ADAM7_GRAY).unwrap();
400 assert_eq!((gray.width, gray.height, gray.channels), (10, 9, 1));
401 assert!((0..9).all(|y| (0..10).all(|x| gray.sample(x, y, 0) == ((7 * x + 13 * y) % 256) as u16)));
402 let palette = png_decode(PALETTE_2BIT).unwrap();
403 assert_eq!(palette.channels, 4);
404 assert_eq!(&palette.samples[..8], &[255, 0, 0, 255, 0, 255, 0, 128]);
405 assert_eq!(&palette.samples[12..16], &[9, 9, 9, 255]); }
407
408 #[test]
409 fn round_trips_every_encodable_format_and_detects_corruption() {
410 for (channels, depth) in [(1, 8), (2, 8), (3, 8), (4, 8), (1, 16), (3, 16), (4, 16)] {
411 let (w, h) = (37, 23);
412 let max = if depth == 8 { 255 } else { 65535 };
413 let samples = (0..w * h * channels).map(|i| ((((i * 2654435761usize) >> 7) % (max + 1)) / if i % 3 == 0 { 1 } else { 7 }) as u16).collect();
414 let image = RasterImage::new(w, h, channels, depth, samples).unwrap();
415 let encoded = png_encode(&image, 6).unwrap();
416 assert_eq!(png_decode(&encoded).unwrap(), image, "{channels} channels, {depth} bits");
417 }
418 let gradient = RasterImage::new(256, 256, 1, 8, (0..65536).map(|i| ((i % 256 + i / 256) / 2) as u16).collect()).unwrap();
420 assert!(png_encode(&gradient, 9).unwrap().len() < 4000);
421 let mut bad = png_encode(&gradient, 6).unwrap();
422 bad[40] ^= 0xff;
423 assert!(png_decode(&bad).is_err());
424 assert!(png_decode(b"not a png").is_err());
425 assert!(RasterImage::new(2, 2, 5, 8, vec![0; 20]).is_err() && RasterImage::new(2, 2, 1, 8, vec![300; 4]).is_err());
426 }
427}