crates/format/image/src/png.rs 7.4 KiB 233 lines Raw
1 //! A png encoder with stored deflate blocks.2 //!3 //! The engine needs a correct png, not a small one, so the encoder never4 //! searches for a match. Every scanline carries filter byte 0 and the zlib5 //! stream holds the filtered bytes in stored blocks. The bytes are legal for6 //! every reader and the encoder is small enough to audit.7 8 use crate::ImageError;9 use crate::pixel::{Format, Frame, expected_len};10 11 /// The eight bytes that every png starts with.12 const SIGNATURE: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];13 14 /// The largest side that the png header can carry. The field is 31 bits.15 const MAX_SIDE: u32 = i32::MAX as u32;16 17 /// The bit depth of every format that the engine carries.18 const BIT_DEPTH: u8 = 8;19 20 /// The png colour type for each format.21 const COLOR_RGB: u8 = 2;22 const COLOR_RGBA: u8 = 6;23 const COLOR_GRAY: u8 = 0;24 25 /// The only compression and filter methods that png defines for now.26 const METHOD_DEFLATE: u8 = 0;27 const FILTER_ADAPTIVE: u8 = 0;28 29 /// The only interlace method that this encoder writes.30 const INTERLACE_NONE: u8 = 0;31 32 /// No scanline is filtered. The stored block framing is the part under test.33 const FILTER_NONE: u8 = 0;34 35 /// The zlib header. `CMF` is deflate with a 32 KiB window. `FLG` gives FLEVEL36 /// 0 and an FCHECK that makes the two bytes a multiple of 31, as zlib requires.37 const ZLIB_CMF: u8 = 0x78;38 const ZLIB_FLG: u8 = 0x01;39 40 /// A deflate stored block carries at most `u16::MAX` bytes.41 const STORED_MAX: usize = u16::MAX as usize;42 43 /// The first byte of a stored block. Bit 0 is BFINAL, bits 1 and 2 are BTYPE44 /// 00. A non-final block therefore starts with zero.45 const STORED_MORE: u8 = 0x00;46 const STORED_FINAL: u8 = 0x01;47 48 /// A stored block writes the length, its complement, and the bytes.49 const STORED_HEADER_LEN: usize = 5;50 51 /// The two header bytes of the zlib stream and its four Adler-32 bytes.52 const ZLIB_HEADER_LEN: usize = 2;53 const ZLIB_ADLER_LEN: usize = 4;54 55 /// Adler-32 works modulo the largest prime below 65536.56 const ADLER_MOD: u32 = 65_521;57 const ADLER_INIT: u32 = 1;58 59 /// The reflected CRC-32 polynomial that png uses.60 const CRC_POLY: u32 = 0xEDB8_8320;61 const CRC_INIT: u32 = 0xFFFF_FFFF;62 63 /// A png of one image.64 pub fn encode(frame: &Frame) -> Result<Vec<u8>, ImageError> {65     if frame.width == 0 || frame.height == 0 {66         return Err(ImageError::Empty);67     }68     if frame.width > MAX_SIDE || frame.height > MAX_SIDE {69         return Err(ImageError::TooLarge);70     }71     let want = expected_len(frame.format, frame.width, frame.height).ok_or(ImageError::Size)?;72     if frame.pixels.len() != want {73         return Err(ImageError::Size);74     }75     let raw = stored_bytes(frame)?;76     Ok(encode_valid(frame, &raw))77 }78 79 /// The png of one opaque white pixel: the smallest legal image, used by a80 /// conformance plugin.81 pub fn one_pixel() -> Vec<u8> {82     let frame = Frame {83         format: Format::Rgba8,84         width: 1,85         height: 1,86         pixels: vec![0xFF, 0xFF, 0xFF, 0xFF],87     };88     let raw = [FILTER_NONE, 0xFF, 0xFF, 0xFF, 0xFF];89     encode_valid(&frame, &raw)90 }91 92 /// The bytes of a frame that [`encode`] has already checked.93 fn encode_valid(frame: &Frame, raw: &[u8]) -> Vec<u8> {94     let color = match frame.format {95         Format::Rgb8 => COLOR_RGB,96         Format::Rgba8 => COLOR_RGBA,97         Format::Gray8 => COLOR_GRAY,98     };99     let mut ihdr = Vec::with_capacity(13);100     ihdr.extend_from_slice(&frame.width.to_be_bytes());101     ihdr.extend_from_slice(&frame.height.to_be_bytes());102     ihdr.push(BIT_DEPTH);103     ihdr.push(color);104     ihdr.push(METHOD_DEFLATE);105     ihdr.push(FILTER_ADAPTIVE);106     ihdr.push(INTERLACE_NONE);107 108     let mut out = Vec::new();109     out.extend_from_slice(&SIGNATURE);110     chunk(&mut out, b"IHDR", &ihdr);111     let idat = zlib(raw);112     chunk(&mut out, b"IDAT", &idat);113     chunk(&mut out, b"IEND", &[]);114     out115 }116 117 /// The scanlines with the filter byte that every row starts with.118 ///119 /// `None` means the length does not fit the zlib framing, which only a frame120 /// that skipped [`Frame::new`] can cause.121 fn stored_bytes(frame: &Frame) -> Result<Vec<u8>, ImageError> {122     let stride = frame.stride();123     let row = stride.checked_add(1).ok_or(ImageError::Size)?;124     let len = row125         .checked_mul(frame.height as usize)126         .ok_or(ImageError::Size)?;127     let blocks = len.div_ceil(STORED_MAX);128     let framed = len129         .checked_add(blocks.saturating_mul(STORED_HEADER_LEN))130         .and_then(|n| n.checked_add(ZLIB_HEADER_LEN + ZLIB_ADLER_LEN))131         .ok_or(ImageError::Size)?;132     if u32::try_from(framed).is_err() {133         return Err(ImageError::Size);134     }135     let mut raw = Vec::with_capacity(len);136     for y in 0..frame.height {137         let start = y as usize * stride;138         let end = start + stride;139         let Some(row) = frame.pixels.get(start..end) else {140             return Err(ImageError::Size);141         };142         raw.push(FILTER_NONE);143         raw.extend_from_slice(row);144     }145     Ok(raw)146 }147 148 /// One png chunk: length, type, data, and the CRC of type and data.149 fn chunk(out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {150     // `encode` bounds the whole zlib stream to u32, so every length here fits.151     out.extend_from_slice(&(data.len() as u32).to_be_bytes());152     out.extend_from_slice(kind);153     out.extend_from_slice(data);154     out.extend_from_slice(&crc32(&[kind, data]).to_be_bytes());155 }156 157 /// A zlib stream with stored deflate blocks and a trailing Adler-32.158 fn zlib(raw: &[u8]) -> Vec<u8> {159     let mut out = Vec::with_capacity(raw.len() + raw.len() / STORED_MAX * STORED_HEADER_LEN + 6);160     out.push(ZLIB_CMF);161     out.push(ZLIB_FLG);162     if raw.is_empty() {163         out.push(STORED_FINAL);164         out.extend_from_slice(&0u16.to_le_bytes());165         out.extend_from_slice(&(!0u16).to_le_bytes());166     } else {167         let mut at = 0;168         while at < raw.len() {169             let end = (at + STORED_MAX).min(raw.len());170             let block = &raw[at..end];171             let final_block = end == raw.len();172             out.push(if final_block {173                 STORED_FINAL174             } else {175                 STORED_MORE176             });177             let len = block.len() as u16;178             out.extend_from_slice(&len.to_le_bytes());179             out.extend_from_slice(&(!len).to_le_bytes());180             out.extend_from_slice(block);181             at = end;182         }183     }184     out.extend_from_slice(&adler32(raw).to_be_bytes());185     out186 }187 188 /// The CRC-32 of the parts, in order.189 fn crc32(parts: &[&[u8]]) -> u32 {190     let mut crc = CRC_INIT;191     for part in parts {192         for &byte in *part {193             let index = ((crc ^ u32::from(byte)) & 0xFF) as usize;194             crc = CRC_TABLE[index] ^ (crc >> 8);195         }196     }197     !crc198 }199 200 /// Adler-32 of the raw scanlines, which zlib puts after the blocks.201 fn adler32(data: &[u8]) -> u32 {202     let mut a = ADLER_INIT;203     let mut b = 0u32;204     for &byte in data {205         a = (a + u32::from(byte)) % ADLER_MOD;206         b = (b + a) % ADLER_MOD;207     }208     (b << 16) | a209 }210 211 /// The table that makes CRC-32 one lookup per byte.212 const CRC_TABLE: [u32; 256] = crc_table();213 214 /// Builds [`CRC_TABLE`] at compile time, so no run-time state is needed.215 const fn crc_table() -> [u32; 256] {216     let mut table = [0u32; 256];217     let mut i = 0;218     while i < 256 {219         let mut crc = i as u32;220         let mut bit = 0;221         while bit < 8 {222             crc = if crc & 1 == 0 {223                 crc >> 1224             } else {225                 CRC_POLY ^ (crc >> 1)226             };227             bit += 1;228         }229         table[i] = crc;230         i += 1;231     }232     table233 }