Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

16.6 KB
Raw Blame
//! Image decoding/encoding over ImageIO, and base64 for data URLs.
//!
//! Decoded pixels are premultiplied RGBA8 in sRGB, rows top-down — the layout of every bitmap in
//! the registry. Untagged and sRGB images are copied without color conversion (exactly like
//! Chrome's canvas, which treats untagged images as sRGB); tagged images in other color spaces
//! are converted to sRGB by CoreGraphics. EXIF orientation is applied, as Chrome does by default.
use objc2_core_foundation::{CFData, CFDictionary, CFMutableData, CFNumber, CFRetained, CFString, CFType, CGFloat, CGPoint, CGRect, CGSize};
use objc2_core_graphics::{
    kCGColorSpaceSRGB, CGBitmapContextCreate, CGBitmapInfo, CGColorRenderingIntent, CGColorSpace, CGColorSpaceModel, CGContext, CGDataProvider,
    CGImage, CGImageAlphaInfo, CGImageByteOrderInfo,
};
use objc2_image_io::{
    kCGImageDestinationLossyCompressionQuality, kCGImagePropertyOrientation, kCGImageSourceCreateThumbnailFromImageAlways,
    kCGImageSourceCreateThumbnailWithTransform, kCGImageSourceShouldCache, kCGImageSourceThumbnailMaxPixelSize, CGImageDestination, CGImageSource,
};

/// Premultiplied RGBA8, rows top-down, stride = width × 4.
pub struct Decoded {
    pub width: u32,
    pub height: u32,
    pub data: Vec<u8>,
}

pub(crate) fn srgb() -> CFRetained<CGColorSpace> {
    thread_local! {
        static SRGB: CFRetained<CGColorSpace> = CGColorSpace::with_name(Some(unsafe { kCGColorSpaceSRGB })).expect("sRGB color space");
    }
    SRGB.with(|s| s.clone())
}

/// Decode PNG / JPEG / GIF (first frame) / WebP / HEIC … into premultiplied RGBA.
pub fn decode(bytes: &[u8]) -> Result<Decoded, String> {
    if bytes.is_empty() {
        return Err("empty image data".into());
    }
    let data = CFData::from_bytes(bytes);
    let no_cache = CFDictionary::<CFString, CFType>::from_slices(&[unsafe { kCGImageSourceShouldCache }], &[objc2_core_foundation::CFBoolean::new(false) as &CFType]);
    let src = unsafe { CGImageSource::with_data(&data, Some(no_cache.as_opaque())) }.ok_or("unsupported image format")?;
    if unsafe { src.count() } == 0 {
        return Err("unsupported or corrupt image".into());
    }
    let idx = unsafe { src.primary_image_index() };
    let orientation = unsafe { src.properties_at_index(idx, None) }
        .and_then(|p| {
            let p: CFRetained<CFDictionary<CFString, CFType>> = unsafe { CFRetained::cast_unchecked(p) };
            p.get(unsafe { kCGImagePropertyOrientation })
        })
        .and_then(|v| v.downcast::<CFNumber>().ok())
        .and_then(|n| n.as_i32())
        .unwrap_or(1);
    let img = if (2..=8).contains(&orientation) {
        let plain = unsafe { src.image_at_index(idx, Some(no_cache.as_opaque())) }.ok_or("corrupt image")?;
        let side = CGImage::width(Some(&plain)).max(CGImage::height(Some(&plain)));
        let max = CFNumber::new_i64(side as i64);
        let t = objc2_core_foundation::CFBoolean::new(true);
        let opts = CFDictionary::<CFString, CFType>::from_slices(
            &[unsafe { kCGImageSourceCreateThumbnailWithTransform }, unsafe { kCGImageSourceCreateThumbnailFromImageAlways }, unsafe { kCGImageSourceThumbnailMaxPixelSize }, unsafe { kCGImageSourceShouldCache }],
            &[t as &CFType, t as &CFType, &*max as &CFType, objc2_core_foundation::CFBoolean::new(false) as &CFType],
        );
        unsafe { src.thumbnail_at_index(idx, Some(opts.as_opaque())) }.unwrap_or(plain)
    } else {
        unsafe { src.image_at_index(idx, Some(no_cache.as_opaque())) }.ok_or("corrupt image")?
    };
    to_premultiplied_rgba(&img).ok_or_else(|| "could not read image pixels".into())
}

fn is_srgb_or_untagged(cs: &CGColorSpace) -> bool {
    if CGColorSpace::model(Some(cs)) != CGColorSpaceModel::RGB {
        return false;
    }
    match CGColorSpace::name(Some(cs)) {
        Some(n) => {
            let n = n.to_string();
            n == "kCGColorSpaceSRGB" || n == "kCGColorSpaceDeviceRGB" || n == "kCGColorSpaceGenericRGB" && CGColorSpace::icc_data(Some(cs)).is_none()
        }
        None => CGColorSpace::icc_data(Some(cs)).is_none_or(|icc| is_srgb_icc(&icc.to_vec())),
    }
}

/// An embedded ICC profile that describes sRGB (the common "sRGB IEC61966-2.1" profiles).
fn is_srgb_icc(icc: &[u8]) -> bool {
    // 'desc' tag text contains "sRGB" in practically every sRGB profile in the wild.
    icc.len() > 132 && icc.windows(4).any(|w| w == b"sRGB")
}

/// Pixels of a CGImage as premultiplied sRGB RGBA, copying directly when the layout allows
/// (exact: PNG round trips stay bit-identical), drawing through CoreGraphics otherwise.
pub(crate) fn to_premultiplied_rgba(img: &CGImage) -> Option<Decoded> {
    let w = CGImage::width(Some(img));
    let h = CGImage::height(Some(img));
    if w == 0 || h == 0 || w > 32767 || h > 32767 || w * h > 268_435_456 {
        return None;
    }
    let bpc = CGImage::bits_per_component(Some(img));
    let bpp = CGImage::bits_per_pixel(Some(img));
    let alpha = CGImage::alpha_info(Some(img));
    let order = CGImage::byte_order_info(Some(img));
    let float = CGImage::bitmap_info(Some(img)).0 & (1 << 8) != 0;
    let cs = CGImage::color_space(Some(img));
    let direct = bpc == 8 && !float && (bpp == 24 || bpp == 32) && cs.as_deref().is_some_and(is_srgb_or_untagged) && CGImage::decode(Some(img)).is_null();
    if direct {
        if let Some(provider) = CGImage::data_provider(Some(img)) {
            if let Some(bytes) = CGDataProvider::data(Some(&provider)) {
                let src = bytes.to_vec();
                let stride = CGImage::bytes_per_row(Some(img));
                if src.len() >= stride * (h - 1) + w * bpp / 8 {
                    if let Some(out) = convert_8bit(&src, w, h, stride, bpp, alpha, order) {
                        return Some(Decoded { width: w as u32, height: h as u32, data: out });
                    }
                }
            }
        }
    }
    let mut out = vec![0u8; w * h * 4];
    let cg = unsafe { CGBitmapContextCreate(out.as_mut_ptr().cast(), w, h, 8, w * 4, Some(&srgb()), CGImageAlphaInfo::PremultipliedLast.0) }?;
    CGContext::set_blend_mode(Some(&cg), objc2_core_graphics::CGBlendMode::Copy);
    CGContext::draw_image(Some(&cg), CGRect { origin: CGPoint { x: 0.0, y: 0.0 }, size: CGSize { width: w as CGFloat, height: h as CGFloat } }, Some(img));
    drop(cg);
    Some(Decoded { width: w as u32, height: h as u32, data: out })
}

#[inline]
pub(crate) fn premul(c: u8, a: u8) -> u8 {
    ((c as u32 * a as u32 + 127) / 255) as u8
}

#[inline]
pub(crate) fn unpremul(c: u8, a: u8) -> u8 {
    if a == 0 {
        0
    } else if a == 255 {
        c
    } else {
        ((c as u32 * 255 + a as u32 / 2) / a as u32).min(255) as u8
    }
}

fn convert_8bit(src: &[u8], w: usize, h: usize, stride: usize, bpp: usize, alpha: CGImageAlphaInfo, order: CGImageByteOrderInfo) -> Option<Vec<u8>> {
    let little = order == CGImageByteOrderInfo::Order32Little;
    if !(order == CGImageByteOrderInfo::OrderDefault || order == CGImageByteOrderInfo::Order32Big || little) {
        return None;
    }
    let mut out = vec![0u8; w * h * 4];
    // For each layout: byte offsets of r, g, b, a (a = None for opaque) and whether premultiplied.
    let (r, g, b, a, pre): (usize, usize, usize, Option<usize>, bool) = match (bpp, alpha, little) {
        (24, CGImageAlphaInfo::None, false) => (0, 1, 2, None, false),
        (32, CGImageAlphaInfo::NoneSkipLast, false) => (0, 1, 2, None, false),
        (32, CGImageAlphaInfo::NoneSkipFirst, false) => (1, 2, 3, None, false),
        (32, CGImageAlphaInfo::Last, false) => (0, 1, 2, Some(3), false),
        (32, CGImageAlphaInfo::First, false) => (1, 2, 3, Some(0), false),
        (32, CGImageAlphaInfo::PremultipliedLast, false) => (0, 1, 2, Some(3), true),
        (32, CGImageAlphaInfo::PremultipliedFirst, false) => (1, 2, 3, Some(0), true),
        // 32-bit little endian: the word is read backwards
        (32, CGImageAlphaInfo::NoneSkipLast, true) => (3, 2, 1, None, false),
        (32, CGImageAlphaInfo::NoneSkipFirst, true) => (2, 1, 0, None, false),
        (32, CGImageAlphaInfo::Last, true) => (3, 2, 1, Some(0), false),
        (32, CGImageAlphaInfo::First, true) => (2, 1, 0, Some(3), false),
        (32, CGImageAlphaInfo::PremultipliedLast, true) => (3, 2, 1, Some(0), true),
        (32, CGImageAlphaInfo::PremultipliedFirst, true) => (2, 1, 0, Some(3), true),
        _ => return None,
    };
    let px = bpp / 8;
    for y in 0..h {
        let row = &src[y * stride..];
        let dst = &mut out[y * w * 4..(y + 1) * w * 4];
        for x in 0..w {
            let s = &row[x * px..x * px + px];
            let d = &mut dst[x * 4..x * 4 + 4];
            match a {
                None => {
                    d[0] = s[r];
                    d[1] = s[g];
                    d[2] = s[b];
                    d[3] = 255;
                }
                Some(ai) => {
                    let al = s[ai];
                    if pre {
                        d[0] = s[r].min(al);
                        d[1] = s[g].min(al);
                        d[2] = s[b].min(al);
                    } else {
                        d[0] = premul(s[r], al);
                        d[1] = premul(s[g], al);
                        d[2] = premul(s[b], al);
                    }
                    d[3] = al;
                }
            }
        }
    }
    Some(out)
}

/// Output format of an encode.
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Format {
    Png,
    Jpeg(f64),
}

impl Format {
    /// `canvas.toDataURL(type, quality)` semantics: unknown types fall back to PNG; JPEG quality
    /// outside 0..1 uses the default 0.92.
    pub fn from_mime(mime: &str, quality: Option<f64>) -> Format {
        match mime.trim().to_ascii_lowercase().as_str() {
            "image/jpeg" | "image/jpg" => Format::Jpeg(quality.filter(|q| (0.0..=1.0).contains(q)).unwrap_or(0.92)),
            _ => Format::Png,
        }
    }
    pub fn mime(self) -> &'static str {
        match self {
            Format::Png => "image/png",
            Format::Jpeg(_) => "image/jpeg",
        }
    }
}

/// Encode RGBA8 pixels (rows top-down, stride `w*4`). `premultiplied` says how `rgba` is stored.
/// JPEG has no alpha: pixels are composited onto black, as browsers do.
pub fn encode(w: u32, h: u32, rgba: &[u8], premultiplied: bool, format: Format) -> Option<Vec<u8>> {
    let (w, h) = (w as usize, h as usize);
    if w == 0 || h == 0 || rgba.len() < w * h * 4 {
        return None;
    }
    let src = &rgba[..w * h * 4];
    let (pixels, info): (Vec<u8>, CGImageAlphaInfo) = match format {
        Format::Png => {
            let opaque = src.chunks_exact(4).all(|p| p[3] == 255);
            if opaque {
                (src.to_vec(), CGImageAlphaInfo::NoneSkipLast)
            } else if premultiplied {
                let mut v = src.to_vec();
                for p in v.chunks_exact_mut(4) {
                    let a = p[3];
                    p[0] = unpremul(p[0], a);
                    p[1] = unpremul(p[1], a);
                    p[2] = unpremul(p[2], a);
                }
                (v, CGImageAlphaInfo::Last)
            } else {
                (src.to_vec(), CGImageAlphaInfo::Last)
            }
        }
        Format::Jpeg(_) => {
            let mut v = src.to_vec();
            if !premultiplied {
                for p in v.chunks_exact_mut(4) {
                    let a = p[3];
                    p[0] = premul(p[0], a);
                    p[1] = premul(p[1], a);
                    p[2] = premul(p[2], a);
                }
            }
            for p in v.chunks_exact_mut(4) {
                p[3] = 255;
            }
            (v, CGImageAlphaInfo::NoneSkipLast)
        }
    };
    let data = CFData::from_bytes(&pixels);
    let provider = CGDataProvider::with_cf_data(Some(&data))?;
    let image = unsafe {
        CGImage::new(w, h, 8, 32, w * 4, Some(&srgb()), CGBitmapInfo(info.0), Some(&provider), std::ptr::null(), false, CGColorRenderingIntent::RenderingIntentDefault)
    }?;
    let out = CFMutableData::new(None, 0)?;
    let uti = CFString::from_static_str(match format {
        Format::Png => "public.png",
        Format::Jpeg(_) => "public.jpeg",
    });
    let dest = unsafe { CGImageDestination::with_data(&out, &uti, 1, None) }?;
    match format {
        Format::Jpeg(q) => {
            let qn = CFNumber::new_f64(q);
            let props = CFDictionary::<CFString, CFType>::from_slices(&[unsafe { kCGImageDestinationLossyCompressionQuality }], &[&*qn as &CFType]);
            unsafe { dest.add_image(&image, Some(props.as_opaque())) };
        }
        Format::Png => unsafe { dest.add_image(&image, None) },
    }
    if !unsafe { dest.finalize() } {
        return None;
    }
    Some(out.to_vec())
}

// ------------------------------------------------------------------------------------- base64

const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

pub fn base64_encode_into(out: &mut String, bytes: &[u8]) {
    out.reserve(bytes.len().div_ceil(3) * 4);
    let mut chunks = bytes.chunks_exact(3);
    for c in &mut chunks {
        let n = (c[0] as u32) << 16 | (c[1] as u32) << 8 | c[2] as u32;
        out.push(B64[(n >> 18) as usize & 63] as char);
        out.push(B64[(n >> 12) as usize & 63] as char);
        out.push(B64[(n >> 6) as usize & 63] as char);
        out.push(B64[n as usize & 63] as char);
    }
    match chunks.remainder() {
        [a] => {
            let n = (*a as u32) << 16;
            out.push(B64[(n >> 18) as usize & 63] as char);
            out.push(B64[(n >> 12) as usize & 63] as char);
            out.push_str("==");
        }
        [a, b] => {
            let n = (*a as u32) << 16 | (*b as u32) << 8;
            out.push(B64[(n >> 18) as usize & 63] as char);
            out.push(B64[(n >> 12) as usize & 63] as char);
            out.push(B64[(n >> 6) as usize & 63] as char);
            out.push('=');
        }
        _ => {}
    }
}

/// Forgiving base64 (whitespace ignored, padding optional, URL-safe alphabet accepted).
pub fn base64_decode(s: &[u16]) -> Option<Vec<u8>> {
    let mut out = Vec::with_capacity(s.len() * 3 / 4);
    let mut acc: u32 = 0;
    let mut bits = 0;
    for &c in s {
        let v = match c {
            0x41..=0x5A => c - 0x41,
            0x61..=0x7A => c - 0x61 + 26,
            0x30..=0x39 => c - 0x30 + 52,
            0x2B | 0x2D => 62,
            0x2F | 0x5F => 63,
            0x3D => break,
            0x20 | 0x09 | 0x0A | 0x0C | 0x0D => continue,
            _ => return None,
        } as u32;
        acc = acc << 6 | v;
        bits += 6;
        if bits >= 8 {
            bits -= 8;
            out.push((acc >> bits) as u8);
        }
    }
    Some(out)
}

/// Bytes of a `data:` URL (base64 or percent-encoded payload) and its MIME type.
pub fn parse_data_url(url: &[u16]) -> Option<(String, Vec<u8>)> {
    let comma = url.iter().position(|&c| c == b',' as u16)?;
    let head = String::from_utf16_lossy(&url[..comma]);
    let head = head.trim();
    let meta = head.get(..5).filter(|p| p.eq_ignore_ascii_case("data:")).map(|_| &head[5..])?;
    let body = &url[comma + 1..];
    let is_b64 = meta.to_ascii_lowercase().split(';').any(|p| p.trim() == "base64");
    let mime = meta.split(';').next().unwrap_or("").trim().to_ascii_lowercase();
    let bytes = if is_b64 {
        base64_decode(body)?
    } else {
        let s = String::from_utf16_lossy(body);
        let mut out = Vec::with_capacity(s.len());
        let b = s.as_bytes();
        let mut i = 0;
        while i < b.len() {
            if b[i] == b'%' && i + 2 < b.len() {
                if let Ok(v) = u8::from_str_radix(&s[i + 1..i + 3], 16) {
                    out.push(v);
                    i += 3;
                    continue;
                }
            }
            out.push(b[i]);
            i += 1;
        }
        out
    };
    Some((mime, bytes))
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn b64_roundtrip() {
        for n in 0..20 {
            let v: Vec<u8> = (0..n).map(|i| (i * 37 + 11) as u8).collect();
            let mut s = String::new();
            base64_encode_into(&mut s, &v);
            let u: Vec<u16> = s.encode_utf16().collect();
            assert_eq!(base64_decode(&u).unwrap(), v);
        }
    }
    #[test]
    fn png_roundtrip_exact() {
        let (w, h) = (7u32, 5u32);
        let mut px = vec![0u8; 7 * 5 * 4];
        for (i, p) in px.chunks_exact_mut(4).enumerate() {
            let a = (i * 23 % 256) as u8;
            p[3] = a;
            p[0] = premul((i * 7) as u8, a);
            p[1] = premul((i * 13) as u8, a);
            p[2] = premul((i * 29) as u8, a);
        }
        let png = encode(w, h, &px, true, Format::Png).unwrap();
        let d = decode(&png).unwrap();
        assert_eq!((d.width, d.height), (w, h));
        assert_eq!(d.data, px);
    }
}