mln-rs-engine 0.0.21

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
// zune-jpeg decodes every color space the reader accepts to RGB:
//
//   grayscale    -> the gray, replicated
//   YCbCr, RGB   -> RGB
//   CMYK, YCCK   -> RGB, as R = C' * K' / 255 (and so on for G and B) of the
//                   inverted CMYK that Adobe's JPEGs store, YCCK's C', M'
//                   and Y' the complements of its YCC's RGB
//
// The decoder runs in strict mode, so that truncated data and stray bytes or
// markers fail rather than decode to a partial image.

use mln_style::bitmap::PremultipliedImage;
use mln_style::error::Error;
use mln_style::size::Size;
use zune_jpeg::JpegDecoder;
use zune_jpeg::errors::DecodeErrors;
use zune_jpeg::zune_core::bytestream::ZCursor;
use zune_jpeg::zune_core::colorspace::ColorSpace;
use zune_jpeg::zune_core::options::DecoderOptions;

pub(crate) fn decode_jpeg(data: &[u8]) -> Result<PremultipliedImage, Error> {
    let invalid = |e: DecodeErrors| Error::invalid_argument(format!("invalid JPEG: {e}"));
    let options = DecoderOptions::default().set_strict_mode(true).jpeg_set_out_colorspace(ColorSpace::RGB);

    let mut decoder = JpegDecoder::new_with_options(ZCursor::new(data), options);
    decoder.decode_headers().map_err(invalid)?;
    match decoder.input_colorspace() {
        Some(ColorSpace::Luma | ColorSpace::YCbCr | ColorSpace::RGB | ColorSpace::CMYK | ColorSpace::YCCK) => {}
        other => return Err(Error::invalid_argument(format!("invalid JPEG: unsupported color space {other:?}"))),
    }

    let pixels = decoder.decode().map_err(invalid)?;
    let Some((width, height)) = decoder.dimensions().filter(|&(width, height)| width > 0 && height > 0) else {
        return Err(Error::invalid_argument("invalid JPEG: empty image"));
    };

    // zune-jpeg caps both dimensions far below u32::MAX.
    let mut image = PremultipliedImage::new(Size::new(width as u32, height as u32));
    for (src, dst) in pixels.as_chunks::<3>().0.iter().zip(image.data.as_chunks_mut::<4>().0) {
        *dst = [src[0], src[1], src[2], 0xff];
    }
    Ok(image)
}

#[cfg(test)]
mod tests {
    // The expected pixels are libjpeg-turbo's (`djpeg -pnm`).
    use super::*;

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

    fn tile() -> Vec<u8> {
        read("testdata/test/fixtures/image/tile.jpeg")
    }

    /// The fixture, with its Adobe marker's color transform set to
    /// `transform` (0: CMYK, 2: YCCK).
    fn adobe(transform: u8) -> Vec<u8> {
        let mut data = read("tests/fixtures/ycck.jpeg");
        let adobe = data.windows(5).position(|w| w == b"Adobe").unwrap();
        data[adobe + 11] = transform;
        data
    }

    #[test]
    fn opaque() {
        let image = decode_jpeg(&tile()).unwrap();
        assert!(image.data.as_chunks::<4>().0.iter().all(|p| p[3] == 255));
    }

    #[test]
    fn grayscale_is_replicated() {
        let image = decode_jpeg(&read("tests/fixtures/gray.jpeg")).unwrap();
        assert_eq!(&image.data[..4], &[111, 111, 111, 255]);
        assert!(image.data.as_chunks::<4>().0.iter().all(|p| p[0] == p[1] && p[1] == p[2]));
    }

    // The fixture's first pixel stores C' = 5, M' = 139, Y' = 130 and
    // K' = 115 (inverted, as Adobe stores CMYK), so R = 5 * 115 / 255 = 2,
    // G = 139 * 115 / 255 = 63 and B = 130 * 115 / 255 = 59.
    #[test]
    fn cmyk_converts_to_rgb() {
        let image = decode_jpeg(&adobe(0)).unwrap();
        assert_eq!(&image.data[..4], &[2, 63, 59, 255]);
    }

    // As YCCK, the first pixel's YCC is the RGB (8, 0, 24), so C' = 247,
    // M' = 255, Y' = 231 and K' = 115.
    #[test]
    fn ycck_converts_to_rgb() {
        let image = decode_jpeg(&adobe(2)).unwrap();
        assert_eq!(&image.data[..4], &[111, 115, 104, 255]);
    }

    #[test]
    fn malformed() {
        let data = tile();
        for bytes in [&data[..2], &data[..data.len() / 2], b"\xff\xd8\xff\xc0\x00\x02"] {
            let error = decode_jpeg(bytes).unwrap_err();
            assert!(error.message.starts_with("invalid JPEG: "), "{error}");
        }
    }

    #[test]
    fn corrupt_never_panics() {
        let data = adobe(2);
        for len in 0..data.len() {
            let _ = decode_jpeg(&data[..len]);
        }
        let mut seed = 0x2545_f491_4f6c_dd1du64;
        for _ in 0..2000 {
            let mut corrupt = data.clone();
            for _ in 0..3 {
                seed ^= seed << 13;
                seed ^= seed >> 7;
                seed ^= seed << 17;
                let at = 2 + (seed as usize) % (corrupt.len() - 2);
                corrupt[at] = (seed >> 32) as u8;
            }
            let _ = decode_jpeg(&corrupt);
        }
    }
}