mln-rs-engine 0.0.22

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
// Encodes PNGs without a PNG library: unpremultiply, one IDAT chunk with
// filter type 0 on every scanline, zlib-compressed by `compress`.

use flate2::{Compress, Compression, FlushCompress, Status};
use mln_style::bitmap::PremultipliedImage;

use crate::image::premultiply::unpremultiply;

fn deflate_zlib(raw: &[u8]) -> Vec<u8> {
    let mut compressor = Compress::new(Compression::new(6), true);
    let mut out = Vec::with_capacity(raw.len().clamp(64, 64 * 1024));
    loop {
        let consumed = compressor.total_in() as usize;
        let before_out = compressor.total_out();
        if out.len() == out.capacity() {
            out.reserve(out.len().max(1024));
        }
        match compressor.compress_vec(&raw[consumed..], &mut out, FlushCompress::Finish) {
            Ok(Status::StreamEnd) | Err(_) => break,
            Ok(Status::Ok | Status::BufError) => {
                if compressor.total_out() == before_out && out.len() == out.capacity() {
                    out.reserve(out.len().max(1024));
                }
            }
        }
    }
    out
}

fn network_byte_u32(value: u32) -> [u8; 4] {
    value.to_be_bytes()
}

fn add_chunk(png: &mut Vec<u8>, kind: [u8; 4], data: &[u8]) {
    // Checksum encompasses type + data
    let mut checksum = flate2::Crc::new();
    checksum.update(&kind);
    checksum.update(data);

    let size = data.len() as u32;
    png.reserve(4 /* length */ + 4 /* type */ + data.len() + 4 /* CRC */);
    png.extend_from_slice(&network_byte_u32(size));
    png.extend_from_slice(&kind);
    png.extend_from_slice(data);
    png.extend_from_slice(&network_byte_u32(checksum.sum()));
}

#[must_use]
pub fn encode_png(pre: &PremultipliedImage) -> Vec<u8> {
    // Make copy of the image so that we can unpremultiply it.
    let src = unpremultiply(pre.clone());

    // PNG magic bytes
    let preamble: [u8; 8] = [0x89, b'P', b'N', b'G', b'\r', b'\n', 0x1a, b'\n'];

    // IHDR chunk for our RGBA image.
    let mut ihdr = [0u8; 13];
    ihdr[0..4].copy_from_slice(&network_byte_u32(src.size.width)); // width
    ihdr[4..8].copy_from_slice(&network_byte_u32(src.size.height)); // height
    ihdr[8] = 8; // bit depth == 8 bits
    ihdr[9] = 6; // color type == RGBA
    ihdr[10] = 0; // compression method == deflate
    ihdr[11] = 0; // filter method == default
    ihdr[12] = 0; // interlace method == none

    // Prepare the (compressed) data chunk.
    let stride = src.stride();
    let mut idat = Vec::with_capacity((stride + 1) * src.size.height as usize);
    for y in 0..src.size.height as usize {
        // Every scanline needs to be prefixed with one byte that indicates the filter type.
        idat.push(0); // filter type 0
        idat.extend_from_slice(&src.data[y * stride..(y + 1) * stride]);
    }
    let idat = deflate_zlib(&idat);

    // Assemble the PNG.
    let mut png = Vec::with_capacity(8 + (12 + 13) + (12 + idat.len()) + 12);
    png.extend_from_slice(&preamble);
    add_chunk(&mut png, *b"IHDR", &ihdr);
    add_chunk(&mut png, *b"IDAT", &idat);
    add_chunk(&mut png, *b"IEND", &[]);
    png
}

#[cfg(test)]
mod tests {
    use mln_style::size::Size;

    use super::*;
    use crate::image::image::decode_image;
    use crate::image::premultiply::premultiply;

    /// An encoded image decodes as the image it was, up to the rounding of
    /// unpremultiplying and premultiplying it again.
    #[test]
    fn an_encoded_png_decodes_to_its_image() {
        let mut every_alpha = Vec::new();
        for y in 0..3u32 {
            for x in 0..256u32 {
                let a = x as u8;
                let c = (((x * (y + 1)) % 256) as u8).min(a);
                every_alpha.extend_from_slice(&[c, c / 2, 0, a]);
            }
        }
        for image in [
            PremultipliedImage::from_vec(Size::new(1, 1), vec![128, 0, 0, 255]),
            PremultipliedImage::from_vec(Size::new(1, 1), vec![128, 0, 0, 128]),
            PremultipliedImage::from_vec(Size::new(256, 3), every_alpha),
        ] {
            let png = encode_png(&image);
            assert_eq!(&png[..8], &[0x89, b'P', b'N', b'G', b'\r', b'\n', 0x1a, b'\n']);
            assert_eq!(decode_image(&png).unwrap(), premultiply(unpremultiply(image.clone())), "{:?}", image.size);
        }
    }

    #[test]
    fn a_truncated_png_fails_to_decode() {
        for data in [&b"\x89PNG"[..], b"\x89PNGxxxxxxxx"] {
            assert_eq!(
                crate::image::png_reader::decode_png(data).unwrap_err().message,
                "invalid PNG: no PNG signature"
            );
        }
        let truncated = &encode_png(&PremultipliedImage::new(Size::new(4, 4)))[..40];
        assert!(crate::image::png_reader::decode_png(truncated).unwrap_err().message.starts_with("invalid PNG: "));
    }
}