Skip to main content

Crate libjpeg_turbo_rs

Crate libjpeg_turbo_rs 

Source
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):

TaskCanonical path
Decode, defaults finedecompress (or decompress_to / decompress_into)
Decode, configuredDecoder — chainable with_*, or imperative set_*
Probe header/metadataprobe (one call), Decoder::new + accessors for more
Encode, defaults finecompress
Encode, configuredEncoder builder — quality, subsampling, progressive, markers
Lossless transformtransform() — DCT-domain rotate/flip/crop, no re-encode
Row streamingScanlineDecoder / ScanlineEncoder, stream::* for readers
Bounded-memory stream decodedecompress_from_reader_incremental — sliding input window for interleaved baseline JPEGs
12/16-bit & losslessprecision 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::io streaming 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-time target_feature only — there is no CPUID probe without std (issue #356).
  • simd (default): architecture intrinsics (NEON / SSE2 / AVX2 / WASM SIMD128).
  • png: PNG helpers for tj3LoadImage8 / tj3SaveImage8 (implies std).

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;png
pub use api::image_io::save_png;png and (WASI or non-WebAssembly)
pub use api::image_io::load_image;std and (WASI or non-WebAssembly)
pub use api::image_io::load_ppm_12bit;std and (WASI or non-WebAssembly)
pub use api::image_io::load_ppm_16bit;std and (WASI or non-WebAssembly)
pub use api::image_io::save_bmp;std and (WASI or non-WebAssembly)
pub use api::image_io::save_ppm;std and (WASI or non-WebAssembly)
pub use api::image_io::save_ppm_12bit;std and (WASI or non-WebAssembly)
pub use api::image_io::save_ppm_16bit;std and (WASI or non-WebAssembly)
pub use api::image_io::load_image_from_bytes;std
pub use api::image_io::load_ppm_12bit_from_bytes;std
pub use api::image_io::load_ppm_16bit_from_bytes;std
pub use api::image_io::LoadedImage;std
pub use api::image_io::LoadedImage12;std
pub use api::image_io::LoadedImage16;std
pub 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;std
pub 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§

ComponentCoefficients
Per-component DCT coefficient data.
Decoder
JPEG decoder. Orchestrates the full decoding pipeline.
Encoder
JPEG encoder with builder-pattern configuration.
EncoderComponentInfo
Per-component info extracted for re-encoding.
EncoderConfig
Critical JPEG parameters extracted from decoded coefficients for re-encoding.
HuffmanTableDef
User-supplied Huffman table definition.
Image
Decoded image data.
ImageInfo
Metadata for a decode that wrote pixels into a caller-provided buffer (Decoder::decode_image_into / decompress_into): everything Image carries except the pixel data.
JpegCoefficients
Complete coefficient representation of a JPEG image.
JpegInfo
Everything a caller usually wants to know about a JPEG before deciding whether/how to decode it — returned by probe in one call (issue #386). Header-parse only; no pixels are decoded.
ProgressiveDecoder
Decoder that supports scan-by-scan progressive output.
ScanlineDecoder
Row-by-row JPEG decoder.
ScanlineEncoder
Row-by-row JPEG encoder.
TransformOptions
All 9 TJXOPT transform flags matching libjpeg-turbo’s jpegtran options, plus a user callback for coefficient inspection/modification.

Enums§

DecodeWarning
Non-fatal warning that allows recovery in lenient mode.
JpegError
All errors that can occur during JPEG processing.
MarkerCopyMode
Marker copy behavior during transform.
TransformOp
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_incrementalstd
Decode a JPEG from a byte stream with bounded input memory.
decompress_from_reader_incremental_instrumentedstd
decompress_from_reader_incremental plus 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::BufferTooSmall if out is shorter than output_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 warnings if 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_into for this stream at format.
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 simd and std cargo 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.