Expand description
Safe Rust API over the encoder of the translation; no upstream unit.
Wraps the translated types and functions in validated Rust types and adds
no codec behavior of its own; see docs/adr/.
Work package: WP17 (safe encoder API).
The decision record is docs/adr/0006-safe-encoder-api.md. Every encoding
calls the translated WebPEncode (webp_encode) with the stored
WebPConfig, so its output is byte-identical to libwebp v1.6.0 with the
same configuration and samples. The API validates dimensions, strides,
buffer lengths and floating-point parameters first, so that caller input
never reaches a panic of the translation, and reports failures as
EncodeError.
§Example
use webp::api::encode::{Config, Encoder, Picture, PixelLayout, PixelRows, SampleForm};
// A 4 by 2 RGBA picture, rows packed.
let rgba = [255_u8, 0, 0, 255].repeat(8);
let rows = PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 4, height: 2, stride: 16 };
let mut picture = Picture::import(rows, SampleForm::Argb)?;
let config = Config::new().quality(80.0).method(4);
let webp = Encoder::new(&config).encode(&mut picture)?;
assert_eq!(&webp[..4], b"RIFF");
assert_eq!(&webp[8..12], b"WEBP");§Pictures and memory
Picture::import copies strided rows into planes that the picture
allocates. Picture::from_argb and Picture::from_yuva borrow planes
that the caller allocated, exclusively for the picture’s lifetime, so that
the caller can account for that memory; libwebp writes into them where the
semantics below say so. Strides count elements of the slice’s type: bytes
for &[u8] rows and planes, pixels for the &mut [u32] ARGB plane. The
encoder converts what it needs: a lossy encoding of an ARGB picture
allocates YUVA planes, a lossless encoding of a YUVA picture an ARGB plane.
Those planes stay with the picture and Picture::owned_sample_bytes
counts them; the encoder’s internal state is not observable.
§Semantics
- Lossy samples are ITU-R BT.601
Y'CbCr4:2:0 in limited range (Y 16 to 235, Cb and Cr 16 to 240), converted with the fixed-point constants of libwebp’ssrc/dsp/yuv.hand gamma-corrected chroma averaging, which is weighted by alpha in blocks with transparency; a decoder converts back with the same matrix. Sharp YUV (Config::sharp_yuv) and dithering (preprocessingbit 2, throughConfig::raw_mut) apply only when the picture holds ARGB samples at encoding time (SampleForm::ArgborPicture::from_argb);SampleForm::Yuvaconverts during the import, without them, as libwebp does. Planes fromPicture::from_yuvaare encoded as they are. - Alpha is straight (not premultiplied); the encoder has no
premultiplied input. Unless
Config::exactis set, the encoder rewrites the samples under fully transparent areas in the picture’s planes, the caller’s included: in 8 by 8 blocks of the Y, U and V planes for a lossy encoding, and every transparent ARGB pixel becomes 0 for a lossless one.show_compressed(throughConfig::raw_mut) writes the decoded samples back into the Y, U and V planes. - Metadata: the output is a still WebP file with no
ICCP,EXIForXMPchunk; WebP carries no other color or orientation signal. Metadata and animation belong to the muxer (WP15).
§Deviations from upstream
Changes of representation that the ADRs allow, or behavior that the Rust side cannot reproduce exactly. Each records the reason.
- Early refusal of dimensions. Widths and heights above 16383 are
refused with
InvalidDimensionsbefore anything is allocated; C imports them and fails inWebPEncodewithVP8_ENC_ERROR_BAD_DIMENSION. Zero dimensions are refused as well, where C fails the import. - Floats. A NaN or infinite
qualityortarget_psnris refused withInvalidParameter; C accepts it and converts it to an integer, which is undefined. A quality outside 0 to 100 isInvalidParameter, where C reportsINVALID_CONFIGURATION(orWebPConfigPresetreturns 0). - Row strides of the X layouts must hold four bytes per pixel, and the
last row
width * bytes_per_pixelbytes; C checks three bytes per pixel, which lets RGBX and BGRX rows overlap, and reads4 * width - 1bytes of the last row. - Negative strides and dimensions cannot be expressed (
u32,usize), so bottom-up rows are not accepted (C reads them upward; the translation panics on them, see item 4 of# Deviations from upstreaminsrc/enc/picture_enc.rs). Encoder::encodereturns the bytes only on success; C’s memory writer keeps the partial output of a failed encoding. Its vector keeps the memory writer’s capacity, up to twice the length.target_sizetakes au32and saturates ati32::MAX, C’sint.- Panicking callbacks leave the picture without planes; C has no panics.
- The simple functions return the recorded error instead of C’s 0, and accept RGBX and BGRX, which C’s simple API lacks; their bytes are C’s.
- A successful encoding is
Okeven when libwebp recordedVP8_ENC_ERROR_USER_ABORTat a report whose answer it ignores (ResetAllMBInfoinsrc/enc/analysis_enc.c, andStatLoop, whose resultVP8EncLoopinsrc/enc/frame_enc.cdrops for lossy methods 0 to 2); C returns 1 and leaves the code in the picture, which the API does not expose on success. - Callbacks receive no picture (ADR 0003, as in the translation).
§Upstream behavior preserved
Behavior of the C code that a reader might take for a defect, which the translation keeps:
- The encoder writes into the picture’s planes unless
exact: the Y, U and V samples under fully transparent 8 by 8 blocks (lossy), every transparent ARGB pixel to 0 (lossless), and withshow_compressedthe decoded samples. A second encoding of a picture sees these writes and the planes of the first encoding’s conversion. - A lossy encoding of ARGB samples converts with sharp YUV or dithering when configured; an import into YUVA converts at once without them.
WebPConfigLosslessPresetoverrideslossless,methodandquality.- libwebp ignores the progress hook’s answer at the end of an analysis
without segments and during the statistics pass of lossy methods 0 to 2;
the documentation of
Encoder::progresstells a cancelling hook to keep returningfalse.
§Checks not applicable
These checks do not apply, or cannot be made, with the reason:
- Source correspondence. This module translates no upstream unit, so
there are no
// upstream:markers, notools/rust_name.pynames and no probe of its own. NULLarguments do not exist in the API (references and slices).- Views, crop, rescale, distortion, alpha blending,
extra_infoand the standalone conversions are not in the API (ADR 0006); their cases intests/support/wp13_cases.rsare left out or run without the map. Metadata chunks and animation belong to the muxer and the animation encoder insrc/mux/. - Undefined behavior in C. The exclusions of the encoder translation
hold through its case records (statistics of alpha with
alpha_compression0 and of failed threaded alpha encodings,extra_info_type6), and the simple-API test skipsWebPEncodeLosslessRGBAon misaligned rows (see# Excluded undefined behaviorinsrc/enc/picture_csp_enc.rs). The API accepts such rows; the translation reads them as bytes, which C cannot confirm. - Allocation failures are not injected;
OutOfMemory,BadWritefrom a refused memory-writer growth andUnreportedare reached only through the translation’s fallible reservations. - 32-bit targets are not run; the
usizeoverflow of a plane’s extent maps toInvalidStrideand is reachable there only.
Re-exports§
pub use crate::webp::encode::WebPAuxStats;
Structs§
- Config
- Compression parameters: a
WebPConfigwith typed setters. - Encoder
- One encoding: a configuration, and optionally a progress hook and
statistics, applied to a
PicturewithEncoder::encodeorEncoder::encode_to. - Picture
- A picture to encode: its dimensions and its samples, either planes it
allocated (
Picture::import) or the caller’s planes, borrowed exclusively for'a(Picture::from_argb,Picture::from_yuva). - Pixel
Rows - Strided rows of packed pixels, the input of
Picture::importand of the simple functions. - Yuva
Planes - The caller’s Y, U, V and optional A planes, the input of
Picture::from_yuva.
Enums§
- Alpha
Filter - The predictive filter of the alpha plane in a lossy encoding
(C:
WebPConfig::alpha_filtering0, 1 and 2). - Encode
Error - Why an encoding or one of its inputs failed.
- Image
Hint - A hint about the content that the lossless encoder uses
(C:
WebPImageHint). - Pixel
Layout - The order of the channels of packed rows, as libwebp’s six importers read
them (C:
WebPPictureImportRGBand its siblings). - Plane
- The input that an
EncodeErrorrefers to. - Preset
- A predefined configuration set, tuned for a kind of content (C:
WebPPreset). - Sample
Form - The samples that an imported picture keeps (C:
WebPPicture::use_argb).
Functions§
- encode_
lossless - Encodes
rowslosslessly with the default preset at quality 70, as libwebp’s simple API does (C:WebPEncodeLosslessRGB,WebPEncodeLosslessBGR,WebPEncodeLosslessRGBAandWebPEncodeLosslessBGRA; the X layouts take the same steps). - encode_
lossy - Encodes
rowslossily atqualitywith the default preset, as libwebp’s simple API does (C:WebPEncodeRGB,WebPEncodeBGR,WebPEncodeRGBAandWebPEncodeBGRA; the X layouts take the same steps).