Technical Article

WebP to PDF in Delphi: Inside the HotPDF VP8L Decoder

RFC 9649 says a WebP lossless bitstream is read least significant bit first, and a decoder that applies that sentence everywhere falls over on its very first prefix code. The bytes are LSB-first, but the Huffman codes stored inside them are walked from the root of the tree, so the first bit pulled off the stream is the most significant bit of the code. Three more one-bit rules in the same RFC behave the same way: each is stated once, and getting any of them wrong still yields a full-size image, made entirely of colored static

The usual route into this problem is mundane. A design tool starts exporting every asset as WebP because that is the modern default, and an invoice or catalog generator that has eaten PNG and JPEG for a decade suddenly receives a file type it has never seen. Binding libwebp is the obvious fix. It is also the fix that adds a native DLL to an executable that used to deploy as a single file

Putting a .webp file on a PDF page from Delphi

HotPDF reads lossless WebP with a VP8L decoder written in Object Pascal, so THotPDF.AddImage accepts a .webp path directly and nothing extra ships with your executable. In C++Builder the same file-based overload is called AddImageFromFile. The WebP branch sits at the same extension check that routes .jp2, .j2k, .jpt and .jpc files down the path described in adding JPEG 2000 images to PDFs in Delphi: the file is decoded to a 32-bit bitmap first, then embedded with whatever compression you pass, icFlate in the example below

uses
  SysUtils, HPDFDoc;

var
  Pdf: THotPDF;
  Idx: Integer;
begin
  Pdf := THotPDF.Create(nil);
  try
    Pdf.FileName := 'catalog.pdf';
    Pdf.BeginDoc;
    try
      // the .webp extension sends the file to the built-in VP8L decoder
      Idx := Pdf.AddImage('product-shot.webp', icFlate);
      Pdf.CurrentPage.ShowImage(Idx, 50, 500, 240, 180, 0);
    except
      on E: Exception do
        // lossy or animated WebP ends up here; queue it for conversion
        Writeln('Skipped: ', E.Message);
    end;
    Pdf.EndDoc;
  finally
    Pdf.Free;
  end;
end;
HotPDF pipeline diagram showing AddImage (AddImageFromFile in C++Builder) dispatching a .webp path beside the jp2, j2k, jpt and jpc extensions into HPDFDecodeWebPLossless, a pure Object Pascal VP8L decoder in HPDFWebP.pas that walks the RIFF container and decodes prefix codes, LZ77 references, the color cache and four transforms into $AARRGGBB pixels
The WebP branch sits at the same extension dispatch that already routes JPEG 2000 files, so a self-contained component gains .webp support with no DLL, no helper process and no new deployment story

The dispatch looks at the extension and nothing else. A lossless WebP saved as asset.img never reaches the WebP decoder, while a lossy photo saved as hero.webp does reach it and comes back as an exception whose message reads Failed to decode WebP image (lossless VP8L only), followed by the file name. When the image arrives as bytes instead of a file (a database BLOB, an HTTP response body), skip the path and call the decoder unit yourself:

uses
  SysUtils, Graphics, HPDFDoc, HPDFWebP;

// AddWebPBytes is your own helper, not part of the library
function AddWebPBytes(Pdf: THotPDF; const Bytes: TBytes): Integer;
var
  Bmp: TBitmap;
begin
  Bmp := HPDFDecodeWebPToBitmap(Bytes);   // nil unless lossless VP8L
  if Bmp = nil then
    raise Exception.Create('Not a lossless WebP image');
  try
    Result := Pdf.AddImage(Bmp, icFlate);
  finally
    Bmp.Free;
  end;
end;

HPDFDecodeWebPToBitmap returns a pf32bit TBitmap that the caller owns, or nil. One level lower, HPDFDecodeWebPLossless(Data, Width, Height, Pixels) fills a TWebPCardinalArray with Width × Height values in $AARRGGBB layout, scan-line order, and returns False instead of raising. That is the entry point for code that wants pixels with no PDF in sight, such as a thumbnail step or a triage pass that sorts incoming assets into a lossless pile and a needs-conversion pile

Writing the codec in Pascal was a deliberate trade. A component that customers compile into their own executable should not quietly acquire a runtime DLL: that means a 32-bit and a 64-bit binary to track, a version to pin, a code-signing chain to explain to whoever runs the deployment, and one more file that endpoint security on a locked-down terminal may decide it dislikes. Against that, VP8L is a small format, a prefix-code and LZ77 scheme with four inverse transforms and a 120-entry distance table, and the whole decoder in HPDFWebP.pas stays under a thousand lines. For a lossless-only scope, owning that code costs less than shipping a DLL. Lossy VP8 is a far larger codec built on video keyframe coding, and it stays outside this decoder, so lossy files go through a converter before they reach AddImage

Why does a VP8L bitstream read in two directions at once?

Because RFC 9649 specifies the container bit order and the prefix code bit order independently, and they point opposite ways. Section 3.2 states plainly that the stream is read least significant bit first: start at bit 0 of a byte and walk up. The canonical prefix codes carried in that stream are decoded from the root, so the walk shifts its accumulator left and ORs each new bit in at the bottom. Reader and walk therefore run in opposite directions inside the same loop. Reread that loop a week later and it looks like a bug

The LSB-first sentence in the RFC is emphatic enough that applying it to the code walk as well feels like the faithful reading, and that reading is wrong: with an LSB-first walk, the first prefix code decodes to the wrong symbol and every table after it is noise. The sketch below puts the reader and the walk side by side; Counts holds how many codes exist at each length and Symbols lists the symbols in canonical order

HotPDF bit diagram explaining why a VP8L stream reads in two directions: RFC 9649 3.2 reads the container least significant bit first through a ReadBit routine, while the canonical prefix code walk shifts Code left and ORs each newly read bit in at the bottom, so the first bit off the stream becomes the most significant bit
The bitstream reader walks each byte from bit 0 upward while the canonical decode walk shifts its accumulator left, and both directions run inside the same loop over the same bits
// LSB first, RFC 9649 section 3.2: bit 0 of each byte comes off first
function ReadBit(const Data: TBytes; var BytePos, BitPos: Integer): Integer;
begin
  if BytePos >= Length(Data) then
    raise Exception.Create('WebP bitstream exhausted');
  Result := (Data[BytePos] shr BitPos) and 1;
  Inc(BitPos);
  if BitPos = 8 then
  begin
    BitPos := 0;
    Inc(BytePos);
  end;
end;

// the canonical walk runs the other way: the first bit off the stream
// is the most significant bit of the code
Code := 0;
First := 0;
Index := 0;
for Len := 1 to 15 do
begin
  Code := (Code shl 1) or ReadBit(Data, BytePos, BitPos);
  if Counts[Len] > 0 then
  begin
    if Code - First < Counts[Len] then
      Exit(Symbols[Index + Code - First]);
    First := (First + Counts[Len]) shl 1;
    Index := Index + Counts[Len];
  end
  else
    First := First shl 1;
end;

Three one-bit traps in RFC 9649 section 3

Three more semantics are stated exactly once, are easy to read past, and each one costs or saves a single bit. One bit is plenty. Once the reader is a position off, every following prefix code table is read from the wrong place, and the decode still runs all the way to the last pixel

HotPDF trap diagram of three RFC 9649 details that desynchronize a VP8L stream: a non-primary entropy-coded image writes no meta-prefix bit, a single-leaf prefix code consumes zero bits and decodes its one symbol without reading, and cache_bits 0 means a color cache of zero entries, keeping the green alphabet at 280 rather than 281
Each of the three semantics costs or saves exactly one bit, which is enough to turn every later prefix code table into noise while the image still decodes to completion
  • An entropy-coded image in a non-primary role carries no meta prefix bit. The ABNF for entropy-coded-image simply does not contain the item; per section 3.8.3 only the main ARGB image has it. HotPDF reads that bit for the main image alone and skips it for the meta prefix image, the predictor and color transform data, and the color-indexing palette
  • A prefix code with a single leaf consumes zero bits. Section 3.7.2.1 says so directly, yet a generic canonical walk reads a bit anyway and then fails to place it. The decoder notices a code with exactly one symbol while building the table and returns that symbol without touching the stream
  • A cache_bits value of 0 means there is no color cache. The convenient 1 shl CacheBits gives 1, which makes the green alphabet 256 + 24 + CacheSize come out as 281 instead of 280, and every table read after it lands out of step. When a cache is present, cache_bits must fall between 1 and 11; anything else is rejected

Not one of the three looks like an off-by-one when it happens. Each produces an image of the right width and height that looks like static, and nothing in the picture tells you which rule was broken

Bit-position diffing beats staring at pixels

The way out of that blindness is to stop comparing pictures and compare bit counters. Run two decoders over the same file, yours and a reference, and have both log the running bit position beside every read. The first position where the logs disagree is where the bug lives, so the question shrinks from why is this picture wrong to why did the stream diverge at this bit. Any reference you can instrument will do: a small script-language model of the RFC is enough for the bit log, and a mature library can supply the expected RGBA output for the final pixel comparison

Start with the dullest image you can produce, a flat-color 32×32 file that only exercises the simple-code path. Get that matching. Then add gradients, odd dimensions, a palette image and an alpha channel, one at a time. Guessing at bit order instead is a reliable way to lose a day

The reference can be wrong too. A hand-written model of the RFC walks into the same traps as the decoder under test: skip the cache_bits read, or end the transform loop one entry early, and the reference loses sync first, so the first divergence points at code that is correct. Neither decoder gets the benefit of the doubt; each divergence is settled against the RFC text. Take that text from the published RFC itself, because search snippets and summaries regularly mangle numeric tables, and the 120-entry distance map, the 14 predictor modes and the color cache multiplier $1e35a7bd all have to be transcribed exactly

Where Pascal div and C shifts part ways

The color transform is where a straight port from C goes wrong. VP8L stores the transform multipliers as signed 3.5 fixed-point bytes and computes each delta as the product of two sign-extended bytes shifted right by 5. The C reference code relies on an arithmetic right shift, which floors negative values on mainstream compilers, while Pascal div truncates toward zero. For every negative product the two results differ by one, so the inverse color transform drifts by one channel step on every pixel whose delta happens to be negative

// C's arithmetic shift floors negative values; Pascal div truncates
// toward zero, so the negative case needs an explicit correction
function FloorDivBy32(V: Integer): Integer;
begin
  Result := V div 32;
  if (V < 0) and (V mod 32 <> 0) then
    Dec(Result);
end;

// RFC 9649 ColorTransformDelta: both bytes are sign-extended first
function ColorTransformDelta(T, C: Integer): Integer;
var
  T8, C8: Integer;
begin
  T8 := T;
  if T8 >= 128 then
    Dec(T8, 256);
  C8 := C;
  if C8 >= 128 then
    Dec(C8, 256);
  Result := FloorDivBy32(T8 * C8);
end;

HotPDF does that floor explicitly instead of trusting div. The mismatch hides from any test whose products stay non-negative, because div and floor agree there, and a one-step drift sails through a tolerance-based image comparison. For a lossless codec the only meaningful check is pixel-exact: compare every decoded pixel, bit for bit, against a reference decode of the same files, with gradients, odd sizes and a palette image in the set. A perceptual threshold is the wrong tool here

What the decoder refuses, and why the whole container is checked first

HPDFDecodeWebPLossless accepts exactly one shape of file: a RIFF WEBP container holding a single VP8L chunk. It returns False for lossy VP8 data, for ANIM and ANMF chunks, for a VP8X header with the animation flag set, and for a container that carries a second VP8L chunk; AddImage turns that False into the exception quoted earlier. Failing at the call site is the behavior you want. A caller can pre-convert a lossy file, whereas a gray rectangle in a shipped invoice gets found by the customer

Container validation finishes before a single pixel is decoded. The RIFF size field, not the length of the byte array, decides which chunks belong to the file. Each chunk size is widened to 64 bits before the 8-byte header and the odd-size padding byte are added, and that padding byte must be zero. Only when the walk reaches the declared end does the decoder copy out the VP8L payload, so a truncated metadata chunk or an animation chunk placed after the image cannot slip past. Bytes after the declared RIFF end, and unknown chunks inside it, are tolerated for compatibility

Inside the bitstream the checks continue. The 3-bit version field must be 0, at most four transforms may be stacked, every backward reference must point inside the pixels decoded so far, and a meta prefix image may not name more prefix-code groups than it has pixels. That last rule matters more than it looks: each group costs five Huffman tables, so an unchecked group index read from a few hundred bytes of input could demand hundreds of megabytes of tables. Any of these violations ends the decode with False, and no exception escapes into your code

Decoding on import is the opposite direction from pulling pictures back out of a document you opened, which is covered in extracting images from a loaded PDF and their decode filters. And a WebP decoder is still a parser fed by files you did not create. If the assets come from customers or the public internet, these bounds checks are the floor, and running image codecs in an isolated worker process keeps a malformed frame from taking the host application down with it

For a Delphi or C++Builder application, the net effect is that a lossless WebP asset goes into a PDF with the same two calls as a PNG and adds nothing to the installer. The HotPDF Delphi PDF component page lists the image, loading and rendering features that share that unit set