Technical Article

JBIG2 Encoder Backends and the Free Pascal Linker

Encode the same scanned page twice, once with the external-encoder bit set and once with it cleared, then compare the two PDFs. If they match byte for byte, the request for the arithmetic-coded encoder was never answered. Which encoder runs is decided by what the program links, so the fix lives in a uses clause and a one-line check at startup

Where the encoder request is actually decided

PDF Library for Delphi (PDFlibPas) has two JBIG2 encoders behind a single call. The native Object Pascal encoder compresses the bilevel scanlines with CCITT G4 (MMR) and wraps the result in JBIG2 segment headers; it is compiled into every build. The external encoder is the jbig2enc arithmetic coder, and it exists only when a backend has been registered through RegisterJBIG2EncoderBackend in the PDFlibJBIG2Enc unit

A caller asks for it with option bit PDF_JBIG2_OPTION_EXTERNAL_ENCODER (value 4) or with the UseExternalEncoder argument of AddImageJBIG2FromFileEx, AddImageJBIG2FromStreamEx and AddImageJBIG2FromStringEx. DefaultJBIG2EncodeOptions switches it on as well. The dispatch inside TPLJBIG2Encoder.EncodeToByteArray is one condition: if the request is set and a backend is registered, the backend encodes; otherwise the MMR path does. Nothing at the call site tells you which branch ran

The registration itself comes from the PDFlibJBIG2EncC unit, whose initialisation section calls RegisterJBIG2EncoderBackend. The PDFlibrary umbrella unit deliberately leaves it out, because the encoder object set is large and carrying it should be each project's call. Two further conditions apply. The unit registers only on 64-bit x64 Windows builds; on Win32 or Windows on ARM its initialisation section registers nothing. And there is a single backend slot, so the last unit to call RegisterJBIG2EncoderBackend wins

PDFlibPas JBIG2 encode request flow where a request for the external encoder runs a registered generic-region backend and otherwise falls back silently to the native Pascal MMR encoder
Asking for the external encoder is a preference: with a backend registered, its generic-region coder runs; with none, the native Pascal MMR path runs and the files come out larger

My position on this is firm: if a job asks for the external encoder because archive size matters, it should refuse to start without it. IsJBIG2EncoderBackendAvailable answers the question in one call, and a failure at startup on a misconfigured build is far cheaper than months of archives encoded with the wrong codec

uses
  SysUtils,
  PDFlibrary,
  PDFlibJBIG2Enc,     // IsJBIG2EncoderBackendAvailable
  PDFlibJBIG2EncC;    // registers the jbig2enc backend on Win64 x64

var
  Pdf: TPDFlib;
  ImageId: Integer;
begin
  // A guard you add yourself: an archive job that asked for the
  // arithmetic coder should not run on a build that cannot provide it
  if not IsJBIG2EncoderBackendAvailable then
    raise Exception.Create('No external JBIG2 encoder registered in this build');

  Pdf := TPDFlib.Create;
  try
    Pdf.NewDocument;            // creates and selects page 1
    // Interpolate, SymbolExtract, UseExternalEncoder, SkipBlackDots,
    // BlackDotSize, LossyLevel. The source is loaded through TBitmap,
    // so pass a bitmap file
    ImageId := Pdf.AddImageJBIG2FromFileEx('scan-page-1.bmp',
      0, 0, 1, 0, 0, 0);
    if ImageId = 0 then
      raise Exception.Create('JBIG2 encoding failed');
    // place the image with SelectImage / DrawImage as usual
    Pdf.SaveToFile('archive.pdf');
  finally
    Pdf.Free;
  end;
end;

One behaviour is easy to misread. The fallback to MMR happens only when no backend is registered. Once a backend sits in the slot and it returns False, EncodeToByteArray fails and the AddImageJBIG2* call returns 0; there is no second attempt with the native encoder. That is the right default in my view, since a registered encoder that rejects a page points at the page or at the backend, and quietly switching codecs would hide both

How do you plug in an encoder that lives in a DLL?

Write a small unit that loads the DLL, resolves its entry points and registers a function matching TJBIG2EncodeCallback only once every entry point has resolved. If the DLL is missing, nothing is registered and requests fall back to MMR exactly as they would in a build without PDFlibJBIG2EncC. That is the whole contract

The reasons for doing this are practical. You may want a jbig2enc build of your own, with a different upstream version or encoding mode, and swap it in without relinking the application. Or you may be on a toolchain whose linker will not accept the C++ objects at all, which is the subject of the next section

The callback receives scanlines that have already been validated: EncodeToByteArray checks that width and height are positive and that every row holds at least (Width + 7) div 8 bytes before it calls the backend. Rows are packed most significant bit first, top to bottom. The backend returns the encoded stream in ImageData and must leave GlobalData empty, because the image entry points embed one self-contained stream per image and reject a result that carries global segments. A jbig2enc mode that emits a shared symbol dictionary across pages therefore does not fit through this door; per-image generic-region output does

unit MyJBIG2DllBackend;   // your own unit, not part of the library
{$IFDEF FPC}{$MODE DELPHI}{$ENDIF}

interface

implementation

uses
  Windows, SysUtils, PDFlibJBIG2Enc;

type
  // Example signatures for a flat C wrapper you build into the DLL
  TEncodeGeneric = function(Bitmap: PByte; Width, Height, RowBytes,
    XRes, YRes: Integer; OutLength: PInteger): PByte; cdecl;
  TFreeBuffer = procedure(P: PByte); cdecl;

var
  DllHandle: HMODULE = 0;
  EncodeGeneric: TEncodeGeneric = nil;
  FreeBuffer: TFreeBuffer = nil;

function DllBackend(const Scanlines: TJBIG2ScanlineArray;
  Width, Height: Integer; const Options: TJBIG2EncodeOptions;
  var ImageData, GlobalData: TJBIG2ByteArray): Boolean;
var
  RowBytes, Row, I, OutLen: Integer;
  Flat: array of Byte;
  P: PByte;
begin
  Result := False;
  SetLength(ImageData, 0);
  SetLength(GlobalData, 0);           // must stay empty
  RowBytes := (Width + 7) div 8;
  SetLength(Flat, RowBytes * Height);
  for Row := 0 to Height - 1 do
    Move(Scanlines[Row][0], Flat[Row * RowBytes], RowBytes);
  for I := 0 to High(Flat) do
    Flat[I] := Flat[I] xor $FF;       // see the polarity section
  OutLen := 0;
  P := EncodeGeneric(@Flat[0], Width, Height, RowBytes, 0, 0, @OutLen);
  if P = nil then
    Exit;
  try
    if OutLen <= 0 then
      Exit;
    SetLength(ImageData, OutLen);
    Move(P^, ImageData[0], OutLen);
    Result := True;
  finally
    FreeBuffer(P);                    // the DLL frees what the DLL allocated
  end;
end;

procedure LoadEncoderDll;
begin
  // Full path next to the executable, never a bare file name
  DllHandle := LoadLibrary(PChar(ExtractFilePath(ParamStr(0)) + 'myjbig2enc.dll'));
  if DllHandle = 0 then
    Exit;
  EncodeGeneric := TEncodeGeneric(GetProcAddress(DllHandle, 'my_jbig2_encode_generic'));
  FreeBuffer := TFreeBuffer(GetProcAddress(DllHandle, 'my_jbig2_free'));
  if Assigned(EncodeGeneric) and Assigned(FreeBuffer) then
    RegisterJBIG2EncoderBackend(DllBackend)
  else
  begin
    FreeLibrary(DllHandle);
    DllHandle := 0;
  end;
end;

initialization
  LoadEncoderDll;

finalization
  if DllHandle <> 0 then
  begin
    RegisterJBIG2EncoderBackend(nil);  // empty the slot before unloading
    FreeLibrary(DllHandle);
  end;
end.

Three details in that unit come from Windows rather than from JBIG2. The buffer goes back through the DLL's own free function because the DLL links its own C runtime, and a pointer from one CRT heap handed to another runtime's free corrupts memory or crashes far from the cause. The load uses a full path because a bare name sends LoadLibrary down the standard DLL search order, and the working directory of a service or a scheduled task is rarely what you expect. And the finalisation empties the slot with RegisterJBIG2EncoderBackend(nil) rather than ClearJBIG2Backends, which would also drop any registered JBIG2 decoder backends

Mind the single slot too. Link this unit and PDFlibJBIG2EncC into the same program and whichever initialisation section runs later owns the slot. Unit initialisation follows uses-clause order, so the outcome depends on where each unit sits in the uses graph. Pick one backend per program

Polarity: the bug that still produces a valid file

The scanlines handed to an encoder backend are copied from a TBitmap converted to pf1bit, and in a Windows one-bit DIB a set bit means white. jbig2enc and the leptonica image library beneath it read a set bit as black. Feed the bytes across unchanged and the first round trip through jbig2enc comes back as a full photographic negative, while the same page through the MMR path comes back pixel-identical. The stream is valid. A conforming reader displays it without complaint. It is simply the wrong picture

One-bit DIB and JBIG2 polarity conventions where a set bit is white in the scanline and black in the encoder, fixed by inverting every byte
Same bytes, opposite meaning: without inverting each byte the encoder produces a valid JBIG2 stream of the photographic negative

The shipped backend in PDFlibJBIG2EncC flattens the rows and XORs every byte before calling the encoder, and a DLL backend has to do the same. The core of it is two lines:

// One-bit DIB: set bit = white. jbig2enc / leptonica: set bit = black
for I := 0 to RowBytes * Height - 1 do
  Flat[I] := Flat[I] xor $FF;

Checking the result needs more care than writing it. Comparing compressed lengths proves nothing, since a negative compresses to roughly the size of the positive. Glancing at the page catches a full inversion and misses a subtler mistake, such as a backend that pads rows differently and shifts the last few pixels of every line. Both encoders are lossless on the same input, so the reliable check is to encode one page through each path, render both PDFs to PNG at the same resolution and compare the pixels exactly. Any difference at all is a bug in the adapter. Pick a test page with text running to the right edge, because an odd width such as 2481 pixels leaves a partial byte at the end of every row and exercises the padding

Why does the Free Pascal linker push towards a DLL?

A DLL boundary is attractive on Free Pascal because the linker then sees only an import table, never the C++ object files. Linking those objects directly runs into refusals that no compiler switch reaches

The internal Free Pascal linker rejects associative COMDAT sections outright, and objects from one C++ compiler are full of them. Switching to an external link through the binutils bundled with Free Pascal crashes during section garbage collection, a flag Free Pascal passes unconditionally for the 64-bit Windows target, and the documented switches for suppressing it are ignored on this path. A newer binutils fails differently: without the Free Pascal link script it produces an empty output, and with it a wall of relocation errors. Rebuilding the C++ side with another compiler trades one refusal for another, because template and inline instantiation emits weak external symbols by construction and Free Pascal will not accept that symbol class

One more trap appears on the external-linker route even if everything else worked. Object files named in a relative include directive are resolved against the executable output directory, not the source tree, so the directive works only while the output directory happens to equal the compile-time working directory. A library cannot assume that about someone else's project

Three failed routes for linking unmodified C++ JBIG2 encoder objects into a Free Pascal program, and a DLL exposing two flat C entry points as the boundary that sidesteps all three
COMDAT sections defeat the internal linker and both external linkers fail, which is why a DLL boundary appeals when you build your own C++ encoder for a Free Pascal program

The DLL avoids all of this. The C++ encoder and leptonica are built into one library with its own toolchain, two flat extern "C" entry points cross the boundary, and the Pascal side binds them at run time as shown above. The cost is real: one more file to deploy, a load path to get right, and a version of that file to keep matched to the application. The alternative is to rewrite the objects themselves until Free Pascal accepts them, which is how PDFlibJBIG2EncC links the same encoder statically into Free Pascal programs; that route is covered in static linking of jbig2enc into Free Pascal

For a stock encoder on Win64 x64, I would link PDFlibJBIG2EncC and skip the DLL entirely, since nothing ships beside the executable and nothing can go missing at deployment. The DLL backend earns its keep when the encoder build is yours to change

Choosing between MMR and the arithmetic coder

For dithered halftones, line art and mixed graphics the native MMR encoder is adequate and has no deployment cost at all. For dense scanned text, arithmetic coding generally compresses bilevel content tighter than MMR, and across a large archive that difference adds up. Per call, passing 0 for UseExternalEncoder forces the MMR path even when a backend is registered, so one program can make the choice image by image

The SymbolExtract argument reaches a backend as Options.UseSymbolDictionary. The shipped backend drives jbig2enc's lossless generic-region path and does not read it; a DLL backend of your own can honour it as long as whatever it produces stays self-contained in ImageData. Lossy settings are applied before any encoder sees the page: SkipBlackDots, BlackDotSize and LossyLevel clear small black specks from the scanlines, and both encoders then code the cleaned image losslessly

The encoder is only half of the size story. How the bilevel image is produced matters just as much, which is the topic of monochrome region rendering, and scan sets with repeated pages often gain more from perceptual image deduplication than from a better codec. Platform support for both JBIG2 encoders, along with the rest of the image pipeline, is listed on the losLab PDF Developer Library product page