LibTIFF 4.7.2
TIFF library public API and implementation reference
Loading...
Searching...
No Matches
Files | Data Structures | Macros | Typedefs | Enumerations | Functions | Variables

Encode and decode Group3 Group4 and aligned bilevel runs. More...

Collaboration diagram for CCITT fax codecs:

Files

file  tif_fax3sm.c
 Provide generated CCITT fax decoder lookup tables.
 

Data Structures

struct  tableentry
 Describe one CCITT Huffman run-length code. More...
 
struct  Fax3BaseState
 Prefix fax state with geometry options and saved method chains. More...
 
struct  Fax3CodecState
 Own fax run/reference buffers and bit-stream progress. More...
 
struct  TIFFFaxTabEnt
 Describe one generated fax decoding state transition. More...
 

Macros

#define EOL   0x001 /* EOL code value - 0000 0000 0000 1 */
 Represent the twelve-bit EOL code value.
 
#define G3CODE_EOL   -1 /* NB: ACT_EOL - ACT_WRUNT */
 Mark the EOL entry of a Huffman code table.
 
#define G3CODE_INVALID   -2 /* NB: ACT_INVALID - ACT_WRUNT */
 Mark an invalid-code entry of a Huffman code table.
 
#define G3CODE_EOF   -3 /* end of input data */
 Legacy end-of-input run-length status value.
 
#define G3CODE_INCOMP   -4 /* incomplete run code */
 Legacy incomplete-code run-length status value.
 
#define G3CODES
 Instantiate the Huffman code tables from t4.h.
 
#define EOF_REACHED_COUNT_THRESHOLD   8192
 Limit repeated fax recovery conditions per strile.
 
#define Fax3State(tif)   ((Fax3BaseState *)(tif)->tif_data)
 Borrow the shared fax state prefix.
 
#define DecoderState(tif)   ((Fax3CodecState *)Fax3State(tif))
 Borrow the complete fax decoder state.
 
#define EncoderState(tif)   ((Fax3CodecState *)Fax3State(tif))
 Borrow the complete fax encoder state.
 
#define is2DEncoding(sp)   (sp->b.groupoptions & GROUP3OPT_2DENCODING)
 Test Group3 two-dimensional mode.
 
#define isAligned(p, t)   ((((size_t)(p)) & (sizeof(t) - 1)) == 0)
 Test a pointer against a type-sized alignment.
 
#define DECLARE_STATE(tif, sp, mod)
 Declare cached local one-dimensional decode state.
 
#define DECLARE_STATE_2D(tif, sp, mod)
 Declare local two-dimensional decode and reference state.
 
#define CACHE_STATE(tif, sp)
 Load codec and raw cursor state into decode locals.
 
#define UNCACHE_STATE(tif, sp)
 Commit local bit state and consumed raw bytes.
 
#define unexpected(table, a0)
 Diagnose a bad code and increment its recovery counter.
 
#define extension(a0)    Fax3Extension(module, tif, (uint32_t)sp->line, (uint32_t)(a0))
 Diagnose an unsupported uncompressed extension.
 
#define badlength(a0, lastx)
 Warn about row width and increment its recovery counter.
 
#define prematureEOF(a0)
 Warn about input exhaustion and increment its recovery counter.
 
#define tryG3WithoutEOL(a0)
 Warn about retrying Group3 data without EOL.
 
#define SWAP(t, a, b)
 Exchange current and reference run-array pointers.
 
#define SWAP(t, a, b)
 Exchange current and reference run-array pointers.
 
#define FILL(n, cp)
 Set complete black output bytes and advance the pointer.
 
#define ZERO(n, cp)
 Clear complete white output bytes and advance the pointer.
 
#define Fax3FlushBits(tif, sp)
 Append a partial code byte and flush raw output when full.
 
#define _FlushBits(tif)
 Append local code bits and reset local byte state.
 
#define _PutBits(tif, bits, length)
 Append local code bits across partial-byte boundaries.
 
#define putcode(tif, te)   Fax3PutBits(tif, (te)->code, (te)->length)
 Emit one Huffman table entry.
 
#define finddiff(_cp, _bs, _be, _color)    (_bs + (_color ? find1span(_cp, _bs, _be) : find0span(_cp, _bs, _be)))
 Find the next pixel differing from the selected colour.
 
#define finddiff2(_cp, _bs, _be, _color)    (_bs < _be ? finddiff(_cp, _bs, _be, _color) : _be)
 Find a change while bounding an already exhausted start.
 
#define PIXEL(buf, ix)   ((((buf)[(ix) >> 3]) >> (7 - ((ix) & 7))) & 1)
 Read one MSB-first packed pixel bit.
 
#define FIELD_BADFAXLINES   (FIELD_CODEC + 0)
 Reserve the BadFaxLines codec field bit.
 
#define FIELD_CLEANFAXDATA   (FIELD_CODEC + 1)
 Reserve the CleanFaxData codec field bit.
 
#define FIELD_BADFAXRUN   (FIELD_CODEC + 2)
 Reserve the consecutive-bad-lines codec field bit.
 
#define FIELD_OPTIONS   (FIELD_CODEC + 7)
 Reserve the Group3/4 options codec field bit.
 
#define S_Null   0
 Mark a table entry that matches no code.
 
#define S_Pass   1
 Select pass mode.
 
#define S_Horiz   2
 Select horizontal mode.
 
#define S_V0   3
 Select zero-offset vertical mode.
 
#define S_VR   4
 Select right-offset vertical mode.
 
#define S_VL   5
 Select left-offset vertical mode.
 
#define S_Ext   6
 Select unsupported extension mode.
 
#define S_TermW   7
 Finish a white run.
 
#define S_TermB   8
 Finish a black run.
 
#define S_MakeUpW   9
 Extend a white run.
 
#define S_MakeUpB   10
 Extend a black run.
 
#define S_MakeUp   11
 Extend either run colour.
 
#define S_EOL   12
 Recognise end of line.
 
#define EndOfData()   (cp >= ep)
 Test whether the local raw cursor is exhausted.
 
#define NeedBits8(n, eoflab)
 Load bits or branch to the caller EOF label.
 
#define NeedBits16(n, eoflab)
 Load up to sixteen bits or branch to EOF.
 
#define GetBits(n)   (BitAcc & ((1 << (n)) - 1))
 Inspect low bits of the local accumulator.
 
#define ClrBits(n)
 Consume low bits from the local accumulator.
 
#define LOOKUP8(wid, tab, eoflab)
 Fetch and consume an eight-bit-bounded transition.
 
#define LOOKUP16(wid, tab, eoflab)
 Fetch and consume a sixteen-bit-bounded transition.
 
#define SETVALUE(x)
 Append a checked decoded run and reset its local length.
 
#define SYNC_EOL(eoflab, retrywithouteol)
 Synchronise EOL or retry configured no-EOL recovery.
 
#define CLEANUP_RUNS()
 Repair the current row run total to the requested width.
 
#define EXPAND1D(eoflab)
 Expand a one-dimensional Huffman row into runs.
 
#define CHECK_b1
 Advance the reference change cursor with capacity checks.
 
#define EXPAND2D(eoflab)
 Expand a two-dimensional row relative to reference runs.
 

Typedefs

typedef struct tableentry tableentry
 Describe one CCITT Huffman run-length code.
 
typedef void(* TIFFFaxFillFunc) (unsigned char *buf, uint32_t *runs, uint32_t *erun, uint32_t lastx)
 Render decoded fax runs through an installed callback.
 

Enumerations

enum  Ttag { G3_1D , G3_2D }
 Select the next Group3 encoded row dimensionality. More...
 

Functions

static int Fax3PreDecode (TIFF *tif, uint16_t s)
 Reset fax bit state run pointers and recovery counters.
 
static void Fax3Unexpected (const char *module, TIFF *tif, uint32_t line, uint32_t a0)
 Diagnose an invalid fax code word.
 
static void Fax3Extension (const char *module, TIFF *tif, uint32_t line, uint32_t a0)
 Diagnose unsupported fax uncompressed extension data.
 
static void Fax3BadLength (const char *module, TIFF *tif, uint32_t line, uint32_t a0, uint32_t lastx)
 Warn about a fax row-length mismatch.
 
static void Fax3PrematureEOF (const char *module, TIFF *tif, uint32_t line, uint32_t a0)
 Warn about premature fax input exhaustion.
 
static void Fax3TryG3WithoutEOL (const char *module, TIFF *tif, uint32_t line, uint32_t a0)
 Warn that Group3 recovery will retry without EOL.
 
static int CheckReachedCounters (TIFF *tif, const char *module, Fax3CodecState *sp)
 Stop fax recovery after repeated EOF EOL or bad-code conditions.
 
static void Fax3ClearUnwritten (int has_buf, uint8_t *buf, tmsize_t occ)
 Zero the part of the caller buffer the decoder will not write.
 
static int Fax3Decode1D (TIFF *tif, uint8_t *buf, tmsize_t occ, uint16_t s)
 Decode complete Group3 one-dimensional fax rows.
 
static int Fax3Decode2D (TIFF *tif, uint8_t *buf, tmsize_t occ, uint16_t s)
 Decode complete Group3 mixed-dimensional fax rows.
 
static int Fax3FixupTags (TIFF *tif)
 Accept fax tag fixup without changes.
 
static int Fax3SetupState (TIFF *tif)
 Validate bilevel geometry and allocate fax run/reference storage.
 
static int Fax3PutBits (TIFF *tif, unsigned int bits, unsigned int length)
 Append up to sixteen significant fax code bits.
 
static int putspan (TIFF *tif, int32_t span, const tableentry *tab)
 Emit makeup and terminating Huffman codes for one fax run.
 
static int Fax3PutEOL (TIFF *tif)
 Append Group3 EOL padding and optional dimensional tag.
 
static int Fax3PreEncode (TIFF *tif, uint16_t s)
 Reset fax encoding bits reference line and dimensional schedule.
 
static int32_t find0span (unsigned char *bp, int32_t bs, int32_t be)
 Measure the leading zero bit run in a bounded packed row.
 
static int32_t find1span (unsigned char *bp, int32_t bs, int32_t be)
 Measure the leading one bit run in a bounded packed row.
 
static int Fax3Encode1DRow (TIFF *tif, unsigned char *bp, uint32_t bits)
 Encode alternating white and black runs for one bilevel row.
 
static int Fax3Encode2DRow (TIFF *tif, unsigned char *bp, unsigned char *rp, uint32_t bits)
 Encode one bilevel row relative to its reference row.
 
static int Fax3Encode (TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
 Encode complete Group3 or aligned RLE rows.
 
static int Fax3PostEncode (TIFF *tif)
 Pad and buffer the final partial fax code byte.
 
static int _Fax3Close (TIFF *tif)
 Append an optional six-EOL fax return-to-control sequence.
 
static void Fax3Close (TIFF *tif)
 Invoke fax return-to-control completion without a status channel.
 
static void Fax3Cleanup (TIFF *tif)
 Restore fax tag/print methods and release run/reference state.
 
static int Fax3VSetField (TIFF *tif, uint32_t tag, va_list ap)
 Assign fax pseudo-tags or persistent fax metadata.
 
static int Fax3VGetField (TIFF *tif, uint32_t tag, va_list ap)
 Retrieve fax mode callback or persistent fax values.
 
static void Fax3PrintDir (TIFF *tif, FILE *fd, long flags)
 Print present fax values then chain the saved directory printer.
 
static uint64_t Fax3GetMaxCompressionRatio (TIFF *tif)
 Report the fax expansion allocation heuristic.
 
static int InitCCITTFax3 (TIFF *tif)
 Allocate shared fax state and install tag and transfer methods.
 
static int Fax4Decode (TIFF *tif, uint8_t *buf, tmsize_t occ, uint16_t s)
 Decode complete Group4 two-dimensional fax rows.
 
static int Fax4Encode (TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
 Encode complete Group4 rows relative to the preceding row.
 
static int Fax4PostEncode (TIFF *tif)
 Append Group4 EOFB and align the final byte.
 
static uint64_t Fax4GetMaxCompressionRatio (TIFF *tif)
 Report the fax expansion allocation heuristic.
 
static int Fax3DecodeRLE (TIFF *tif, uint8_t *buf, tmsize_t occ, uint16_t s)
 Decode complete aligned modified-Huffman fax rows.
 
static uint64_t Fax3RLEGetMaxCompressionRatio (TIFF *tif)
 Report the fax expansion allocation heuristic.
 
void _TIFFFax3fillruns (unsigned char *buf, uint32_t *runs, uint32_t *erun, uint32_t lastx)
 Render alternating white/black fax runs into an MSB-first row.
 
int TIFFInitCCITTRLE (TIFF *tif, int scheme)
 Install CCITTRLE fax callbacks and default mode.
 
int TIFFInitCCITTRLEW (TIFF *tif, int scheme)
 Install CCITTRLEW fax callbacks and default mode.
 
int TIFFInitCCITTFax3 (TIFF *tif, int scheme)
 Install CCITTFax3 fax callbacks and default mode.
 
int TIFFInitCCITTFax4 (TIFF *tif, int scheme)
 Install CCITTFax4 fax callbacks and default mode.
 

Variables

const tableentry TIFFFaxWhiteCodes []
 Describe white CCITT terminating and makeup run codes.
 
const tableentry TIFFFaxBlackCodes []
 Describe black CCITT terminating and makeup run codes.
 
static const int _msbmask [9]
 Mask the requested low bit count for encoder code packing.
 
static const unsigned char zeroruns [256]
 Count leading zero bits in each byte.
 
static const unsigned char oneruns [256]
 Count leading one bits in each byte.
 
static const tableentry horizcode = {3, 0x1, 0}
 Encode the Group4 horizontal mode prefix.
 
static const tableentry passcode = {4, 0x1, 0}
 Encode the Group4 pass mode prefix.
 
static const tableentry vcodes [7]
 Encode Group4 vertical offsets minus three through three.
 
static const TIFFField faxFields []
 Define common fax metadata and pseudo-tags.
 
static const TIFFField fax3Fields []
 Define Group3 options metadata.
 
static const TIFFField fax4Fields []
 Define Group4 options metadata.
 
const TIFFFaxTabEnt TIFFFaxMainTable []
 Decode seven-bit two-dimensional (Group3 2D and Group4) mode prefixes.
 
const TIFFFaxTabEnt TIFFFaxWhiteTable []
 Decode twelve-bit white-run prefixes.
 
const TIFFFaxTabEnt TIFFFaxBlackTable []
 Decode thirteen-bit black-run prefixes.
 

Detailed Description

Encode and decode Group3 Group4 and aligned bilevel runs.

Macro Definition Documentation

◆ _FlushBits

#define _FlushBits (   tif)
Value:
{ \
if ((tif)->tif_rawcc >= (tif)->tif_rawdatasize) \
{ \
if (!TIFFFlushData1(tif)) \
return 0; \
} \
*(tif)->tif_rawcp++ = (uint8_t)data; \
(tif)->tif_rawcc++; \
data = 0, bit = 8; \
}
int TIFFFlushData1(TIFF *tif)
Append buffered encoded bytes without invoking postencode recursively.
Definition tif_write.c:1213

Append local code bits and reset local byte state.

Same as Fax3FlushBits() but uses the enclosing function's locals data and bit instead of sp->data and sp->bit: appends the low byte of data to the raw buffer and sets data to 0 and bit to 8. Executes return 0 from the enclosing function if TIFFFlushData1() fails. Expands to a braced block.

Parameters
[in,out]tifEncoding handle whose raw buffer is written.

Definition at line 1027 of file tif_fax3.c.

◆ _PutBits

#define _PutBits (   tif,
  bits,
  length 
)
Value:
{ \
while (length > bit) \
{ \
data |= (int)((unsigned int)bits >> (length - bit)); \
length -= bit; \
_FlushBits(tif); \
} \
assert(length < 9); \
data |= (int)(((unsigned int)bits & (unsigned int)_msbmask[length]) \
<< (unsigned int)(bit - length)); \
bit -= length; \
if (bit == 0) \
_FlushBits(tif); \
}
static const int _msbmask[9]
Mask the requested low bit count for encoder code packing.
Definition tif_fax3.c:1044

Append local code bits across partial-byte boundaries.

Appends the low length bits of bits, most significant first, to the enclosing function's locals data and bit, writing each completed byte with _FlushBits(). bits must have no set bits above length. Updates data and bit, and decrements length while splitting the code, so length must be a modifiable lvalue; the final partial byte asserts length < 9. If a flush fails, the enclosing function returns 0 before it copies data and bit back to sp->data and sp->bit, while bytes already flushed stay in the raw buffer. Expands to a braced block; bits and length are evaluated several times.

Parameters
[in,out]tifEncoding handle whose raw buffer is written.
[in]bitsCode value to write.
[in,out]lengthNumber of bits to write; modified by the expansion.

Definition at line 1046 of file tif_fax3.c.

◆ badlength

#define badlength (   a0,
  lastx 
)
Value:
do \
{ \
Fax3BadLength(module, tif, (uint32_t)sp->line, (uint32_t)(a0), \
(uint32_t)(lastx)); \
++sp->eolReachedCount; \
} while (0)

Warn about row width and increment its recovery counter.

Calls Fax3BadLength() with the enclosing module, tif and sp->line, then increments sp->eolReachedCount.

Parameters
[in]a0Decoded row length.
[in]lastxExpected row width in pixels.

Definition at line 379 of file tif_fax3.c.

◆ CACHE_STATE

#define CACHE_STATE (   tif,
  sp 
)
Value:
do \
{ \
BitAcc = sp->data; \
BitsAvail = sp->bit; \
EOLcnt = sp->EOLcnt; \
cp = (unsigned char *)tif->tif_rawcp; \
ep = cp + tif->tif_rawcc; \
} while (0)

Load codec and raw cursor state into decode locals.

Copies sp->data, sp->bit and sp->EOLcnt into BitAcc, BitsAvail and EOLcnt, and sets cp and ep to the unread raw data tif_rawcp to tif_rawcp + tif_rawcc.

Parameters
[in]tifDecoding handle.
[in]spDecoder state.

Definition at line 210 of file tif_fax3.c.

◆ CHECK_b1

#define CHECK_b1
Value:
do \
{ \
if (pa != thisrun) \
while (b1 <= a0 && b1 < (int)lastx) \
{ \
if (pb + 1 >= sp->refruns + sp->nruns) \
{ \
TIFFErrorExtR(tif, module, \
"Buffer overflow at line %d of %s %u", \
sp->line, isTiled(tif) ? "tile" : "strip", \
isTiled(tif) ? tif->tif_dir.td_curtile \
: tif->tif_dir.td_curstrip); \
goto RUN_OVERFLOW; \
} \
b1 += (int)(pb[0] + pb[1]); \
pb += 2; \
} \
} while (0)
#define isTiled(tif)
Test whether a handle uses tiled storage.
Definition tiffiop.h:833

Advance the reference change cursor with capacity checks.

Unless pa is still at thisrun, advances the reference-line cursor pb two runs at a time, adding both to b1, while b1 is at most a0 and below lastx. Writes b1 and pb. If pb + 1 reaches sp->refruns + sp->nruns it reports "Buffer overflow" with TIFFErrorExtR() and jumps to the enclosing function's RUN_OVERFLOW label.

Definition at line 550 of file tif_fax3.h.

◆ CLEANUP_RUNS

#define CLEANUP_RUNS ( )
Value:
do \
{ \
if (RunLength) \
SETVALUE(0); \
if (a0 != (int)lastx) \
{ \
badlength(a0, lastx); \
while (a0 > (int)lastx && pa > thisrun) \
a0 -= (int)*--pa; \
if (a0 < (int)lastx) \
{ \
if (a0 < 0) \
a0 = 0; \
if ((pa - thisrun) & 1) \
SETVALUE(0); \
SETVALUE((uint32_t)((int)lastx - a0)); \
} \
else if (a0 > (int)lastx) \
{ \
SETVALUE(lastx); \
SETVALUE(0); \
} \
} \
} while (0)

Repair the current row run total to the requested width.

Appends any pending RunLength with SETVALUE(0). If a0 then differs from lastx, it warns through badlength() (incrementing sp->eolReachedCount), drops trailing runs from pa until a0 is at most lastx, and pads the row: a white run of lastx - a0 (after a zero-length run if needed to keep the colour parity), or, if a0 still exceeds lastx with no runs left, a run of lastx followed by a zero-length run. Writes pa, a0 and RunLength and the run array at thisrun. Through SETVALUE() it can report "Buffer overflow" and jump to the enclosing function's RUN_OVERFLOW label.

Definition at line 443 of file tif_fax3.h.

◆ ClrBits

#define ClrBits (   n)
Value:
do \
{ \
BitsAvail -= (n); \
BitAcc >>= (n); \
} while (0)

Consume low bits from the local accumulator.

Subtracts n from the local BitsAvail and shifts BitAcc right by n. n is evaluated twice.

Parameters
[in]nNumber of bits to consume, at most BitsAvail.

Definition at line 283 of file tif_fax3.h.

◆ DECLARE_STATE

#define DECLARE_STATE (   tif,
  sp,
  mod 
)
Value:
static const char module[] = mod; \
int a0; /* reference element */ \
int lastx = (int)sp->b.rowpixels; /* last element in row */ \
uint32_t BitAcc; /* bit accumulator */ \
int BitsAvail; /* # valid bits in BitAcc */ \
int RunLength; /* length of current run */ \
unsigned char *cp; /* next byte of input data */ \
unsigned char *ep; /* end of input data */ \
uint32_t *pa; /* place to stuff next run */ \
uint32_t *thisrun; /* current row's run array */ \
int EOLcnt; /* # EOL codes recognized */ \
const unsigned char *bitmap = sp->bitmap; /* input data bit reverser */ \
const TIFFFaxTabEnt *TabEnt
#define DecoderState(tif)
Borrow the complete fax decoder state.
Definition tif_fax3.c:175
uint32_t rowpixels
Pixels per scanline/tile row, within signed decoder limits.
Definition tif_fax3.c:78
Own fax run/reference buffers and bit-stream progress.
Definition tif_fax3.c:117
Fax3BaseState b
Shared base prefix, first in codec state.
Definition tif_fax3.c:119
const unsigned char * bitmap
Borrowed immutable byte reversal table selected for current FillOrder.
Definition tif_fax3.c:125
Describe one generated fax decoding state transition.
Definition tif_fax3.h:144

Declare cached local one-dimensional decode state.

Declares, at the start of a decoder function, module (set to mod), sp (set to DecoderState(tif)), lastx (the row width), bitmap (the bit-reversal table) and the uninitialised locals used by the decoding macros: a0, BitAcc, BitsAvail, RunLength, cp, ep, pa, thisrun, EOLcnt and TabEnt. CACHE_STATE() then loads the bit and raw-data state.

Parameters
[in]tifDecoding handle.
[in]spName of the Fax3CodecState pointer to declare.
[in]modString literal used as the diagnostic module name.

Definition at line 189 of file tif_fax3.c.

◆ DECLARE_STATE_2D

#define DECLARE_STATE_2D (   tif,
  sp,
  mod 
)
Value:
DECLARE_STATE(tif, sp, mod); \
int b1; /* next change on prev line */ \
uint32_t \
*pb /* next run in reference line */ /* \
* Load any state that may be \
* changed during decoding. \
*/
#define DECLARE_STATE(tif, sp, mod)
Declare cached local one-dimensional decode state.
Definition tif_fax3.c:189

Declare local two-dimensional decode and reference state.

Expands to DECLARE_STATE() plus the locals b1 (next change on the reference row) and pb (cursor into the reference runs) used by EXPAND2D().

Parameters
[in]tifDecoding handle.
[in]spName of the Fax3CodecState pointer to declare.
[in]modString literal used as the diagnostic module name.

Definition at line 205 of file tif_fax3.c.

◆ DecoderState

#define DecoderState (   tif)    ((Fax3CodecState *)Fax3State(tif))

Borrow the complete fax decoder state.

Casts Fax3State(tif) to Fax3CodecState *. Decoding and encoding share this structure.

Parameters
[in]tifHandle whose tif_data holds fax codec state.

Definition at line 175 of file tif_fax3.c.

◆ EncoderState

#define EncoderState (   tif)    ((Fax3CodecState *)Fax3State(tif))

Borrow the complete fax encoder state.

Casts Fax3State(tif) to Fax3CodecState *. Decoding and encoding share this structure.

Parameters
[in]tifHandle whose tif_data holds fax codec state.

Definition at line 176 of file tif_fax3.c.

◆ EndOfData

#define EndOfData ( )    (cp >= ep)

Test whether the local raw cursor is exhausted.

Expands to (cp >= ep) using the decoder locals declared by DECLARE_STATE. Only defined if not already defined, so a user of the decoder macros can supply a different end-of-input test.

Definition at line 205 of file tif_fax3.h.

◆ EOF_REACHED_COUNT_THRESHOLD

#define EOF_REACHED_COUNT_THRESHOLD   8192

Limit repeated fax recovery conditions per strile.

Default 8192; it can be overridden at build time because the definition is guarded by #ifndef. CheckReachedCounters() fails decoding once eofReachedCount, eolReachedCount or unexpectedReachedCount reaches it. The counters are reset by Fax3PreDecode() for each strile. The limit stops apparently endless looping on corrupt single-strip files with a very large ImageLength (issue 583).

Definition at line 54 of file tif_fax3.c.

◆ EOL

#define EOL   0x001 /* EOL code value - 0000 0000 0000 1 */

Represent the twelve-bit EOL code value.

Right-adjusted value of the end-of-line code 0000 0000 0001. The Group3 encoder writes it with a length of 12 bits (13 with the 1D/2D tag bit in two-dimensional mode) before rows and in the RTC sequence written at close.

Definition at line 52 of file t4.h.

◆ EXPAND1D

#define EXPAND1D (   eoflab)

Expand a one-dimensional Huffman row into runs.

Decodes alternating white and black runs with LOOKUP16() until a0 reaches lastx, an EOL code (which sets EOLcnt to 1) or an invalid code (reported by unexpected(), which increments sp->unexpectedReachedCount), and then runs CLEANUP_RUNS(). Appends runs at pa with SETVALUE() and updates a0, RunLength, TabEnt and the bit state. Does not use the reference runs.

At the end of input it warns through prematureEOF() (incrementing sp->eofReachedCount), runs CLEANUP_RUNS() and jumps to eoflab, so that label must not run CLEANUP_RUNS() again. Through SETVALUE() it can report "Buffer overflow" and jump to the enclosing function's RUN_OVERFLOW label. Defines internal labels (eof1d, done1d, doneWhite1d, doneBlack1d), so it can be used only once per function.

Parameters
[in]eoflabCaller label jumped to after a premature end of input.

Definition at line 481 of file tif_fax3.h.

◆ EXPAND2D

#define EXPAND2D (   eoflab)

Expand a two-dimensional row relative to reference runs.

Decodes mode codes with LOOKUP8() and TIFFFaxMainTable while a0 is below lastx: pass, horizontal (two runs from the white and black tables) and vertical modes, using b1 and pb on the reference runs (advanced with CHECK_b1). Appends runs at pa with SETVALUE() and writes a0, RunLength, b1, pb, TabEnt, EOLcnt and the bit state. A pending run at the end of the row is appended, after checking for a final V0 bit if the row would otherwise be short. The row is finished with CLEANUP_RUNS().

An invalid code is reported by unexpected() (incrementing sp->unexpectedReachedCount) and an uncompressed-mode extension by extension(); both end the row. An EOL code sets EOLcnt to 1 and ends the row. At the end of input it warns through prematureEOF() (incrementing sp->eofReachedCount), runs CLEANUP_RUNS() and jumps to eoflab. If the current or reference run array would overflow it reports "Buffer overflow" with TIFFErrorExtR() and jumps to the enclosing function's RUN_OVERFLOW label. Defines internal labels (eof2d, eol2d and others), so it can be used only once per function.

Parameters
[in]eoflabCaller label jumped to after a premature end of input.

Definition at line 573 of file tif_fax3.h.

◆ extension

#define extension (   a0)     Fax3Extension(module, tif, (uint32_t)sp->line, (uint32_t)(a0))

Diagnose an unsupported uncompressed extension.

Calls Fax3Extension() with the enclosing module, tif and sp->line. No recovery counter is incremented.

Parameters
[in]a0Pixel position of the extension code.

Definition at line 348 of file tif_fax3.c.

◆ Fax3FlushBits

#define Fax3FlushBits (   tif,
  sp 
)
Value:
{ \
if ((tif)->tif_rawcc >= (tif)->tif_rawdatasize) \
{ \
if (!TIFFFlushData1(tif)) \
return 0; \
} \
*(tif)->tif_rawcp++ = (uint8_t)(sp)->data; \
(tif)->tif_rawcc++; \
(sp)->data = 0, (sp)->bit = 8; \
}

Append a partial code byte and flush raw output when full.

If the raw buffer is full (tif_rawcc >= tif_rawdatasize), calls TIFFFlushData1() and executes return 0 from the enclosing function if it fails. Then appends the low byte of sp->data at tif_rawcp, advances tif_rawcp and tif_rawcc, and sets sp->data to 0 and sp->bit to 8. Expands to a braced block, not a do/while statement. Both operands are evaluated several times.

Parameters
[in,out]tifEncoding handle whose raw buffer is written.
[in,out]spEncoder state whose data and bit are flushed and reset.

Definition at line 1016 of file tif_fax3.c.

◆ Fax3State

#define Fax3State (   tif)    ((Fax3BaseState *)(tif)->tif_data)

Borrow the shared fax state prefix.

Casts tif->tif_data to Fax3BaseState *; it does not check that the handle uses a fax codec.

Parameters
[in]tifHandle whose tif_data holds fax codec state.

Definition at line 96 of file tif_fax3.c.

◆ FIELD_BADFAXLINES

#define FIELD_BADFAXLINES   (FIELD_CODEC + 0)

Reserve the BadFaxLines codec field bit.

Codec-private field bit FIELD_CODEC + 0, set with TIFFTAG_BADFAXLINES and tested by Fax3PrintDir().

Definition at line 1907 of file tif_fax3.c.

◆ FIELD_BADFAXRUN

#define FIELD_BADFAXRUN   (FIELD_CODEC + 2)

Reserve the consecutive-bad-lines codec field bit.

Codec-private field bit FIELD_CODEC + 2, set with TIFFTAG_CONSECUTIVEBADFAXLINES and tested by Fax3PrintDir().

Definition at line 1909 of file tif_fax3.c.

◆ FIELD_CLEANFAXDATA

#define FIELD_CLEANFAXDATA   (FIELD_CODEC + 1)

Reserve the CleanFaxData codec field bit.

Codec-private field bit FIELD_CODEC + 1, set with TIFFTAG_CLEANFAXDATA and tested by Fax3PrintDir().

Definition at line 1908 of file tif_fax3.c.

◆ FIELD_OPTIONS

#define FIELD_OPTIONS   (FIELD_CODEC + 7)

Reserve the Group3/4 options codec field bit.

Codec-private field bit FIELD_CODEC + 7, shared by TIFFTAG_GROUP3OPTIONS and TIFFTAG_GROUP4OPTIONS. Fax3VSetField() sets it, and Fax3PrintDir() tests it.

Definition at line 1911 of file tif_fax3.c.

◆ FILL

#define FILL (   n,
  cp 
)
Value:
for (int32_t ifill = 0; ifill < (n); ++ifill) \
{ \
(cp)[ifill] = 0xff; \
} \
(cp) += (n);

Set complete black output bytes and advance the pointer.

Writes n bytes of 0xff at cp, then advances cp by n. Expands to two statements without a do/while wrapper, so it must be braced when used as the body of a conditional.

Parameters
[in]nNumber of bytes to set.
[in,out]cpOutput byte pointer.

Definition at line 713 of file tif_fax3.c.

◆ finddiff

#define finddiff (   _cp,
  _bs,
  _be,
  _color 
)     (_bs + (_color ? find1span(_cp, _bs, _be) : find0span(_cp, _bs, _be)))

Find the next pixel differing from the selected colour.

Returns the offset of the first bit in [_bs, _be) of _cp that differs from _color, or _be if there is none. _bs is evaluated twice.

Parameters
[in]_cpPacked MSB-first row.
[in]_bsStarting bit offset.
[in]_beEnd bit offset.
[in]_colorColour of the run to skip (0 or 1).

Definition at line 1543 of file tif_fax3.c.

◆ finddiff2

#define finddiff2 (   _cp,
  _bs,
  _be,
  _color 
)     (_bs < _be ? finddiff(_cp, _bs, _be, _color) : _be)

Find a change while bounding an already exhausted start.

Like finddiff(), but returns _be when _bs is not less than _be. _bs and _be are evaluated more than once.

Parameters
[in]_cpPacked MSB-first row.
[in]_bsStarting bit offset.
[in]_beEnd bit offset.
[in]_colorColour of the run to skip (0 or 1).

Definition at line 1549 of file tif_fax3.c.

◆ G3CODE_EOF

#define G3CODE_EOF   -3 /* end of input data */

Legacy end-of-input run-length status value.

Value -3. Currently unused: no libtiff code or table refers to it.

Definition at line 57 of file t4.h.

◆ G3CODE_EOL

#define G3CODE_EOL   -1 /* NB: ACT_EOL - ACT_WRUNT */

Mark the EOL entry of a Huffman code table.

Value -1, stored in tableentry.runlen of the EOL entries of TIFFFaxWhiteCodes and TIFFFaxBlackCodes in place of a run length.

Definition at line 55 of file t4.h.

◆ G3CODE_INCOMP

#define G3CODE_INCOMP   -4 /* incomplete run code */

Legacy incomplete-code run-length status value.

Value -4. Currently unused: no libtiff code or table refers to it.

Definition at line 58 of file t4.h.

◆ G3CODE_INVALID

#define G3CODE_INVALID   -2 /* NB: ACT_INVALID - ACT_WRUNT */

Mark an invalid-code entry of a Huffman code table.

Value -2, stored in tableentry.runlen of the trailing invalid-code entries of TIFFFaxWhiteCodes and TIFFFaxBlackCodes.

Definition at line 56 of file t4.h.

◆ G3CODES

#define G3CODES

Instantiate the Huffman code tables from t4.h.

Defined (empty) before including t4.h so that t4.h defines TIFFFaxWhiteCodes and TIFFFaxBlackCodes, rather than only declaring them. tif_fax3.c is the only file that defines it.

Definition at line 45 of file tif_fax3.c.

◆ GetBits

#define GetBits (   n)    (BitAcc & ((1 << (n)) - 1))

Inspect low bits of the local accumulator.

Expands to the low n bits of the local BitAcc without consuming them. A NeedBits8() or NeedBits16() call must first make n bits available.

Parameters
[in]nNumber of bits to inspect, at most 16.

Definition at line 282 of file tif_fax3.h.

◆ is2DEncoding

#define is2DEncoding (   sp)    (sp->b.groupoptions & GROUP3OPT_2DENCODING)

Test Group3 two-dimensional mode.

Nonzero when GROUP3OPT_2DENCODING is set in sp->b.groupoptions. sp is not parenthesised in the expansion, so pass a plain identifier.

Parameters
[in]spFax3CodecState pointer.

Definition at line 178 of file tif_fax3.c.

◆ isAligned

#define isAligned (   p,
  t 
)    ((((size_t)(p)) & (sizeof(t) - 1)) == 0)

Test a pointer against a type-sized alignment.

Nonzero when the address p is a multiple of sizeof(t), which must be a power of two.

Parameters
[in]pPointer to test.
[in]tType whose size gives the alignment.

Definition at line 179 of file tif_fax3.c.

◆ LOOKUP16

#define LOOKUP16 (   wid,
  tab,
  eoflab 
)
Value:
do \
{ \
NeedBits16(wid, eoflab); \
TabEnt = tab + GetBits(wid); \
ClrBits(TabEnt->Width); \
} while (0)
#define GetBits(n)
Inspect low bits of the local accumulator.
Definition tif_fax3.h:282

Fetch and consume a sixteen-bit-bounded transition.

Same as LOOKUP8() but uses NeedBits16(), so wid may be up to 16. The decoder uses it with 12 bits for TIFFFaxWhiteTable and 13 bits for TIFFFaxBlackTable. Writes TabEnt, BitAcc, BitsAvail and cp.

Parameters
[in]widNumber of bits used to index tab, at most 16.
[in]tabDecoding table (TIFFFaxTabEnt array) to index.
[in]eoflabCaller label jumped to by NeedBits16() at the end of input.

Definition at line 364 of file tif_fax3.h.

◆ LOOKUP8

#define LOOKUP8 (   wid,
  tab,
  eoflab 
)
Value:
do \
{ \
NeedBits8(wid, eoflab); \
TabEnt = tab + GetBits(wid); \
ClrBits(TabEnt->Width); \
} while (0)

Fetch and consume an eight-bit-bounded transition.

Calls NeedBits8(wid, eoflab), sets the local TabEnt to tab + GetBits(wid), then consumes TabEnt->Width bits with ClrBits(). The table must have 2^wid entries. Writes TabEnt, BitAcc, BitsAvail and cp. wid is evaluated several times and tab once. With FAX3_DEBUG the expansion also prints the state and code bits to stdout.

Parameters
[in]widNumber of bits used to index tab, at most 8.
[in]tabDecoding table (TIFFFaxTabEnt array) to index.
[in]eoflabCaller label jumped to by NeedBits8() at the end of input.

Definition at line 357 of file tif_fax3.h.

◆ NeedBits16

#define NeedBits16 (   n,
  eoflab 
)
Value:
do \
{ \
if (BitsAvail < (n)) \
{ \
if (EndOfData()) \
{ \
if (BitsAvail == 0) /* no valid bits */ \
goto eoflab; \
BitsAvail = (n); /* pad with zeros */ \
} \
else \
{ \
BitAcc |= ((uint32_t)bitmap[*cp++]) << BitsAvail; \
if ((BitsAvail += 8) < (n)) \
{ \
if (EndOfData()) \
{ \
/* NB: we know BitsAvail is non-zero here */ \
BitsAvail = (n); /* pad with zeros */ \
} \
else \
{ \
BitAcc |= ((uint32_t)bitmap[*cp++]) << BitsAvail; \
BitsAvail += 8; \
} \
} \
} \
} \
} while (0)
#define EndOfData()
Test whether the local raw cursor is exhausted.
Definition tif_fax3.h:205

Load up to sixteen bits or branch to EOF.

Like NeedBits8() but loads up to two bytes from the local cp, so n may be up to 16. At the end of input it jumps to eoflab only when no valid bits remain before the first byte would be read; otherwise it sets BitsAvail to n, treating the missing bits as zero. Writes BitAcc, BitsAvail and cp. n is evaluated up to three times.

Parameters
[in]nNumber of bits required, at most 16.
[in]eoflabCaller label jumped to when the input is exhausted and BitsAvail is zero.

Definition at line 251 of file tif_fax3.h.

◆ NeedBits8

#define NeedBits8 (   n,
  eoflab 
)
Value:
do \
{ \
if (BitsAvail < (n)) \
{ \
if (EndOfData()) \
{ \
if (BitsAvail == 0) /* no valid bits */ \
goto eoflab; \
BitsAvail = (n); /* pad with zeros */ \
} \
else \
{ \
BitAcc |= ((uint32_t)bitmap[*cp++]) << BitsAvail; \
BitsAvail += 8; \
} \
} \
} while (0)

Load bits or branch to the caller EOF label.

If the local BitsAvail is below n, loads one byte from the local cp (through the bit-reversal table bitmap) into BitAcc above the valid bits and advances cp, so n must not exceed BitsAvail + 8. At the end of input (EndOfData()) it jumps to eoflab when no valid bits remain; otherwise it sets BitsAvail to n, treating the missing bits as zero. Writes BitAcc, BitsAvail and cp. n is evaluated up to twice.

Parameters
[in]nNumber of bits required, at most 8.
[in]eoflabCaller label jumped to when the input is exhausted and BitsAvail is zero.

Definition at line 231 of file tif_fax3.h.

◆ PIXEL

#define PIXEL (   buf,
  ix 
)    ((((buf)[(ix) >> 3]) >> (7 - ((ix) & 7))) & 1)

Read one MSB-first packed pixel bit.

Returns bit ix (0 or 1) of buf, counting from the most significant bit of byte 0. ix is evaluated twice.

Parameters
[in]bufPacked row bytes.
[in]ixPixel index.

◆ prematureEOF

#define prematureEOF (   a0)
Value:
do \
{ \
Fax3PrematureEOF(module, tif, (uint32_t)sp->line, (uint32_t)(a0)); \
++sp->eofReachedCount; \
} while (0)

Warn about input exhaustion and increment its recovery counter.

Calls Fax3PrematureEOF() with the enclosing module, tif and sp->line, then increments sp->eofReachedCount.

Parameters
[in]a0Pixel position reached in the row.

Definition at line 412 of file tif_fax3.c.

◆ putcode

#define putcode (   tif,
  te 
)    Fax3PutBits(tif, (te)->code, (te)->length)

Emit one Huffman table entry.

Expands to Fax3PutBits(tif, te->code, te->length), so its value is 1 on success and 0 when flushing raw data fails.

Parameters
[in,out]tifEncoding handle.
[in]teCode table entry to write.

Definition at line 1099 of file tif_fax3.c.

◆ S_EOL

#define S_EOL   12

Recognise end of line.

TIFFFaxTabEnt.State value 12, assigned by mkg3states to the EOL code in all three tables. The decoder macros set EOLcnt and end the row.

Definition at line 129 of file tif_fax3.h.

◆ S_Ext

#define S_Ext   6

Select unsupported extension mode.

TIFFFaxTabEnt.State value 6, assigned by mkg3states in TIFFFaxMainTable. Uncompressed-mode extensions are not supported: EXPAND2D reports them with extension() and ends the row.

Definition at line 123 of file tif_fax3.h.

◆ S_Horiz

#define S_Horiz   2

Select horizontal mode.

TIFFFaxTabEnt.State value 2, assigned by mkg3states in TIFFFaxMainTable. EXPAND2D then decodes two runs from the white and black tables.

Definition at line 119 of file tif_fax3.h.

◆ S_MakeUp

#define S_MakeUp   11

Extend either run colour.

TIFFFaxTabEnt.State value 11, assigned by mkg3states in both TIFFFaxWhiteTable and TIFFFaxBlackTable for the extended makeup codes (runs of 1792 to 2560) that both colours share.

Definition at line 128 of file tif_fax3.h.

◆ S_MakeUpB

#define S_MakeUpB   10

Extend a black run.

TIFFFaxTabEnt.State value 10, assigned by mkg3states in TIFFFaxBlackTable. TIFFFaxTabEnt.Param, a multiple of 64, is added to the current run and decoding continues with the same table.

Definition at line 127 of file tif_fax3.h.

◆ S_MakeUpW

#define S_MakeUpW   9

Extend a white run.

TIFFFaxTabEnt.State value 9, assigned by mkg3states in TIFFFaxWhiteTable. TIFFFaxTabEnt.Param, a multiple of 64, is added to the current run and decoding continues with the same table.

Definition at line 126 of file tif_fax3.h.

◆ S_Null

#define S_Null   0

Mark a table entry that matches no code.

TIFFFaxTabEnt.State value 0, left in generated table entries that mkg3states does not assign. The decoder macros report such an entry as a bad code word through unexpected().

Definition at line 117 of file tif_fax3.h.

◆ S_Pass

#define S_Pass   1

Select pass mode.

TIFFFaxTabEnt.State value 1, assigned by mkg3states in TIFFFaxMainTable. EXPAND2D moves a0 to b2 without ending a run.

Definition at line 118 of file tif_fax3.h.

◆ S_TermB

#define S_TermB   8

Finish a black run.

TIFFFaxTabEnt.State value 8, assigned by mkg3states in TIFFFaxBlackTable. TIFFFaxTabEnt.Param is the terminating run length (0 to 63).

Definition at line 125 of file tif_fax3.h.

◆ S_TermW

#define S_TermW   7

Finish a white run.

TIFFFaxTabEnt.State value 7, assigned by mkg3states in TIFFFaxWhiteTable. TIFFFaxTabEnt.Param is the terminating run length (0 to 63).

Definition at line 124 of file tif_fax3.h.

◆ S_V0

#define S_V0   3

Select zero-offset vertical mode.

TIFFFaxTabEnt.State value 3, assigned by mkg3states in TIFFFaxMainTable. The next change a1 is directly below b1.

Definition at line 120 of file tif_fax3.h.

◆ S_VL

#define S_VL   5

Select left-offset vertical mode.

TIFFFaxTabEnt.State value 5, assigned by mkg3states in TIFFFaxMainTable. The next change a1 is TIFFFaxTabEnt.Param pixels to the left of b1.

Definition at line 122 of file tif_fax3.h.

◆ S_VR

#define S_VR   4

Select right-offset vertical mode.

TIFFFaxTabEnt.State value 4, assigned by mkg3states in TIFFFaxMainTable. The next change a1 is TIFFFaxTabEnt.Param pixels to the right of b1.

Definition at line 121 of file tif_fax3.h.

◆ SETVALUE

#define SETVALUE (   x)
Value:
do \
{ \
if (pa >= thisrun + sp->nruns) \
{ \
TIFFErrorExtR(tif, module, "Buffer overflow at line %d of %s %u", \
sp->line, isTiled(tif) ? "tile" : "strip", \
isTiled(tif) ? tif->tif_dir.td_curtile \
: tif->tif_dir.td_curstrip); \
goto RUN_OVERFLOW; \
} \
*pa++ = (uint32_t)((uint32_t)RunLength + (uint32_t)(x)); \
a0 += (int)(uint32_t)(x); \
RunLength = 0; \
} while (0)

Append a checked decoded run and reset its local length.

Stores RunLength + x at the local pa and advances pa, adds x to a0 and sets RunLength to 0. If pa has reached thisrun + sp->nruns it instead reports "Buffer overflow" with TIFFErrorExtR() and jumps to the enclosing function's RUN_OVERFLOW label, which clears the unwritten output, releases the cached state and returns -1. The FAX3_DEBUG variant omits this check and prints the run to stdout. x is evaluated twice (three times with FAX3_DEBUG).

Parameters
[in]xPixel count added to the pending RunLength.

Definition at line 376 of file tif_fax3.h.

◆ SWAP [1/2]

#define SWAP (   t,
  a,
  b 
)
Value:
{ \
t x; \
x = (a); \
(a) = (b); \
(b) = x; \
}

Exchange current and reference run-array pointers.

Exchanges the lvalues a and b through a temporary of type t. Expands to a braced block, not a do/while statement. Defined separately for Fax3Decode2D() and Fax4Decode() and undefined after each.

Parameters
[in]tType of a and b.
[in,out]aFirst lvalue.
[in,out]bSecond lvalue.

Definition at line 601 of file tif_fax3.c.

◆ SWAP [2/2]

#define SWAP (   t,
  a,
  b 
)
Value:
{ \
t x; \
x = (a); \
(a) = (b); \
(b) = x; \
}

Exchange current and reference run-array pointers.

Exchanges the lvalues a and b through a temporary of type t. Expands to a braced block, not a do/while statement. Defined separately for Fax3Decode2D() and Fax4Decode() and undefined after each.

Parameters
[in]tType of a and b.
[in,out]aFirst lvalue.
[in,out]bSecond lvalue.

Definition at line 601 of file tif_fax3.c.

◆ SYNC_EOL

#define SYNC_EOL (   eoflab,
  retrywithouteol 
)

Synchronise EOL or retry configured no-EOL recovery.

Does nothing if FAXMODE_NOEOL is set in sp->b.mode. Otherwise, when the local EOLcnt is 0, discards bits until 11 zero bits are found; then skips the remaining zero bits and the terminating 1 bit of the EOL code and resets EOLcnt to 0. Writes BitAcc, BitsAvail, cp and EOLcnt.

If the input ends while scanning for the final 1 bit, it sets FAXMODE_NOEOL in sp->b.mode, which persists in the codec state and affects all later rows and strips, warns through tryG3WithoutEOL(), and jumps to retrywithouteol. Defines the label noEOLFound, so it can be used only once per function.

Parameters
[in]eoflabCaller label jumped to when the input ends while searching for the 11 zero bits.
[in]retrywithouteolCaller label jumped to after switching to FAXMODE_NOEOL; the decoders place it before CACHE_STATE(), so the bit state and input cursor are reloaded from sp and the raw buffer.

Definition at line 403 of file tif_fax3.h.

◆ tryG3WithoutEOL

#define tryG3WithoutEOL (   a0)
Value:
do \
{ \
Fax3TryG3WithoutEOL(module, tif, (uint32_t)sp->line, (uint32_t)(a0)); \
} while (0)

Warn about retrying Group3 data without EOL.

Calls Fax3TryG3WithoutEOL() with the enclosing module, tif and sp->line. No recovery counter is incremented.

Parameters
[in]a0Pixel position reached in the row.

Definition at line 445 of file tif_fax3.c.

◆ UNCACHE_STATE

#define UNCACHE_STATE (   tif,
  sp 
)
Value:
do \
{ \
sp->bit = BitsAvail; \
sp->data = BitAcc; \
sp->EOLcnt = EOLcnt; \
tif->tif_rawcc -= (tmsize_t)((uint8_t *)cp - tif->tif_rawcp); \
tif->tif_rawcp = (uint8_t *)cp; \
} while (0)
TIFF_SSIZE_T tmsize_t
Represent a signed memory or I/O size in bytes.
Definition tiffio.h:89

Commit local bit state and consumed raw bytes.

Stores BitsAvail, BitAcc and EOLcnt back into sp, and advances tif_rawcp to cp, reducing tif_rawcc by the bytes consumed. Paths that return without it leave the state as of the last CACHE_STATE().

Parameters
[in,out]tifDecoding handle.
[in,out]spDecoder state.

Definition at line 222 of file tif_fax3.c.

◆ unexpected

#define unexpected (   table,
  a0 
)
Value:
do \
{ \
Fax3Unexpected(module, tif, (uint32_t)sp->line, (uint32_t)(a0)); \
++sp->unexpectedReachedCount; \
} while (0)

Diagnose a bad code and increment its recovery counter.

Calls Fax3Unexpected() with the enclosing module, tif and sp->line, then increments sp->unexpectedReachedCount. table is not used by the expansion.

Parameters
[in]tableName of the table that failed (unused).
[in]a0Pixel position of the bad code.

Definition at line 315 of file tif_fax3.c.

◆ ZERO

#define ZERO (   n,
  cp 
)
Value:
for (int32_t izero = 0; izero < (n); ++izero) \
{ \
(cp)[izero] = 0; \
} \
(cp) += (n);

Clear complete white output bytes and advance the pointer.

Writes n zero bytes at cp, then advances cp by n. Expands to two statements without a do/while wrapper, so it must be braced when used as the body of a conditional.

Parameters
[in]nNumber of bytes to clear.
[in,out]cpOutput byte pointer.

Definition at line 720 of file tif_fax3.c.

Typedef Documentation

◆ TIFFFaxFillFunc

typedef void(* TIFFFaxFillFunc) (unsigned char *buf, uint32_t *runs, uint32_t *erun, uint32_t lastx)

Render decoded fax runs through an installed callback.

Called synchronously per decoded row. Borrows output/runs only for the call; never retain them or close/redecode the active handle. Default callback writes MSB-first bilevel bytes. Custom callbacks may render elsewhere and can explicitly accept NULL buf. Keep code/context live while installed or in flight. No status channel or ownership transfer; error reporting is callback-defined.

Parameters
[out]bufBorrowed decoded row destination; NULL only for a callback explicitly supporting output elsewhere.
[in,out]runsBorrowed alternating white/black run storage with at least the decoder-required row capacity; callback may modify it.
[in,out]erunBorrowed end cursor with room for callback-specific sentinel padding.
[in]lastxRow width in pixels.

Definition at line 78 of file tif_fax3.h.

Enumeration Type Documentation

◆ Ttag

enum Ttag

Select the next Group3 encoded row dimensionality.

Enumerator
G3_1D 

Encode the next row independently.

G3_2D 

Encode the next row relative to its predecessor.

Definition at line 102 of file tif_fax3.c.

Function Documentation

◆ _Fax3Close()

static int _Fax3Close ( TIFF *  tif)
static

Append an optional six-EOL fax return-to-control sequence.

Runs only when NORTC is clear and raw cursor exists. Ignores Fax3PutBits statuses while emitting EOLs; final flush macro can fail. Can modify buffered/file state without rollback, allocation or ownership transfer.

Parameters
[in,out]tifNon-NULL live fax handle with matching geometry/state; serialise operations.
Returns
One on normal exit, zero from final flush failure; earlier ignored code-write failures need not be reflected.

Definition at line 1840 of file tif_fax3.c.

◆ _TIFFFax3fillruns()

void _TIFFFax3fillruns ( unsigned char *  buf,
uint32_t *  runs,
uint32_t *  erun,
uint32_t  lastx 
)
extern

Render alternating white/black fax runs into an MSB-first row.

Requires nonoverlapping valid row/run storage and representable run arithmetic. Appends a zero run for odd count, clips overlong runs in place, clears white bits and sets black bits using aligned bulk stores. A trailing partial byte is zeroed first, so its padding bits beyond lastx are always zero. Asserts final row width; does not validate every allocation bound. No allocation, I/O, diagnostics, retained pointers or ownership transfer.

Parameters
[out]bufBorrowed writable ceil(lastx/8)-byte row; must be non-NULL for the default filler.
[in,out]runsBorrowed writable white/black alternating run lengths, with room at erun for a possible zero sentinel; at least the decoder-required capacity.
[in,out]erunEnd cursor within runs storage; an odd run count appends a zero here.
[in]lastxRow width in pixels within signed loop/count limits; runs must describe that row.

Definition at line 731 of file tif_fax3.c.

References FILL, isAligned, and ZERO.

◆ CheckReachedCounters()

static int CheckReachedCounters ( TIFF *  tif,
const char *  module,
Fax3CodecState *  sp 
)
static

Stop fax recovery after repeated EOF EOL or bad-code conditions.

Compares three recovery counters with EOF_REACHED_COUNT_THRESHOLD and diagnoses the first exhausted threshold. Does not increment counters or allocate/read/write payload; no ownership transfer.

Parameters
[in,out]tifNon-NULL live fax handle with matching geometry/state; serialise operations.
[in]moduleBorrowed diagnostic label.
[in]spBorrowed live fax decoder state with recovery counters.
Returns
Minus one when a threshold is reached, zero otherwise.

Definition at line 465 of file tif_fax3.c.

◆ Fax3BadLength()

static void Fax3BadLength ( const char *  module,
TIFF *  tif,
uint32_t  line,
uint32_t  a0,
uint32_t  lastx 
)
static

Warn about a fax row-length mismatch.

Reports a warning through the handle with the row and pixel position. Does not itself increment recovery counters (the wrapping macro does), allocate, access payload or return status; diagnostic handlers can have application effects.

Parameters
[in]moduleBorrowed diagnostic label.
[in]tifHandle that receives the diagnostic and supplies the current strip or tile number.
[in]lineRow number within the strile for diagnostics.
[in]a0Decoded row length in pixels.
[in]lastxExpected row width in pixels.

Definition at line 367 of file tif_fax3.c.

◆ Fax3Cleanup()

static void Fax3Cleanup ( TIFF *  tif)
static

Restore fax tag/print methods and release run/reference state.

Requires live initialised state. Frees owned runs/reference row and outer Ext allocation, clears tif_data and restores default compression callbacks. Invalidates all codec-owned views. Does not emit RTC, finish or flush payload, close the handle or return status.

Parameters
[in,out]tifNon-NULL live fax handle with matching geometry/state; serialise operations.

Definition at line 1886 of file tif_fax3.c.

◆ Fax3ClearUnwritten()

static void Fax3ClearUnwritten ( int  has_buf,
uint8_t *  buf,
tmsize_t  occ 
)
static

Zero the part of the caller buffer the decoder will not write.

Keeps a truncated or damaged strip from handing back whatever the caller's memory happened to contain. Does nothing without a caller buffer: when a custom fill callback is used instead (see TIFFReadEncodedStrip()), buf is a bogus pointer that the decode loop has advanced past NULL, so the decoder records whether a buffer was supplied before it starts.

Parameters
[in]has_bufNonzero if the caller supplied an output buffer.
[out]bufCurrent output position; ignored when has_buf is zero.
[in]occNumber of bytes remaining from buf to the end of the request.

Definition at line 511 of file tif_fax3.c.

◆ Fax3Close()

static void Fax3Close ( TIFF *  tif)
static

Invoke fax return-to-control completion without a status channel.

Calls _Fax3Close and discards its result. Output diagnostics and partial file/cache effects can occur. Does not free codec state or close the client handle; no ownership transfer.

Parameters
[in,out]tifNon-NULL live fax handle with matching geometry/state; serialise operations.

Definition at line 1872 of file tif_fax3.c.

◆ Fax3Decode1D()

static int Fax3Decode1D ( TIFF *  tif,
uint8_t *  buf,
tmsize_t  occ,
uint16_t  s 
)
static

Decode complete Group3 one-dimensional fax rows.

Requires setup/predecode, positive rowbytes, signed-representable pixel coordinates, nonnegative complete-row occ and valid run capacity. Expands cached codes through state macros and invokes the installed fill callback synchronously; NULL buf is valid only for a custom callback that explicitly supports it. Can recover bad row lengths or missing EOL with diagnostics and counter limits. Updates the current run array, line/bit state and raw cursors; failure can leave a partially filled current row and earlier output. No direct allocation/client I/O or ownership transfer; a custom filler has its own effects. Negative error status is not a Boolean success result.

With a caller buffer, a rejected request, counter limit or decoding error first zeroes the remaining output from the current row onwards, so rows that are not decoded never expose stale memory; a partial current row may then be filled on top. With a NULL buffer (custom fill callback) nothing is cleared.

Parameters
[in,out]tifNon-NULL live fax handle with matching geometry/state; serialise operations.
[out]bufBorrowed decoded row storage of occ bytes, or NULL only with a compatible custom fill callback.
[in]occNonnegative complete-row decoded extent.
[in]sUnused sample-plane compatibility argument.
Returns
One on normal completion, minus one on detected extent/counter/decoding failure.

Definition at line 547 of file tif_fax3.c.

◆ Fax3Decode2D()

static int Fax3Decode2D ( TIFF *  tif,
uint8_t *  buf,
tmsize_t  occ,
uint16_t  s 
)
static

Decode complete Group3 mixed-dimensional fax rows.

Requires setup/predecode, positive rowbytes, signed-representable pixel coordinates, nonnegative complete-row occ and valid run/reference capacities. Expands cached codes through state macros and invokes the installed fill callback synchronously; NULL buf is valid only for a custom callback that explicitly supports it. Can recover bad row lengths or missing EOL with diagnostics and counter limits. Updates run/reference arrays, line/bit state and raw cursors; failure can leave a partially filled current row and earlier output. No direct allocation/client I/O or ownership transfer; a custom filler has its own effects. Negative error status is not a Boolean success result.

With a caller buffer, a rejected request, counter limit or decoding error first zeroes the remaining output from the current row onwards, so rows that are not decoded never expose stale memory; a partial current row may then be filled on top. With a NULL buffer (custom fill callback) nothing is cleared.

Parameters
[in,out]tifNon-NULL live fax handle with matching geometry/state; serialise operations.
[out]bufBorrowed decoded row storage of occ bytes, or NULL only with a compatible custom fill callback.
[in]occNonnegative complete-row decoded extent.
[in]sUnused sample-plane compatibility argument.
Returns
One on normal completion, minus one on detected extent/counter/decoding failure.

Definition at line 641 of file tif_fax3.c.

◆ Fax3DecodeRLE()

static int Fax3DecodeRLE ( TIFF *  tif,
uint8_t *  buf,
tmsize_t  occ,
uint16_t  s 
)
static

Decode complete aligned modified-Huffman fax rows.

Requires setup/predecode, positive rowbytes, signed-representable pixel coordinates, nonnegative complete-row occ and valid run capacity. Expands cached codes through state macros and invokes the installed fill callback synchronously; NULL buf is valid only for a custom callback that explicitly supports it. Can recover bad row lengths with diagnostics and counter limits. After each row, discards the remaining bits up to the next byte (FAXMODE_BYTEALIGN) or 16-bit word (FAXMODE_WORDALIGN) boundary. Updates the current run array, line/bit state and raw cursors; failure can leave a partially filled current row and earlier output. No direct allocation/client I/O or ownership transfer; a custom filler has its own effects. Negative error status is not a Boolean success result.

With a caller buffer, a rejected request, counter limit or decoding error first zeroes the remaining output from the current row onwards, so rows that are not decoded never expose stale memory; a partial current row may then be filled on top. With a NULL buffer (custom fill callback) nothing is cleared.

Parameters
[in,out]tifNon-NULL live fax handle with matching geometry/state; serialise operations.
[out]bufBorrowed decoded row storage of occ bytes, or NULL only with a compatible custom fill callback.
[in]occNonnegative complete-row decoded extent.
[in]sUnused sample-plane compatibility argument.
Returns
One on normal completion, minus one on detected extent/counter/decoding failure.

Definition at line 2583 of file tif_fax3.c.

◆ Fax3Encode()

static int Fax3Encode ( TIFF *  tif,
uint8_t *  bp,
tmsize_t  cc,
uint16_t  s 
)
static

Encode complete Group3 or aligned RLE rows.

Requires positive cached row size, nonnegative complete-row cc and valid raw/reference state. Emits EOL when enabled, chooses 1D/2D schedule, updates reference data and advances input. Does not change caller samples. Fractional requests diagnose; output failure can leave partial state/file data. No allocation or ownership transfer.

Parameters
[in,out]tifNon-NULL live fax handle with matching geometry/state; serialise operations.
[in]bpBorrowed readable packed MSB-first row/input bytes, unchanged.
[in]ccNonnegative complete-row input extent.
[in]sUnused sample-plane compatibility argument.
Returns
One after requested rows, zero on extent or output failure.

Definition at line 1756 of file tif_fax3.c.

◆ Fax3Encode1DRow()

static int Fax3Encode1DRow ( TIFF *  tif,
unsigned char *  bp,
uint32_t  bits 
)
static

Encode alternating white and black runs for one bilevel row.

Requires positive bit count within INT32_MAX and a readable packed MSB-first row. Emits Huffman spans and applies requested byte/word alignment. Can flush client output; errors retain partial code/file progress. Does not modify input or transfer ownership.

Parameters
[in,out]tifNon-NULL live fax handle with matching geometry/state; serialise operations.
[in]bpBorrowed readable packed MSB-first row/input bytes, unchanged.
[in]bitsRow width in pixels (number of bits in bp to encode); positive and at most INT32_MAX.
Returns
One after row coding, zero on output failure.

Definition at line 1574 of file tif_fax3.c.

◆ Fax3Encode2DRow()

static int Fax3Encode2DRow ( TIFF *  tif,
unsigned char *  bp,
unsigned char *  rp,
uint32_t  bits 
)
static

Encode one bilevel row relative to its reference row.

Requires positive bit count within INT32_MAX and readable current/reference rows including safe boundary-byte accesses used by change detection. Emits horizontal, vertical or pass codes without updating the reference row itself. Can flush client output and leave partial state/file changes on failure. No allocation, input mutation or ownership transfer.

Parameters
[in,out]tifNon-NULL live fax handle with matching geometry/state; serialise operations.
[in]bpBorrowed readable packed MSB-first row/input bytes, unchanged.
[in]rpBorrowed readable packed reference row, unchanged.
[in]bitsRow width in pixels (number of bits in bp to encode); positive and at most INT32_MAX.
Returns
One after row coding, zero on output failure.

Definition at line 1660 of file tif_fax3.c.

◆ Fax3Extension()

static void Fax3Extension ( const char *  module,
TIFF *  tif,
uint32_t  line,
uint32_t  a0 
)
static

Diagnose unsupported fax uncompressed extension data.

Reports an error through the handle with the row and pixel position. Does not itself increment recovery counters (the wrapping macro does), allocate, access payload or return status; diagnostic handlers can have application effects.

Parameters
[in]moduleBorrowed diagnostic label.
[in]tifHandle that receives the diagnostic and supplies the current strip or tile number.
[in]lineRow number within the strile for diagnostics.
[in]a0Pixel position of the extension code.

Definition at line 337 of file tif_fax3.c.

◆ Fax3FixupTags()

static int Fax3FixupTags ( TIFF *  tif)
static

Accept fax tag fixup without changes.

Ignores the handle; no allocation, I/O, diagnostics, state or ownership effects.

Parameters
[in]tifUnused handle.
Returns
One unconditionally.

Definition at line 851 of file tif_fax3.c.

◆ Fax3GetMaxCompressionRatio()

static uint64_t Fax3GetMaxCompressionRatio ( TIFF *  tif)
static

Report the fax expansion allocation heuristic.

No allocation, diagnostics, I/O, mutation or ownership transfer. The heuristic is not proof of payload validity or universal success.

Parameters
[in]tifUnused handle.
Returns
250.

Definition at line 2162 of file tif_fax3.c.

◆ Fax3PostEncode()

static int Fax3PostEncode ( TIFF *  tif)
static

Pad and buffer the final partial fax code byte.

Requires valid encoder/raw state. Flush macro can write a full raw buffer before appending its byte and return early on failure. Does not otherwise flush the final payload or persist metadata; no ownership transfer.

Parameters
[in,out]tifNon-NULL live fax handle with matching geometry/state; serialise operations.
Returns
One after byte alignment, zero on required flush failure.

Definition at line 1818 of file tif_fax3.c.

◆ Fax3PreDecode()

static int Fax3PreDecode ( TIFF *  tif,
uint16_t  s 
)
static

Reset fax bit state run pointers and recovery counters.

Requires allocated runs and valid positive row geometry. Clears the bit accumulator, EOL count and recovery counters, selects a borrowed bit-reversal table from the current FillOrder and sets the line index to zero. Repoints curruns to the start of runs without clearing it; when a reference partition exists, re-anchors refruns at runs + nruns (undoing any earlier swap) and initialises it to one all-white run. No allocation, client I/O, diagnostics or caller ownership transfer.

Parameters
[in,out]tifNon-NULL live fax handle with matching geometry/state; serialise operations.
[in]sUnused sample-plane compatibility argument.
Returns
One unconditionally.

Definition at line 252 of file tif_fax3.c.

◆ Fax3PreEncode()

static int Fax3PreEncode ( TIFF *  tif,
uint16_t  s 
)
static

Reset fax encoding bits reference line and dimensional schedule.

Requires setup-owned buffers. Clears the reference row, selects initial 1D mode and derives the 2D K schedule from vertical resolution (centimetres converted to inches, threshold 150). No allocation, payload I/O, diagnostics or ownership transfer.

Parameters
[in,out]tifNon-NULL live fax handle with matching geometry/state; serialise operations.
[in]sUnused sample-plane compatibility argument.
Returns
One unconditionally.

Definition at line 1278 of file tif_fax3.c.

◆ Fax3PrematureEOF()

static void Fax3PrematureEOF ( const char *  module,
TIFF *  tif,
uint32_t  line,
uint32_t  a0 
)
static

Warn about premature fax input exhaustion.

Reports a warning through the handle with the row and pixel position. Does not itself increment recovery counters (the wrapping macro does), allocate, access payload or return status; diagnostic handlers can have application effects.

Parameters
[in]moduleBorrowed diagnostic label.
[in]tifHandle that receives the diagnostic and supplies the current strip or tile number.
[in]lineRow number within the strile for diagnostics.
[in]a0Pixel position reached in the row.

Definition at line 402 of file tif_fax3.c.

◆ Fax3PrintDir()

static void Fax3PrintDir ( TIFF *  tif,
FILE *  fd,
long  flags 
)
static

Print present fax values then chain the saved directory printer.

Writes to borrowed FILE without checking stdio errors, then invokes optional saved printer. Does not close the stream or transfer ownership; parent callback effects apply. No separate error status.

Parameters
[in]tifNon-NULL fax handle whose field bits and cached fax values are printed; not modified.
[in,out]fdBorrowed writable FILE stream; remains caller-owned.
[in]flagsPrint flags forwarded to the saved parent printer.

Definition at line 2087 of file tif_fax3.c.

◆ Fax3PutBits()

static int Fax3PutBits ( TIFF *  tif,
unsigned int  bits,
unsigned int  length 
)
static

Append up to sixteen significant fax code bits.

Requires valid encoder bit accumulator and positive raw capacity. Flushes full bytes/buffers through helper macros, then commits local bit state. Early flush failure can leave local/cached progress inconsistent and file data changed; no ownership transfer.

Parameters
[in,out]tifNon-NULL live fax handle with matching geometry/state; serialise operations.
[in]bitsCode value whose low length bits are written, most significant first; at most 16 significant bits.
[in]lengthCode width at most sixteen bits.
Returns
One after append, zero on flush failure.

Definition at line 1083 of file tif_fax3.c.

◆ Fax3PutEOL()

static int Fax3PutEOL ( TIFF *  tif)
static

Append Group3 EOL padding and optional dimensional tag.

Uses fill-bit options to align EOL and emits the next 1D/2D tag where applicable. Requires valid encoder/raw state; output helpers can flush and fail after partial changes. No allocation or ownership transfer.

Parameters
[in,out]tifNon-NULL live fax handle with matching geometry/state; serialise operations.
Returns
One after append, zero on flush failure.

Definition at line 1221 of file tif_fax3.c.

◆ Fax3RLEGetMaxCompressionRatio()

static uint64_t Fax3RLEGetMaxCompressionRatio ( TIFF *  tif)
static

Report the fax expansion allocation heuristic.

No allocation, diagnostics, I/O, mutation or ownership transfer. The heuristic is not proof of payload validity or universal success.

Parameters
[in]tifUnused handle.
Returns
250.

Definition at line 2659 of file tif_fax3.c.

◆ Fax3SetupState()

static int Fax3SetupState ( TIFF *  tif)
static

Validate bilevel geometry and allocate fax run/reference storage.

Requires one-bit single-sample or separate-plane data and consistent row bytes/pixels. Caches row extent, replaces owned run arrays with checked rounded counts and optionally replaces the reference line. Changes decoder dispatch for Group3 2D options. Detected extent/allocation failures diagnose and can leave earlier buffers freed, cached geometry changed or partial new state retained for cleanup. Requires representable rowpixels+1 and signed decoder coordinates in addition to the explicit checks. No payload I/O or caller ownership transfer.

Parameters
[in,out]tifNon-NULL live fax handle with matching geometry/state; serialise operations.
Returns
One after setup, zero on detected geometry/extent/allocation failure.

Definition at line 882 of file tif_fax3.c.

◆ Fax3TryG3WithoutEOL()

static void Fax3TryG3WithoutEOL ( const char *  module,
TIFF *  tif,
uint32_t  line,
uint32_t  a0 
)
static

Warn that Group3 recovery will retry without EOL.

Reports a warning through the handle with the row and pixel position. Does not itself increment recovery counters (the wrapping macro does), allocate, access payload or return status; diagnostic handlers can have application effects.

Parameters
[in]moduleBorrowed diagnostic label.
[in]tifHandle that receives the diagnostic and supplies the current strip or tile number.
[in]lineRow number within the strile for diagnostics.
[in]a0Pixel position reached in the row.

Definition at line 434 of file tif_fax3.c.

◆ Fax3Unexpected()

static void Fax3Unexpected ( const char *  module,
TIFF *  tif,
uint32_t  line,
uint32_t  a0 
)
static

Diagnose an invalid fax code word.

Reports an error through the handle with the row and pixel position. Does not itself increment recovery counters (the wrapping macro does), allocate, access payload or return status; diagnostic handlers can have application effects.

Parameters
[in]moduleBorrowed diagnostic label.
[in]tifHandle that receives the diagnostic and supplies the current strip or tile number.
[in]lineRow number within the strile for diagnostics.
[in]a0Pixel position of the bad code word.

Definition at line 305 of file tif_fax3.c.

◆ Fax3VGetField()

static int Fax3VGetField ( TIFF *  tif,
uint32_t  tag,
va_list  ap 
)
static

Retrieve fax mode callback or persistent fax values.

FAXMODE consumes int*; FAXFILLFUNC consumes TIFFFaxFillFunc* and returns a borrowed installed callback. Options/bad-line counters consume uint32_t*; CLEANFAXDATA consumes uint16_t*. All outputs must be non-NULL. Other tags follow parent contracts. No allocation or ownership transfer.

Parameters
[in,out]tifNon-NULL live fax handle with matching geometry/state; serialise operations.
[in]tagFax or delegated tag identifier.
[in,out]apLive tag-specific va_list, consumed synchronously without retention.
Returns
One for fax retrieval, otherwise parent status.

Definition at line 2041 of file tif_fax3.c.

◆ Fax3VSetField()

static int Fax3VSetField ( TIFF *  tif,
uint32_t  tag,
va_list  ap 
)
static

Assign fax pseudo-tags or persistent fax metadata.

FAXMODE consumes int; FAXFILLFUNC consumes a non-NULL callable TIFFFaxFillFunc kept live while installed/in flight. GROUP3/4OPTIONS, BADFAXLINES and CONSECUTIVEBADFAXLINES consume uint32_t; options are consumed only for matching compression. CLEANFAXDATA consumes uint16_vap. Persistent tags mark field bits and directory dirty after assignment; lookup failure can leave changed cached values. If the compression does not match GROUP3OPTIONS/GROUP4OPTIONS, the value is not read and groupoptions is unchanged, but FIELD_OPTIONS and TIFF_DIRTYDIRECT are still set and 1 is returned. Other tags delegate to parent contracts. No ownership transfer; callbacks/diagnostics can run.

Parameters
[in,out]tifNon-NULL live fax handle with matching geometry/state; serialise operations.
[in]tagFax or delegated tag identifier.
[in,out]apLive tag-specific va_list, consumed synchronously without retention.
Returns
One after accepted assignment, zero on field lookup failure, otherwise parent status.

Definition at line 1977 of file tif_fax3.c.

◆ Fax4Decode()

static int Fax4Decode ( TIFF *  tif,
uint8_t *  buf,
tmsize_t  occ,
uint16_t  s 
)
static

Decode complete Group4 two-dimensional fax rows.

Requires setup/predecode, positive rowbytes, signed-representable pixel coordinates, nonnegative complete-row occ and valid run/reference capacities. Expands cached codes through state macros and invokes the installed fill callback synchronously; NULL buf is valid only for a custom callback that explicitly supports it. Can recover bad row lengths with diagnostics and counter limits; an EOL/EOFB code ends decoding of the strile. Updates run/reference arrays, line/bit state and raw cursors; failure can leave a partially filled current row and earlier output. The "Buffer overrun detected" failure returns without committing the cached bit and raw cursor state. Group4 can return success at early termination after at least one completed row, tolerating badly terminated striles; not all requested rows are thereby proved filled. No direct allocation/client I/O or ownership transfer; a custom filler has its own effects. Negative error status is not a Boolean success result.

With a caller buffer, a rejected request, counter limit or decoding error first zeroes the remaining output from the current row onwards, so rows that are not decoded never expose stale memory; a partial current row may then be filled on top. With a NULL buffer (custom fill callback) nothing is cleared. Accepted early termination clears the remaining rows the same way.

Parameters
[in,out]tifNon-NULL live fax handle with matching geometry/state; serialise operations.
[out]bufBorrowed decoded row storage of occ bytes, or NULL only with a compatible custom fill callback.
[in]occNonnegative complete-row decoded extent.
[in]sUnused sample-plane compatibility argument.
Returns
One on normal completion or accepted early Group4 termination, minus one on detected extent/counter/decoding failure.

Definition at line 2337 of file tif_fax3.c.

◆ Fax4Encode()

static int Fax4Encode ( TIFF *  tif,
uint8_t *  bp,
tmsize_t  cc,
uint16_t  s 
)
static

Encode complete Group4 rows relative to the preceding row.

Requires positive row size, complete-row nonnegative cc and valid reference/raw storage. Calls the 2D encoder and copies each successful row into reference storage. Fractional requests diagnose; I/O failure leaves earlier reference/bit/file changes. Caller input remains unchanged; no allocation or ownership transfer.

Parameters
[in,out]tifNon-NULL live fax handle with matching geometry/state; serialise operations.
[in]bpBorrowed readable packed MSB-first row/input bytes, unchanged.
[in]ccNonnegative complete-row input extent.
[in]sUnused sample-plane compatibility argument.
Returns
One after requested rows, zero on extent/output failure.

Definition at line 2444 of file tif_fax3.c.

◆ Fax4GetMaxCompressionRatio()

static uint64_t Fax4GetMaxCompressionRatio ( TIFF *  tif)
static

Report the fax expansion allocation heuristic.

No allocation, diagnostics, I/O, mutation or ownership transfer. The heuristic is not proof of payload validity or universal success.

Parameters
[in]tifHandle whose directory supplies the tile or image width; not modified.
Returns
TileWidth for tiled data, otherwise ImageWidth.

Definition at line 2502 of file tif_fax3.c.

◆ Fax4PostEncode()

static int Fax4PostEncode ( TIFF *  tif)
static

Append Group4 EOFB and align the final byte.

Emits two EOL codes but ignores their individual statuses, then aligns with the flush macro. Requires valid encoder/raw state. Can leave partial output/file state and does not persist IFD or promise durability; no ownership transfer.

Parameters
[in,out]tifNon-NULL live fax handle with matching geometry/state; serialise operations.
Returns
One on normal exit, zero from final required flush; ignored EOL write failures need not be reflected.

Definition at line 2479 of file tif_fax3.c.

◆ find0span()

static int32_t find0span ( unsigned char *  bp,
int32_t  bs,
int32_t  be 
)
inlinestatic

Measure the leading zero bit run in a bounded packed row.

Requires 0<=bs<=be<=INT32_MAX and live bytes through the last inspected bit. Uses immutable run lookup tables, with no mutation, allocation, I/O, diagnostics, bounds validation or ownership transfer.

Parameters
[in]bpBorrowed readable packed MSB-first row/input bytes, unchanged.
[in]bsNonnegative starting bit offset.
[in]beExclusive ending bit offset, not less than bs.
Returns
Run length in bits, limited by the exclusive end position be.

Definition at line 1386 of file tif_fax3.c.

◆ find1span()

static int32_t find1span ( unsigned char *  bp,
int32_t  bs,
int32_t  be 
)
inlinestatic

Measure the leading one bit run in a bounded packed row.

Requires 0<=bs<=be<=INT32_MAX and live bytes through the last inspected bit. Uses immutable run lookup tables, with no mutation, allocation, I/O, diagnostics, bounds validation or ownership transfer.

Parameters
[in]bpBorrowed readable packed MSB-first row/input bytes, unchanged.
[in]bsNonnegative starting bit offset.
[in]beExclusive ending bit offset, not less than bs.
Returns
Run length in bits, limited by the exclusive end position be.

Definition at line 1468 of file tif_fax3.c.

◆ InitCCITTFax3()

static int InitCCITTFax3 ( TIFF *  tif)
static

Allocate shared fax state and install tag and transfer methods.

Requires prior codec cleanup/default methods. Merges common fields, allocates zeroed Ext state, saves tag/print chains, installs default fill callback and row/strile/setup/close methods. Read-only mode sets NOBITREV because decoder handles FillOrder. Default fill setter status is ignored. Merge/allocation errors diagnose without general rollback. Buffers are allocated at setup; no payload I/O.

Parameters
[in,out]tifNon-NULL live fax handle with matching geometry/state; serialise operations.
Returns
One after shared installation, zero on field merge or outer allocation failure.

Definition at line 2194 of file tif_fax3.c.

◆ putspan()

static int putspan ( TIFF *  tif,
int32_t  span,
const tableentry *  tab 
)
static

Emit makeup and terminating Huffman codes for one fax run.

Requires nonnegative representable span and the corresponding complete white/black table. Repeats long makeup codes, emits terminating code and updates bit state. Can flush client output and diagnose; early failure leaves partial state/file effects. No input modification or ownership transfer.

Parameters
[in,out]tifNon-NULL live fax handle with matching geometry/state; serialise operations.
[in]spanNonnegative run length in pixels within signed arithmetic limits.
[in]tabBorrowed immutable complete white/black Huffman code table.
Returns
One after codes buffered, zero on flush failure.

Definition at line 1160 of file tif_fax3.c.

◆ TIFFInitCCITTFax3()

int TIFFInitCCITTFax3 ( TIFF *  tif,
int  scheme 
)
extern

Install CCITTFax3 fax callbacks and default mode.

Uses shared fax installation, merges applicable Group3/4 fields and/or overrides transfer methods, then sets mode through TIFFSetField. Defaults to Class/F without RTC. Requires cleaned-up prior codec state. Field/allocation/setter failure can leave partially installed state for lifecycle cleanup; diagnostics can run, no pixel I/O or caller ownership transfer.

Parameters
[in,out]tifNon-NULL handle whose previous codec state has been cleaned up; receives the new fax codec state. Serialise operations.
[in]schemeCompatibility scheme argument; this wrapper selects its own fax variant.
Returns
One after successful setup/mode assignment, zero on shared setup, field merge or setter failure.

Definition at line 2263 of file tif_fax3.c.

◆ TIFFInitCCITTFax4()

int TIFFInitCCITTFax4 ( TIFF *  tif,
int  scheme 
)
extern

Install CCITTFax4 fax callbacks and default mode.

Uses shared fax installation, merges applicable Group3/4 fields and/or overrides transfer methods, then sets mode through TIFFSetField. Selects Group4 transfer/EOFB and suppresses RTC. Requires cleaned-up prior codec state. Field/allocation/setter failure can leave partially installed state for lifecycle cleanup; diagnostics can run, no pixel I/O or caller ownership transfer.

Parameters
[in,out]tifNon-NULL handle whose previous codec state has been cleaned up; receives the new fax codec state. Serialise operations.
[in]schemeCompatibility scheme argument; this wrapper selects its own fax variant.
Returns
One after successful setup/mode assignment, zero on shared setup, field merge or setter failure.

Definition at line 2512 of file tif_fax3.c.

◆ TIFFInitCCITTRLE()

int TIFFInitCCITTRLE ( TIFF *  tif,
int  scheme 
)
extern

Install CCITTRLE fax callbacks and default mode.

Uses shared fax installation, merges applicable Group3/4 fields and/or overrides transfer methods, then sets mode through TIFFSetField. Suppresses RTC/EOL and byte-aligns encoded rows. Requires cleaned-up prior codec state. Field/allocation/setter failure can leave partially installed state for lifecycle cleanup; diagnostics can run, no pixel I/O or caller ownership transfer.

Parameters
[in,out]tifNon-NULL handle whose previous codec state has been cleaned up; receives the new fax codec state. Serialise operations.
[in]schemeCompatibility scheme argument; this wrapper selects its own fax variant.
Returns
One after successful setup/mode assignment, zero on shared setup, field merge or setter failure.

Definition at line 2674 of file tif_fax3.c.

◆ TIFFInitCCITTRLEW()

int TIFFInitCCITTRLEW ( TIFF *  tif,
int  scheme 
)
extern

Install CCITTRLEW fax callbacks and default mode.

Uses shared fax installation, merges applicable Group3/4 fields and/or overrides transfer methods, then sets mode through TIFFSetField. Suppresses RTC/EOL and word-aligns encoded rows. Requires cleaned-up prior codec state. Field/allocation/setter failure can leave partially installed state for lifecycle cleanup; diagnostics can run, no pixel I/O or caller ownership transfer.

Parameters
[in,out]tifNon-NULL handle whose previous codec state has been cleaned up; receives the new fax codec state. Serialise operations.
[in]schemeCompatibility scheme argument; this wrapper selects its own fax variant.
Returns
One after successful setup/mode assignment, zero on shared setup, field merge or setter failure.

Definition at line 2693 of file tif_fax3.c.

Variable Documentation

◆ _msbmask

const int _msbmask[9]
static
Initial value:
= {0x00, 0x01, 0x03, 0x07, 0x0f,
0x1f, 0x3f, 0x7f, 0xff}

Mask the requested low bit count for encoder code packing.

Immutable library-lifetime storage; no ownership transfer.

Definition at line 1044 of file tif_fax3.c.

◆ fax3Fields

const TIFFField fax3Fields[]
static
Initial value:
= {
FIELD_OPTIONS, FALSE, FALSE, "Group3Options", NULL},
}
#define FIELD_OPTIONS
Reserve the Group3/4 options codec field bit.
Definition tif_fax3.c:1911
@ TIFF_SETGET_UINT32
Unsigned 32-bit scalar storage.
Definition tif_dir.h:748
#define FALSE
Represent the legacy internal false value.
Definition tiffiop.h:136
#define TIFFTAG_GROUP3OPTIONS
TIFF tag: 32 flag bits.
Definition tiff.h:500
@ TIFF_LONG
Unsigned 32-bit integer.
Definition tiff.h:239

Define Group3 options metadata.

Immutable library-lifetime metadata merged into a handle; no caller ownership transfer.

Definition at line 1938 of file tif_fax3.c.

◆ fax4Fields

const TIFFField fax4Fields[]
static
Initial value:
= {
FIELD_OPTIONS, FALSE, FALSE, "Group4Options", NULL},
}
#define TIFFTAG_GROUP4OPTIONS
TIFF tag: 32 flag bits.
Definition tiff.h:510

Define Group4 options metadata.

Immutable library-lifetime metadata merged into a handle; no caller ownership transfer.

Definition at line 1949 of file tif_fax3.c.

◆ faxFields

const TIFFField faxFields[]
static
Initial value:
= {
FALSE, "FaxMode", NULL},
FALSE, FALSE, "FaxFillFunc", NULL},
FIELD_BADFAXLINES, TRUE, FALSE, "BadFaxLines", NULL},
FIELD_CLEANFAXDATA, TRUE, FALSE, "CleanFaxData", NULL},
FIELD_BADFAXRUN, TRUE, FALSE, "ConsecutiveBadFaxLines", NULL}}
#define FIELD_BADFAXRUN
Reserve the consecutive-bad-lines codec field bit.
Definition tif_fax3.c:1909
#define FIELD_BADFAXLINES
Reserve the BadFaxLines codec field bit.
Definition tif_fax3.c:1907
#define FIELD_CLEANFAXDATA
Reserve the CleanFaxData codec field bit.
Definition tif_fax3.c:1908
#define FIELD_PSEUDO
Share bit zero with FIELD_IGNORE for pseudo-tags.
Definition tif_dir.h:620
@ TIFF_SETGET_INT
Promoted int scalar representation.
Definition tif_dir.h:762
@ TIFF_SETGET_UINT16
Unsigned 16-bit scalar storage.
Definition tif_dir.h:744
@ TIFF_SETGET_OTHER
Tag-specific calling convention outside the regular encodings.
Definition tif_dir.h:838
#define TRUE
Represent the legacy internal true value.
Definition tiffiop.h:131
#define TIFF_ANY
Match any data type when searching for a field descriptor.
Definition tiffio.h:1289
#define TIFFTAG_FAXFILLFUNC
Pseudo-tag: G3/G4 fill function.
Definition tiff.h:1560
#define TIFFTAG_FAXMODE
Pseudo-tag: Group 3/4 format control.
Definition tiff.h:1530
#define TIFFTAG_CONSECUTIVEBADFAXLINES
TIFF tag: Max consecutive bad lines.
Definition tiff.h:582
#define TIFFTAG_CLEANFAXDATA
TIFF tag: Regenerated line info.
Definition tiff.h:574
#define TIFFTAG_BADFAXLINES
TIFF tag: Lines w/ wrong pixel count.
Definition tiff.h:572
@ TIFF_SHORT
Unsigned 16-bit integer.
Definition tiff.h:237

Define common fax metadata and pseudo-tags.

Immutable library-lifetime metadata merged into a handle; no caller ownership transfer.

Definition at line 1920 of file tif_fax3.c.

◆ horizcode

const tableentry horizcode = {3, 0x1, 0}
static

Encode the Group4 horizontal mode prefix.

Immutable library-lifetime storage; no ownership transfer.

Definition at line 1612 of file tif_fax3.c.

◆ oneruns

const unsigned char oneruns[256]
static
Initial value:
= {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 7, 8,
}

Count leading one bits in each byte.

Immutable library-lifetime storage; no ownership transfer.

Definition at line 1348 of file tif_fax3.c.

◆ passcode

const tableentry passcode = {4, 0x1, 0}
static

Encode the Group4 pass mode prefix.

Immutable library-lifetime storage; no ownership transfer.

Definition at line 1619 of file tif_fax3.c.

◆ TIFFFaxBlackCodes

const tableentry TIFFFaxBlackCodes[]
extern

Describe black CCITT terminating and makeup run codes.

Immutable library-lifetime storage; index by terminating run or sixty-four-pixel makeup offset as used by putspan. Negative sentinels also support state-table generation. Do not modify or free it.

◆ TIFFFaxBlackTable

const TIFFFaxTabEnt TIFFFaxBlackTable[]
extern

Decode thirteen-bit black-run prefixes.

Generated immutable library-lifetime table; canonical declaration covers tif_fax3sm.c storage. Do not modify or free it.

Definition at line 442 of file tif_fax3sm.c.

◆ TIFFFaxMainTable

const TIFFFaxTabEnt TIFFFaxMainTable[]
extern

Decode seven-bit two-dimensional (Group3 2D and Group4) mode prefixes.

Generated immutable library-lifetime table; canonical declaration covers tif_fax3sm.c storage. Do not modify or free it.

Definition at line 15 of file tif_fax3sm.c.

◆ TIFFFaxWhiteCodes

const tableentry TIFFFaxWhiteCodes[]
extern

Describe white CCITT terminating and makeup run codes.

Immutable library-lifetime storage; index by terminating run or sixty-four-pixel makeup offset as used by putspan. Negative sentinels also support state-table generation. Do not modify or free it.

◆ TIFFFaxWhiteTable

const TIFFFaxTabEnt TIFFFaxWhiteTable[]
extern

Decode twelve-bit white-run prefixes.

Generated immutable library-lifetime table; canonical declaration covers tif_fax3sm.c storage. Do not modify or free it.

Definition at line 30 of file tif_fax3sm.c.

◆ vcodes

const tableentry vcodes[7]
static
Initial value:
= {
{7, 0x03, 0},
{6, 0x03, 0},
{3, 0x03, 0},
{1, 0x1, 0},
{3, 0x2, 0},
{6, 0x02, 0},
{7, 0x02, 0}
}

Encode Group4 vertical offsets minus three through three.

Immutable library-lifetime storage; no ownership transfer.

Definition at line 1626 of file tif_fax3.c.

◆ zeroruns

const unsigned char zeroruns[256]
static
Initial value:
= {
8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
}

Count leading zero bits in each byte.

Immutable library-lifetime storage; no ownership transfer.

Definition at line 1324 of file tif_fax3.c.