RFC 9649 | WebP Image Format | November 2024 |
Zern, et al. | Informational | [Page] |
This document defines the WebP image format and registers a media type supporting its use.¶
This document is not an Internet Standards Track specification; it is published for informational purposes.¶
This document is a product of the Internet Engineering Task Force (IETF). It represents the consensus of the IETF community. It has received public review and has been approved for publication by the Internet Engineering Steering Group (IESG). Not all documents approved by the IESG are candidates for any level of Internet Standard; see Section 2 of RFC 7841.¶
Information about the current status of this document, any errata, and how to provide feedback on it may be obtained athttps://www.rfc-editor.org/info/rfc9649.¶
Copyright (c) 2024 IETF Trust and the persons identified as the document authors. All rights reserved.¶
This document is subject to BCP 78 and the IETF Trust's Legal Provisions Relating to IETF Documents (https://trustee.ietf.org/license-info) in effect on the date of publication of this document. Please review these documents carefully, as they describe your rights and restrictions with respect to this document. Code Components extracted from this document must include Revised BSD License text as described in Section 4.e of the Trust Legal Provisions and are provided without warranty as described in the Revised BSD License.¶
WebP is an image file format based on theResource Interchange File Format (RIFF) [RIFF-spec] (Section 2) that supports lossless and lossy compression as well as alpha (transparency) and animation. It covers use cases similar toJPEG [JPEG-spec],PNG [RFC2083], and theGraphics Interchange Format (GIF) [GIF-spec].¶
WebP consists of two compression algorithms used to reduce the size of image pixel data, including alpha (transparency) information. Lossy compression is achieved using VP8 intra-frame encoding[RFC6386]. Thelossless algorithm (Section 3) stores and restores the pixel values exactly, including the color values for fully transparent pixels. A universal algorithm for sequential data compression[LZ77],prefix coding [Huffman], and a color cache are used for compression of the bulk data.¶
Note that this section is based on the documentation in thelibwebp source repository [webp-riff-src].¶
WebP is an image format that uses either (i) the VP8 intra-frame encoding[RFC6386] to compress image data in a lossy way or (ii) theWebP lossless encoding (Section 3). These encoding schemes should make it more efficient than older formats, such as JPEG, GIF, and PNG. It is optimized for fast image transfer over the network (for example, for websites). The WebP format has feature parity (color profile, metadata, animation, etc.) with other formats as well. This section describes the structure of a WebP file.¶
The WebP container (that is, the RIFF container for WebP) allows feature support over and above the basic use case of WebP (that is, a file containing a single image encoded as a VP8 key frame). The WebP container provides additional support for the following:¶
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in BCP 14[RFC2119][RFC8174] when, and only when, they appear in all capitals, as shown here.¶
A WebP file contains either a still image (that is, an encoded matrix of pixels) or ananimation (Section 2.7.1.1). Optionally, it can also contain transparency information, a color profile, and metadata. We refer to the matrix of pixels as thecanvas of the image.¶
Bit numbering in chunk diagrams starts at0
for the most significant bit ('MSB 0'), as described in[RFC1166].¶
Below are additional terms used throughout this section:¶
The WebP file format is based on theRIFF [RIFF-spec] document format.¶
The basic element of a RIFF file is achunk. It consists of:¶
0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+| Chunk FourCC |+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+| Chunk Size |+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+: Chunk Payload :+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
0
to conform withRIFF [RIFF-spec] -- is added.¶Note: RIFF has a convention that all uppercase chunk FourCCs are standard chunks that apply to any RIFF file format, while FourCCs specific to a file format are all lowercase. WebP does not follow this convention.¶
0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+| 'R' | 'I' | 'F' | 'F' |+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+| File Size |+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+| 'W' | 'E' | 'B' | 'P' |+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
A WebP fileMUST begin with a RIFF header with the FourCC 'WEBP'. The file size in the header is the total size of the chunks that follow plus4
bytes for the 'WEBP' FourCC. The fileSHOULD NOT contain any data after the data specified byFile Size. ReadersMAY parse such files, ignoring the trailing data. As the size of any chunk is even, the size given by the RIFF header is also even. The contents of individual chunks are described in the following sections.¶
This layoutSHOULD be used if the image requires lossy encoding and does not require transparency or other advanced features provided by the extended format. Files with this layout are smaller and supported by older software.¶
0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+| || WebP file header (12 bytes) || |+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+: 'VP8 ' Chunk :+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+| ChunkHeader('VP8 ') || |+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+: VP8 data :+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Note that the fourth character in the 'VP8 ' FourCC is an ASCII space (0x20).¶
The VP8 bitstream format specification is described in[RFC6386].¶
Note that the VP8 frame header contains the VP8 frame width and height. That is assumed to be the width and height of the canvas.¶
The VP8 specification describes how to decode the image into Y'CbCr format. To convert to RGB,Recommendation 601 [REC601]SHOULD be used. ApplicationsMAY use another conversion method, but visual results may differ among decoders.¶
Note: Older readers may not support files using the lossless format.¶
This layoutSHOULD be used if the image requires lossless encoding (with an optional transparency channel) and does not require advanced features provided by the extended format.¶
0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+| || WebP file header (12 bytes) || |+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+: 'VP8L' Chunk :+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+| ChunkHeader('VP8L') || |+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+: VP8L data :+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
The specification of the VP8L bitstream can be found inSection 3.¶
Note that the VP8L header contains the VP8L image width and height. That is assumed to be the width and height of the canvas.¶
Note: Older readers may not support files using the extended format.¶
An extended format file consists of:¶
For astill image, theimage data consists of a single frame, which is made up of:¶
For ananimated image, theimage data consists of multiple frames. More details about frames can be found inSection 2.7.1.1.¶
All chunks necessary for reconstruction and color correction, that is, 'VP8X', 'ICCP', 'ANIM', 'ANMF', 'ALPH', 'VP8 ', and 'VP8L',MUST appear in the order described earlier. ReadersSHOULD fail when chunks necessary for reconstruction and color correction are out of order.¶
Metadata (Section 2.7.1.5) andunknown chunks (Section 2.7.1.6) MAY appear out of order.¶
Rationale: The chunks necessary for reconstruction should appear first in the file to allow a reader to begin decoding an image before receiving all of the data. An application may benefit from varying the order of metadata and custom chunks to suit the implementation.¶
0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+| || WebP file header (12 bytes) || |+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+| ChunkHeader('VP8X') || |+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+|Rsv|I|L|E|X|A|R| Reserved |+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+| Canvas Width Minus One | ...+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+... Canvas Height Minus One |+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
0
. ReadersMUST ignore this field.¶0
. ReadersMUST ignore this field.¶0
. ReadersMUST ignore this field.¶1 + Canvas Width Minus One
.¶1 + Canvas Height Minus One
.¶The product ofCanvas Width andCanvas HeightMUST be at most232 - 1
.¶
Future specifications may add more fields. Unknown fieldsMUST be ignored.¶
An animation is controlled by 'ANIM' and 'ANMF' Chunks.¶
0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+| ChunkHeader('ANIM') || |+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+| Background Color |+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+| Loop Count |+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
For an animated image, this chunk contains theglobal parameters of the animation.¶
The default background color of the canvas in [Blue, Green, Red, Alpha] byte order. This colorMAY be used to fill the unused space on the canvas around the frames, as well as the transparent pixels of the first frame. The background color is also used when the Disposal method is1
.¶
Notes:¶
0
, this means infinitely.¶This chunkMUST appear if theAnimation flag in the 'VP8X' Chunk is set. If theAnimation flag is not set and this chunk is present, itMUST be ignored.¶
0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+| ChunkHeader('ANMF') || |+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+| Frame X | ...+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+... Frame Y | Frame Width Minus One ...+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+... | Frame Height Minus One |+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+| Frame Duration | Reserved |B|D|+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+: Frame Data :+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
For animated images, this chunk contains information about asingle frame. If theAnimation flag is not set, then this chunkSHOULD NOT be present.¶
Frame X * 2
.¶Frame Y * 2
.¶1 + Frame Width Minus One
.¶1 + Frame Height Minus One
.¶0
. ReadersMUST ignore this field.¶Indicates how transparent pixels ofthe current frame are to be blended with corresponding pixels of the previous canvas:¶
0
: Use alpha-blending. After disposing of the previous frame, render the current frame on the canvas usingalpha-blending. If the current frame does not have an alpha channel, assume the alpha value is 255, effectively replacing the rectangle.¶1
: Do not blend. After disposing of the previous frame, render the current frame on the canvas by overwriting the rectangle covered by the current frame.¶Indicates howthe current frame is to be treated after it has been displayed (before rendering the next frame) on the canvas:¶
0
: Do not dispose. Leave the canvas as is.¶1
: Dispose to the background color. Fill therectangle on the canvas covered by thecurrent frame with the background color specified in the'ANIM' Chunk (Figure 8).¶Notes:¶
Alpha-blending:¶
Given that each of the R, G, B, and A channels is 8 bits and the RGB channels arenot premultiplied by alpha, the formula for blending 'dst' onto 'src' is:¶
blend.A = src.A + dst.A * (1 - src.A / 255)if blend.A = 0 then blend.RGB = 0else blend.RGB = (src.RGB * src.A + dst.RGB * dst.A * (1 - src.A / 255)) / blend.A¶
16
Consists of:¶
Note: The 'ANMF' payload,Frame Data, consists of individualpadded chunks, as described by theRIFF file format (Section 2.3).¶
0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+| ChunkHeader('ALPH') || |+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+|Rsv| P | F | C | Alpha Bitstream... |+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
0
. ReadersMUST ignore this field.¶These informative bits are used to signal the preprocessing that has been performed during compression. The decoder can use this information to, for example, dither the values or smooth the gradients prior to display.¶
Decoders are not required to use this information in any specified way.¶
The filtering methods used are described as follows:¶
For each pixel, filtering is performed using the following calculations. Assume the alpha values surrounding the currentX
position are labeled as:¶
C | B |---+---+ A | X |
We seek to compute the alpha value at position X. First, a prediction is made depending on the filtering method:¶
0
: predictor = 0¶1
: predictor = A¶2
: predictor = B¶3
: predictor = clip(A + B - C)¶whereclip(v)
is equal to:¶
The final value is derived by adding the decompressed valueX
to the predictor and using modulo-256 arithmetic to wrap the [256..511] range into the [0..255] one:¶
alpha = (predictor + X) % 256¶
There are special cases for the left-most and top-most pixel positions.¶
For example, the top-left value at location (0, 0) uses 0 as the predictor value. Otherwise:¶
The compression method used:¶
1
This optional chunk contains encoded alpha data for this frame. A frame containing a 'VP8L' ChunkSHOULD NOT contain this chunk.¶
Rationale: The transparency information is already part of the 'VP8L' Chunk.¶
The alpha channel data is stored as uncompressed raw data (when the compression method is '0') or compressed using the lossless format (when the compression method is '1').¶
Lossless format compression: The byte sequence is a compressed image-stream (as described inSection 3) of implicit dimensions width x height. That is, this image-stream does NOT contain any headers describing the image dimensions.¶
Rationale: The dimensions are already known from other sources, so storing them again would be redundant and prone to errors.¶
Once the image-stream is decoded into Alpha, Red, Green, Blue (ARGB) color values, following the process described in the lossless format specification, the transparency information must be extracted from the green channel of the ARGB quadruplet.¶
Rationale: The green channel is allowed extra transformation steps in the specification -- unlike the other channels -- that can improve compression.¶
This chunk contains compressed bitstream data for a single frame.¶
A bitstream chunk may be either (i) a 'VP8 ' Chunk, using 'VP8 ' (note the significant fourth-character space) as its FourCC,or (ii) a 'VP8L' Chunk, using 'VP8L' as its FourCC.¶
The formats of' VP8 ' and 'VP8L' Chunks are as described in Sections2.5 and2.6, respectively.¶
0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+| ChunkHeader('ICCP') || |+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+: Color Profile :+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
This chunkMUST appear before the image data.¶
ThereSHOULD be at most one such chunk. If there are more such chunks, readersMAY ignore all except the first one. See theICC specification [ICC] for details.¶
If this chunk is not present, sRGBSHOULD be assumed.¶
Metadata can be stored in 'EXIF' or 'XMP ' Chunks.¶
ThereSHOULD be at most one chunk of each type ('EXIF' and 'XMP '). If there are more such chunks, readersMAY ignore all except the first one.¶
The chunks are defined as follows:¶
0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+| ChunkHeader('EXIF') || |+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+: Exif Metadata :+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+| ChunkHeader('XMP ') || |+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+: XMP Metadata :+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Note that the fourth character in the 'XMP ' FourCC is an ASCII space (0x20).¶
Additional guidance about handling metadata can be found in the Metadata Working Group's"Guidelines For Handling Image Metadata" [MWG].¶
A RIFF chunk (described inSection 2.3) whoseFourCC is different from any of the chunks described in this section is considered anunknown chunk.¶
Rationale: Allowing unknown chunks gives a provision for future extension of the format and also allows storage of any application-specific data.¶
A fileMAY contain unknown chunks:¶
ReadersSHOULD ignore these chunks. WritersSHOULD preserve them in their original order (unless they specifically intend to modify these chunks).¶
Here, we provide an overview of how a readerMUST assemble a canvas in the case of an animated image.¶
The process begins with creating a canvas using the dimensions given in the 'VP8X' Chunk,Canvas Width Minus One + 1
pixels wide byCanvas Height Minus One + 1
pixels high. TheLoop Count
field from the 'ANIM' Chunk controls how many times the animation process is repeated. This isLoop Count - 1
for nonzeroLoop Count
values or infinite if theLoop Count
is zero.¶
At the beginning of each loop iteration, the canvas is filled using the background color from the 'ANIM' Chunk or an application-defined color.¶
'ANMF' Chunks contain individual frames given in display order. Before rendering each frame, the previous frame'sDisposal method
is applied.¶
The rendering of the decoded frame begins at the Cartesian coordinates (2 * Frame X
,2 * Frame Y
), using the top-left corner of the canvas as the origin.Frame Width Minus One + 1
pixels wide byFrame Height Minus One + 1
pixels high are rendered onto the canvas using theBlending method
.¶
The canvas is displayed forFrame Duration
milliseconds. This continues until all frames given by 'ANMF' Chunks have been displayed. A new loop iteration is then begun, or the canvas is left in its final state if all iterations have been completed.¶
The following pseudocode illustrates the rendering process. The notationVP8X.field means the field in the 'VP8X' Chunk with the same description.¶
VP8X.flags.hasAnimation MUST be TRUEcanvas <- new image of size VP8X.canvasWidth x VP8X.canvasHeight with background color ANIM.background_color or application-defined color.loop_count <- ANIM.loopCountdispose_method <- Dispose to background colorif loop_count == 0: loop_count = infframe_params <- nilnext chunk in image_data is ANMF MUST be TRUEfor loop = 0..loop_count - 1 clear canvas to ANIM.background_color or application-defined color until eof or non-ANMF chunk frame_params.frameX = Frame X frame_params.frameY = Frame Y frame_params.frameWidth = Frame Width Minus One + 1 frame_params.frameHeight = Frame Height Minus One + 1 frame_params.frameDuration = Frame Duration frame_right = frame_params.frameX + frame_params.frameWidth frame_bottom = frame_params.frameY + frame_params.frameHeight VP8X.canvasWidth >= frame_right MUST be TRUE VP8X.canvasHeight >= frame_bottom MUST be TRUE for subchunk in 'Frame Data': if subchunk.tag == "ALPH": alpha subchunks not found in 'Frame Data' earlier MUST be TRUE frame_params.alpha = alpha_data else if subchunk.tag == "VP8 " OR subchunk.tag == "VP8L": bitstream subchunks not found in 'Frame Data' earlier MUST be TRUE frame_params.bitstream = bitstream_data apply dispose_method. render frame with frame_params.alpha and frame_params.bitstream on canvas with top-left corner at (frame_params.frameX, frame_params.frameY), using Blending method frame_params.blendingMethod. canvas contains the decoded image. Show the contents of the canvas for frame_params.frameDuration * 1 ms. dispose_method = frame_params.disposeMethod¶
A lossy-encoded image with alpha may look as follows:¶
RIFF/WEBP+- VP8X (descriptions of features used)+- ALPH (alpha bitstream)+- VP8 (bitstream)
A lossless-encoded image may look as follows:¶
RIFF/WEBP+- VP8X (descriptions of features used)+- VP8L (lossless bitstream)+- XYZW (unknown chunk)
A lossless image with an ICC profile and XMP metadata may look as follows:¶
RIFF/WEBP+- VP8X (descriptions of features used)+- ICCP (color profile)+- VP8L (lossless bitstream)+- XMP (metadata)
An animated image with Exif metadata may look as follows:¶
RIFF/WEBP+- VP8X (descriptions of features used)+- ANIM (global animation parameters)+- ANMF (frame1 parameters + data)+- ANMF (frame2 parameters + data)+- ANMF (frame3 parameters + data)+- ANMF (frame4 parameters + data)+- EXIF (metadata)
Note that this section is based on the documentation in thelibwebp source repository [webp-lossless-src].¶
WebP lossless is an image format for lossless compression of ARGB images. The lossless format stores and restores the pixel values exactly, including the color values for pixels whose alpha value is 0. The format uses subresolution images, recursively embedded into the format itself, for storing statistical data about the images, such as the used entropy codes, spatial predictors, color space conversion, and color table. A universal algorithm for sequential data compression[LZ77], prefix coding, and a color cache are used for compression of the bulk data. Decoding speeds faster than PNG have been demonstrated, as well as 25% denser compression than can be achieved using today's PNG format[webp-lossless-study].¶
This section describes the compressed data representation of a WebP lossless image.¶
In this section, we extensively use C programming language syntax[ISO.9899.2018] to describe the bitstream and assume the existence of a function for reading bits,ReadBits(n)
. The bytes are read in the natural order of the stream containing them, and bits of each byte are read in least-significant-bit-first order. When multiple bits are read at the same time, the integer is constructed from the original data in the original order. The most significant bits of the returned integer are also the most significant bits of the original data. Thus, the statement¶
b = ReadBits(2);¶
is equivalent with the two statements below:¶
b = ReadBits(1);b |= ReadBits(1) << 1;¶
We assume that each color component (that is, alpha, red, blue, and green) is represented using an 8-bit byte. We define the corresponding type as uint8. A whole ARGB pixel is represented by a type called uint32, which is an unsigned integer consisting of 32 bits. In the code showing the behavior of the transforms, these values are codified in the following bits: alpha in bits 31..24, red in bits 23..16, green in bits 15..8, and blue in bits 7..0; however, implementations of the format are free to use another representation internally.¶
Broadly, a WebP lossless image contains header data, transform information, and actual image data. Headers contain the width and height of the image. A WebP lossless image can go through four different types of transforms before being entropy encoded. The transform information in the bitstream contains the data required to apply the respective inverse transforms.¶
The beginning of the header has the RIFF container. This consists of the following 21 bytes:¶
The first 28 bits of the bitstream specify the width and height of the image. Width and height are decoded as 14-bit integers as follows:¶
int image_width = ReadBits(14) + 1;int image_height = ReadBits(14) + 1;¶
The 14-bit precision for image width and height limits the maximum size of a WebP lossless image to 16384x16384 pixels.¶
The alpha_is_used bit is a hint only andSHOULD NOT impact decoding. ItSHOULD be set to 0 when all alpha values are 255 in the picture and 1 otherwise.¶
int alpha_is_used = ReadBits(1);¶
The version_number is a 3-bit code thatMUST be set to 0. Any other valueMUST be treated as an error.¶
int version_number = ReadBits(3);¶
The transforms are reversible manipulations of the image data that can reduce the remaining symbolic entropy by modeling spatial and color correlations. They can make the final compression more dense.¶
An image can go through four types of transforms. A 1 bit indicates the presence of a transform. Each transform is allowed to be used only once. The transforms are used only for the main-level ARGB image; the subresolution images (color transform image, entropy image, and predictor image) have no transforms, not even the 0 bit indicating the end of transforms.¶
Typically, an encoder would use these transforms to reduce the Shannon entropy in the residual image. Also, the transform data can be decided based on entropy minimization.¶
while (ReadBits(1)) { // Transform present. // Decode transform type. enum TransformType transform_type = ReadBits(2); // Decode transform data. ...}// Decode actual image data.¶
If a transform is present, then the next two bits specify the transform type. There are four types of transforms.¶
Transform | Bit |
---|---|
PREDICTOR_TRANSFORM | 0 |
COLOR_TRANSFORM | 1 |
SUBTRACT_GREEN_TRANSFORM | 2 |
COLOR_INDEXING_TRANSFORM | 3 |
The transform type is followed by the transform data. Transform data contains the information required to apply the inverse transform and depends on the transform type. The inverse transforms are applied in the reverse order that they are read from the bitstream, that is, last one first.¶
Next, we describe the transform data for different types.¶
The predictor transform can be used to reduce entropy by exploiting the fact that neighboring pixels are often correlated. In the predictor transform, the current pixel value is predicted from the pixels already decoded (in scan-line order) and only the residual value (actual - predicted) is encoded. The green component of a pixel defines which of the 14 predictors is used within a particular block of the ARGB image. Theprediction mode determines the type of prediction to use. We divide the image into squares, and all the pixels in a square use the same prediction mode.¶
The first 3 bits of prediction data define the block width and height in number of bits.¶
int size_bits = ReadBits(3) + 2;int block_width = (1 << size_bits);int block_height = (1 << size_bits);#define DIV_ROUND_UP(num, den) (((num) + (den) - 1) / (den))int transform_width = DIV_ROUND_UP(image_width, 1 << size_bits);¶
The transform data contains the prediction mode for each block of the image. It is a subresolution image where the green component of a pixel defines which of the 14 predictors is used for all theblock_width * block_height
pixels within a particular block of the ARGB image. This subresolution image is encoded using the same techniques described inSection 3.6.¶
The number of block columns,transform_width
, is used in two-dimensional indexing. For a pixel (x, y), one can compute the respective filter block address by:¶
int block_index = (y >> size_bits) * transform_width + (x >> size_bits);¶
There are 14 different prediction modes. In each prediction mode, the current pixel value is predicted from one or more neighboring pixels whose values are already known.¶
We chose the neighboring pixels (TL, T, TR, and L) of the current pixel (P) as follows:¶
O O O O O O O O O O OO O O O O O O O O O OO O O O TL T TR O O O OO O O O L P X X X X XX X X X X X X X X X XX X X X X X X X X X X
where TL means top-left, T means top, TR means top-right, and L means left. At the time of predicting a value for P, all O, TL, T, TR, and L pixels have already been processed, and the P pixel and all X pixels are unknown.¶
Given the preceding neighboring pixels, the different prediction modes are defined as follows.¶
Mode | Predicted Value of Each Channel of the Current Pixel |
---|---|
0 | 0xff000000 (represents solid black color in ARGB) |
1 | L |
2 | T |
3 | TR |
4 | TL |
5 | Average2(Average2(L, TR), T) |
6 | Average2(L, TL) |
7 | Average2(L, T) |
8 | Average2(TL, T) |
9 | Average2(T, TR) |
10 | Average2(Average2(L, TL), Average2(T, TR)) |
11 | Select(L, T, TL) |
12 | ClampAddSubtractFull(L, T, TL) |
13 | ClampAddSubtractHalf(Average2(L, T), TL) |
Average2
is defined as follows for each ARGB component:¶
uint8 Average2(uint8 a, uint8 b) { return (a + b) / 2;}¶
The Select predictor is defined as follows:¶
uint32 Select(uint32 L, uint32 T, uint32 TL) { // L = left pixel, T = top pixel, TL = top-left pixel. // ARGB component estimates for prediction. int pAlpha = ALPHA(L) + ALPHA(T) - ALPHA(TL); int pRed = RED(L) + RED(T) - RED(TL); int pGreen = GREEN(L) + GREEN(T) - GREEN(TL); int pBlue = BLUE(L) + BLUE(T) - BLUE(TL); // Manhattan distances to estimates for left and top pixels. int pL = abs(pAlpha - ALPHA(L)) + abs(pRed - RED(L)) + abs(pGreen - GREEN(L)) + abs(pBlue - BLUE(L)); int pT = abs(pAlpha - ALPHA(T)) + abs(pRed - RED(T)) + abs(pGreen - GREEN(T)) + abs(pBlue - BLUE(T)); // Return either left or top, the one closer to the prediction. if (pL < pT) { return L; } else { return T; }}¶
The functionsClampAddSubtractFull
andClampAddSubtractHalf
are performed for each ARGB component as follows:¶
// Clamp the input value between 0 and 255.int Clamp(int a) { return (a < 0) ? 0 : (a > 255) ? 255 : a;}int ClampAddSubtractFull(int a, int b, int c) { return Clamp(a + b - c);}int ClampAddSubtractHalf(int a, int b) { return Clamp(a + (a - b) / 2);}¶
There are special handling rules for some border pixels. If there is a predictor transform, regardless of the mode [0..13] for these pixels, the predicted value for the left-topmost pixel of the image is 0xff000000, all pixels on the top row are L-pixel, and all pixels on the leftmost column are T-pixel.¶
Addressing the TR-pixel for pixels on the rightmost column is exceptional. The pixels on the rightmost column are predicted by using the modes [0..13], just like pixels not on the border, but the leftmost pixel on the same row as the current pixel is instead used as the TR-pixel.¶
The final pixel value is obtained by adding each channel of the predicted value to the encoded residual value.¶
void PredictorTransformOutput(uint32 residual, uint32 pred, uint8* alpha, uint8* red, uint8* green, uint8* blue) { *alpha = ALPHA(residual) + ALPHA(pred); *red = RED(residual) + RED(pred); *green = GREEN(residual) + GREEN(pred); *blue = BLUE(residual) + BLUE(pred);}¶
The goal of the color transform is to decorrelate the R, G, and B values of each pixel. The color transform keeps the green (G) value as it is, transforms the red (R) value based on the green value, and transforms the blue (B) value based on the green value and then on the red value.¶
As is the case for the predictor transform, first the image is divided into blocks, and the same transform mode is used for all the pixels in a block. For each block, there are three types of color transform elements.¶
typedef struct { uint8 green_to_red; uint8 green_to_blue; uint8 red_to_blue;} ColorTransformElement;¶
The actual color transform is done by defining a color transform delta. The color transform delta depends on theColorTransformElement
, which is the same for all the pixels in a particular block. The delta is subtracted during the color transform. The inverse color transform then is just adding those deltas.¶
The color transform function is defined as follows:¶
void ColorTransform(uint8 red, uint8 blue, uint8 green, ColorTransformElement *trans, uint8 *new_red, uint8 *new_blue) { // Transformed values of red and blue components int tmp_red = red; int tmp_blue = blue; // Applying the transform is just subtracting the transform deltas tmp_red -= ColorTransformDelta(trans->green_to_red, green); tmp_blue -= ColorTransformDelta(trans->green_to_blue, green); tmp_blue -= ColorTransformDelta(trans->red_to_blue, red); *new_red = tmp_red & 0xff; *new_blue = tmp_blue & 0xff;}¶
ColorTransformDelta
is computed using a signed 8-bit integer representing a 3.5-fixed-point number and a signed 8-bit RGB color channel (c) [-128..127] and is defined as follows:¶
int8 ColorTransformDelta(int8 t, int8 c) { return (t * c) >> 5;}¶
A conversion from the 8-bit unsigned representation (uint8
) to the 8-bit signed one (int8
) is required before callingColorTransformDelta()
. The signed value should be interpreted as an 8-bit two's complement number (that is: uint8 range [128..255] is mapped to the [-128..-1] range of its converted int8 value).¶
The multiplication is to be done using more precision (with at least 16-bit precision). The sign extension property of the shift operation does not matter here; only the lowest 8 bits are used from the result, and in these bits, the sign extension shifting and unsigned shifting are consistent with each other.¶
Now, we describe the contents of color transform data so that decoding can apply the inverse color transform and recover the original red and blue values. The first 3 bits of the color transform data contain the width and height of the image block in number of bits, just like the predictor transform:¶
int size_bits = ReadBits(3) + 2;int block_width = 1 << size_bits;int block_height = 1 << size_bits;¶
The remaining part of the color transform data containsColorTransformElement
instances, corresponding to each block of the image. EachColorTransformElement
'cte'
is treated as a pixel in a subresolution image whose alpha component is255
, red component iscte.red_to_blue
, green component iscte.green_to_blue
, and blue component iscte.green_to_red
.¶
During decoding,ColorTransformElement
instances of the blocks are decoded and the inverse color transform is applied on the ARGB values of the pixels. As mentioned earlier, that inverse color transform is just addingColorTransformElement
values to the red and blue channels. The alpha and green channels are left as is.¶
void InverseTransform(uint8 red, uint8 green, uint8 blue, ColorTransformElement *trans, uint8 *new_red, uint8 *new_blue) { // Transformed values of red and blue components int tmp_red = red; int tmp_blue = blue; // Applying the inverse transform is just adding the // color transform deltas tmp_red += ColorTransformDelta(trans->green_to_red, green); tmp_blue += ColorTransformDelta(trans->green_to_blue, green); tmp_blue += ColorTransformDelta(trans->red_to_blue, tmp_red & 0xff); *new_red = tmp_red & 0xff; *new_blue = tmp_blue & 0xff;}¶
The subtract green transform subtracts green values from red and blue values of each pixel. When this transform is present, the decoder needs to add the green value to both the red and blue values. There is no data associated with this transform. The decoder applies the inverse transform as follows:¶
void AddGreenToBlueAndRed(uint8 green, uint8 *red, uint8 *blue) { *red = (*red + green) & 0xff; *blue = (*blue + green) & 0xff;}¶
This transform is redundant, as it can be modeled using the color transform, but since there is no additional data here, the subtract green transform can be coded using fewer bits than a full-blown color transform.¶
If there are not many unique pixel values, it may be more efficient to create a color index array and replace the pixel values by the array's indices. The color indexing transform achieves this. (In the context of WebP lossless, we specifically do not call this a palette transform because a similar but more dynamic concept exists in WebP lossless encoding: color cache.)¶
The color indexing transform checks for the number of unique ARGB values in the image. If that number is below a threshold (256), it creates an array of those ARGB values, which is then used to replace the pixel values with the corresponding index: the green channel of the pixels are replaced with the index, all alpha values are set to 255, and all red and blue values are set to 0.¶
The transform data contains the color table size and the entries in the color table. The decoder reads the color indexing transform data as follows:¶
// 8-bit value for the color table sizeint color_table_size = ReadBits(8) + 1;¶
The color table is stored using the image storage format itself. The color table can be obtained by reading an image, without the RIFF header, image size, and transforms, assuming the height of 1 pixel and the width ofcolor_table_size
. The color table is always subtraction-coded to reduce image entropy. The deltas of palette colors contain typically much less entropy than the colors themselves, leading to significant savings for smaller images. In decoding, every final color in the color table can be obtained by adding the previous color component values by each ARGB component separately and storing the least significant 8 bits of the result.¶
The inverse transform for the image is simply replacing the pixel values (which are indices to the color table) with the actual color table values. The indexing is done based on the green component of the ARGB color.¶
// Inverse transformargb = color_table[GREEN(argb)];¶
If the index is equal to or larger thancolor_table_size
, the argb color value should be set to 0x00000000 (transparent black).¶
When the color table is small (equal to or less than 16 colors), several pixels are bundled into a single pixel. The pixel bundling packs several (2, 4, or 8) pixels into a single pixel, reducing the image width respectively.¶
Pixel bundling allows for a more efficient joint distribution entropy coding of neighboring pixels and gives some arithmetic coding-like benefits to the entropy code, but it can only be used when there are 16 or fewer unique values.¶
color_table_size
specifies how many pixels are combined:¶
color_table_size | width_bits value |
---|---|
1..2 | 3 |
3..4 | 2 |
5..16 | 1 |
17..256 | 0 |
width_bits
has a value of 0, 1, 2, or 3. A value of 0 indicates no pixel bundling is to be done for the image. A value of 1 indicates that two pixels are combined, and each pixel has a range of [0..15]. A value of 2 indicates that four pixels are combined, and each pixel has a range of [0..3]. A value of 3 indicates that eight pixels are combined, and each pixel has a range of [0..1], that is, a binary value.¶
The values are packed into the green component as follows:¶
width_bits
= 1: For every x value, where x = 2k + 0, a green value at x is positioned into the 4 least significant bits of the green value at x / 2, and a green value at x + 1 is positioned into the 4 most significant bits of the green value at x / 2.¶width_bits
= 2: For every x value, where x = 4k + 0, a green value at x is positioned into the 2 least significant bits of the green value at x / 4, and green values at x + 1 to x + 3 are positioned in order to the more significant bits of the green value at x / 4.¶width_bits
= 3: For every x value, where x = 8k + 0, a green value at x is positioned into the least significant bit of the green value at x / 8, and green values at x + 1 to x + 7 are positioned in order to the more significant bits of the green value at x / 8.¶After reading this transform,image_width
is subsampled bywidth_bits
. This affects the size of subsequent transforms. The new size can be calculated usingDIV_ROUND_UP
, as defined inSection 3.5.1.¶
image_width = DIV_ROUND_UP(image_width, 1 << width_bits);¶
Image data is an array of pixel values in scan-line order.¶
We use image data in five different roles:¶
ColorTransformElement
values (defined in"Color Transform" (Section 3.5.2)) for different blocks of the image.¶color_table_size
(up to 256 ARGB values) that stores the metadata for the color indexing transform (see"Color Indexing Transform" (Section 3.5.4)).¶The encoding of image data is independent of its role.¶
The image is first divided into a set of fixed-size blocks (typically 16x16 blocks). Each of these blocks are modeled using their own entropy codes. Also, several blocks may share the same entropy codes.¶
Rationale: Storing an entropy code incurs a cost. This cost can be minimized if statistically similar blocks share an entropy code, thereby storing that code only once. For example, an encoder can find similar blocks by clustering them using their statistical properties or by repeatedly joining a pair of randomly selected clusters when it reduces the overall amount of bits needed to encode the image.¶
Each pixel is encoded using one of the three possible methods:¶
The following subsections describe each of these in detail.¶
The pixel is stored as prefix-coded values of green, red, blue, and alpha (in that order). SeeSection 3.7.2.3 for details.¶
Backward references are tuples oflength anddistance code:¶
The length and distance values are stored usingLZ77 prefix coding.¶
LZ77 prefix coding divides large integer values into two parts: theprefix code and theextra bits. The prefix code is stored using an entropy code, while the extra bits are stored as they are (without an entropy code).¶
Rationale: This approach reduces the storage requirement for the entropy code. Also, large values are usually rare, so extra bits would be used for very few values in the image. Thus, this approach results in better compression overall.¶
The following table denotes the prefix codes and extra bits used for storing different ranges of values.¶
Note: The maximum backward reference length is limited to 4096. Hence, only the first 24 prefix codes (with the respective extra bits) are meaningful for length values. For distance values, however, all the 40 prefix codes are valid.¶
Value Range | Prefix Code | Extra Bits |
---|---|---|
1 | 0 | 0 |
2 | 1 | 0 |
3 | 2 | 0 |
4 | 3 | 0 |
5..6 | 4 | 1 |
7..8 | 5 | 1 |
9..12 | 6 | 2 |
13..16 | 7 | 2 |
... | ... | ... |
3072..4096 | 23 | 10 |
... | ... | ... |
524289..786432 | 38 | 18 |
786433..1048576 | 39 | 18 |
The pseudocode to obtain a (length or distance) value from the prefix code is as follows:¶
if (prefix_code < 4) { return prefix_code + 1;}int extra_bits = (prefix_code - 2) >> 1;int offset = (2 + (prefix_code & 1)) << extra_bits;return offset + ReadBits(extra_bits) + 1;¶
As noted previously, a distance code is a number indicating the position of a previously seen pixel, from which the pixels are to be copied. This subsection defines the mapping between a distance code and the position of a previous pixel.¶
Distance codes larger than 120 denote the pixel distance in scan-line order, offset by 120.¶
The smallest distance codes [1..120] are special and are reserved for a close neighborhood of the current pixel. This neighborhood consists of 120 pixels:¶
7 * (8 + 1 + 7) = 112
].¶8
such pixels].¶The mapping between distance codedistance_code
and the neighboring pixel offset(xi, yi)
is as follows:¶
(0, 1), (1, 0), (1, 1), (-1, 1), (0, 2), (2, 0), (1, 2),(-1, 2), (2, 1), (-2, 1), (2, 2), (-2, 2), (0, 3), (3, 0),(1, 3), (-1, 3), (3, 1), (-3, 1), (2, 3), (-2, 3), (3, 2),(-3, 2), (0, 4), (4, 0), (1, 4), (-1, 4), (4, 1), (-4, 1),(3, 3), (-3, 3), (2, 4), (-2, 4), (4, 2), (-4, 2), (0, 5),(3, 4), (-3, 4), (4, 3), (-4, 3), (5, 0), (1, 5), (-1, 5),(5, 1), (-5, 1), (2, 5), (-2, 5), (5, 2), (-5, 2), (4, 4),(-4, 4), (3, 5), (-3, 5), (5, 3), (-5, 3), (0, 6), (6, 0),(1, 6), (-1, 6), (6, 1), (-6, 1), (2, 6), (-2, 6), (6, 2),(-6, 2), (4, 5), (-4, 5), (5, 4), (-5, 4), (3, 6), (-3, 6),(6, 3), (-6, 3), (0, 7), (7, 0), (1, 7), (-1, 7), (5, 5),(-5, 5), (7, 1), (-7, 1), (4, 6), (-4, 6), (6, 4), (-6, 4),(2, 7), (-2, 7), (7, 2), (-7, 2), (3, 7), (-3, 7), (7, 3),(-7, 3), (5, 6), (-5, 6), (6, 5), (-6, 5), (8, 0), (4, 7),(-4, 7), (7, 4), (-7, 4), (8, 1), (8, 2), (6, 6), (-6, 6),(8, 3), (5, 7), (-5, 7), (7, 5), (-7, 5), (8, 4), (6, 7),(-6, 7), (7, 6), (-7, 6), (8, 5), (7, 7), (-7, 7), (8, 6),(8, 7)
For example, the distance code1
indicates an offset of(0, 1)
for the neighboring pixel, that is, the pixel above the current pixel (0 pixel difference in the X direction and 1 pixel difference in the Y direction). Similarly, the distance code3
indicates the top-left pixel.¶
The decoder can convert a distance codedistance_code
to a scan-line order distancedist
as follows:¶
(xi, yi) = distance_map[distance_code - 1]dist = xi + yi * image_widthif (dist < 1) { dist = 1}¶
wheredistance_map
is the mapping noted above, andimage_width
is the width of the image in pixels.¶
Color cache stores a set of colors that have been recently used in the image.¶
Rationale: This way, the recently used colors can sometimes be referred to more efficiently than emitting them using the other two methods (described in Sections3.6.2.1 and3.6.2.2).¶
Color cache codes are stored as follows. First, there is a 1-bit value that indicates if the color cache is used. If this bit is 0, no color cache codes exist, and they are not transmitted in the prefix code that decodes the green symbols and the length prefix codes. However, if this bit is 1, the color cache size is read next:¶
int color_cache_code_bits = ReadBits(4);int color_cache_size = 1 << color_cache_code_bits;¶
color_cache_code_bits
defines the size of the color cache (1 << color_cache_code_bits
). The range of allowed values forcolor_cache_code_bits
is [1..11]. Compliant decodersMUST indicate a corrupted bitstream for other values.¶
A color cache is an array of sizecolor_cache_size
. Each entry stores one ARGB color. Colors are looked up by indexing them by(0x1e35a7bd * color) >> (32 - color_cache_code_bits)
. Only one lookup is done in a color cache; there is no conflict resolution.¶
In the beginning of decoding or encoding of an image, all entries in all color cache values are set to zero. The color cache code is converted to this color at decoding time. The state of the color cache is maintained by inserting every pixel, be it produced by backward referencing or as literals, into the cache in the order they appear in the stream.¶
Most of the data is coded using acanonical prefix code [Huffman]. Hence, the codes are transmitted by sending theprefix code lengths, as opposed to the actualprefix codes.¶
In particular, the format usesspatially variant prefix coding. In other words, different blocks of the image can potentially use different entropy codes.¶
Rationale: Different areas of the image may have different characteristics. So, allowing them to use different entropy codes provides more flexibility and potentially better compression.¶
The encoded image data consists of several parts:¶
For any given pixel (x, y), there is a set of five prefix codes associated with it. These codes are (in bitstream order):¶
From here on, we refer to this set as aprefix code group.¶
This section describes how to read the prefix code lengths from the bitstream.¶
The prefix code lengths can be coded in two ways. The method used is specified by a 1-bit value.¶
In both cases, there can be unused code lengths that are still part of the stream. This may be inefficient, but it is allowed by the format. The described tree must be a complete binary tree. A single leaf node is considered a complete binary tree and can be encoded using either the simple code length code or the normal code length code. When coding a single leaf node using thenormal code length code, all but one code length are zeros, and the single leaf node value is marked with the length of 1 -- even when no bits are consumed when that single leaf node tree is used.¶
This variant is used in the special case when only 1 or 2 prefix symbols are in the range [0..255] with code length1
. All other prefix code lengths are implicitly zeros.¶
The first bit indicates the number of symbols:¶
int num_symbols = ReadBits(1) + 1;¶
The following are the symbol values. This first symbol is coded using 1 or 8 bits, depending on the value ofis_first_8bits
. The range is [0..1] or [0..255], respectively. The second symbol, if present, is always assumed to be in the range [0..255] and coded using 8 bits.¶
int is_first_8bits = ReadBits(1);symbol0 = ReadBits(1 + 7 * is_first_8bits);code_lengths[symbol0] = 1;if (num_symbols == 2) { symbol1 = ReadBits(8); code_lengths[symbol1] = 1;}¶
The two symbols should be different. Duplicate symbols are allowed, but inefficient.¶
Note: Another special case is whenall prefix code lengths arezeros (an empty prefix code). For example, a prefix code for distance can be empty if there are no backward references. Similarly, prefix codes for alpha, red, and blue can be empty if all pixels within the same meta prefix code are produced using the color cache. However, this case doesn't need special handling, as empty prefix codes can be coded as those containing a single symbol0
.¶
The code lengths of the prefix code fit in 8 bits and are read as follows. First,num_code_lengths
specifies the number of code lengths.¶
int num_code_lengths = 4 + ReadBits(4);¶
The code lengths are themselves encoded using prefix codes; lower-level code lengths,code_length_code_lengths
, first have to be read. The rest of thosecode_length_code_lengths
(according to the order inkCodeLengthCodeOrder
) are zeros.¶
int kCodeLengthCodes = 19;int kCodeLengthCodeOrder[kCodeLengthCodes] = { 17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};int code_length_code_lengths[kCodeLengthCodes] = { 0 }; // All zerosfor (i = 0; i < num_code_lengths; ++i) { code_length_code_lengths[kCodeLengthCodeOrder[i]] = ReadBits(3);}¶
Next, ifReadBits(1) == 0
, the maximum number of different read symbols (max_symbol
) for each symbol type (A, R, G, B, and distance) is set to its alphabet size:¶
Otherwise, it is defined as:¶
int length_nbits = 2 + 2 * ReadBits(3);int max_symbol = 2 + ReadBits(length_nbits);¶
Ifmax_symbol
is larger than the size of the alphabet for the symbol type, the bitstream is invalid.¶
A prefix table is then built fromcode_length_code_lengths
and used to read up tomax_symbol
code lengths.¶
Code [0..15] indicates literal code lengths.¶
3 + ReadBits(2)
times. If code 16 is used before a nonzero value has been emitted, a value of 8 is repeated.¶3 + ReadBits(3)
times.¶11 + ReadBits(7)
times.¶Once code lengths are read, a prefix code for each symbol type (A, R, G, B, and distance) is formed using their respective alphabet sizes.¶
As noted earlier, the format allows the use of different prefix codes for different blocks of the image.Meta prefix codes are indexes identifying which prefix codes to use in different parts of the image.¶
Meta prefix codes may be usedonly when the image is being used in therole (Section 3.6.1) of anARGB image.¶
There are two possibilities for the meta prefix codes, indicated by a 1-bit value:¶
The red and green components of a pixel define a 16-bit meta prefix code used in a particular block of the ARGB image.¶
The entropy image defines which prefix codes are used in different parts of the image.¶
The first 3 bits contain theprefix_bits
value. The dimensions of the entropy image are derived fromprefix_bits
:¶
int prefix_bits = ReadBits(3) + 2;int prefix_image_width = DIV_ROUND_UP(image_width, 1 << prefix_bits);int prefix_image_height = DIV_ROUND_UP(image_height, 1 << prefix_bits);¶
whereDIV_ROUND_UP
is as defined inSection 3.5.1.¶
The next bits contain an entropy image of widthprefix_image_width
and heightprefix_image_height
.¶
The number of prefix code groups in the ARGB image can be obtained by finding thelargest meta prefix code from the entropy image:¶
int num_prefix_groups = max(entropy image) + 1;¶
wheremax(entropy image)
indicates the largest prefix code stored in the entropy image.¶
As each prefix code group contains five prefix codes, the total number of prefix codes is:¶
int num_prefix_codes = 5 * num_prefix_groups;¶
Given a pixel (x, y) in the ARGB image, we can obtain the corresponding prefix codes to be used as follows:¶
int position = (y >> prefix_bits) * prefix_image_width + (x >> prefix_bits);int meta_prefix_code = (entropy_image[position] >> 8) & 0xffff;PrefixCodeGroup prefix_group = prefix_code_groups[meta_prefix_code];¶
where we have assumed the existence ofPrefixCodeGroup
structure, which represents a set of five prefix codes. Also,prefix_code_groups
is an array ofPrefixCodeGroup
(of sizenum_prefix_groups
).¶
The decoder then uses prefix code groupprefix_group
to decode the pixel (x, y), as explained inSection 3.7.2.3.¶
For the current position (x, y) in the image, the decoder first identifies the corresponding prefix code group (as explained in the last section). Given the prefix code group, the pixel is read and decoded as follows.¶
Next, read symbol S from the bitstream using prefix code #1.¶
Note that S is any integer in the range0
to(256 + 24 + color_cache_size - 1)
. SeeSection 3.6.2.3 for details aboutcolor_cache_size
.¶
The interpretation of S depends on its value:¶
If S < 256¶
If S >= 256 & S < 256 + 24¶
If S >= 256 + 24¶
Below is a view into the format in Augmented Backus-Naur Form[RFC5234][RFC7405]. It does not cover all details. The end-of-image (EOI) is only implicitly coded into the number of pixels (image_width * image_height).¶
Note that*element
meanselement
can be repeated 0 or more times.5element
meanselement
is repeated exactly 5 times.%b
represents a binary value.¶
format = RIFF-header image-header image-streamRIFF-header = %s"RIFF" 4OCTET %s"WEBPVP8L" 4OCTETimage-header = %x2F image-size alpha-is-used versionimage-size = 14BIT 14BIT ; width - 1, height - 1alpha-is-used = 1BITversion = 3BIT ; 0image-stream = optional-transform spatially-coded-image¶
optional-transform = (%b1 transform optional-transform) / %b0transform = predictor-tx / color-tx / subtract-green-txtransform =/ color-indexing-txpredictor-tx = %b00 predictor-imagepredictor-image = 3BIT ; sub-pixel code entropy-coded-imagecolor-tx = %b01 color-imagecolor-image = 3BIT ; sub-pixel code entropy-coded-imagesubtract-green-tx = %b10color-indexing-tx = %b11 color-indexing-imagecolor-indexing-image = 8BIT ; color count entropy-coded-image¶
spatially-coded-image = color-cache-info meta-prefix dataentropy-coded-image = color-cache-info datacolor-cache-info = %b0color-cache-info =/ (%b1 4BIT) ; 1 followed by color cache sizemeta-prefix = %b0 / (%b1 entropy-image)data = prefix-codes lz77-coded-imageentropy-image = 3BIT ; subsample value entropy-coded-imageprefix-codes = prefix-code-group *prefix-codesprefix-code-group = 5prefix-code ; See "Interpretation of Meta Prefix Codes" to ; understand what each of these five prefix ; codes are for.prefix-code = simple-prefix-code / normal-prefix-codesimple-prefix-code = ; see "Simple Code Length Code" for detailsnormal-prefix-code = ; see "Normal Code Length Code" for detailslz77-coded-image = *((argb-pixel / lz77-copy / color-cache-code) lz77-coded-image)¶
The following is a possible example sequence:¶
RIFF-header image-size %b1 subtract-green-tx%b1 predictor-tx %b0 color-cache-info%b0 prefix-codes lz77-coded-image¶
Implementations of this format face security risks, such as integer overflows, out-of-bounds reads and writes to both heap and stack, uninitialized data usage, null pointer dereferences, resource (disk or memory) exhaustion, and extended resource usage (long running time) as part of the demuxing and decoding process. In particular, implementations reading this format are likely to take input from unknown and possibly unsafe sources -- both clients (for example, web browsers or email clients) and servers (for example, applications that accept uploaded images). These may result in arbitrary code execution, information leakage (memory layout and contents), or crashes and thereby allow a device to be compromised or cause a denial of service to an application using the format[mitre-libwebp][issues-security].¶
The format does not employ "active content" but does allow metadata (for example,[XMP] and[Exif]) and custom chunks to be embedded in a file. Applications that interpret these chunks may be subject to security considerations for those formats.¶
The format is defined using little-endian byte ordering (seeSection 3.1 of [RFC2781]), but demuxing and decoding are possible on platforms using a different ordering with the appropriate conversion. The container is based on RIFF and allows extension via user-defined chunks, but nothing beyond the chunks defined by the container format (Section 2) are required for decoding of the image. These have been finalized, but they were extended in the format's early stages, so some older readers may not support lossless or animated image decoding.¶
IANA has registered the 'image/webp' media type[RFC2046].¶
This section contains the media type registration details per[RFC6838].¶