Skip to content

About

bindgen'd FFI bindings to libwebp

Topics

Resources

Stars

50 stars

Watchers

1 watching

Forks

Latest commit

 

History

125 Commits

Folders and files

Repository files navigation

libwebp-sys

Low-level Rust FFI bindings to libwebp, including encoding, decoding, muxing, and demuxing.

By default, the bundled libwebp 1.6.0 is built and linked statically using the cc crate. A C compiler is required; CMake is not. Pregenerated Rust bindings are included.

Usage

Add the following to the Cargo.toml in your project:

[dependencies]
libwebp-sys = "0.14.5"

or to require no_std support:

libwebp-sys = { version = "0.14.5", default-features = false, features = ["parallel"] }

no_std applies to the Rust bindings. The bundled C library still requires a compatible C toolchain and runtime for the target.

Features and building

Feature Default Behavior
std Yes Uses Rust's standard library and enables threading support in bundled libwebp.
parallel Yes Compiles C sources in parallel; this controls build-time parallelism.
system-dylib No Uses a system libwebp discovered through pkg-config, instead of building the bundled sources.
generate-bindings No Regenerates src/ffi.rs using bindgen; requires libclang and the relevant libwebp headers.
neon, sse41, avx2 No Enables the corresponding SIMD paths for supported targets in the bundled build.

The neon, sse41 and avx2 feature flags can be set to force support for Neon, SSE 4.1 and AVX2 respectively, but this is usually unnecessary as it can be set through -Ctarget-feature (e.g. RUSTFLAGS="-Ctarget-feature=avx2") as well. Only enable CPU features supported by the machines that will run the binary.

When building from a Git checkout, initialize the bundled sources first:

git submodule update --init --recursive

Examples

These examples use std and tightly packed RGBA pixels (four bytes per pixel). FFI calls are unsafe: validate buffer lengths and check for failures before using returned pointers. Buffers allocated by libwebp must be released with WebPFree.

Encode

use libwebp_sys::{WebPEncodeRGBA, WebPFree};

pub fn encode_webp(
    rgba: &[u8],
    width: u32,
    height: u32,
    quality: f32,
) -> Result<Vec<u8>, &'static str> {
    let width = i32::try_from(width).map_err(|_| "width is too large")?;
    let height = i32::try_from(height).map_err(|_| "height is too large")?;
    if width <= 0 || height <= 0 || !(0.0..=100.0).contains(&quality) {
        return Err("invalid dimensions or quality");
    }
    let stride = width.checked_mul(4).ok_or("stride overflow")?;
    let expected_len = (stride as usize)
        .checked_mul(height as usize)
        .ok_or("image size overflow")?;
    if rgba.len() != expected_len {
        return Err("RGBA buffer length does not match dimensions");
    }

    unsafe {
        let mut output = std::ptr::null_mut();
        let len = WebPEncodeRGBA(rgba.as_ptr(), width, height, stride, quality, &mut output);
        if len == 0 || output.is_null() || len > isize::MAX as usize {
            WebPFree(output.cast());
            return Err("WebP encoding failed");
        }
        let encoded = std::slice::from_raw_parts(output, len).to_vec();
        WebPFree(output.cast());
        Ok(encoded)
    }
}

Decode

Decode directly into a Rust-owned buffer, returning the pixels and dimensions. This avoids allocating a separate output buffer with libwebp.

use libwebp_sys::{WebPDecodeRGBAInto, WebPGetInfo};

pub fn decode_webp(data: &[u8]) -> Result<(Vec<u8>, u32, u32), &'static str> {
    let mut width = 0;
    let mut height = 0;
    let valid = unsafe { WebPGetInfo(data.as_ptr(), data.len(), &mut width, &mut height) };
    if valid == 0 || width <= 0 || height <= 0 {
        return Err("invalid WebP header");
    }
    let stride = width.checked_mul(4).ok_or("stride overflow")?;
    let len = (stride as usize)
        .checked_mul(height as usize)
        .filter(|&len| len <= isize::MAX as usize)
        .ok_or("image size overflow")?;
    let mut rgba = vec![0; len];
    let output = unsafe {
        WebPDecodeRGBAInto(
            data.as_ptr(),
            data.len(),
            rgba.as_mut_ptr(),
            rgba.len(),
            stride,
        )
    };
    if output.is_null() {
        return Err("WebP decoding failed");
    }
    Ok((rgba, width as u32, height as u32))
}

About

bindgen'd FFI bindings to libwebp

Topics

Resources

Stars

50 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages