Skip to main content

Module decode

Module decode 

Source
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 VP8 bitstream holds Y'CbCr 4: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’s src/dsp/yuv.h (VP8YUVToR, VP8YUVToG, VP8YUVToB), with fancy upsampling of the chroma unless Config::fancy_upsampling is off or the output is scaled (the rescaler then upsamples). The in-loop filter runs unless Config::bypass_filtering is set or the output is scaled below 3/4 in both directions. ColorMode::Yuv and ColorMode::Yuva return the decoded planes as stored, so their caller converts with the same limited-range matrix. Config::dithering adds libwebp’s dither to lossy output.
  • Lossless color. A VP8L bitstream stores ARGB exactly; the RGB modes reorder its bytes (the 16-bit modes keep the high bits), and the YUV modes convert it with WebPConvertARGBToY and WebPConvertARGBToUV (the same limited-range matrix, chroma from 2 by 2 averages).
  • Alpha is straight in ColorMode::Rgba, ColorMode::Bgra, ColorMode::Argb, ColorMode::Rgba4444 and the alpha plane of ColorMode::Yuva, and premultiplied in the four Premultiplied modes. The alpha of a lossy image comes from its ALPH chunk; Config::alpha_dithering smooths quantized alpha. Modes without alpha drop it.
  • Precision. Every mode has 8 bits per channel at most; ColorMode::Rgba4444 and ColorMode::Rgb565 pack 4 or 5 and 6 bits per channel into two bytes, red first.
  • Color signal and orientation. WebP carries no color signal besides an ICCP chunk and no orientation besides an EXIF chunk. Container returns 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.

  1. Odd crop offsets are refused with InvalidCrop. libwebp moves an odd crop_left or crop_top of a lossy image to the even position below it (WebPIoInitFromOptions snaps when the source is YUV) and crops a lossless image exactly.
  2. 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.
  3. Dithering strengths above 100 are refused with InvalidParameter, as WebPValidateDecoderConfig refuses them; WebPDecode, which does not validate, clamps them.
  4. Order of errors. decode and decode_into check the configuration first, then the features, then the crop, scale and caller memory against them, and call webp_decode last. C reports a bitstream error in a frame header before the VP8_STATUS_INVALID_PARAM of 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.
  5. 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 in MODE_YUV.
  6. An empty append before any data returns NeedsMoreData without calling the decoder. C asserts against it (see # Excluded undefined behavior in src/dec/idec_dec.rs), and the translation’s debug_assert panics in the dev and checked profiles; release builds of both return SUSPENDED. An append that fails with OutOfMemory does not count as data, since a first piece above MAX_CHUNK_PAYLOAD or a failed reservation stores nothing; if that failure came from decoding a stored first piece instead, C would answer the empty call with BITSTREAM_ERROR.
  7. The incremental decoder owns its output buffer (C’s WebPINewRGB, WebPINewYUVA and WebPINewDecoder buffers) and takes the options as WebPIDecode does; C’s WebPIDecode decodes into the configuration’s buffer, which keeps the memory after WebPIDelete. The samples are equal (tests/wp16_incremental.rs compares them); into_image moves the library memory out. Slow memory is not offered.
  8. Errors without a C status. AnimationDecoder::new and Container::new classify a failure by running Features::parse and the partial demuxer on the data; C returns NULL and the demuxer reports a non-WebP file as a header in progress. A failed next_frame is FrameFailed. On failure Features::parse returns no features, where C writes what it parsed.
  9. IncrementalDecoder::output_size is None while libwebp’s decoded area exists with a width of 0 (between a lossless header and the allocation of the output); rows then lends the caller’s memory with 0 rows, as C’s getter returns the caller’s pointer.
  10. 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:

  1. A whole-image decoding of a truncated file returns libwebp’s status: BitstreamError when the file ends before the image’s dimensions (C maps the features’ NOT_ENOUGH_DATA), and the decoder’s NotEnoughData or BitstreamError later; caller memory then holds the rows decoded so far.
  2. 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.
  3. After a failed incremental step every later step returns BitstreamError.
  4. 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:

  1. Source correspondence. This module translates no upstream unit, so there are no // upstream: markers, no tools/rust_name.py names and no probe of its own.
  2. NULL arguments do not exist in the API (references and slices).
  3. Callbacks. The API takes no callbacks, so a panicking callback (the test of the encoder API in tests/wp17_misuse.rs) cannot occur.
  4. I/O hooks, slow memory, WebPCopyDecBuffer, WebPGrabDecBuffer, the demuxer’s frame iterators, WebPGetInfo and the simple functions are not in the API (ADR 0007); the simple functions are compared through decode. The fconfig commands of the probe tools/oracle/probes/wp12/decode.c (features first, which matters only for slow memory) and its constructor cases that the API cannot express (WebPINewRGB with a YUV mode, YUVA memory without a V plane) are not replayed.
  5. 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 int in TransformOne_C (see # Excluded undefined behavior in src/dsp/dec.rs) still panic in the dev and checked profiles and wrap in release; the API cannot detect them before decoding. WebPIAppend of zero bytes before any data (see # Excluded undefined behavior in src/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.
  6. Allocation failures are not injected; OutOfMemory is reached only through the translation’s fallible reservations.
  7. 32-bit targets are not run; the usize overflow of a plane’s extent maps to InvalidStride and is reachable there only.

Structs§

AnimationDecoder
A decoder of a WebP animation into full canvases (C: WebPAnimDecoder).
AnimationInfo
The parameters of an animation (C: WebPAnimInfo).
AnimationOptions
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 WebPDecoderOptions with 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.
IncrementalDecoder
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.
YuvaPlanes
The caller’s Y, U, V and optional alpha planes, an Output for ColorMode::Yuv and ColorMode::Yuva.
YuvaRows
The rows of the Y, U, V and, for ColorMode::Yuva, alpha planes.

Enums§

AnimationMode
The color mode of an animation’s canvas: the four modes that libwebp’s animation decoder supports.
ColorMode
The layout of the decoded samples (C: WEBP_CSP_MODE, in its order).
DecodeError
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::format 1 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: WebPDecode with an output buffer without memory). WebPDecodeRGBA and the other simple functions of libwebp are this function with Config::new(mode).
decode_into
Decodes a still WebP image into the caller’s memory (C: WebPDecode with is_external_memory 1), 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.