Expand description
Pure-Rust reimplementation of libjpeg-turbo with NEON / SSE2 / AVX2 / WASM-SIMD128 acceleration — no C dependencies, no unsafe FFI.
The one-shot functions cover most uses: decompress /
decompress_to / decompress_into for decoding, compress
and the Encoder builder for encoding, transform() for
lossless (DCT-domain) rotation and flips. The configurable
Decoder adds scaling, cropping, output formats, and resource
limits.
§Quickstart
Decode a JPEG to RGB pixels:
use libjpeg_turbo_rs::{decompress, PixelFormat, Subsampling};
let image = decompress(&jpeg_bytes)?;
assert_eq!(image.pixel_format, PixelFormat::Rgb);
assert_eq!(image.data.len(), image.width * image.height * 3);Encode RGB pixels to a JPEG:
use libjpeg_turbo_rs::{compress, PixelFormat, Subsampling};
let (width, height) = (32, 24);
let rgb = vec![200u8; width * height * 3];
let jpeg = compress(&rgb, width, height, PixelFormat::Rgb, 85, Subsampling::S420)?;
assert_eq!(&jpeg[..2], &[0xFF, 0xD8], "SOI marker");Probe a header without decoding any pixels — probe parses
markers only (multi-scan streams are walked byte-wise to find scan
boundaries, so worst-case cost is linear in the compressed size,
far below a decode):
let info = libjpeg_turbo_rs::probe(&jpeg_bytes)?;
assert_eq!((info.width, info.height), (64, 48));
assert_eq!(info.exif_orientation, None); // no EXIF in this fixture§Canonical API map
Rustdoc renders every export flat, so here is which entry point to reach for first (issue #386):
| Task | Canonical path |
|---|---|
| Decode, defaults fine | decompress (or decompress_to / decompress_into) |
| Decode, configured | Decoder — chainable with_*, or imperative set_* |
| Probe header/metadata | probe (one call), Decoder::new + accessors for more |
| Encode, defaults fine | compress |
| Encode, configured | Encoder builder — quality, subsampling, progressive, markers |
| Lossless transform | transform() — DCT-domain rotate/flip/crop, no re-encode |
| Row streaming | ScanlineDecoder / ScanlineEncoder, stream::* for readers |
| Bounded-memory stream decode | decompress_from_reader_incremental — sliding input window for interleaved baseline JPEGs |
| 12/16-bit & lossless | precision module |
Specialised compress_* entry points. The remaining
free-function encode variants (compress_optimized,
compress_progressive, compress_arithmetic,
compress_arithmetic_progressive, the compress_lossless*
family, compress_with_metadata, …) predate the Encoder
builder, which can express every one of them —
e.g. Encoder::new(&px, w, h, fmt).progressive(true) replaces
compress_progressive. compress_into is the exception: it
fills a caller-owned buffer, and Encoder::encode always returns
a fresh Vec. They stay for source compatibility and
one-line convenience; new code should prefer Encoder once more
than one knob is involved. Deprecation intent: these variants
are candidates for #[deprecated] at the next semver-major once
Encoder has shipped a full release cycle without gaps; none are
removed before that.
§Feature flags
std(default):std::iostreaming API, file-path helpers, runtime CPU-feature detection, and std-backed error types.no_std+alloc: disable default features for the core codec (headers, entropy decode, IDCT, upsample, colour convert, encode). SIMD then dispatches on compile-timetarget_featureonly — there is no CPUID probe withoutstd(issue #356).simd(default): architecture intrinsics (NEON / SSE2 / AVX2 / WASM SIMD128).png: PNG helpers fortj3LoadImage8/tj3SaveImage8(impliesstd).
Performance against C libjpeg-turbo and zune-jpeg, replacement-tier status for the C ABI shims, and build-flag guidance live in the repository README.
Re-exports§
pub use api::abbreviated::read_header;pub use api::abbreviated::HeaderResult;pub use api::abbreviated::TablesOnlyState;pub use api::image_io::load_png_from_bytes;pngpub use api::image_io::save_png;pngand (WASI or non-WebAssembly)pub use api::image_io::load_image;stdand (WASI or non-WebAssembly)pub use api::image_io::load_ppm_12bit;stdand (WASI or non-WebAssembly)pub use api::image_io::load_ppm_16bit;stdand (WASI or non-WebAssembly)pub use api::image_io::save_bmp;stdand (WASI or non-WebAssembly)pub use api::image_io::save_ppm;stdand (WASI or non-WebAssembly)pub use api::image_io::save_ppm_12bit;stdand (WASI or non-WebAssembly)pub use api::image_io::save_ppm_16bit;stdand (WASI or non-WebAssembly)pub use api::image_io::load_image_from_bytes;stdpub use api::image_io::load_ppm_12bit_from_bytes;stdpub use api::image_io::load_ppm_16bit_from_bytes;stdpub use api::image_io::LoadedImage;stdpub use api::image_io::LoadedImage12;stdpub use api::image_io::LoadedImage16;stdpub use api::precision::compress_12bit;pub use api::precision::compress_16bit;pub use api::precision::decompress_12bit;pub use api::precision::decompress_16bit;pub use api::precision::read_scanlines_12;pub use api::precision::read_scanlines_16;pub use api::precision::write_scanlines_12;pub use api::precision::write_scanlines_16;pub use api::quality::quality_scaling;pub use api::quantize::requantize;pub use api::raw_data::compress_raw;pub use api::raw_data::decompress_raw;pub use api::raw_data::RawImage;pub use api::raw_thumbnail::extract_embedded_jpeg;pub use encode::marker_writer::MarkerStreamWriter;pub use api::stream;stdpub use common::bufsize::calc_jpeg_dimensions;pub use common::bufsize::calc_output_dimensions;pub use common::bufsize::jpeg_buf_size;pub use common::bufsize::transform_buf_size;pub use common::bufsize::yuv_buf_size;pub use common::bufsize::yuv_plane_height;pub use common::bufsize::yuv_plane_size;pub use common::bufsize::yuv_plane_width;pub use common::jfif::extract_jfif_thumbnail;pub use common::sample::Sample;pub use common::traits::DefaultErrorHandler;pub use common::traits::ErrorHandler;pub use common::traits::ProgressInfo;pub use common::traits::ProgressListener;pub use decode::resync::DefaultResyncStrategy;pub use decode::resync::RestartResyncStrategy;pub use decode::resync::ResyncAction;pub use common::types::*;
Modules§
- api
- common
- decode
- encode
- precision
- 12-bit and 16-bit sample precision support.
- quantize
- Color quantization for 8-bit indexed/palette output.
- raw_
data_ 12 - 12-bit raw planar encode/decode (YCbCr component planes at native resolution).
- simd
- SIMD dispatch layer for hot-path JPEG decode and encode operations.
- tj3
- TJ3-compatible handle/parameter API.
- transform
Structs§
- Component
Coefficients - Per-component DCT coefficient data.
- Decoder
- JPEG decoder. Orchestrates the full decoding pipeline.
- Encoder
- JPEG encoder with builder-pattern configuration.
- Encoder
Component Info - Per-component info extracted for re-encoding.
- Encoder
Config - Critical JPEG parameters extracted from decoded coefficients for re-encoding.
- Huffman
Table Def - User-supplied Huffman table definition.
- Image
- Decoded image data.
- Image
Info - Metadata for a decode that wrote pixels into a caller-provided buffer
(
Decoder::decode_image_into/decompress_into): everythingImagecarries except the pixeldata. - Jpeg
Coefficients - Complete coefficient representation of a JPEG image.
- Jpeg
Info - Everything a caller usually wants to know about a JPEG before
deciding whether/how to decode it — returned by
probein one call (issue #386). Header-parse only; no pixels are decoded. - Progressive
Decoder - Decoder that supports scan-by-scan progressive output.
- Scanline
Decoder - Row-by-row JPEG decoder.
- Scanline
Encoder - Row-by-row JPEG encoder.
- Transform
Options - All 9 TJXOPT transform flags matching libjpeg-turbo’s jpegtran options, plus a user callback for coefficient inspection/modification.
Enums§
- Decode
Warning - Non-fatal warning that allows recovery in lenient mode.
- Jpeg
Error - All errors that can occur during JPEG processing.
- Marker
Copy Mode - Marker copy behavior during transform.
- Transform
Op - Lossless transform operations.
Functions§
- compress
- Compress raw pixel data into a JPEG byte stream.
- compress_
arithmetic - Compress with arithmetic entropy coding (SOF9).
- compress_
arithmetic_ progressive - Compress with arithmetic progressive encoding (SOF10).
- compress_
into - Compress into a pre-allocated buffer. Returns the number of bytes written.
- compress_
lossless - Compress as lossless JPEG (SOF3).
- compress_
lossless_ arithmetic - Compress as lossless JPEG with arithmetic entropy coding (SOF11).
- compress_
lossless_ extended - Compress as lossless JPEG (SOF3) with configurable predictor and point transform.
- compress_
optimized - Compress with optimized Huffman tables (2-pass encoding).
- compress_
progressive - Compress as progressive JPEG (SOF2, multi-scan).
- compress_
with_ metadata - Compress with optional ICC profile and/or EXIF metadata embedded.
- copy_
critical_ parameters - Copy critical JPEG parameters from decoded coefficients for re-encoding.
- decompress
- Decompress a JPEG byte slice into an Image (default: RGB for color, Grayscale for gray).
- decompress_
cropped - Decompress a cropped region of a JPEG.
- decompress_
from_ reader_ incremental std - Decode a JPEG from a byte stream with bounded input memory.
- decompress_
from_ reader_ incremental_ instrumented std decompress_from_reader_incrementalplus the peak input storage held at any point, measured as allocation CAPACITY (not just live bytes): header prefix + entropy window + the fixed 64 KiB read-staging buffer. This is the observable P4-58’s bounded-memory acceptance test asserts on. Exposed (rather than a test-only hook) so callers tuning window behaviour can measure too.- decompress_
into - Decode into a caller-provided buffer (issue #354): no output-sized
heap allocation on the standard decode paths, so frame loops can
reuse one buffer. Errors with
crate::JpegError::BufferTooSmallifoutis shorter thanoutput_buffer_size. - decompress_
lenient - Decompress a JPEG in lenient mode — continue on errors, filling corrupt areas with gray.
The returned Image may have non-empty
warningsif errors were encountered. - decompress_
to - Decompress a JPEG byte slice into an Image with the specified pixel format.
- jpeg_
write_ tables - Produce a tables-only abbreviated JPEG datastream for the given encoder configuration.
- output_
buffer_ size - Bytes required by
decompress_intofor this stream atformat. - probe
- One-call header probe: dimensions, coding mode, subsampling, colorspace, and metadata presence without decoding any pixels (issue #386).
- read_
coefficients - Read DCT coefficients from a JPEG byte stream.
- simd_
and_ std_ features_ enabled - Whether this build of the codec has both the
simdandstdcargo features — the feature wiring a repackaging crate must preserve. - transform
- Apply a lossless transform to a JPEG image.
- transform_
jpeg_ with_ options - Apply a lossless transform with full TJXOPT-compatible options.
- write_
coefficients - Write DCT coefficients to a JPEG byte stream.
- write_
coefficients_ arithmetic - Write DCT coefficients with arithmetic entropy coding (SOF9).
- write_
coefficients_ optimized - Write DCT coefficients with optimized Huffman tables (2-pass encoding).
- write_
coefficients_ progressive - Write DCT coefficients as progressive JPEG (SOF2, multi-scan) with per-scan optimized Huffman tables.
- write_
coefficients_ progressive_ arithmetic - Write DCT coefficients with arithmetic progressive entropy coding (SOF10).
Type Aliases§
- Result
- Convenience alias used throughout the crate.