mln-rs-engine 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
use mln_style::bitmap::PremultipliedImage;
use mln_style::error::Error;

/// The image formats `decode_image` recognizes, by their magic bytes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ImageType {
    Png,
    Webp,
    Jpeg,
}

/// The type of the image in `data` by its magic bytes, if it is one of the
/// three.
#[must_use]
pub(crate) fn image_type(data: &[u8]) -> Option<ImageType> {
    let read_uint = |offset: usize| -> u32 {
        let ptr = &data[offset..offset + 4];
        (u32::from(ptr[0]) << 24) | (u32::from(ptr[1]) << 16) | (u32::from(ptr[2]) << 8) | u32::from(ptr[3])
    };

    let size = data.len();

    if size >= 16 {
        let magic1 = read_uint(0x0);
        let magic2 = read_uint(0x8);
        // RIFF <xxxx = file size> WEBP
        if magic1 == 0x5249_4646 && magic2 == 0x5745_4250 {
            return Some(ImageType::Webp);
        }
    }

    if size >= 4 {
        let magic = read_uint(0x0);
        if magic == 0x8950_4E47 {
            return Some(ImageType::Png);
        }
    }

    if size >= 2 {
        let magic = (u16::from(data[0]) << 8) | u16::from(data[1]);
        if magic == 0xFFD8 {
            return Some(ImageType::Jpeg);
        }
    }

    None
}

/// The message of the error for data of no type `decode_image` recognizes.
pub(crate) const UNSUPPORTED: &str = "unsupported image type";

/// Decodes `data`, choosing the format by its magic bytes. Data of no type
/// it recognizes fails with
/// [`ErrorKind::Unsupported`](mln_style::error::ErrorKind), and an image that
/// doesn't decode with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind).
pub fn decode_image(data: &[u8]) -> Result<PremultipliedImage, Error> {
    match image_type(data) {
        Some(ImageType::Webp) => crate::image::webp_reader::decode_webp(data),
        Some(ImageType::Png) => crate::image::png_reader::decode_png(data),
        #[cfg(not(target_family = "wasm"))]
        Some(ImageType::Jpeg) => crate::image::jpeg_reader::decode_jpeg(data),
        // The browser build decodes JPEG with the browser (`decoder::decode`).
        #[cfg(target_family = "wasm")]
        Some(ImageType::Jpeg) => Err(Error::unsupported("JPEG Reader: JPEG is decoded by the browser")),
        None => Err(Error::unsupported(UNSUPPORTED)),
    }
}

/// Widens the pixels of `N` bytes packed at the front of `data` to the
/// four-byte pixels that fill it, each by `to_rgba`, in place.
pub(crate) fn expand_to_rgba<const N: usize>(data: &mut [u8], to_rgba: impl Fn([u8; N]) -> [u8; 4]) {
    // Back to front: a pixel's wider copy lands at or past where it was, so
    // it overwrites only pixels already widened.
    for i in (0..data.len() / 4).rev() {
        let mut pixel = [0; N];
        pixel.copy_from_slice(&data[i * N..i * N + N]);
        data[i * 4..i * 4 + 4].copy_from_slice(&to_rgba(pixel));
    }
}

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

    use super::*;

    fn read_file(path: &str) -> Vec<u8> {
        let path = std::path::Path::new(&std::env::var_os("CARGO_MANIFEST_DIR").unwrap()).join("testdata").join(path);
        std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()))
    }

    #[test]
    fn pngs_decode_premultiplied_whatever_their_color_profile() {
        // (fixture, first pixel)
        let cases = [
            ("no_profile.png", [128, 0, 0, 255]),
            ("no_profile_alpha.png", [64, 0, 0, 128]),
            ("profile.png", [128, 0, 0, 255]),
            ("profile_alpha.png", [64, 0, 0, 128]),
        ];
        for (fixture, pixel) in cases {
            let image = decode_image(&read_file(&format!("test/fixtures/image/{fixture}"))).unwrap();
            assert_eq!(image.data[..4], pixel, "{fixture}");
        }
    }

    #[test]
    fn png_jpeg_and_webp_tiles_decode_at_their_size() {
        for (fixture, size) in [
            ("test/fixtures/image/tile.png", 256),
            ("test/fixtures/image/tile.jpeg", 256),
            ("test/fixtures/image/tile.webp", 256),
            // Lossless (VP8L) and opaque.
            ("metrics/integration/tiles/1-0-0.ocean.webp", 512),
        ] {
            let image = decode_image(&read_file(fixture)).unwrap();
            assert_eq!(image.size, Size::new(size, size), "{fixture}");
            if fixture.ends_with("ocean.webp") {
                assert!(image.data.as_chunks::<4>().0.iter().all(|p| p[3] == 255));
            }
        }
    }

    #[test]
    fn unsupported_and_corrupt_images_fail_to_decode() {
        assert_eq!(decode_image(b"").unwrap_err(), Error::unsupported("unsupported image type"));
        assert_eq!(decode_image(b"GIF89a").unwrap_err(), Error::unsupported("unsupported image type"));

        let mut webp = b"RIFF\x10\x00\x00\x00WEBPVP8L".to_vec();
        webp.extend_from_slice(&[0u8; 8]);
        let error = decode_image(&webp).unwrap_err();
        assert_eq!(error.kind, mln_style::error::ErrorKind::InvalidArgument);
        assert!(error.message.starts_with("invalid WebP: "), "{error}");
    }
}