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.78usecrate::ImageError;9usecrate::pixel::{Format, Frame, expected_len};1011/// The eight bytes that every png starts with.12constSIGNATURE: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];1314/// The largest side that the png header can carry. The field is 31 bits.15constMAX_SIDE: u32 = i32::MAXas u32;1617/// The bit depth of every format that the engine carries.18constBIT_DEPTH: u8 = 8;1920/// The png colour type for each format.21constCOLOR_RGB: u8 = 2;22constCOLOR_RGBA: u8 = 6;23constCOLOR_GRAY: u8 = 0;2425/// The only compression and filter methods that png defines for now.26constMETHOD_DEFLATE: u8 = 0;27constFILTER_ADAPTIVE: u8 = 0;2829/// The only interlace method that this encoder writes.30constINTERLACE_NONE: u8 = 0;3132/// No scanline is filtered. The stored block framing is the part under test.33constFILTER_NONE: u8 = 0;3435/// 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.37constZLIB_CMF: u8 = 0x78;38constZLIB_FLG: u8 = 0x01;3940/// A deflate stored block carries at most `u16::MAX` bytes.41constSTORED_MAX: usize = u16::MAXas usize;4243/// 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.45constSTORED_MORE: u8 = 0x00;46constSTORED_FINAL: u8 = 0x01;4748/// A stored block writes the length, its complement, and the bytes.49constSTORED_HEADER_LEN: usize = 5;5051/// The two header bytes of the zlib stream and its four Adler-32 bytes.52constZLIB_HEADER_LEN: usize = 2;53constZLIB_ADLER_LEN: usize = 4;5455/// Adler-32 works modulo the largest prime below 65536.56constADLER_MOD: u32 = 65_521;57constADLER_INIT: u32 = 1;5859/// The reflected CRC-32 polynomial that png uses.60constCRC_POLY: u32 = 0xEDB8_8320;61constCRC_INIT: u32 = 0xFFFF_FFFF;6263/// A png of one image.64pubfnencode(frame: &Frame) -> Result<Vec<u8>, ImageError> {65if frame.width == 0 || frame.height == 0 {66returnErr(ImageError::Empty);67 }68if frame.width > MAX_SIDE || frame.height > MAX_SIDE {69returnErr(ImageError::TooLarge);70 }71let want = expected_len(frame.format, frame.width, frame.height).ok_or(ImageError::Size)?;72if frame.pixels.len() != want {73returnErr(ImageError::Size);74 }75let raw = stored_bytes(frame)?;76Ok(encode_valid(frame, &raw))77 }7879/// The png of one opaque white pixel: the smallest legal image, used by a80/// conformance plugin.81pubfnone_pixel() -> Vec<u8> {82let frame = Frame {83 format: Format::Rgba8,84 width: 1,85 height: 1,86 pixels: vec![0xFF, 0xFF, 0xFF, 0xFF],87 };88let raw = [FILTER_NONE, 0xFF, 0xFF, 0xFF, 0xFF];89encode_valid(&frame, &raw)90 }9192/// The bytes of a frame that [`encode`] has already checked.93fnencode_valid(frame: &Frame, raw: &[u8]) -> Vec<u8> {94let color = match frame.format {95Format::Rgb8 => COLOR_RGB,96Format::Rgba8 => COLOR_RGBA,97Format::Gray8 => COLOR_GRAY,98 };99letmut 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);107108letmut out = Vec::new();109 out.extend_from_slice(&SIGNATURE);110chunk(&mut out, b"IHDR", &ihdr);111let idat = zlib(raw);112chunk(&mut out, b"IDAT", &idat);113chunk(&mut out, b"IEND", &[]);114 out115 }116117/// 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.121fnstored_bytes(frame: &Frame) -> Result<Vec<u8>, ImageError> {122let stride = frame.stride();123let row = stride.checked_add(1).ok_or(ImageError::Size)?;124let len = row125 .checked_mul(frame.height as usize)126 .ok_or(ImageError::Size)?;127let blocks = len.div_ceil(STORED_MAX);128let 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)?;132if u32::try_from(framed).is_err() {133returnErr(ImageError::Size);134 }135letmut raw = Vec::with_capacity(len);136for y in0..frame.height {137let start = y as usize * stride;138let end = start + stride;139letSome(row) = frame.pixels.get(start..end) else {140returnErr(ImageError::Size);141 };142 raw.push(FILTER_NONE);143 raw.extend_from_slice(row);144 }145Ok(raw)146 }147148/// One png chunk: length, type, data, and the CRC of type and data.149fnchunk(out: &mutVec<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 }156157/// A zlib stream with stored deflate blocks and a trailing Adler-32.158fnzlib(raw: &[u8]) -> Vec<u8> {159letmut out = Vec::with_capacity(raw.len() + raw.len() / STORED_MAX * STORED_HEADER_LEN + 6);160 out.push(ZLIB_CMF);161 out.push(ZLIB_FLG);162if 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 {167letmut at = 0;168while at < raw.len() {169let end = (at + STORED_MAX).min(raw.len());170let block = &raw[at..end];171let final_block = end == raw.len();172 out.push(if final_block {173STORED_FINAL174 } else {175STORED_MORE176 });177let 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 }187188/// The CRC-32 of the parts, in order.189fncrc32(parts: &[&[u8]]) -> u32 {190letmut crc = CRC_INIT;191for part in parts {192for &byte in *part {193let index = ((crc ^ u32::from(byte)) & 0xFF) as usize;194 crc = CRC_TABLE[index] ^ (crc >> 8);195 }196 }197 !crc198 }199200/// Adler-32 of the raw scanlines, which zlib puts after the blocks.201fnadler32(data: &[u8]) -> u32 {202letmut a = ADLER_INIT;203letmut b = 0u32;204for &byte in data {205 a = (a + u32::from(byte)) % ADLER_MOD;206 b = (b + a) % ADLER_MOD;207 }208 (b << 16) | a209 }210211/// The table that makes CRC-32 one lookup per byte.212constCRC_TABLE: [u32; 256] = crc_table();213214/// Builds [`CRC_TABLE`] at compile time, so no run-time state is needed.215constfncrc_table() -> [u32; 256] {216letmut table = [0u32; 256];217letmut i = 0;218while i < 256 {219letmut crc = i as u32;220letmut bit = 0;221while bit < 8 {222 crc = if crc & 1 == 0 {223 crc >> 1224 } else {225CRC_POLY ^ (crc >> 1)226 };227 bit += 1;228 }229 table[i] = crc;230 i += 1;231 }232 table233 }