Skip to content

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

5.1 KB
Raw Blame
//! Pure-Rust lossless WebP (`VP8L`, RFC 9649) RGBA8 encoder for zero-canvas desktop image export.

struct LsbBitWriter {
    buf: Vec<u8>,
    bit_buf: u64,
    bit_count: u32,
}

impl LsbBitWriter {
    fn with_capacity(cap: usize) -> Self {
        Self {
            buf: Vec::with_capacity(cap),
            bit_buf: 0,
            bit_count: 0,
        }
    }

    #[inline]
    fn write_bits(&mut self, val: u32, nbits: u32) {
        debug_assert!(nbits <= 32);
        let mask = if nbits == 32 { u32::MAX } else { (1u32 << nbits) - 1 };
        self.bit_buf |= ((val & mask) as u64) << self.bit_count;
        self.bit_count += nbits;
        while self.bit_count >= 8 {
            self.buf.push((self.bit_buf & 0xFF) as u8);
            self.bit_buf >>= 8;
            self.bit_count -= 8;
        }
    }

    fn finish(mut self) -> Vec<u8> {
        if self.bit_count > 0 {
            self.buf.push((self.bit_buf & 0xFF) as u8);
        }
        self.buf
    }
}

/// Writes a VP8L normal prefix code where symbols `0..=255` all have code length 8
/// (and any symbols >= 256 have length 0), encoded via the code-length-code RLE symbol 16.
fn write_uniform_8bit_prefix_code(bw: &mut LsbBitWriter) {
    // is_simple = 0 (normal code length code)
    bw.write_bits(0, 1);
    // num_code_lengths = 19 (all kCodeLengthCodeOrder entries up to symbol 16 at index 18)
    bw.write_bits(19 - 4, 4);
    // kCodeLengthCodeOrder = [17, 18, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
    // Assign length 1 to symbol 8 (index 10) and symbol 16 (index 18), 0 to all others.
    // Canonical 1-bit codes: symbol 8 -> 0, symbol 16 -> 1.
    for idx in 0..19 {
        let len = if idx == 10 || idx == 18 { 1 } else { 0 };
        bw.write_bits(len, 3);
    }
    // use_max_symbol = 1 -> max_symbol = 256 (length_nbits = 2 + 2*3 = 8, value = 254 -> 2 + 254 = 256)
    bw.write_bits(1, 1);
    bw.write_bits(3, 3);
    bw.write_bits(254, 8);

    // Emit 256 code lengths of value 8:
    // 1 literal '8' (code 0) + 42 * repeat-6 (code 1, extra 3) + 1 * repeat-3 (code 1, extra 0)
    // Total = 1 + 252 + 3 = 256.
    bw.write_bits(0, 1);
    for _ in 0..42 {
        bw.write_bits(1, 1);
        bw.write_bits(3, 2);
    }
    bw.write_bits(1, 1);
    bw.write_bits(0, 2);
}

/// Encodes a straight RGBA8 image buffer into a valid lossless WebP (`RIFF WEBP VP8L`) file.
pub fn encode_rgba8_to_webp(width: u32, height: u32, rgba: &[u8]) -> Result<Vec<u8>, String> {
    if width == 0 || height == 0 || width > 16384 || height > 16384 {
        return Err(format!("Invalid WebP dimensions: {width}x{height}"));
    }
    let expected = (width as usize)
        .checked_mul(height as usize)
        .and_then(|p| p.checked_mul(4))
        .ok_or_else(|| "WebP buffer size overflow".to_string())?;
    if rgba.len() != expected {
        return Err(format!(
            "WebP RGBA buffer mismatch: expected {expected}, got {}",
            rgba.len()
        ));
    }

    let mut bw = LsbBitWriter::with_capacity(expected + 128);
    // VP8L signature byte (0x2f)
    bw.write_bits(0x2f, 8);
    // width - 1 (14 bits), height - 1 (14 bits), alpha_is_used (1 bit), version (3 bits = 0)
    bw.write_bits(width - 1, 14);
    bw.write_bits(height - 1, 14);
    bw.write_bits(1, 1);
    bw.write_bits(0, 3);

    // No transforms, no color cache, no meta prefix codes
    bw.write_bits(0, 1);
    bw.write_bits(0, 1);
    bw.write_bits(0, 1);

    // 4 channel prefix codes (Green, Red, Blue, Alpha) — uniform 8-bit canonical codes
    write_uniform_8bit_prefix_code(&mut bw); // Green (+ len + cache)
    write_uniform_8bit_prefix_code(&mut bw); // Red
    write_uniform_8bit_prefix_code(&mut bw); // Blue
    write_uniform_8bit_prefix_code(&mut bw); // Alpha

    // 5th prefix code (Distance) — unused single-symbol simple code (symbol 0)
    bw.write_bits(1, 1); // is_simple = 1
    bw.write_bits(0, 1); // num_symbols - 1 = 0 (1 symbol)
    bw.write_bits(0, 1); // is_first_8bits = 0 (1-bit symbol)
    bw.write_bits(0, 1); // symbol0 = 0

    // Pixels in VP8L channel order: Green, Red, Blue, Alpha.
    // Canonical 8-bit Huffman code for symbol s is s, transmitted MSB-first into LSB bit stream
    // -> bit-reversed 8-bit value.
    for px in rgba.as_chunks::<4>().0 {
        bw.write_bits(px[1].reverse_bits() as u32, 8); // G
        bw.write_bits(px[0].reverse_bits() as u32, 8); // R
        bw.write_bits(px[2].reverse_bits() as u32, 8); // B
        bw.write_bits(px[3].reverse_bits() as u32, 8); // A
    }

    let vp8l = bw.finish();
    let pad = vp8l.len() & 1;
    let riff_size = u32::try_from(4 + 8 + vp8l.len() + pad)
        .map_err(|_| "WebP output exceeds RIFF 4 GB limit".to_string())?;
    let vp8l_len = u32::try_from(vp8l.len())
        .map_err(|_| "VP8L chunk exceeds 4 GB limit".to_string())?;

    let mut out = Vec::with_capacity(12 + 8 + vp8l.len() + pad);
    out.extend_from_slice(b"RIFF");
    out.extend_from_slice(&riff_size.to_le_bytes());
    out.extend_from_slice(b"WEBP");
    out.extend_from_slice(b"VP8L");
    out.extend_from_slice(&vp8l_len.to_le_bytes());
    out.extend_from_slice(&vp8l);
    if pad == 1 {
        out.push(0);
    }
    Ok(out)
}