Expand description
Safe Rust API over the decoder 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: WP16 (safe decoder API).
The decision record is docs/adr/0007-safe-decoder-api.md. Every decoding
calls the translation with the stored options: decode and
decode_into call the translated WebPDecode (webp_decode),
IncrementalDecoder the translated incremental decoder and
AnimationDecoder the translated WebPAnimDecoder, so the samples are
those of libwebp v1.6.0 with the same options. The API validates crops,
scales, strides and buffer lengths first, so that caller input never
reaches a panic of the translation, and reports failures as
DecodeError.
§Example
use webp::api::decode::{decode, ColorMode, Config, Features, Format};
// `file` holds a lossless 6 by 4 WebP image.
let features = Features::parse(&file)?;
assert_eq!((features.width, features.height, features.format), (6, 4, Some(Format::Lossless)));
let config = Config::new(ColorMode::Rgba).crop(2, 0, 4, 4);
let image = decode(&file, &config)?;
let rows = image.rows().expect("an RGB mode");
assert_eq!((image.width(), image.height(), rows.len()), (4, 4, 4));
assert_eq!(rows.row(0), Some(&[200_u8, 100, 50, 255].repeat(4)[..]));§Memory
decode returns an Image in memory that libwebp allocates; the image
owns it and hands it over without a copy (Image::into_samples).
decode_into and IncrementalDecoder::with_output write into the
caller’s rows or planes (Output), so that the caller can budget that
memory; every stride counts bytes. Config::output_size gives the size
of the output before decoding. AnimationDecoder::new allocates two
canvases of 4 * canvas_width * canvas_height bytes and zeroes them.
§Semantics
- Lossy color. A
VP8bitstream holdsY'CbCr4:2:0 after ITU-R BT.601 in limited range (Y 16 to 235, Cb and Cr 16 to 240). The RGB modes convert with the fixed-point matrix of libwebp’ssrc/dsp/yuv.h(VP8YUVToR,VP8YUVToG,VP8YUVToB), with fancy upsampling of the chroma unlessConfig::fancy_upsamplingis off or the output is scaled (the rescaler then upsamples). The in-loop filter runs unlessConfig::bypass_filteringis set or the output is scaled below 3/4 in both directions.ColorMode::YuvandColorMode::Yuvareturn the decoded planes as stored, so their caller converts with the same limited-range matrix.Config::ditheringadds libwebp’s dither to lossy output. - Lossless color. A
VP8Lbitstream stores ARGB exactly; the RGB modes reorder its bytes (the 16-bit modes keep the high bits), and the YUV modes convert it withWebPConvertARGBToYandWebPConvertARGBToUV(the same limited-range matrix, chroma from 2 by 2 averages). - Alpha is straight in
ColorMode::Rgba,ColorMode::Bgra,ColorMode::Argb,ColorMode::Rgba4444and the alpha plane ofColorMode::Yuva, and premultiplied in the fourPremultipliedmodes. The alpha of a lossy image comes from itsALPHchunk;Config::alpha_ditheringsmooths quantized alpha. Modes without alpha drop it. - Precision. Every mode has 8 bits per channel at most;
ColorMode::Rgba4444andColorMode::Rgb565pack 4 or 5 and 6 bits per channel into two bytes, red first. - Color signal and orientation. WebP carries no color signal besides an
ICCPchunk and no orientation besides anEXIFchunk.Containerreturns the raw payloads and parses neither; without a profile, readers assume sRGB. - Animation. Full canvases after blending and disposal, premultiplied blending in the premultiplied modes, a transparent black start, the background color reported and not applied, timestamps as end times in milliseconds.
§Cropping
A crop decodes the rows from the top of the image down to the crop’s
bottom (with 2 or 8 rows of filter margin for lossy images), so it saves
the rows below the crop and nothing above it; a horizontal crop saves
nothing, and the incremental decoder parses every macroblock row of a lossy
image whatever the crop. Scaling runs after decoding at full resolution.
tests/wp12_crop_rows.rs has the counts.
§Deviations from upstream
Changes of representation that the ADRs allow, or behavior that the Rust side cannot reproduce exactly. Each records the reason.
- Odd crop offsets are refused with
InvalidCrop. libwebp moves an oddcrop_leftorcrop_topof a lossy image to the even position below it (WebPIoInitFromOptionssnaps when the source is YUV) and crops a lossless image exactly. - Scales need both sides, each 1 to 16383. libwebp derives a side given
as 0 and accepts outputs up to
i32::MAX / 2, for which it reserves and zeroes up to 16 GiB of library memory. - Dithering strengths above 100 are refused with
InvalidParameter, asWebPValidateDecoderConfigrefuses them;WebPDecode, which does not validate, clamps them. - Order of errors.
decodeanddecode_intocheck the configuration first, then the features, then the crop, scale and caller memory against them, and callwebp_decodelast. C reports a bitstream error in a frame header before theVP8_STATUS_INVALID_PARAMof a crop, scale or buffer that does not fit, and a features error before any configuration error. The samples of every accepted decoding are libwebp’s. - Caller memory has one stride for both chroma planes, and the API
refuses an alpha plane for
Yuv(OutputMismatch); C takes separate U and V strides and ignores an alpha plane inMODE_YUV. - An empty
appendbefore any data returnsNeedsMoreDatawithout calling the decoder. C asserts against it (see# Excluded undefined behaviorinsrc/dec/idec_dec.rs), and the translation’sdebug_assertpanics in the dev andcheckedprofiles; release builds of both returnSUSPENDED. Anappendthat fails withOutOfMemorydoes not count as data, since a first piece aboveMAX_CHUNK_PAYLOADor a failed reservation stores nothing; if that failure came from decoding a stored first piece instead, C would answer the empty call withBITSTREAM_ERROR. - The incremental decoder owns its output buffer (C’s
WebPINewRGB,WebPINewYUVAandWebPINewDecoderbuffers) and takes the options asWebPIDecodedoes; C’sWebPIDecodedecodes into the configuration’s buffer, which keeps the memory afterWebPIDelete. The samples are equal (tests/wp16_incremental.rscompares them);into_imagemoves the library memory out. Slow memory is not offered. - Errors without a C status.
AnimationDecoder::newandContainer::newclassify a failure by runningFeatures::parseand the partial demuxer on the data; C returnsNULLand the demuxer reports a non-WebP file as a header in progress. A failednext_frameisFrameFailed. On failureFeatures::parsereturns no features, where C writes what it parsed. IncrementalDecoder::output_sizeisNonewhile libwebp’s decoded area exists with a width of 0 (between a lossless header and the allocation of the output);rowsthen lends the caller’s memory with 0 rows, as C’s getter returns the caller’s pointer.- The canvas of a failed frame is not exposed: the borrow of the
previous frame ends at the next call (see the deviation on the canvas
after a failure in
src/demux/anim_decode.rs).
§Upstream behavior preserved
Behavior of the C code that a reader might take for a defect, which the translation keeps:
- A whole-image decoding of a truncated file returns libwebp’s status:
BitstreamErrorwhen the file ends before the image’s dimensions (C maps the features’NOT_ENOUGH_DATA), and the decoder’sNotEnoughDataorBitstreamErrorlater; caller memory then holds the rows decoded so far. - The incremental getters follow libwebp’s pointer and stride: while a flipped decoding runs, row 0 is the bottom row of the output and the stride is negative; once complete, the stride is positive. With a scale, chroma and alpha rows lag behind the luma rows.
- After a failed incremental step every later step returns
BitstreamError. - A still image through the animation decoder is one frame with
timestamp 0, loop count 1 and background
0xFFFFFFFF.
§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).- Callbacks. The API takes no callbacks, so a panicking callback (the
test of the encoder API in
tests/wp17_misuse.rs) cannot occur. - I/O hooks, slow memory,
WebPCopyDecBuffer,WebPGrabDecBuffer, the demuxer’s frame iterators,WebPGetInfoand the simple functions are not in the API (ADR 0007); the simple functions are compared throughdecode. Thefconfigcommands of the probetools/oracle/probes/wp12/decode.c(features first, which matters only for slow memory) and its constructor cases that the API cannot express (WebPINewRGBwith a YUV mode, YUVA memory without a V plane) are not replayed. - Undefined behavior in C. The exclusions of the decoder translation
hold. The API passes the bitstream to the translation, so crafted lossy
streams whose coefficients overflow
intinTransformOne_C(see# Excluded undefined behaviorinsrc/dsp/dec.rs) still panic in the dev andcheckedprofiles and wrap in release; the API cannot detect them before decoding.WebPIAppendof zero bytes before any data (see# Excluded undefined behaviorinsrc/dec/idec_dec.rs) no longer reaches the translation (item 6 of# Deviations from upstream). Negative strides and overlapping input and output memory, which the decoder translation also excludes, cannot be expressed. - Allocation failures are not injected;
OutOfMemoryis 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.
Structs§
- Animation
Decoder - A decoder of a WebP animation into full canvases (C:
WebPAnimDecoder). - Animation
Info - The parameters of an animation (C:
WebPAnimInfo). - Animation
Options - The options of an
AnimationDecoder(C:WebPAnimDecoderOptions). - Chunks
- The payloads of the chunks with one tag; see
Container::chunks. - Config
- Decoding options and the color mode: a
WebPDecoderOptionswith typed setters, and the output colorspace. - Container
- The container of a WebP file: its metadata chunks and the canvas and
animation parameters, through libwebp’s demuxer (C:
WebPDemuxer). - Features
- What a WebP file says about itself before decoding (C:
WebPBitstreamFeatures). - Frame
- A decoded frame: the whole canvas after the frame was blended and the previous one disposed, and the frame’s end time.
- Image
- A decoded image in memory that libwebp allocated, which the image owns.
- Incremental
Decoder - A decoder that takes a still WebP file in pieces and lends the rows
decoded so far (C:
WebPIDecoder). - Rows
- Rows of one plane: a region of memory, the position of the first row, a signed stride in bytes and the number of rows.
- Yuva
Planes - The caller’s Y, U, V and optional alpha planes, an
OutputforColorMode::YuvandColorMode::Yuva. - Yuva
Rows - The rows of the Y, U, V and, for
ColorMode::Yuva, alpha planes.
Enums§
- Animation
Mode - The color mode of an animation’s canvas: the four modes that libwebp’s animation decoder supports.
- Color
Mode - The layout of the decoded samples (C:
WEBP_CSP_MODE, in its order). - Decode
Error - Why a decoding or one of its inputs failed.
- Format
- The compression of a still image or of an animation’s first frame
(C:
WebPBitstreamFeatures::format1 and 2). - Output
- Caller memory that a decoding writes into.
- Plane
- Which output a stride or buffer error is about.
- Status
- How far an incremental decoding has come.
Functions§
- decode
- Decodes a still WebP image into memory that libwebp allocates (C:
WebPDecodewith an output buffer without memory).WebPDecodeRGBAand the other simple functions of libwebp are this function withConfig::new(mode). - decode_
into - Decodes a still WebP image into the caller’s memory (C:
WebPDecodewithis_external_memory1), which is checked against the output size first. Returns the output’s width and height. On failure, the rows that were decoded stay in the caller’s memory.