WebP #
Part of z2dimg.
A RIFF container — twelve bytes, then chunks — over two unrelated bitstreams, and that split is the whole shape of the format.
VP8L, the lossless one, is prefix codes, a colour cache, backward references and four reversible transforms. VP8, the lossy one, is a video codec's keyframe path: a boolean arithmetic decoder, coefficient probability tables, intra prediction, an inverse DCT and a loop filter. Both are read, still images and animations alike.
A third thing sits beside them. VP8 is a video codec and video is opaque, so
a lossy WebP that is not opaque carries its transparency in an ALPH
chunk of its own — a plane of one byte a pixel, row-filtered, and usually
compressed as a lossless WebP image with the values hidden in its green
channel. A transparent lossy file is therefore two decodes, and the one
thing about it that is not lossy is the alpha.
Only the lossless half is written. WebP is the first format here that is read more than it is written, and that had to be said in a way the compiler enforces rather than left as an omission; see below.
Two of the three pieces live elsewhere #
Neither the container nor the lossy bitstream is in this repository, and neither should be.
RIFF is what WAV and AVI are made of too — a twelve-byte header naming a
form type, and then chunks of a four-character identifier and a length — and
it has nothing to do with images. It is
zig-riff, which handles the
even-length padding, LIST nesting, the big-endian RIFX variant and RF64
(by refusing it by name), and which WebP uses through one extra operation that
this format needed: ANMF is a container that is not a LIST, so
descend takes a chunk's header from whatever the caller has already read
rather than assuming a four-character list type.
VP8 is a video codec that this format happens to carry one keyframe of, and is zig-vp8. It decodes a keyframe to three planes of samples and converts those to pixels, and what it produces is bit for bit what libwebp produces — which is the only exact claim a lossy decoder can make, since the file it was given already differs from the picture that was encoded. It knows nothing about RIFF, alpha or surfaces.
What is left in src/webp.zig is the part that is actually about WebP: which
chunks mean what, and how a frame becomes a surface.
What the lossless bitstream is #
Four ideas, and each of them is decoded by the same machinery:
- Prefix codes, five per pixel — one for green, which doubles as the backward-reference lengths and the colour-cache indices, then red, blue, alpha and distance. The stream is read least significant bit first and each code most significant bit of the code first, which are opposite conventions and both correct; this is DEFLATE's arrangement.
- An entropy image that says which set of five codes a block of pixels uses, so the statistics can vary across a picture.
- A colour cache of recently used colours, addressed by a hash.
- Four reversible transforms — a spatial predictor with fourteen modes, a cross-channel colour transform, subtract-green, and a palette — declared at the front and undone at the end in the reverse of the order they were read.
And the thing worth knowing before reading any of it: four of those are themselves VP8L images. The entropy image, the predictor's per-block modes, the colour transform's per-block coefficients and the palette are all decoded by the same function as the picture, at a lower resolution, with the payload in whichever channel that particular thing uses.
The recursion that implies is bounded at exactly two levels, and the bound is
stated as a call graph rather than as a counter: decodeTop is the only
function that reads transforms or an entropy image, and the only caller of
decodeSub, which reads neither. A third level is not something the decoder
declines to do — it is something it cannot say.
Where a few bytes buy a large allocation #
Every format here has one place where a small header asks for a large
allocation, and Limits exists for those. WebP's is not the image size.
The number of prefix-code groups is one more than the largest value in the entropy image, and that value is two bytes of a pixel. So a three-pixel entropy image may legitimately declare sixty-five thousand groups, at about six kilobytes of table each for a hundred and thirty bytes of input — a fifty-to-one amplification with nothing in the format bounding it.
Two things answer it. Only the groups some pixel actually names are stored;
the rest still have to be read, since they sit one after another in the stream
with nowhere to seek to, but reading and discarding them costs nothing. And
every symbol any code stores is drawn through a single budget, derived from
Limits.max_pixels with a floor so that a caller who lowered that for
thumbnails is not refused a legitimate small file. Overrunning it is
error.ImageTooLarge rather than error.InvalidData: the file is well formed
and the budget refused it.
Animation #
An ANMF frame maps onto this library's animation model with nothing left
over, which is the return on having built that model for GIF and APNG rather
than for either:
ANMF |
anim |
|---|---|
| frame X and Y, stored halved | Frame.x, Frame.y |
| width and height, minus one | Frame.width, Frame.height |
| duration, in milliseconds | Frame.delay_ms |
| blending method 0 / 1 | Blend.over / Blend.source |
| disposal method 0 / 1 | Dispose.keep / Dispose.background |
There is no dispose-to-previous, so a third of the disposal state machine goes
unused. ANIM's loop count already counts plays with zero meaning forever,
which is exactly what anim.Info.loop_count means — so unlike GIF it needs no
conversion at all.
decode is written in terms of the animation, the way gif.decode is: play
one frame onto a canvas, and the canvas is the answer. A file with no ANMF
in it is an animation of one frame covering the canvas, which costs nothing to
say and saves writing the still path twice.
Three refusals are worth naming because each closes a gap between entry points rather than a hole in a file:
- An
ANMFin a file whoseVP8Xdid not set the animation flag is refused.probehas already told a caller that this does not animate, and a decoder that then played two frames would be contradicting it. APNG gatesfcTLonacTLfor the same reason and was fixed for the same bug. - A frame must fit inside the canvas, and a frame's bitstream must declare
the size its
ANMFdeclared. The first is held against the canvas rather than againstLimits, and the second is checked before the limits are — a bitstream claiming sixteen thousand pixels inside a frame that declared nine is a malformed file, not a large one, and answeringImageTooLargewould haveprobepromise something small anddecoderefuse it as big. - An
ALPHchunk in a file whoseVP8Xdid not set the alpha flag is refused. Same shape again:probereported an opaque surface, so a decoder that then produced transparency would be contradicting it, and quietly discarding the alpha instead would be worse than either.
Sandboxing one #
sandbox.decode runs a decoder on a fixed arena of
Limits.max_pixels * 4 + Options.working_bytes, and this is the one decoder
here that needs a whole second image's worth of scratch. A backward reference
may reach anywhere earlier in the picture, so there is no streaming form of
VP8L: the ARGB buffer has to exist alongside the surface being filled from
it, which is eight bytes a pixel at the peak where every other decoder here
allocates the surface and little else. A lossy frame is no cheaper for a
different reason — three planes of samples, then the RGBA they convert to,
then the surface — and a transparent one adds the alpha plane and the
lossless image it was decoded from.
The default eight megabytes of working memory therefore covers an image of
about half max_pixels. A caller sandboxing WebP at the full budget should
raise working_bytes to match.
The order things are allocated in matters here and is deliberate. The child runs on an arena that can only give back the block it handed out most recently, so the surface is allocated first and the scratch above it — which leaves the residue four bytes a pixel rather than eight when the scratch is freed.
Metadata sits on both sides of the pixels #
ICCP comes before the image data and EXIF after it, which the format
requires and which has a consequence worth saying out loud: probe can
never report a WebP's orientation. probe stops at the first image chunk
— that is what makes it cheap — and EXIF is past it, so Info.orientation
is always .top_left for a WebP however the file is turned. The real answer
comes from passing DecodeOptions.orientation to decode, which keeps
walking the container after it has the picture.
This is the only decoder here that reads a container after the image, and
it does it only when a caller asked for something that lives out there:
stepping over a chunk on a stream means reading it, and reading to the end
of an animation to find out which way up it goes is a poor trade for a
caller who never asked. Nothing is decoded by that walk — an ANMF is a
chunk like any other to a walk that does not descend into it — so it costs
the bytes it discards and no more.
The profile is the raw thing, unlike PNG's iCCP, which deflates it behind
a name; there is nothing to inflate and no name to skip. Both readers follow
the rule the rest of the library follows for metadata: a malformed profile
or a malformed TIFF block is dropped, never an error, because a camera
that wrote a broken block fifteen years ago still wrote a perfectly good
photograph. A profile that is not shaped like one never reaches the caller,
so there is no way to be handed sixty-four bytes of nonsense to write into
the next file.
The flags byte reads backwards #
VP8X holds its feature bits in one byte, and the specification's prose
numbers those bits most significant first — so a careful reading of it
produces exactly the inverse of what every implementation uses. The constants
in src/webp.zig are libwebp's: animation 0x02, XMP 0x04, Exif 0x08,
alpha 0x10, ICC 0x20.
The alpha bit is a hint #
Both VP8X and the VP8L header carry a bit saying the image has
transparency, and in both places the specification says it should be zero
when every pixel is opaque rather than that it must be. This library takes it
at its word, because probe and decode have to agree about the surface type
and the hint is all probe can see — which is also what libwebp reports and
so what Pillow shows. animated-red-blue.webp is the illustration: its
VP8X claims alpha while every one of its frames disclaims it, because the
container is describing the file and not any particular frame.
Transparency for a codec that has none #
VP8 is a video codec and video is opaque, so a lossy WebP keeps its
transparency in an ALPH chunk in front of the frame: one header byte, then
a plane of one byte a pixel the same size as the frame. Two things about it
are worth knowing.
The plane is usually a lossless WebP image of its own, with the alpha
values in the green channel and the other three left at zero — which is not
an oddity for its own sake, it is what lets the subtract-green transform and
the colour cache do anything for a single-channel image. So src/webp.zig
reads it by handing the bytes to the same vp8l decoder the VP8L chunk
uses, minus the five-byte header the frame has already made unnecessary, and
keeps one channel of what comes back. The other option the format allows is
the plane exactly as it is, uncompressed.
Then it is unfiltered, by one of four fixed rules over bytes — none, from the left, from above, or left plus above minus the corner between them. It is not the predictor transform next door and does not share any code with it: four rules over bytes rather than fourteen over pixels.
The consequence worth stating is that a lossy WebP's alpha is not lossy.
That makes it checkable against ground truth where nothing else in the file
is, and the corpus does exactly that:
hippopotamus.masked-with-muybridge.lossy.webp is held against the PNG of
the same picture on the alpha channel alone, 1008 pixels, many of them
partly transparent, every one exact.
Writing one #
Lossless only, and still images only. A lossy encoder is a different kind of work from a lossy decoder: decoding has one right answer and encoding has a great many, and choosing between them is rate control and mode decision rather than anything this library is about. Reading one is what an image library owes its callers; writing one is a project of its own.
What it does is a real VP8L encoder rather than a conforming minimum:
- Prefix codes built from the image's own histograms, length-limited to fifteen bits. Huffman's algorithm does not respect a limit — frequencies growing like the Fibonacci numbers produce a code as long as the alphabet — so the length distribution is fixed up afterwards and the shortest codes are handed to the most frequent symbols at the end.
- Backward references, found with a chained hash table over three-pixel sequences. The chain is followed from the most recent match backwards, which finds the nearest match first — and near is also cheap, since the first hundred and twenty distance codes name a neighbourhood rather than a number.
- A colour cache, sized by the number of pixels, because every entry costs a symbol in the green alphabet whether anything uses it or not.
- Subtract-green, chosen by measuring rather than assumed: both forms of the red and blue histograms are built and the one that codes to fewer bits wins.
A code of one symbol spends no bits at all, which is why an opaque alpha channel costs nothing and a picture of one colour codes to under two hundred bytes however large it is.
Against libwebp at its default effort, on the corpus:
| image | this | libwebp | ratio |
|---|---|---|---|
bricks-nodither 160×120 |
12,118 | 10,814 | 1.12 |
hat 90×112 |
25,442 | 22,152 | 1.15 |
hippopotamus 36×28 |
2,270 | 1,880 | 1.21 |
harvesters 1165×859 |
2,392,584 | 1,466,150 | 1.63 |
The gap that remains is the predictor transform, which is what libwebp spends on a photograph and this does not write yet. The decoder here reads it, so the files are read correctly either way; they are simply larger than they need to be.