In a two-dimensional CCITT fax stream, six zero bits in a row can mean two unrelated things. If the seventh bit is 0, the encoder is partway through the end-of-facsimile block and the image is over; if it is 1, the encoder has switched to uncompressed mode and is about to send literal pixels, usually for a dense patch such as a signature or a rubber stamp. A decoder that stops at the sixth zero returns a page that ends at exactly the spot where the fax got interesting
That prefix belongs to one of two corners of ITU-T T.4 and T.6 that most fax decoders skip. The other is damaged-row recovery, which PDF exposes through the DamagedRowsBeforeError entry. Streams from scanner drivers and capture pipelines are almost always plain Group 4 and never touch either feature, so a decoder that ignores both can look complete for years. Archives from older fax servers are a different population. They mix Group 3 one- and two-dimensional rows, they use uncompressed mode for halftone regions, and some of them carry rows that were corrupted on the phone line and never repaired
The DecodeParms entries that decide where a row starts
Four entries in the DecodeParms dictionary change how a decoder frames the bit stream: K, EndOfLine, EncodedByteAlign and DamagedRowsBeforeError. ISO 32000-1 §7.4.6 (Table 11) defines them, and a wrong guess on any one of them shifts every row after the first mismatch. BlackIs1, Columns, Rows and EndOfBlock matter too, but they govern polarity, geometry and where decoding stops; none of them changes how a row boundary is found
Kselects the coding scheme: negative means pure two-dimensional Group 4 (T.6), zero means one-dimensional Modified Huffman (Group 3 1D), and positive means mixed Group 3 2D, where a tag bit after each EOL says whether the next row is 1D or 2DEndOfLinesays every Group 3 row is preceded by an EOL code, eleven zero bits followed by a oneEncodedByteAlignsays each encoded row starts on a byte boundary, so padding bits have to be discarded before the row is readDamagedRowsBeforeErroris how many corrupt rows the decoder may tolerate before giving up; the default is 0
HotPDF reads all of these from the image dictionary when you call THotPDF.ExtractLoadedImage or THotPDF.DecodeLoadedImageStream. It departs from the spec in one place, on purpose. When Columns is missing, HotPDF uses the image Width instead of the spec default of 1728, and when Rows is missing it uses Height. A producer that omits Columns on a 2480-pixel A4 scan is wrong, yet that mistake is common enough in the wild that trusting the image geometry is the better bet: the literal default would decode every row at 1728 pixels and turn the page into diagonal stripes
Why can 000000 not be treated as the end of the block?
Six leading zeros in a two-dimensional row are ambiguous, and treating them as the start of EOFB misreads a valid uncompressed-mode entry as the end of the image. Group 4 has no EOLs between rows. The only zero-heavy codes it can contain are EOFB, which is two EOLs back to back, and the extension codes defined in T.4 and T.6. Both start with 000000. They part ways at bit seven
The HotPDF CCITT decoder resolves the prefix one bit at a time. A seventh bit of 1 means three more bits follow and form an extension code, the full pattern being 0000001xxx. Only xxx = 111 enters uncompressed mode, and any other extension value is rejected as malformed because a PDF fax filter has no use for the rest. A seventh bit of 0 can only continue an EOL, so the decoder then requires four more zeros and a closing 1, eleven zeros and a one in total, before it accepts EOFB. A zero run that is one bit short or one bit long fails the row
A lenient reading is tempting. Every truncated or slightly garbled stream would end gracefully with a shorter image and no error, and a test suite full of broken samples would go green. The cost is that legitimate faxes get cut off at their first stretch of uncompressed data, and on a scanned form that stretch is usually the signature. Strict is the right default here, because it keeps one guarantee intact: when HotPDF hands back a short image, the encoder really did end the image there
Uncompressed mode: literal pixels counted by leading zeros
Uncompressed mode swaps run-length coding for literal pixel patterns, each code word carrying at most five pixels, until an exit code switches back. One-dimensional rows enter it with the 12-bit code 000000001111, while two-dimensional rows use the 10-bit extension 0000001111 from the previous section. Encoders reach for it in halftone-like regions, where runs of one or two pixels would cost more bits than the pixels themselves
Inside the mode, every code word is identified by how many zeros precede its 1. Zero to four zeros mean that many white pixels followed by one black pixel. Five zeros mean five white pixels and nothing else. Six to ten zeros form an exit code: each zero beyond the sixth adds one white pixel, up to four, and the single bit after the exit code, the tag bit, sets the colour that ordinary run coding resumes with. Eleven or more zeros are not a valid code word
{ Uncompressed-mode code words (ITU-T T.4 / T.6)
W = white pixel, B = black pixel, T = tag bit
1 B
01 W B
001 W W B
0001 W W W B
00001 W W W W B
000001 W W W W W
0000001T exit, then resume runs with colour T
00000001T W, exit
000000001T W W, exit
0000000001T W W W, exit
00000000001T W W W W, exit
more than ten zeros: malformed }
The tag bit is where hand-written decoders usually slip. Run coding carries state: a 1D row alternates white and black runs, and a 2D row tracks the colour at the current changing element a0. After the exit code, decoding has to resume in whatever colour the tag names, and that colour may or may not match the last literal pixel. HotPDF records a colour change at the current position whenever the tag differs from the colour it was tracking, so the next run starts in the right colour. Skip that step and the rest of the row comes out inverted. In 2D mode it gets worse, since every following row uses the broken row as its reference line and inherits the error
What does DamagedRowsBeforeError recover, and what does it not?
DamagedRowsBeforeError lets HotPDF replace a corrupt row and keep going, provided K is 0 or positive and EndOfLine is true. Those two conditions follow from how recovery works. Once the bits stop making sense, the decoder needs a landmark that marks where the next row begins, and the only reliable landmark in a CCITT stream is the EOL code. Group 4 data has no EOLs at all, and Group 3 data without mandatory EOLs gives no guarantee that one is coming. For both, a damaged row ends decoding whatever value the parameter holds
When a row fails, the decoder scans forward to the next EOL, at least eleven zero bits followed by a one, and writes a replacement row. The first damaged row after a good one becomes a copy of the previous row; on a page of scanned text that copy is usually hard to spot. A damaged row that directly follows another damaged row becomes all white instead. Copying a copy would stretch one line of glyphs into a tall black bar, and a white gap is the less misleading artefact. The replacement then serves as the reference line for the next 2D row, which is what keeps a mixed-mode stream decodable after the repair
Two boundaries are easy to miss. The budget counts damaged rows across the whole image, so DamagedRowsBeforeError 3 tolerates three bad rows in total, scattered or adjacent, and the fourth fails the decode. And a failed decode is all or nothing: THotPDF.ExtractLoadedImage returns nil, never a bitmap with a ragged bottom edge. THPDFLoadedImageInfo.Decodable only reports that the build supports the filter. It says nothing about whether this particular stream is intact, so the nil check on the bitmap is the one that counts
Why the resynchronisation scan stops at the start of the EOL
The recovery scan leaves the bit reader on the first zero of the EOL, not after it. One framing loop in the decoder consumes EOLs, checks for the double EOL that ends the block, and reads the mixed-mode tag bit. If the recovery scan swallowed the EOL itself, that loop would see a row with no EOL, mark it damaged as well, spend a second unit of budget, and throw away a good row. A skipped tag bit is worse still: the next 2D row gets decoded as 1D, or the reverse. The same rule covers a 1D run decoder that hits an unexpected EOL mid-row. It rewinds to where the run code started, so the marker is still in place when the recovery scan looks for it
Inventorying CCITT images in a loaded PDF
A batch of archived faxes deserves an inventory first: which images use CCITTFaxDecode, and which of those fail to decode. THotPDF.GetLoadedImageInfo returns geometry and the filter name without decoding anything, and THotPDF.ExtractLoadedImage tells you whether the stream survived. The guide to extracting loaded PDF images and their decode filters shows how the same calls route the other filters
var
Pdf: THotPDF;
Info: THPDFLoadedImageInfo;
Bmp: TBitmap;
I: Integer;
begin
Pdf := THotPDF.Create(nil);
try
if Pdf.LoadFromFile('fax-archive.pdf', '') <= 0 then
Exit;
for I := 0 to Pdf.GetLoadedImageCount - 1 do
begin
if not Pdf.GetLoadedImageInfo(I, Info) then
Continue;
if Pos('CCITT', UpperCase(String(Info.Filter))) = 0 then
Continue;
Bmp := Pdf.ExtractLoadedImage(I); // nil when the stream is too damaged
try
if Bmp = nil then
Writeln(Format('obj %d: %dx%d CCITT failed to decode',
[Info.ObjectNumber, Info.Width, Info.Height]))
else
Bmp.SaveToFile(Format('fax_%d.bmp', [I]));
finally
Bmp.Free; // caller owns the bitmap
end;
end;
finally
Pdf.Free;
end;
end;
Keep the raw bytes of every failure. THotPDF.ExtractLoadedImageToStream in its default lismEncoded mode writes the stored stream untouched, which is the form you can feed to a second decoder or wrap in a TIFF container to inspect the damage. A re-encoded copy would no longer show where the corrupt rows were
procedure SaveRawFax(Pdf: THotPDF; ImageIndex: Integer; const FileName: string);
var
Fs: TFileStream;
begin
Fs := TFileStream.Create(FileName, fmCreate);
try
if not Pdf.ExtractLoadedImageToStream(ImageIndex, Fs, lismEncoded) then
raise Exception.CreateFmt('Image %d has no stream data', [ImageIndex]);
finally
Fs.Free;
end;
end;
Code that walks image streams itself through THotPDF.CollectLoadedImageStreams gets the same behaviour by passing each THPDFStreamObject to THotPDF.DecodeLoadedImageStream: same CCITT path, same parameters, same recovery rules. Free the returned TList when you are done with it, but leave the stream objects alone, because the document still owns them
Leave DamagedRowsBeforeError where the producer put it
Raising DamagedRowsBeforeError on files you did not produce is almost always a mistake, whether by editing the PDF or by patching the parameter in your own pipeline. The value belongs to the producer, the only party that knows whether its transmission channel drops bits. A file that declares DamagedRowsBeforeError 0 and then contains a damaged row is reporting that the archive copy is corrupt, and a decode failure you can log is the honest result. Patching rows on a contract or a medical record turns a detectable defect into a clean-looking image with one line missing, and whoever relies on that page later has no way to know
For untrusted archives, keep the decode strict, record the object numbers that fail, and route those pages to a person or to a second decoder. When the archive is large and comes from many sources, moving image decoding into a separate process limits what a hostile stream can do to the host application; the article on isolating image codecs when processing untrusted PDFs covers that setup. Scanned archives also tend to contain JBIG2 alongside CCITT, and the JBIG2 bilevel compression guide covers that filter
The fax path in HotPDF is native Object Pascal with no external DLL, and it sits next to the JBIG2, JPEG, JPEG 2000 and Flate decoders behind the same loaded-image calls in Delphi and C++Builder. Editions and licensing are listed on the HotPDF Delphi PDF component page