Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

9.7 KB
Raw Blame
//! Windows Imaging Component (WIC) universal image decoder & JPEG encoder,
//! paired with pure-Rust lossless PNG & WebP (`VP8L`) codecs from `ink-engine`.
//!
//! Eliminates all `HTMLCanvasElement` allocations in WebView2 during PNG/JPEG/WebP/BMP/GIF
//! open, import, and export.

/// Encodes straight RGBA8 pixels into PNG, JPEG, or WebP bytes entirely in Rust / Windows WIC.
pub fn encode_image_rgba8(
    width: u32,
    height: u32,
    rgba: &[u8],
    format: &str,
    quality: f32,
) -> Result<Vec<u8>, String> {
    let fmt = format.trim().trim_start_matches('.').to_ascii_lowercase();
    match fmt.as_str() {
        "png" => ink_engine::io::encode_rgba8_to_png(width, height, rgba),
        "webp" => ink_engine::io::encode_rgba8_to_webp(width, height, rgba),
        "jpg" | "jpeg" => encode_jpeg_rgba8(width, height, rgba, quality),
        other => Err(format!("Unsupported export image format: {other}")),
    }
}

/// Decodes PNG, JPEG, WebP, BMP, GIF, ICO, or TIFF bytes into straight RGBA8 `(width, height, rgba)`.
pub fn decode_image_rgba8(bytes: &[u8]) -> Result<(u32, u32, Vec<u8>), String> {
    // Fast pure-Rust PNG path first (handles 8/16-bit Gray/RGB/Palette/GA/RGBA cleanly)
    if bytes.len() >= 8 && &bytes[0..8] == b"\x89PNG\r\n\x1a\n" {
        if let Ok(decoded) = ink_engine::io::decode_png_rgba8(bytes) {
            return Ok(decoded);
        }
    }
    decode_image_wic(bytes)
}

#[cfg(target_os = "windows")]
fn encode_jpeg_rgba8(width: u32, height: u32, rgba: &[u8], quality: f32) -> Result<Vec<u8>, String> {
    use windows::Win32::Foundation::HGLOBAL;
    use windows::Win32::Graphics::Imaging::{
        CLSID_WICImagingFactory, GUID_ContainerFormatJpeg, GUID_WICPixelFormat24bppBGR,
        IWICImagingFactory, WICBitmapEncoderNoCache,
    };
    use windows::Win32::System::Com::StructuredStorage::{CreateStreamOnHGlobal, PROPBAG2};
    use windows::Win32::System::Com::{
        CoCreateInstance, CoInitializeEx, CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED,
        STREAM_SEEK_END, STREAM_SEEK_SET,
    };
    use windows::Win32::System::Variant::VARIANT;
    use windows_core::PWSTR;

    if width == 0 || height == 0 || width > 16384 || height > 16384 {
        return Err(format!("Invalid JPEG dimensions: {width}x{height}"));
    }
    let expected = (width as usize)
        .checked_mul(height as usize)
        .and_then(|p| p.checked_mul(4))
        .ok_or_else(|| "JPEG buffer size overflow".to_string())?;
    if rgba.len() != expected {
        return Err(format!(
            "JPEG RGBA buffer mismatch: expected {expected}, got {}",
            rgba.len()
        ));
    }

    // Flatten alpha onto white and pack into 24-bit BGR with 4-byte aligned stride
    let stride = ((width as usize) * 3 + 3) & !3;
    let mut bgr = vec![0u8; stride * (height as usize)];
    for y in 0..(height as usize) {
        let src_row = &rgba[y * (width as usize) * 4..(y + 1) * (width as usize) * 4];
        let dst_row = &mut bgr[y * stride..y * stride + (width as usize) * 3];
        for x in 0..(width as usize) {
            let si = x * 4;
            let di = x * 3;
            let a = src_row[si + 3] as u32;
            let inv_a = 255 - a;
            let r = ((src_row[si] as u32 * a + 255 * inv_a + 127) / 255) as u8;
            let g = ((src_row[si + 1] as u32 * a + 255 * inv_a + 127) / 255) as u8;
            let b = ((src_row[si + 2] as u32 * a + 255 * inv_a + 127) / 255) as u8;
            dst_row[di] = b;
            dst_row[di + 1] = g;
            dst_row[di + 2] = r;
        }
    }

    unsafe {
        let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
        let factory: IWICImagingFactory =
            CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER)
                .map_err(|e| format!("WIC factory init failed: {e}"))?;

        let stream = CreateStreamOnHGlobal(HGLOBAL::default(), true)
            .map_err(|e| format!("WIC CreateStreamOnHGlobal failed: {e}"))?;

        let encoder = factory
            .CreateEncoder(&GUID_ContainerFormatJpeg, std::ptr::null())
            .map_err(|e| format!("WIC CreateEncoder(JPEG) failed: {e}"))?;
        encoder
            .Initialize(&stream, WICBitmapEncoderNoCache)
            .map_err(|e| format!("WIC encoder Initialize failed: {e}"))?;

        let mut frame_opt = None;
        let mut props_opt = None;
        encoder
            .CreateNewFrame(&mut frame_opt, &mut props_opt)
            .map_err(|e| format!("WIC CreateNewFrame failed: {e}"))?;
        let frame = frame_opt.ok_or_else(|| "WIC CreateNewFrame returned null".to_string())?;

        if let Some(ref props) = props_opt {
            let mut name_utf16: Vec<u16> = "ImageQuality\0".encode_utf16().collect();
            let pb = PROPBAG2 {
                pstrName: PWSTR(name_utf16.as_mut_ptr()),
                ..Default::default()
            };
            let q = quality.clamp(0.1, 1.0);
            let var = VARIANT::from(q);
            let _ = props.Write(1, &pb, &var);
        }

        frame
            .Initialize(props_opt.as_ref())
            .map_err(|e| format!("WIC frame Initialize failed: {e}"))?;
        frame
            .SetSize(width, height)
            .map_err(|e| format!("WIC frame SetSize failed: {e}"))?;
        let mut fmt = GUID_WICPixelFormat24bppBGR;
        frame
            .SetPixelFormat(&mut fmt)
            .map_err(|e| format!("WIC frame SetPixelFormat failed: {e}"))?;
        frame
            .WritePixels(height, stride as u32, &bgr)
            .map_err(|e| format!("WIC frame WritePixels failed: {e}"))?;
        frame
            .Commit()
            .map_err(|e| format!("WIC frame Commit failed: {e}"))?;
        encoder
            .Commit()
            .map_err(|e| format!("WIC encoder Commit failed: {e}"))?;

        let mut end_pos = 0u64;
        stream
            .Seek(0, STREAM_SEEK_END, Some(&mut end_pos))
            .map_err(|e| format!("WIC stream Seek(END) failed: {e}"))?;
        stream
            .Seek(0, STREAM_SEEK_SET, None)
            .map_err(|e| format!("WIC stream Seek(SET) failed: {e}"))?;

        let total_len = usize::try_from(end_pos).map_err(|_| "JPEG output too large".to_string())?;
        let mut out = vec![0u8; total_len];
        let mut offset = 0usize;
        while offset < total_len {
            let mut read_now = 0u32;
            let to_read = (total_len - offset).min(u32::MAX as usize) as u32;
            let hr = stream.Read(
                out[offset..].as_mut_ptr() as *mut _,
                to_read,
                Some(&mut read_now),
            );
            if hr.is_err() || read_now == 0 {
                break;
            }
            offset += read_now as usize;
        }
        out.truncate(offset);
        Ok(out)
    }
}

#[cfg(not(target_os = "windows"))]
fn encode_jpeg_rgba8(
    _width: u32,
    _height: u32,
    _rgba: &[u8],
    _quality: f32,
) -> Result<Vec<u8>, String> {
    Err("JPEG encoding requires Windows WIC".to_string())
}

#[cfg(target_os = "windows")]
fn decode_image_wic(bytes: &[u8]) -> Result<(u32, u32, Vec<u8>), String> {
    use windows::Win32::Graphics::Imaging::{
        CLSID_WICImagingFactory, GUID_WICPixelFormat32bppRGBA, IWICImagingFactory,
        WICBitmapDitherTypeNone, WICBitmapPaletteTypeCustom, WICDecodeMetadataCacheOnDemand,
    };
    use windows::Win32::System::Com::{
        CoCreateInstance, CoInitializeEx, CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED,
    };

    if bytes.is_empty() {
        return Err("Empty image payload".to_string());
    }

    unsafe {
        let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
        let factory: IWICImagingFactory =
            CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER)
                .map_err(|e| format!("WIC factory init failed: {e}"))?;

        let stream = factory
            .CreateStream()
            .map_err(|e| format!("WIC CreateStream failed: {e}"))?;
        stream
            .InitializeFromMemory(bytes)
            .map_err(|e| format!("WIC InitializeFromMemory failed: {e}"))?;

        let decoder = factory
            .CreateDecoderFromStream(&stream, std::ptr::null(), WICDecodeMetadataCacheOnDemand)
            .map_err(|e| format!("WIC CreateDecoderFromStream failed: {e}"))?;
        let frame = decoder
            .GetFrame(0)
            .map_err(|e| format!("WIC GetFrame(0) failed: {e}"))?;

        let mut width = 0u32;
        let mut height = 0u32;
        frame
            .GetSize(&mut width, &mut height)
            .map_err(|e| format!("WIC GetSize failed: {e}"))?;
        if width == 0 || height == 0 || width > 16384 || height > 16384 {
            return Err(format!("Unsupported image dimensions: {width}x{height}"));
        }

        let converter = factory
            .CreateFormatConverter()
            .map_err(|e| format!("WIC CreateFormatConverter failed: {e}"))?;
        converter
            .Initialize(
                &frame,
                &GUID_WICPixelFormat32bppRGBA,
                WICBitmapDitherTypeNone,
                None,
                0.0,
                WICBitmapPaletteTypeCustom,
            )
            .map_err(|e| format!("WIC FormatConverter Initialize failed: {e}"))?;

        let stride = width
            .checked_mul(4)
            .ok_or_else(|| "Image stride overflow".to_string())?;
        let byte_len = (stride as usize)
            .checked_mul(height as usize)
            .ok_or_else(|| "Image buffer size overflow".to_string())?;
        let mut rgba = vec![0u8; byte_len];
        converter
            .CopyPixels(std::ptr::null(), stride, &mut rgba)
            .map_err(|e| format!("WIC CopyPixels failed: {e}"))?;

        Ok((width, height, rgba))
    }
}

#[cfg(not(target_os = "windows"))]
fn decode_image_wic(bytes: &[u8]) -> Result<(u32, u32, Vec<u8>), String> {
    ink_engine::io::decode_png_rgba8(bytes)
}