Coverage Report

Created: 2026-09-13 07:02

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libtiff/libtiff/tif_fax3.c
Line
Count
Source
1
/*
2
 * Copyright (c) 1990-1997 Sam Leffler
3
 * Copyright (c) 1991-1997 Silicon Graphics, Inc.
4
 *
5
 * Permission to use, copy, modify, distribute, and sell this software and
6
 * its documentation for any purpose is hereby granted without fee, provided
7
 * that (i) the above copyright notices and this permission notice appear in
8
 * all copies of the software and related documentation, and (ii) the names of
9
 * Sam Leffler and Silicon Graphics may not be used in any advertising or
10
 * publicity relating to the software without the specific, prior written
11
 * permission of Sam Leffler and Silicon Graphics.
12
 *
13
 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
14
 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
15
 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
16
 *
17
 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
18
 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
19
 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
20
 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
21
 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
22
 * OF THIS SOFTWARE.
23
 */
24
25
#include "tiffiop.h"
26
#ifdef CCITT_SUPPORT
27
/*
28
 * TIFF Library.
29
 *
30
 * CCITT Group 3 (T.4) and Group 4 (T.6) Compression Support.
31
 *
32
 * This file contains support for decoding and encoding TIFF
33
 * compression algorithms 2, 3, 4, and 32771.
34
 *
35
 * Decoder support is derived, with permission, from the code
36
 * in Frank Cringle's viewfax program;
37
 *      Copyright (C) 1990, 1995  Frank D. Cringle.
38
 */
39
#include "tif_fax3.h"
40
#define G3CODES
41
#include "t4.h"
42
#include <stdio.h>
43
44
#ifndef EOF_REACHED_COUNT_THRESHOLD
45
/* Arbitrary threshold to avoid corrupted single-strip files with extremely
46
 * large imageheight to cause apparently endless looping, such as in
47
 * https://gitlab.com/libtiff/libtiff/-/issues/583
48
 */
49
393k
#define EOF_REACHED_COUNT_THRESHOLD 8192
50
#endif
51
52
/*
53
 * Compression+decompression state blocks are
54
 * derived from this ``base state'' block.
55
 */
56
typedef struct
57
{
58
    int rw_mode;        /* O_RDONLY for decode, else encode */
59
    int mode;           /* operating mode */
60
    tmsize_t rowbytes;  /* bytes in a decoded scanline */
61
    uint32_t rowpixels; /* pixels in a scanline */
62
63
    uint16_t cleanfaxdata; /* CleanFaxData tag */
64
    uint32_t badfaxrun;    /* BadFaxRun tag */
65
    uint32_t badfaxlines;  /* BadFaxLines tag */
66
    uint32_t groupoptions; /* Group 3/4 options tag */
67
68
    TIFFVGetMethod vgetparent; /* super-class method */
69
    TIFFVSetMethod vsetparent; /* super-class method */
70
    TIFFPrintMethod printdir;  /* super-class method */
71
} Fax3BaseState;
72
541k
#define Fax3State(tif) ((Fax3BaseState *)(tif)->tif_data)
73
74
typedef enum
75
{
76
    G3_1D,
77
    G3_2D
78
} Ttag;
79
typedef struct
80
{
81
    Fax3BaseState b;
82
83
    /* Decoder state info */
84
    const unsigned char *bitmap; /* bit reversal table */
85
    uint32_t data;               /* current i/o byte/word */
86
    int bit;                     /* current i/o bit in byte */
87
    int EOLcnt;                  /* count of EOL codes recognized */
88
    int eofReachedCount;         /* number of times decode has been called with
89
                                    EOF already reached */
90
    int eolReachedCount;         /* number of times decode has been called with
91
                                    EOL already reached */
92
    int unexpectedReachedCount;  /* number of times decode has been called with
93
                                    "unexpedted" already reached */
94
    TIFFFaxFillFunc fill;        /* fill routine */
95
    uint32_t *runs;              /* b&w runs for current/previous row */
96
    uint32_t nruns;              /* size of the refruns / curruns arrays */
97
    uint32_t *refruns;           /* runs for reference line */
98
    uint32_t *curruns;           /* runs for current line */
99
100
    /* Encoder state info */
101
    Ttag tag;               /* encoding state */
102
    unsigned char *refline; /* reference line for 2d decoding */
103
    int k;                  /* #rows left that can be 2d encoded */
104
    int maxk;               /* max #rows that can be 2d encoded */
105
106
    int line;
107
} Fax3CodecState;
108
290k
#define DecoderState(tif) ((Fax3CodecState *)Fax3State(tif))
109
15.1k
#define EncoderState(tif) ((Fax3CodecState *)Fax3State(tif))
110
111
2.56k
#define is2DEncoding(sp) (sp->b.groupoptions & GROUP3OPT_2DENCODING)
112
2.65M
#define isAligned(p, t) ((((size_t)(p)) & (sizeof(t) - 1)) == 0)
113
114
/*
115
 * Group 3 and Group 4 Decoding.
116
 */
117
118
/*
119
 * These macros glue the TIFF library state to
120
 * the state expected by Frank's decoder.
121
 */
122
#define DECLARE_STATE(tif, sp, mod)                                            \
123
131k
    static const char module[] = mod;                                          \
124
131k
    Fax3CodecState *sp = DecoderState(tif);                                    \
125
131k
    int a0;                                   /* reference element */          \
126
131k
    int lastx = (int)sp->b.rowpixels;         /* last element in row */        \
127
131k
    uint32_t BitAcc;                          /* bit accumulator */            \
128
131k
    int BitsAvail;                            /* # valid bits in BitAcc */     \
129
131k
    int RunLength;                            /* length of current run */      \
130
131k
    unsigned char *cp;                        /* next byte of input data */    \
131
131k
    unsigned char *ep;                        /* end of input data */          \
132
131k
    uint32_t *pa;                             /* place to stuff next run */    \
133
131k
    uint32_t *thisrun;                        /* current row's run array */    \
134
131k
    int EOLcnt;                               /* # EOL codes recognized */     \
135
131k
    const unsigned char *bitmap = sp->bitmap; /* input data bit reverser */    \
136
131k
    const TIFFFaxTabEnt *TabEnt
137
138
#define DECLARE_STATE_2D(tif, sp, mod)                                         \
139
107k
    DECLARE_STATE(tif, sp, mod);                                               \
140
107k
    int b1; /* next change on prev line */                                     \
141
107k
    uint32_t                                                                   \
142
107k
        *pb /* next run in reference line */ /*                                \
143
                                              * Load any state that may be     \
144
                                              * changed during decoding.       \
145
                                              */
146
#define CACHE_STATE(tif, sp)                                                   \
147
133k
    do                                                                         \
148
133k
    {                                                                          \
149
133k
        BitAcc = sp->data;                                                     \
150
133k
        BitsAvail = sp->bit;                                                   \
151
133k
        EOLcnt = sp->EOLcnt;                                                   \
152
133k
        cp = (unsigned char *)tif->tif_rawcp;                                  \
153
133k
        ep = cp + tif->tif_rawcc;                                              \
154
133k
    } while (0)
155
/*
156
 * Save state possibly changed during decoding.
157
 */
158
#define UNCACHE_STATE(tif, sp)                                                 \
159
126k
    do                                                                         \
160
126k
    {                                                                          \
161
126k
        sp->bit = BitsAvail;                                                   \
162
126k
        sp->data = BitAcc;                                                     \
163
126k
        sp->EOLcnt = EOLcnt;                                                   \
164
126k
        tif->tif_rawcc -= (tmsize_t)((uint8_t *)cp - tif->tif_rawcp);          \
165
126k
        tif->tif_rawcp = (uint8_t *)cp;                                        \
166
126k
    } while (0)
167
168
/*
169
 * Setup state for decoding a strip.
170
 */
171
static int Fax3PreDecode(TIFF *tif, uint16_t s)
172
131k
{
173
131k
    Fax3CodecState *sp = DecoderState(tif);
174
175
131k
    (void)s;
176
131k
    assert(sp != NULL);
177
131k
    sp->bit = 0; /* force initial read */
178
131k
    sp->data = 0;
179
131k
    sp->EOLcnt = 0; /* force initial scan for EOL */
180
131k
    sp->eofReachedCount = 0;
181
131k
    sp->eolReachedCount = 0;
182
131k
    sp->unexpectedReachedCount = 0;
183
    /*
184
     * Decoder assumes lsb-to-msb bit order.  Note that we select
185
     * this here rather than in Fax3SetupState so that viewers can
186
     * hold the image open, fiddle with the FillOrder tag value,
187
     * and then re-decode the image.  Otherwise they'd need to close
188
     * and open the image to get the state reset.
189
     */
190
131k
    sp->bitmap =
191
131k
        TIFFGetBitRevTable(tif->tif_dir.td_fillorder != FILLORDER_LSB2MSB);
192
131k
    sp->curruns = sp->runs;
193
131k
    if (sp->refruns)
194
107k
    { /* init reference line to white */
195
107k
        sp->refruns = sp->runs + sp->nruns;
196
107k
        sp->refruns[0] = (uint32_t)sp->b.rowpixels;
197
107k
        sp->refruns[1] = 0;
198
107k
    }
199
131k
    sp->line = 0;
200
131k
    return (1);
201
131k
}
202
203
/*
204
 * Routine for handling various errors/conditions.
205
 * Note how they are "glued into the decoder" by
206
 * overriding the definitions used by the decoder.
207
 */
208
209
static void Fax3Unexpected(const char *module, TIFF *tif, uint32_t line,
210
                           uint32_t a0)
211
1.76M
{
212
1.76M
    TIFFErrorExtR(
213
1.76M
        tif, module,
214
1.76M
        "Bad code word at line %" PRIu32 " of %s %" PRIu32 " (x %" PRIu32 ")",
215
1.76M
        line, isTiled(tif) ? "tile" : "strip",
216
1.76M
        (isTiled(tif) ? tif->tif_dir.td_curtile : tif->tif_dir.td_curstrip),
217
1.76M
        a0);
218
1.76M
}
219
#define unexpected(table, a0)                                                  \
220
1.76M
    do                                                                         \
221
1.76M
    {                                                                          \
222
1.76M
        Fax3Unexpected(module, tif, (uint32_t)sp->line, (uint32_t)(a0));       \
223
1.76M
        ++sp->unexpectedReachedCount;                                          \
224
1.76M
    } while (0)
225
226
static void Fax3Extension(const char *module, TIFF *tif, uint32_t line,
227
                          uint32_t a0)
228
188k
{
229
188k
    TIFFErrorExtR(
230
188k
        tif, module,
231
188k
        "Uncompressed data (not supported) at line %" PRIu32 " of %s %" PRIu32
232
188k
        " (x %" PRIu32 ")",
233
188k
        line, isTiled(tif) ? "tile" : "strip",
234
188k
        (isTiled(tif) ? tif->tif_dir.td_curtile : tif->tif_dir.td_curstrip),
235
188k
        a0);
236
188k
}
237
#define extension(a0)                                                          \
238
188k
    Fax3Extension(module, tif, (uint32_t)sp->line, (uint32_t)(a0))
239
240
static void Fax3BadLength(const char *module, TIFF *tif, uint32_t line,
241
                          uint32_t a0, uint32_t lastx)
242
5.36M
{
243
5.36M
    TIFFWarningExtR(
244
5.36M
        tif, module,
245
5.36M
        "%s at line %" PRIu32 " of %s %" PRIu32 " (got %" PRIu32
246
5.36M
        ", expected %" PRIu32 ")",
247
5.36M
        a0 < lastx ? "Premature EOL" : "Line length mismatch", line,
248
5.36M
        isTiled(tif) ? "tile" : "strip",
249
5.36M
        (isTiled(tif) ? tif->tif_dir.td_curtile : tif->tif_dir.td_curstrip), a0,
250
5.36M
        lastx);
251
5.36M
}
252
#define badlength(a0, lastx)                                                   \
253
5.36M
    do                                                                         \
254
5.36M
    {                                                                          \
255
5.36M
        Fax3BadLength(module, tif, (uint32_t)sp->line, (uint32_t)(a0),         \
256
5.36M
                      (uint32_t)(lastx));                                      \
257
5.36M
        ++sp->eolReachedCount;                                                 \
258
5.36M
    } while (0)
259
260
static void Fax3PrematureEOF(const char *module, TIFF *tif, uint32_t line,
261
                             uint32_t a0)
262
48.3k
{
263
48.3k
    TIFFWarningExtR(
264
48.3k
        tif, module,
265
48.3k
        "Premature EOF at line %" PRIu32 " of %s %" PRIu32 " (x %" PRIu32 ")",
266
48.3k
        line, isTiled(tif) ? "tile" : "strip",
267
48.3k
        (isTiled(tif) ? tif->tif_dir.td_curtile : tif->tif_dir.td_curstrip),
268
48.3k
        a0);
269
48.3k
}
270
#define prematureEOF(a0)                                                       \
271
48.3k
    do                                                                         \
272
48.3k
    {                                                                          \
273
48.3k
        Fax3PrematureEOF(module, tif, (uint32_t)sp->line, (uint32_t)(a0));     \
274
48.3k
        ++sp->eofReachedCount;                                                 \
275
48.3k
    } while (0)
276
277
static void Fax3TryG3WithoutEOL(const char *module, TIFF *tif, uint32_t line,
278
                                uint32_t a0)
279
2.27k
{
280
2.27k
    TIFFWarningExtR(
281
2.27k
        tif, module,
282
2.27k
        "Try to decode (read) fax Group 3 data without EOL at line %" PRIu32
283
2.27k
        " of %s %" PRIu32 " (x %" PRIu32 "). Please check result",
284
2.27k
        line, isTiled(tif) ? "tile" : "strip",
285
2.27k
        (isTiled(tif) ? tif->tif_dir.td_curtile : tif->tif_dir.td_curstrip),
286
2.27k
        a0);
287
2.27k
}
288
#define tryG3WithoutEOL(a0)                                                    \
289
2.27k
    do                                                                         \
290
2.27k
    {                                                                          \
291
2.27k
        Fax3TryG3WithoutEOL(module, tif, (uint32_t)sp->line, (uint32_t)(a0));  \
292
2.27k
    } while (0)
293
294
static int CheckReachedCounters(TIFF *tif, const char *module,
295
                                Fax3CodecState *sp)
296
131k
{
297
131k
    if (sp->eofReachedCount >= EOF_REACHED_COUNT_THRESHOLD)
298
0
    {
299
0
        TIFFErrorExtR(tif, module,
300
0
                      "End of file (EOF) has already been reached %d times "
301
0
                      "within that %s.",
302
0
                      sp->eofReachedCount, isTiled(tif) ? "tile" : "strip");
303
0
        return (-1);
304
0
    }
305
131k
    if (sp->eolReachedCount >= EOF_REACHED_COUNT_THRESHOLD)
306
0
    {
307
0
        TIFFErrorExtR(tif, module,
308
0
                      "Bad line length (EOL) has already been reached %d times "
309
0
                      "within that %s",
310
0
                      sp->eolReachedCount, isTiled(tif) ? "tile" : "strip");
311
0
        return (-1);
312
0
    }
313
131k
    if (sp->unexpectedReachedCount >= EOF_REACHED_COUNT_THRESHOLD)
314
0
    {
315
0
        TIFFErrorExtR(tif, module,
316
0
                      "Bad code word (unexpected) has already been reached %d "
317
0
                      "times within that %s",
318
0
                      sp->unexpectedReachedCount,
319
0
                      isTiled(tif) ? "tile" : "strip");
320
0
        return (-1);
321
0
    }
322
131k
    return (0);
323
131k
}
324
325
/**
326
 * Decode the requested amount of G3 1D-encoded data.
327
 * @param buf destination buffer
328
 * @param occ available bytes in destination buffer
329
 * @param s number of planes (ignored)
330
 * @returns 1 for success, -1 in case of error
331
 */
332
static int Fax3Decode1D(TIFF *tif, uint8_t *buf, tmsize_t occ, uint16_t s)
333
14.5k
{
334
14.5k
    DECLARE_STATE(tif, sp, "Fax3Decode1D");
335
14.5k
    (void)s;
336
14.5k
    if (occ % sp->b.rowbytes)
337
0
    {
338
0
        TIFFErrorExtR(tif, module, "Fractional scanlines cannot be read");
339
0
        return (-1);
340
0
    }
341
14.5k
    if (CheckReachedCounters(tif, module, sp))
342
0
        return (-1);
343
15.3k
RETRY_WITHOUT_EOL_1D:
344
15.3k
    CACHE_STATE(tif, sp);
345
15.3k
    thisrun = sp->curruns;
346
1.48M
    while (occ > 0)
347
1.47M
    {
348
1.47M
        a0 = 0;
349
1.47M
        RunLength = 0;
350
1.47M
        pa = thisrun;
351
#ifdef FAX3_DEBUG
352
        printf("\nBitAcc=%08" PRIX32 ", BitsAvail = %d\n", BitAcc, BitsAvail);
353
        printf("-------------------- %" PRIu32 "\n", tif->tif_dir.td_row);
354
        fflush(stdout);
355
#endif
356
1.47M
        SYNC_EOL(EOF1D, RETRY_WITHOUT_EOL_1D);
357
1.47M
        EXPAND1D(EOF1Da);
358
1.47M
        (*sp->fill)(buf, thisrun, pa, (uint32_t)lastx);
359
1.47M
        buf += sp->b.rowbytes;
360
1.47M
        occ -= sp->b.rowbytes;
361
1.47M
        sp->line++;
362
1.47M
        continue;
363
0
    EOF1D: /* premature EOF */
364
0
        CLEANUP_RUNS();
365
936
    EOF1Da: /* premature EOF */
366
936
        (*sp->fill)(buf, thisrun, pa, (uint32_t)lastx);
367
936
        UNCACHE_STATE(tif, sp);
368
936
        return (-1);
369
0
    }
370
13.6k
    UNCACHE_STATE(tif, sp);
371
13.6k
    return (1);
372
15.3k
}
373
374
#define SWAP(t, a, b)                                                          \
375
3.64M
    {                                                                          \
376
3.64M
        t x;                                                                   \
377
3.64M
        x = (a);                                                               \
378
3.64M
        (a) = (b);                                                             \
379
3.64M
        (b) = x;                                                               \
380
3.64M
    }
381
/*
382
 * Decode the requested amount of G3 2D-encoded data.
383
 */
384
static int Fax3Decode2D(TIFF *tif, uint8_t *buf, tmsize_t occ, uint16_t s)
385
54.8k
{
386
54.8k
    DECLARE_STATE_2D(tif, sp, "Fax3Decode2D");
387
54.8k
    int is1D; /* current line is 1d/2d-encoded */
388
54.8k
    (void)s;
389
54.8k
    if (occ % sp->b.rowbytes)
390
0
    {
391
0
        TIFFErrorExtR(tif, module, "Fractional scanlines cannot be read");
392
0
        return (-1);
393
0
    }
394
54.8k
    if (CheckReachedCounters(tif, module, sp))
395
0
        return (-1);
396
56.3k
RETRY_WITHOUT_EOL_2D:
397
56.3k
    CACHE_STATE(tif, sp);
398
3.70M
    while (occ > 0)
399
3.69M
    {
400
3.69M
        a0 = 0;
401
3.69M
        RunLength = 0;
402
3.69M
        pa = thisrun = sp->curruns;
403
#ifdef FAX3_DEBUG
404
        printf("\nBitAcc=%08" PRIX32 ", BitsAvail = %d EOLcnt = %d", BitAcc,
405
               BitsAvail, EOLcnt);
406
#endif
407
3.69M
        SYNC_EOL(EOF2D, RETRY_WITHOUT_EOL_2D);
408
3.69M
        NeedBits8(1, EOF2D);
409
3.68M
        is1D = GetBits(1); /* 1D/2D-encoding tag bit */
410
3.68M
        ClrBits(1);
411
#ifdef FAX3_DEBUG
412
        printf(" %s\n-------------------- %" PRIu32 "\n", is1D ? "1D" : "2D",
413
               tif->tif_dir.td_row);
414
        fflush(stdout);
415
#endif
416
3.68M
        pb = sp->refruns;
417
3.68M
        b1 = (int)*pb++;
418
3.68M
        if (is1D)
419
1.13M
            EXPAND1D(EOF2Da);
420
2.55M
        else
421
2.55M
            EXPAND2D(EOF2Da);
422
3.64M
        (*sp->fill)(buf, thisrun, pa, (uint32_t)lastx);
423
3.64M
        if (pa < thisrun + sp->nruns)
424
3.64M
        {
425
3.64M
            SETVALUE(0); /* imaginary change for reference */
426
3.64M
        }
427
3.64M
        SWAP(uint32_t *, sp->curruns, sp->refruns);
428
3.64M
        buf += sp->b.rowbytes;
429
3.64M
        occ -= sp->b.rowbytes;
430
3.64M
        sp->line++;
431
3.64M
        continue;
432
6.37k
    EOF2D: /* premature EOF */
433
6.37k
        CLEANUP_RUNS();
434
41.5k
    EOF2Da: /* premature EOF */
435
41.5k
        (*sp->fill)(buf, thisrun, pa, (uint32_t)lastx);
436
41.5k
        UNCACHE_STATE(tif, sp);
437
41.5k
        return (-1);
438
6.37k
    }
439
9.73k
    UNCACHE_STATE(tif, sp);
440
9.73k
    return (1);
441
56.3k
}
442
#undef SWAP
443
444
#define FILL(n, cp)                                                            \
445
440k
    for (int32_t ifill = 0; ifill < (n); ++ifill)                              \
446
318k
    {                                                                          \
447
318k
        (cp)[ifill] = 0xff;                                                    \
448
318k
    }                                                                          \
449
121k
    (cp) += (n);
450
451
#define ZERO(n, cp)                                                            \
452
12.5M
    for (int32_t izero = 0; izero < (n); ++izero)                              \
453
8.80M
    {                                                                          \
454
8.80M
        (cp)[izero] = 0;                                                       \
455
8.80M
    }                                                                          \
456
3.77M
    (cp) += (n);
457
458
/*
459
 * Bit-fill a row according to the white/black
460
 * runs generated during G3/G4 decoding.
461
 */
462
void _TIFFFax3fillruns(unsigned char *buf, uint32_t *runs, uint32_t *erun,
463
                       uint32_t lastx)
464
6.97M
{
465
6.97M
    static const unsigned char _fillmasks[] = {0x00, 0x80, 0xc0, 0xe0, 0xf0,
466
6.97M
                                               0xf8, 0xfc, 0xfe, 0xff};
467
6.97M
    unsigned char *cp;
468
6.97M
    uint32_t x, bx, run;
469
6.97M
    int32_t n, nw;
470
6.97M
    int64_t *lp;
471
472
6.97M
    if ((erun - runs) & 1)
473
6.49M
        *erun++ = 0;
474
6.97M
    x = 0;
475
17.6M
    for (; runs < erun; runs += 2)
476
10.6M
    {
477
10.6M
        run = runs[0];
478
10.6M
        if (x + run > lastx || run > lastx)
479
1.47M
            run = runs[0] = (uint32_t)(lastx - x);
480
10.6M
        if (run)
481
8.93M
        {
482
8.93M
            cp = buf + (x >> 3);
483
8.93M
            bx = x & 7;
484
8.93M
            if (run > 8 - bx)
485
4.58M
            {
486
4.58M
                if (bx)
487
1.18M
                { /* align to byte boundary */
488
1.18M
                    *cp++ &= (unsigned char)(0xff << (8 - bx));
489
1.18M
                    run -= 8 - bx;
490
1.18M
                }
491
4.58M
                if ((n = (int32_t)(run >> 3)) != 0)
492
3.77M
                { /* multiple bytes to fill */
493
3.77M
                    if (((size_t)n / sizeof(int64_t)) > 1)
494
680k
                    {
495
                        /*
496
                         * Align to int64_tword boundary and fill.
497
                         */
498
2.52M
                        for (; n && !isAligned(cp, int64_t); n--)
499
1.84M
                            *cp++ = 0x00;
500
680k
                        lp = (int64_t *)cp;
501
680k
                        nw = (int32_t)((size_t)n / sizeof(int64_t));
502
680k
                        n -= (int32_t)((size_t)nw * sizeof(int64_t));
503
680k
                        do
504
8.10M
                        {
505
8.10M
                            *lp++ = 0L;
506
8.10M
                        } while (--nw);
507
680k
                        cp = (unsigned char *)lp;
508
680k
                    }
509
3.77M
                    ZERO(n, cp);
510
3.77M
                    run &= 7;
511
3.77M
                }
512
4.58M
                if (run)
513
3.98M
                    cp[0] &= (unsigned char)(0xff >> run);
514
4.58M
            }
515
4.35M
            else
516
4.35M
                cp[0] &= (unsigned char)~(_fillmasks[run] >> bx);
517
8.93M
            x += runs[0];
518
8.93M
        }
519
10.6M
        run = runs[1];
520
10.6M
        if (x + run > lastx || run > lastx)
521
0
            run = runs[1] = lastx - x;
522
10.6M
        if (run)
523
2.18M
        {
524
2.18M
            cp = buf + (x >> 3);
525
2.18M
            bx = x & 7;
526
2.18M
            if (run > 8 - bx)
527
701k
            {
528
701k
                if (bx)
529
687k
                { /* align to byte boundary */
530
687k
                    *cp++ |= (unsigned char)(0xff >> bx);
531
687k
                    run -= 8 - bx;
532
687k
                }
533
701k
                if ((n = (int32_t)(run >> 3)) != 0)
534
121k
                { /* multiple bytes to fill */
535
121k
                    if (((size_t)n / sizeof(int64_t)) > 1)
536
21.3k
                    {
537
                        /*
538
                         * Align to int64_t boundary and fill.
539
                         */
540
101k
                        for (; n && !isAligned(cp, int64_t); n--)
541
80.4k
                            *cp++ = 0xff;
542
21.3k
                        lp = (int64_t *)cp;
543
21.3k
                        nw = (int32_t)((size_t)n / sizeof(int64_t));
544
21.3k
                        n -= (int32_t)((size_t)nw * sizeof(int64_t));
545
21.3k
                        do
546
175k
                        {
547
175k
                            *lp++ = -1L;
548
175k
                        } while (--nw);
549
21.3k
                        cp = (unsigned char *)lp;
550
21.3k
                    }
551
121k
                    FILL(n, cp);
552
121k
                    run &= 7;
553
121k
                }
554
                /* Explicit 0xff masking to make icc -check=conversions happy */
555
701k
                if (run)
556
677k
                    cp[0] = (unsigned char)((cp[0] | (0xff00 >> run)) & 0xff);
557
701k
            }
558
1.48M
            else
559
1.48M
                cp[0] |= (unsigned char)(_fillmasks[run] >> bx);
560
2.18M
            x += runs[1];
561
2.18M
        }
562
10.6M
    }
563
6.97M
    assert(x == lastx);
564
6.97M
}
565
#undef ZERO
566
#undef FILL
567
568
static int Fax3FixupTags(TIFF *tif)
569
9.14k
{
570
9.14k
    (void)tif;
571
9.14k
    return (1);
572
9.14k
}
573
574
/*
575
 * Setup G3/G4-related compression/decompression state
576
 * before data is processed.  This routine is called once
577
 * per image -- it sets up different state based on whether
578
 * or not decoding or encoding is being done and whether
579
 * 1D- or 2D-encoded data is involved.
580
 */
581
static int Fax3SetupState(TIFF *tif)
582
4.24k
{
583
4.24k
    static const char module[] = "Fax3SetupState";
584
4.24k
    TIFFDirectory *td = &tif->tif_dir;
585
4.24k
    Fax3BaseState *sp = Fax3State(tif);
586
4.24k
    int needsRefLine;
587
4.24k
    Fax3CodecState *dsp = (Fax3CodecState *)Fax3State(tif);
588
4.24k
    tmsize_t rowbytes;
589
4.24k
    uint32_t rowpixels;
590
591
4.24k
    if (td->td_bitspersample != 1)
592
5
    {
593
5
        TIFFErrorExtR(tif, module,
594
5
                      "Bits/sample must be 1 for Group 3/4 encoding/decoding");
595
5
        return (0);
596
5
    }
597
4.24k
    if (td->td_samplesperpixel != 1 &&
598
143
        td->td_planarconfig != PLANARCONFIG_SEPARATE)
599
3
    {
600
3
        TIFFErrorExtR(
601
3
            tif, module,
602
3
            "Samples/pixel shall be 1 for Group 3/4 encoding/decoding, "
603
3
            "or PlanarConfiguration must be set to Separate.");
604
3
        return 0;
605
3
    }
606
    /*
607
     * Calculate the scanline/tile widths.
608
     */
609
4.23k
    if (isTiled(tif))
610
1.88k
    {
611
1.88k
        rowbytes = TIFFTileRowSize(tif);
612
1.88k
        rowpixels = td->td_tilewidth;
613
1.88k
    }
614
2.35k
    else
615
2.35k
    {
616
2.35k
        rowbytes = TIFFScanlineSize(tif);
617
2.35k
        rowpixels = td->td_imagewidth;
618
2.35k
    }
619
4.23k
    if ((int64_t)rowbytes < ((int64_t)rowpixels + 7) / 8)
620
0
    {
621
0
        TIFFErrorExtR(tif, module,
622
0
                      "Inconsistent number of bytes per row : rowbytes=%" PRId64
623
0
                      " rowpixels=%" PRIu32,
624
0
                      (int64_t)rowbytes, rowpixels);
625
0
        return (0);
626
0
    }
627
4.23k
    sp->rowbytes = rowbytes;
628
4.23k
    sp->rowpixels = rowpixels;
629
    /*
630
     * Allocate any additional space required for decoding/encoding.
631
     */
632
4.23k
    needsRefLine = ((sp->groupoptions & GROUP3OPT_2DENCODING) ||
633
2.62k
                    td->td_compression == COMPRESSION_CCITTFAX4);
634
635
    /*
636
      Assure that allocation computations do not overflow.
637
638
      TIFFroundup and TIFFSafeMultiply return zero on integer overflow
639
    */
640
4.23k
    if (dsp->runs != NULL)
641
0
    {
642
0
        _TIFFfreeExt(tif, dsp->runs);
643
0
        dsp->runs = (uint32_t *)NULL;
644
0
    }
645
4.23k
    dsp->nruns = TIFFroundup_32(rowpixels + 1, 32);
646
4.23k
    if (needsRefLine)
647
2.74k
    {
648
2.74k
        dsp->nruns = TIFFSafeMultiply(uint32_t, dsp->nruns, 2);
649
2.74k
    }
650
4.23k
    if ((dsp->nruns == 0) || (TIFFSafeMultiply(uint32_t, dsp->nruns, 2) == 0))
651
0
    {
652
0
        TIFFErrorExtR(tif, tif->tif_name,
653
0
                      "Row pixels integer overflow (rowpixels %" PRIu32 ")",
654
0
                      rowpixels);
655
0
        return (0);
656
0
    }
657
4.23k
    dsp->runs = (uint32_t *)_TIFFCheckMalloc(
658
4.23k
        tif, TIFFSafeMultiply(uint32_t, dsp->nruns, 2), sizeof(uint32_t),
659
4.23k
        "for Group 3/4 run arrays");
660
4.23k
    if (dsp->runs == NULL)
661
0
        return (0);
662
4.23k
    memset(dsp->runs, 0,
663
4.23k
           TIFFSafeMultiply(uint32_t, dsp->nruns, 2) * sizeof(uint32_t));
664
4.23k
    dsp->curruns = dsp->runs;
665
4.23k
    if (needsRefLine)
666
2.74k
        dsp->refruns = dsp->runs + dsp->nruns;
667
1.49k
    else
668
1.49k
        dsp->refruns = NULL;
669
4.23k
    if (td->td_compression == COMPRESSION_CCITTFAX3 && is2DEncoding(dsp))
670
1.60k
    { /* NB: default is 1D routine */
671
1.60k
        tif->tif_decoderow = Fax3Decode2D;
672
1.60k
        tif->tif_decodestrip = Fax3Decode2D;
673
1.60k
        tif->tif_decodetile = Fax3Decode2D;
674
1.60k
    }
675
676
4.23k
    if (needsRefLine)
677
2.74k
    { /* 2d encoding */
678
2.74k
        Fax3CodecState *esp = EncoderState(tif);
679
        /*
680
         * 2d encoding requires a scanline
681
         * buffer for the ``reference line''; the
682
         * scanline against which delta encoding
683
         * is referenced.  The reference line must
684
         * be initialized to be ``white'' (done elsewhere).
685
         */
686
2.74k
        if (esp->refline != NULL)
687
0
        {
688
0
            _TIFFfreeExt(tif, esp->refline);
689
0
        }
690
2.74k
        esp->refline = (unsigned char *)_TIFFmallocExt(tif, rowbytes);
691
2.74k
        if (esp->refline == NULL)
692
0
        {
693
0
            TIFFErrorExtR(tif, module, "No space for Group 3/4 reference line");
694
0
            return (0);
695
0
        }
696
2.74k
    }
697
1.49k
    else /* 1d encoding */
698
1.49k
        EncoderState(tif)->refline = NULL;
699
700
4.23k
    return (1);
701
4.23k
}
702
703
/*
704
 * CCITT Group 3 FAX Encoding.
705
 */
706
707
#define Fax3FlushBits(tif, sp)                                                 \
708
13
    {                                                                          \
709
13
        if ((tif)->tif_rawcc >= (tif)->tif_rawdatasize)                        \
710
13
        {                                                                      \
711
0
            if (!TIFFFlushData1(tif))                                          \
712
0
                return 0;                                                      \
713
0
        }                                                                      \
714
13
        *(tif)->tif_rawcp++ = (uint8_t)(sp)->data;                             \
715
13
        (tif)->tif_rawcc++;                                                    \
716
13
        (sp)->data = 0, (sp)->bit = 8;                                         \
717
13
    }
718
#define _FlushBits(tif)                                                        \
719
212
    {                                                                          \
720
212
        if ((tif)->tif_rawcc >= (tif)->tif_rawdatasize)                        \
721
212
        {                                                                      \
722
0
            if (!TIFFFlushData1(tif))                                          \
723
0
                return 0;                                                      \
724
0
        }                                                                      \
725
212
        *(tif)->tif_rawcp++ = (uint8_t)data;                                   \
726
212
        (tif)->tif_rawcc++;                                                    \
727
212
        data = 0, bit = 8;                                                     \
728
212
    }
729
static const int _msbmask[9] = {0x00, 0x01, 0x03, 0x07, 0x0f,
730
                                0x1f, 0x3f, 0x7f, 0xff};
731
#define _PutBits(tif, bits, length)                                            \
732
883
    {                                                                          \
733
990
        while (length > bit)                                                   \
734
883
        {                                                                      \
735
107
            data |= (int)((unsigned int)bits >> (length - bit));               \
736
107
            length -= bit;                                                     \
737
107
            _FlushBits(tif);                                                   \
738
107
        }                                                                      \
739
883
        assert(length < 9);                                                    \
740
883
        data |= (int)(((unsigned int)bits & (unsigned int)_msbmask[length])    \
741
883
                      << (unsigned int)(bit - length));                        \
742
883
        bit -= length;                                                         \
743
883
        if (bit == 0)                                                          \
744
883
            _FlushBits(tif);                                                   \
745
883
    }
746
747
/*
748
 * Write a variable-length bit-value to
749
 * the output stream.  Values are
750
 * assumed to be at most 16 bits.
751
 */
752
static int Fax3PutBits(TIFF *tif, unsigned int bits, unsigned int length)
753
823
{
754
823
    Fax3CodecState *sp = EncoderState(tif);
755
823
    unsigned int bit = (unsigned int)sp->bit;
756
823
    int data = (int)sp->data;
757
758
823
    _PutBits(tif, bits, length);
759
760
823
    sp->data = (uint32_t)data;
761
823
    sp->bit = (int)bit;
762
823
    return 1;
763
1.64k
}
764
765
/*
766
 * Write a code to the output stream.
767
 */
768
787
#define putcode(tif, te) Fax3PutBits(tif, (te)->code, (te)->length)
769
770
#ifdef FAX3_DEBUG
771
#define DEBUG_COLOR(w) (tab == TIFFFaxWhiteCodes ? w "W" : w "B")
772
#define DEBUG_PRINT(what, len)                                                 \
773
    {                                                                          \
774
        int t;                                                                 \
775
        printf("%08" PRIX32 "/%-2d: %s%5d\t", data, bit, DEBUG_COLOR(what),    \
776
               len);                                                           \
777
        for (t = length - 1; t >= 0; t--)                                      \
778
            putchar(code & (1 << t) ? '1' : '0');                              \
779
        putchar('\n');                                                         \
780
    }
781
#endif
782
783
/*
784
 * Write the sequence of codes that describes
785
 * the specified span of zero's or one's.  The
786
 * appropriate table that holds the make-up and
787
 * terminating codes is supplied.
788
 */
789
static int putspan(TIFF *tif, int32_t span, const tableentry *tab)
790
48
{
791
48
    Fax3CodecState *sp = EncoderState(tif);
792
48
    unsigned int bit = (unsigned int)sp->bit;
793
48
    int data = (int)sp->data;
794
48
    unsigned int code, length;
795
796
48
    while (span >= 2624)
797
0
    {
798
0
        const tableentry *te = &tab[63 + (2560 >> 6)];
799
0
        code = te->code;
800
0
        length = te->length;
801
#ifdef FAX3_DEBUG
802
        DEBUG_PRINT("MakeUp", te->runlen);
803
#endif
804
0
        _PutBits(tif, code, length);
805
0
        span -= te->runlen;
806
0
    }
807
48
    if (span >= 64)
808
12
    {
809
12
        const tableentry *te = &tab[63 + (span >> 6)];
810
12
        assert(te->runlen == 64 * (span >> 6));
811
12
        code = te->code;
812
12
        length = te->length;
813
#ifdef FAX3_DEBUG
814
        DEBUG_PRINT("MakeUp", te->runlen);
815
#endif
816
36
        _PutBits(tif, code, length);
817
36
        span -= te->runlen;
818
36
    }
819
48
    code = tab[span].code;
820
48
    length = tab[span].length;
821
#ifdef FAX3_DEBUG
822
    DEBUG_PRINT("  Term", tab[span].runlen);
823
#endif
824
48
    _PutBits(tif, code, length);
825
826
48
    sp->data = (uint32_t)data;
827
48
    sp->bit = (int)bit;
828
829
48
    return 1;
830
96
}
831
832
/*
833
 * Write an EOL code to the output stream.  The zero-fill
834
 * logic for byte-aligning encoded scanlines is handled
835
 * here.  We also handle writing the tag bit for the next
836
 * scanline when doing 2d encoding.
837
 */
838
static int Fax3PutEOL(TIFF *tif)
839
0
{
840
0
    Fax3CodecState *sp = EncoderState(tif);
841
0
    unsigned int bit = (unsigned int)sp->bit;
842
0
    int data = (int)sp->data;
843
0
    unsigned int code, length, tparm;
844
845
0
    if (sp->b.groupoptions & GROUP3OPT_FILLBITS)
846
0
    {
847
        /*
848
         * Force bit alignment so EOL will terminate on
849
         * a byte boundary.  That is, force the bit alignment
850
         * to 16-12 = 4 before putting out the EOL code.
851
         */
852
0
        int align = 8 - 4;
853
0
        if (align != sp->bit)
854
0
        {
855
0
            if (align > sp->bit)
856
0
                align = sp->bit + (8 - align);
857
0
            else
858
0
                align = sp->bit - align;
859
0
            tparm = (unsigned int)align;
860
0
            _PutBits(tif, 0, tparm);
861
0
        }
862
0
    }
863
0
    code = EOL;
864
0
    length = 12;
865
0
    if (is2DEncoding(sp))
866
0
    {
867
0
        code = (code << 1) | (sp->tag == G3_1D);
868
0
        length++;
869
0
    }
870
0
    _PutBits(tif, code, length);
871
872
0
    sp->data = (uint32_t)data;
873
0
    sp->bit = (int)bit;
874
875
0
    return 1;
876
0
}
877
878
/*
879
 * Reset encoding state at the start of a strip.
880
 */
881
static int Fax3PreEncode(TIFF *tif, uint16_t s)
882
18
{
883
18
    Fax3CodecState *sp = EncoderState(tif);
884
885
18
    (void)s;
886
18
    assert(sp != NULL);
887
18
    sp->bit = 8;
888
18
    sp->data = 0;
889
18
    sp->tag = G3_1D;
890
    /*
891
     * This is necessary for Group 4; otherwise it isn't
892
     * needed because the first scanline of each strip ends
893
     * up being copied into the refline.
894
     */
895
18
    if (sp->refline)
896
18
        _TIFFmemset(sp->refline, 0x00, sp->b.rowbytes);
897
18
    if (is2DEncoding(sp))
898
0
    {
899
0
        float res = tif->tif_dir.td_yresolution;
900
        /*
901
         * The CCITT spec says that when doing 2d encoding, you
902
         * should only do it on K consecutive scanlines, where K
903
         * depends on the resolution of the image being encoded
904
         * (2 for <= 200 lpi, 4 for > 200 lpi).  Since the directory
905
         * code initializes td_yresolution to 0, this code will
906
         * select a K of 2 unless the YResolution tag is set
907
         * appropriately.  (Note also that we fudge a little here
908
         * and use 150 lpi to avoid problems with units conversion.)
909
         */
910
0
        if (tif->tif_dir.td_resolutionunit == RESUNIT_CENTIMETER)
911
0
            res *= 2.54f; /* convert to inches */
912
0
        sp->maxk = (res > 150 ? 4 : 2);
913
0
        sp->k = sp->maxk - 1;
914
0
    }
915
18
    else
916
18
        sp->k = sp->maxk = 0;
917
18
    sp->line = 0;
918
18
    return (1);
919
18
}
920
921
static const unsigned char zeroruns[256] = {
922
    8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, /* 0x00 - 0x0f */
923
    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 0x10 - 0x1f */
924
    2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0x20 - 0x2f */
925
    2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0x30 - 0x3f */
926
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40 - 0x4f */
927
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x50 - 0x5f */
928
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60 - 0x6f */
929
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x70 - 0x7f */
930
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x80 - 0x8f */
931
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x90 - 0x9f */
932
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xa0 - 0xaf */
933
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xb0 - 0xbf */
934
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xc0 - 0xcf */
935
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xd0 - 0xdf */
936
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xe0 - 0xef */
937
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xf0 - 0xff */
938
};
939
static const unsigned char oneruns[256] = {
940
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 - 0x0f */
941
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x10 - 0x1f */
942
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20 - 0x2f */
943
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x30 - 0x3f */
944
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x40 - 0x4f */
945
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x50 - 0x5f */
946
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x60 - 0x6f */
947
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x70 - 0x7f */
948
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x80 - 0x8f */
949
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x90 - 0x9f */
950
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0xa0 - 0xaf */
951
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0xb0 - 0xbf */
952
    2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0xc0 - 0xcf */
953
    2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0xd0 - 0xdf */
954
    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 0xe0 - 0xef */
955
    4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 7, 8, /* 0xf0 - 0xff */
956
};
957
958
/*
959
 * Find a span of ones or zeros using the supplied
960
 * table.  The ``base'' of the bit string is supplied
961
 * along with the start+end bit indices.
962
 */
963
static inline int32_t find0span(unsigned char *bp, int32_t bs, int32_t be)
964
1.44k
{
965
1.44k
    int32_t bits = be - bs;
966
1.44k
    int32_t n, span;
967
968
1.44k
    bp += bs >> 3;
969
    /*
970
     * Check partial byte on lhs.
971
     */
972
1.44k
    if (bits > 0 && (n = (bs & 7)) != 0)
973
252
    {
974
252
        span = zeroruns[(*bp << n) & 0xff];
975
252
        if (span > 8 - n) /* table value too generous */
976
84
            span = 8 - n;
977
252
        if (span > bits) /* constrain span to bit range */
978
7
            span = bits;
979
252
        if (n + span < 8) /* doesn't extend to edge of byte */
980
175
            return (span);
981
77
        bits -= span;
982
77
        bp++;
983
77
    }
984
1.19k
    else
985
1.19k
        span = 0;
986
1.27k
    if (bits >= (int32_t)(2 * 8 * sizeof(int64_t)))
987
1.13k
    {
988
1.13k
        int64_t *lp;
989
        /*
990
         * Align to int64_t boundary and check int64_t words.
991
         */
992
1.52k
        while (!isAligned(bp, int64_t))
993
570
        {
994
570
            if (*bp != 0x00)
995
177
                return (span + zeroruns[*bp]);
996
393
            span += 8;
997
393
            bits -= 8;
998
393
            bp++;
999
393
        }
1000
954
        lp = (int64_t *)bp;
1001
20.9k
        while ((bits >= (int32_t)(size_t)(8 * sizeof(int64_t))) && (0 == *lp))
1002
19.9k
        {
1003
19.9k
            span += (int32_t)(size_t)(8 * sizeof(int64_t));
1004
19.9k
            bits -= (int32_t)(size_t)(8 * sizeof(int64_t));
1005
19.9k
            lp++;
1006
19.9k
        }
1007
954
        bp = (unsigned char *)lp;
1008
954
    }
1009
    /*
1010
     * Scan full bytes for all 0's.
1011
     */
1012
4.24k
    while (bits >= 8)
1013
3.32k
    {
1014
3.32k
        if (*bp != 0x00) /* end of run */
1015
167
            return (span + zeroruns[*bp]);
1016
3.15k
        span += 8;
1017
3.15k
        bits -= 8;
1018
3.15k
        bp++;
1019
3.15k
    }
1020
    /*
1021
     * Check partial byte on rhs.
1022
     */
1023
927
    if (bits > 0)
1024
918
    {
1025
918
        n = zeroruns[*bp];
1026
918
        span += (n > bits ? bits : n);
1027
918
    }
1028
927
    return (span);
1029
1.09k
}
1030
1031
static inline int32_t find1span(unsigned char *bp, int32_t bs, int32_t be)
1032
700
{
1033
700
    int32_t bits = be - bs;
1034
700
    int32_t n, span;
1035
1036
700
    bp += bs >> 3;
1037
    /*
1038
     * Check partial byte on lhs.
1039
     */
1040
700
    if (bits > 0 && (n = (bs & 7)) != 0)
1041
560
    {
1042
560
        span = oneruns[(*bp << n) & 0xff];
1043
560
        if (span > 8 - n) /* table value too generous */
1044
0
            span = 8 - n;
1045
560
        if (span > bits) /* constrain span to bit range */
1046
0
            span = bits;
1047
560
        if (n + span < 8) /* doesn't extend to edge of byte */
1048
261
            return (span);
1049
299
        bits -= span;
1050
299
        bp++;
1051
299
    }
1052
140
    else
1053
140
        span = 0;
1054
439
    if (bits >= (int32_t)(2 * 8 * sizeof(int64_t)))
1055
420
    {
1056
420
        int64_t *lp;
1057
        /*
1058
         * Align to int64_t boundary and check int64_t words.
1059
         */
1060
1.29k
        while (!isAligned(bp, int64_t))
1061
1.11k
        {
1062
1.11k
            if (*bp != 0xff)
1063
245
                return (span + oneruns[*bp]);
1064
874
            span += 8;
1065
874
            bits -= 8;
1066
874
            bp++;
1067
874
        }
1068
175
        lp = (int64_t *)bp;
1069
4.59k
        while ((bits >= (int32_t)(size_t)(8 * sizeof(int64_t))) &&
1070
4.41k
               (~((uint64_t)0) == (uint64_t)*lp))
1071
4.41k
        {
1072
4.41k
            span += (int32_t)(size_t)(8 * sizeof(int64_t));
1073
4.41k
            bits -= (int32_t)(size_t)(8 * sizeof(int64_t));
1074
4.41k
            lp++;
1075
4.41k
        }
1076
175
        bp = (unsigned char *)lp;
1077
175
    }
1078
    /*
1079
     * Scan full bytes for all 1's.
1080
     */
1081
904
    while (bits >= 8)
1082
718
    {
1083
718
        if (*bp != 0xff) /* end of run */
1084
8
            return (span + oneruns[*bp]);
1085
710
        span += 8;
1086
710
        bits -= 8;
1087
710
        bp++;
1088
710
    }
1089
    /*
1090
     * Check partial byte on rhs.
1091
     */
1092
186
    if (bits > 0)
1093
178
    {
1094
178
        n = oneruns[*bp];
1095
178
        span += (n > bits ? bits : n);
1096
178
    }
1097
186
    return (span);
1098
194
}
1099
1100
/*
1101
 * Return the offset of the next bit in the range
1102
 * [bs..be] that is different from the specified
1103
 * color.  The end, be, is returned if no such bit
1104
 * exists.
1105
 */
1106
#define finddiff(_cp, _bs, _be, _color)                                        \
1107
2.14k
    (_bs + (_color ? find1span(_cp, _bs, _be) : find0span(_cp, _bs, _be)))
1108
/*
1109
 * Like finddiff, but also check the starting bit
1110
 * against the end in case start > end.
1111
 */
1112
#define finddiff2(_cp, _bs, _be, _color)                                       \
1113
811
    (_bs < _be ? finddiff(_cp, _bs, _be, _color) : _be)
1114
1115
/*
1116
 * 1d-encode a row of pixels.  The encoding is
1117
 * a sequence of all-white or all-black spans
1118
 * of pixels encoded with Huffman codes.
1119
 */
1120
static int Fax3Encode1DRow(TIFF *tif, unsigned char *bp, uint32_t bits)
1121
0
{
1122
0
    Fax3CodecState *sp = EncoderState(tif);
1123
0
    int32_t span;
1124
0
    uint32_t bs = 0;
1125
1126
0
    for (;;)
1127
0
    {
1128
0
        span = find0span(bp, (int32_t)bs, (int32_t)bits); /* white span */
1129
0
        if (!putspan(tif, span, TIFFFaxWhiteCodes))
1130
0
            return 0;
1131
0
        bs += (uint32_t)span;
1132
0
        if (bs >= bits)
1133
0
            break;
1134
0
        span = find1span(bp, (int32_t)bs, (int32_t)bits); /* black span */
1135
0
        if (!putspan(tif, span, TIFFFaxBlackCodes))
1136
0
            return 0;
1137
0
        bs += (uint32_t)span;
1138
0
        if (bs >= bits)
1139
0
            break;
1140
0
    }
1141
0
    if (sp->b.mode & (FAXMODE_BYTEALIGN | FAXMODE_WORDALIGN))
1142
0
    {
1143
0
        if (sp->bit != 8) /* byte-align */
1144
0
            Fax3FlushBits(tif, sp);
1145
0
        if ((sp->b.mode & FAXMODE_WORDALIGN) &&
1146
0
            !isAligned(tif->tif_rawcp, uint16_t))
1147
0
            Fax3FlushBits(tif, sp);
1148
0
    }
1149
0
    return (1);
1150
0
}
1151
1152
static const tableentry horizcode = {3, 0x1, 0}; /* 001 */
1153
static const tableentry passcode = {4, 0x1, 0};  /* 0001 */
1154
static const tableentry vcodes[7] = {
1155
    {7, 0x03, 0}, /* 0000 011 */
1156
    {6, 0x03, 0}, /* 0000 11 */
1157
    {3, 0x03, 0}, /* 011 */
1158
    {1, 0x1, 0},  /* 1 */
1159
    {3, 0x2, 0},  /* 010 */
1160
    {6, 0x02, 0}, /* 0000 10 */
1161
    {7, 0x02, 0}  /* 0000 010 */
1162
};
1163
1164
/*
1165
 * 2d-encode a row of pixels.  Consult the CCITT
1166
 * documentation for the algorithm.
1167
 */
1168
static int Fax3Encode2DRow(TIFF *tif, unsigned char *bp, unsigned char *rp,
1169
                           uint32_t bits)
1170
509
{
1171
1.04k
#define PIXEL(buf, ix) ((((buf)[(ix) >> 3]) >> (7 - ((ix) & 7))) & 1)
1172
509
    uint32_t a0 = 0;
1173
509
    uint32_t a1 = (PIXEL(bp, 0) != 0
1174
509
                       ? 0
1175
509
                       : (uint32_t)finddiff(bp, (int32_t)0, (int32_t)bits, 0));
1176
509
    uint32_t b1 = (PIXEL(rp, 0) != 0
1177
509
                       ? 0
1178
509
                       : (uint32_t)finddiff(rp, (int32_t)0, (int32_t)bits, 0));
1179
509
    uint32_t a2, b2;
1180
1181
509
    for (;;)
1182
787
    {
1183
787
        b2 = (uint32_t)finddiff2(rp, (int32_t)b1, (int32_t)bits,
1184
787
                                 (int32_t)PIXEL(rp, b1));
1185
787
        if (b2 >= a1)
1186
785
        {
1187
            /* Naive computation triggers
1188
             * -fsanitize=undefined,unsigned-integer-overflow */
1189
            /* although it is correct unless the difference between both is < 31
1190
             * bit */
1191
            /* int32_t d = b1 - a1; */
1192
785
            int32_t d = (b1 >= a1 && b1 - a1 <= 3U)  ? (int32_t)(b1 - a1)
1193
785
                        : (b1 < a1 && a1 - b1 <= 3U) ? -(int32_t)(a1 - b1)
1194
31
                                                     : 0x7FFFFFFF;
1195
785
            if (!(-3 <= d && d <= 3))
1196
24
            { /* horizontal mode */
1197
24
                a2 = (uint32_t)finddiff2(bp, (int32_t)a1, (int32_t)bits,
1198
24
                                         (int32_t)PIXEL(bp, a1));
1199
24
                if (!putcode(tif, &horizcode))
1200
0
                    return 0;
1201
24
                if (a0 + a1 == 0 || PIXEL(bp, a0) == 0)
1202
21
                {
1203
21
                    if (!putspan(tif, (int32_t)(a1 - a0), TIFFFaxWhiteCodes))
1204
0
                        return 0;
1205
21
                    if (!putspan(tif, (int32_t)(a2 - a1), TIFFFaxBlackCodes))
1206
0
                        return 0;
1207
21
                }
1208
3
                else
1209
3
                {
1210
3
                    if (!putspan(tif, (int32_t)(a1 - a0), TIFFFaxBlackCodes))
1211
0
                        return 0;
1212
3
                    if (!putspan(tif, (int32_t)(a2 - a1), TIFFFaxWhiteCodes))
1213
0
                        return 0;
1214
3
                }
1215
24
                a0 = a2;
1216
24
            }
1217
761
            else
1218
761
            { /* vertical mode */
1219
761
                if (!putcode(tif, &vcodes[d + 3]))
1220
0
                    return 0;
1221
761
                a0 = a1;
1222
761
            }
1223
785
        }
1224
2
        else
1225
2
        { /* pass mode */
1226
2
            if (!putcode(tif, &passcode))
1227
0
                return 0;
1228
2
            a0 = b2;
1229
2
        }
1230
787
        if (a0 >= bits)
1231
509
            break;
1232
278
        a1 = (uint32_t)finddiff(bp, (int32_t)a0, (int32_t)bits,
1233
278
                                (int32_t)PIXEL(bp, a0));
1234
278
        b1 = (uint32_t)finddiff(rp, (int32_t)a0, (int32_t)bits,
1235
278
                                (int32_t)!PIXEL(bp, a0));
1236
278
        b1 = (uint32_t)finddiff(rp, (int32_t)b1, (int32_t)bits,
1237
278
                                (int32_t)PIXEL(bp, a0));
1238
278
    }
1239
509
    return (1);
1240
509
#undef PIXEL
1241
509
}
1242
1243
/*
1244
 * Encode a buffer of pixels.
1245
 */
1246
static int Fax3Encode(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
1247
0
{
1248
0
    static const char module[] = "Fax3Encode";
1249
0
    Fax3CodecState *sp = EncoderState(tif);
1250
0
    (void)s;
1251
0
    if (cc % sp->b.rowbytes)
1252
0
    {
1253
0
        TIFFErrorExtR(tif, module, "Fractional scanlines cannot be written");
1254
0
        return (0);
1255
0
    }
1256
0
    while (cc > 0)
1257
0
    {
1258
0
        if ((sp->b.mode & FAXMODE_NOEOL) == 0)
1259
0
        {
1260
0
            if (!Fax3PutEOL(tif))
1261
0
                return 0;
1262
0
        }
1263
0
        if (is2DEncoding(sp))
1264
0
        {
1265
0
            if (sp->tag == G3_1D)
1266
0
            {
1267
0
                if (!Fax3Encode1DRow(tif, bp, sp->b.rowpixels))
1268
0
                    return (0);
1269
0
                sp->tag = G3_2D;
1270
0
            }
1271
0
            else
1272
0
            {
1273
0
                if (!Fax3Encode2DRow(tif, bp, sp->refline, sp->b.rowpixels))
1274
0
                    return (0);
1275
0
                sp->k--;
1276
0
            }
1277
0
            if (sp->k == 0)
1278
0
            {
1279
0
                sp->tag = G3_1D;
1280
0
                sp->k = sp->maxk - 1;
1281
0
            }
1282
0
            else
1283
0
                _TIFFmemcpy(sp->refline, bp, sp->b.rowbytes);
1284
0
        }
1285
0
        else
1286
0
        {
1287
0
            if (!Fax3Encode1DRow(tif, bp, sp->b.rowpixels))
1288
0
                return (0);
1289
0
        }
1290
0
        bp += sp->b.rowbytes;
1291
0
        cc -= sp->b.rowbytes;
1292
0
    }
1293
0
    return (1);
1294
0
}
1295
1296
static int Fax3PostEncode(TIFF *tif)
1297
0
{
1298
0
    Fax3CodecState *sp = EncoderState(tif);
1299
1300
0
    if (sp->bit != 8)
1301
0
        Fax3FlushBits(tif, sp);
1302
0
    return (1);
1303
0
}
1304
1305
static int _Fax3Close(TIFF *tif)
1306
82
{
1307
82
    if ((Fax3State(tif)->mode & FAXMODE_NORTC) == 0 && tif->tif_rawcp)
1308
0
    {
1309
0
        Fax3CodecState *sp = EncoderState(tif);
1310
0
        unsigned int code = EOL;
1311
0
        unsigned int length = 12;
1312
0
        int i;
1313
1314
0
        if (is2DEncoding(sp))
1315
0
        {
1316
0
            code = (code << 1) | (sp->tag == G3_1D);
1317
0
            length++;
1318
0
        }
1319
0
        for (i = 0; i < 6; i++)
1320
0
            Fax3PutBits(tif, code, length);
1321
0
        Fax3FlushBits(tif, sp);
1322
0
    }
1323
82
    return 1;
1324
82
}
1325
1326
82
static void Fax3Close(TIFF *tif) { _Fax3Close(tif); }
1327
1328
static void Fax3Cleanup(TIFF *tif)
1329
9.50k
{
1330
9.50k
    Fax3CodecState *sp = DecoderState(tif);
1331
1332
9.50k
    assert(sp != 0);
1333
1334
9.50k
    tif->tif_tagmethods.vgetfield = sp->b.vgetparent;
1335
9.50k
    tif->tif_tagmethods.vsetfield = sp->b.vsetparent;
1336
9.50k
    tif->tif_tagmethods.printdir = sp->b.printdir;
1337
1338
9.50k
    if (sp->runs)
1339
4.23k
        _TIFFfreeExt(tif, sp->runs);
1340
9.50k
    if (sp->refline)
1341
2.74k
        _TIFFfreeExt(tif, sp->refline);
1342
1343
9.50k
    _TIFFfreeExt(tif, tif->tif_data);
1344
9.50k
    tif->tif_data = NULL;
1345
1346
9.50k
    _TIFFSetDefaultCompressionState(tif);
1347
9.50k
}
1348
1349
#define FIELD_BADFAXLINES (FIELD_CODEC + 0)
1350
#define FIELD_CLEANFAXDATA (FIELD_CODEC + 1)
1351
#define FIELD_BADFAXRUN (FIELD_CODEC + 2)
1352
1353
#define FIELD_OPTIONS (FIELD_CODEC + 7)
1354
1355
static const TIFFField faxFields[] = {
1356
    {TIFFTAG_FAXMODE, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, FIELD_PSEUDO, FALSE,
1357
     FALSE, "FaxMode", NULL},
1358
    {TIFFTAG_FAXFILLFUNC, 0, 0, TIFF_ANY, 0, TIFF_SETGET_OTHER, FIELD_PSEUDO,
1359
     FALSE, FALSE, "FaxFillFunc", NULL},
1360
    {TIFFTAG_BADFAXLINES, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32,
1361
     FIELD_BADFAXLINES, TRUE, FALSE, "BadFaxLines", NULL},
1362
    {TIFFTAG_CLEANFAXDATA, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16,
1363
     FIELD_CLEANFAXDATA, TRUE, FALSE, "CleanFaxData", NULL},
1364
    {TIFFTAG_CONSECUTIVEBADFAXLINES, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32,
1365
     FIELD_BADFAXRUN, TRUE, FALSE, "ConsecutiveBadFaxLines", NULL}};
1366
static const TIFFField fax3Fields[] = {
1367
    {TIFFTAG_GROUP3OPTIONS, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32,
1368
     FIELD_OPTIONS, FALSE, FALSE, "Group3Options", NULL},
1369
};
1370
static const TIFFField fax4Fields[] = {
1371
    {TIFFTAG_GROUP4OPTIONS, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32,
1372
     FIELD_OPTIONS, FALSE, FALSE, "Group4Options", NULL},
1373
};
1374
1375
static int Fax3VSetField(TIFF *tif, uint32_t tag, va_list ap)
1376
86.7k
{
1377
86.7k
    Fax3BaseState *sp = Fax3State(tif);
1378
86.7k
    const TIFFField *fip;
1379
1380
86.7k
    assert(sp != 0);
1381
86.7k
    assert(sp->vsetparent != 0);
1382
1383
86.7k
    switch (tag)
1384
86.7k
    {
1385
9.50k
        case TIFFTAG_FAXMODE:
1386
9.50k
            sp->mode = (int)va_arg(ap, int);
1387
9.50k
            return 1; /* NB: pseudo tag */
1388
9.50k
        case TIFFTAG_FAXFILLFUNC:
1389
9.50k
            DecoderState(tif)->fill = va_arg(ap, TIFFFaxFillFunc);
1390
9.50k
            return 1; /* NB: pseudo tag */
1391
1.93k
        case TIFFTAG_GROUP3OPTIONS:
1392
            /* XXX: avoid reading options if compression mismatches. */
1393
1.93k
            if (tif->tif_dir.td_compression == COMPRESSION_CCITTFAX3)
1394
1.93k
                sp->groupoptions = (uint32_t)va_arg(ap, uint32_t);
1395
1.93k
            break;
1396
61
        case TIFFTAG_GROUP4OPTIONS:
1397
            /* XXX: avoid reading options if compression mismatches. */
1398
61
            if (tif->tif_dir.td_compression == COMPRESSION_CCITTFAX4)
1399
61
                sp->groupoptions = (uint32_t)va_arg(ap, uint32_t);
1400
61
            break;
1401
144
        case TIFFTAG_BADFAXLINES:
1402
144
            sp->badfaxlines = (uint32_t)va_arg(ap, uint32_t);
1403
144
            break;
1404
102
        case TIFFTAG_CLEANFAXDATA:
1405
102
            sp->cleanfaxdata = (uint16_t)va_arg(ap, uint16_vap);
1406
102
            break;
1407
66
        case TIFFTAG_CONSECUTIVEBADFAXLINES:
1408
66
            sp->badfaxrun = (uint32_t)va_arg(ap, uint32_t);
1409
66
            break;
1410
65.4k
        default:
1411
65.4k
            return (*sp->vsetparent)(tif, tag, ap);
1412
86.7k
    }
1413
1414
2.30k
    if ((fip = TIFFFieldWithTag(tif, tag)) != NULL)
1415
2.30k
        TIFFSetFieldBit(tif, fip->field_bit);
1416
0
    else
1417
0
        return 0;
1418
1419
2.30k
    tif->tif_flags |= TIFF_DIRTYDIRECT;
1420
2.30k
    return 1;
1421
2.30k
}
1422
1423
static int Fax3VGetField(TIFF *tif, uint32_t tag, va_list ap)
1424
130k
{
1425
130k
    Fax3BaseState *sp = Fax3State(tif);
1426
1427
130k
    assert(sp != 0);
1428
1429
130k
    switch (tag)
1430
130k
    {
1431
0
        case TIFFTAG_FAXMODE:
1432
0
            *va_arg(ap, int *) = sp->mode;
1433
0
            break;
1434
0
        case TIFFTAG_FAXFILLFUNC:
1435
0
            *va_arg(ap, TIFFFaxFillFunc *) = DecoderState(tif)->fill;
1436
0
            break;
1437
0
        case TIFFTAG_GROUP3OPTIONS:
1438
0
        case TIFFTAG_GROUP4OPTIONS:
1439
0
            *va_arg(ap, uint32_t *) = sp->groupoptions;
1440
0
            break;
1441
0
        case TIFFTAG_BADFAXLINES:
1442
0
            *va_arg(ap, uint32_t *) = sp->badfaxlines;
1443
0
            break;
1444
0
        case TIFFTAG_CLEANFAXDATA:
1445
0
            *va_arg(ap, uint16_t *) = sp->cleanfaxdata;
1446
0
            break;
1447
0
        case TIFFTAG_CONSECUTIVEBADFAXLINES:
1448
0
            *va_arg(ap, uint32_t *) = sp->badfaxrun;
1449
0
            break;
1450
130k
        default:
1451
130k
            return (*sp->vgetparent)(tif, tag, ap);
1452
130k
    }
1453
0
    return (1);
1454
130k
}
1455
1456
static void Fax3PrintDir(TIFF *tif, FILE *fd, long flags)
1457
0
{
1458
0
    Fax3BaseState *sp = Fax3State(tif);
1459
1460
0
    assert(sp != 0);
1461
1462
0
    (void)flags;
1463
0
    if (TIFFFieldSet(tif, FIELD_OPTIONS))
1464
0
    {
1465
0
        const char *sep = " ";
1466
0
        if (tif->tif_dir.td_compression == COMPRESSION_CCITTFAX4)
1467
0
        {
1468
0
            fprintf(fd, "  Group 4 Options:");
1469
0
            if (sp->groupoptions & GROUP4OPT_UNCOMPRESSED)
1470
0
                fprintf(fd, "%suncompressed data", sep);
1471
0
        }
1472
0
        else
1473
0
        {
1474
1475
0
            fprintf(fd, "  Group 3 Options:");
1476
0
            if (sp->groupoptions & GROUP3OPT_2DENCODING)
1477
0
            {
1478
0
                fprintf(fd, "%s2-d encoding", sep);
1479
0
                sep = "+";
1480
0
            }
1481
0
            if (sp->groupoptions & GROUP3OPT_FILLBITS)
1482
0
            {
1483
0
                fprintf(fd, "%sEOL padding", sep);
1484
0
                sep = "+";
1485
0
            }
1486
0
            if (sp->groupoptions & GROUP3OPT_UNCOMPRESSED)
1487
0
                fprintf(fd, "%suncompressed data", sep);
1488
0
        }
1489
0
        fprintf(fd, " (%" PRIu32 " = 0x%" PRIx32 ")\n", sp->groupoptions,
1490
0
                sp->groupoptions);
1491
0
    }
1492
0
    if (TIFFFieldSet(tif, FIELD_CLEANFAXDATA))
1493
0
    {
1494
0
        fprintf(fd, "  Fax Data:");
1495
0
        switch (sp->cleanfaxdata)
1496
0
        {
1497
0
            case CLEANFAXDATA_CLEAN:
1498
0
                fprintf(fd, " clean");
1499
0
                break;
1500
0
            case CLEANFAXDATA_REGENERATED:
1501
0
                fprintf(fd, " receiver regenerated");
1502
0
                break;
1503
0
            case CLEANFAXDATA_UNCLEAN:
1504
0
                fprintf(fd, " uncorrected errors");
1505
0
                break;
1506
0
            default:
1507
0
                break;
1508
0
        }
1509
0
        fprintf(fd, " (%" PRIu16 " = 0x%" PRIx16 ")\n", sp->cleanfaxdata,
1510
0
                sp->cleanfaxdata);
1511
0
    }
1512
0
    if (TIFFFieldSet(tif, FIELD_BADFAXLINES))
1513
0
        fprintf(fd, "  Bad Fax Lines: %" PRIu32 "\n", sp->badfaxlines);
1514
0
    if (TIFFFieldSet(tif, FIELD_BADFAXRUN))
1515
0
        fprintf(fd, "  Consecutive Bad Fax Lines: %" PRIu32 "\n",
1516
0
                sp->badfaxrun);
1517
0
    if (sp->printdir)
1518
0
        (*sp->printdir)(tif, fd, flags);
1519
0
}
1520
1521
static uint64_t Fax3GetMaxCompressionRatio(TIFF *tif)
1522
0
{
1523
0
    (void)tif;
1524
1525
    /* See README_for_libtiff_developpers.md for raw data used to estimate
1526
     * the maximum compression rate. */
1527
1528
    /* 1024x1024: 36 */
1529
    /* 4096x4096: 100 */
1530
    /* 16383x16383: 163 */
1531
    /* 65536x65536: 200 */
1532
    /* 200000x200000: 208 */
1533
1534
0
    return 250;
1535
0
}
1536
1537
static int InitCCITTFax3(TIFF *tif)
1538
9.50k
{
1539
9.50k
    static const char module[] = "InitCCITTFax3";
1540
9.50k
    Fax3BaseState *sp;
1541
1542
    /*
1543
     * Merge codec-specific tag information.
1544
     */
1545
9.50k
    if (!_TIFFMergeFields(tif, faxFields, TIFFArrayCount(faxFields)))
1546
0
    {
1547
0
        TIFFErrorExtR(tif, "InitCCITTFax3",
1548
0
                      "Merging common CCITT Fax codec-specific tags failed");
1549
0
        return 0;
1550
0
    }
1551
1552
    /*
1553
     * Allocate state block so tag methods have storage to record values.
1554
     */
1555
9.50k
    tif->tif_data = (uint8_t *)_TIFFmallocExt(tif, sizeof(Fax3CodecState));
1556
1557
9.50k
    if (tif->tif_data == NULL)
1558
0
    {
1559
0
        TIFFErrorExtR(tif, module, "No space for state block");
1560
0
        return (0);
1561
0
    }
1562
9.50k
    _TIFFmemset(tif->tif_data, 0, sizeof(Fax3CodecState));
1563
1564
9.50k
    sp = Fax3State(tif);
1565
9.50k
    sp->rw_mode = tif->tif_mode;
1566
1567
    /*
1568
     * Override parent get/set field methods.
1569
     */
1570
9.50k
    sp->vgetparent = tif->tif_tagmethods.vgetfield;
1571
9.50k
    tif->tif_tagmethods.vgetfield = Fax3VGetField; /* hook for codec tags */
1572
9.50k
    sp->vsetparent = tif->tif_tagmethods.vsetfield;
1573
9.50k
    tif->tif_tagmethods.vsetfield = Fax3VSetField; /* hook for codec tags */
1574
9.50k
    sp->printdir = tif->tif_tagmethods.printdir;
1575
9.50k
    tif->tif_tagmethods.printdir = Fax3PrintDir; /* hook for codec tags */
1576
9.50k
    sp->groupoptions = 0;
1577
1578
9.50k
    if (sp->rw_mode == O_RDONLY) /* FIXME: improve for in place update */
1579
9.42k
        tif->tif_flags |= TIFF_NOBITREV; /* decoder does bit reversal */
1580
9.50k
    DecoderState(tif)->runs = NULL;
1581
9.50k
    TIFFSetField(tif, TIFFTAG_FAXFILLFUNC, _TIFFFax3fillruns);
1582
9.50k
    EncoderState(tif)->refline = NULL;
1583
1584
    /*
1585
     * Install codec methods.
1586
     */
1587
9.50k
    tif->tif_fixuptags = Fax3FixupTags;
1588
9.50k
    tif->tif_setupdecode = Fax3SetupState;
1589
9.50k
    tif->tif_predecode = Fax3PreDecode;
1590
9.50k
    tif->tif_decoderow = Fax3Decode1D;
1591
9.50k
    tif->tif_decodestrip = Fax3Decode1D;
1592
9.50k
    tif->tif_decodetile = Fax3Decode1D;
1593
9.50k
    tif->tif_setupencode = Fax3SetupState;
1594
9.50k
    tif->tif_preencode = Fax3PreEncode;
1595
9.50k
    tif->tif_postencode = Fax3PostEncode;
1596
9.50k
    tif->tif_encoderow = Fax3Encode;
1597
9.50k
    tif->tif_encodestrip = Fax3Encode;
1598
9.50k
    tif->tif_encodetile = Fax3Encode;
1599
9.50k
    tif->tif_close = Fax3Close;
1600
9.50k
    tif->tif_cleanup = Fax3Cleanup;
1601
9.50k
    tif->tif_getmaxcompressionratio = Fax3GetMaxCompressionRatio;
1602
1603
9.50k
    return (1);
1604
9.50k
}
1605
1606
int TIFFInitCCITTFax3(TIFF *tif, int scheme)
1607
5.62k
{
1608
5.62k
    (void)scheme;
1609
5.62k
    if (InitCCITTFax3(tif))
1610
5.62k
    {
1611
        /*
1612
         * Merge codec-specific tag information.
1613
         */
1614
5.62k
        if (!_TIFFMergeFields(tif, fax3Fields, TIFFArrayCount(fax3Fields)))
1615
0
        {
1616
0
            TIFFErrorExtR(tif, "TIFFInitCCITTFax3",
1617
0
                          "Merging CCITT Fax 3 codec-specific tags failed");
1618
0
            return 0;
1619
0
        }
1620
1621
        /*
1622
         * The default format is Class/F-style w/o RTC.
1623
         */
1624
5.62k
        return TIFFSetField(tif, TIFFTAG_FAXMODE, FAXMODE_CLASSF);
1625
5.62k
    }
1626
0
    else
1627
0
        return 01;
1628
5.62k
}
1629
1630
/*
1631
 * CCITT Group 4 (T.6) Facsimile-compatible
1632
 * Compression Scheme Support.
1633
 */
1634
1635
#define SWAP(t, a, b)                                                          \
1636
1.23M
    {                                                                          \
1637
1.23M
        t x;                                                                   \
1638
1.23M
        x = (a);                                                               \
1639
1.23M
        (a) = (b);                                                             \
1640
1.23M
        (b) = x;                                                               \
1641
1.23M
    }
1642
/*
1643
 * Decode the requested amount of G4-encoded data.
1644
 */
1645
static int Fax4Decode(TIFF *tif, uint8_t *buf, tmsize_t occ, uint16_t s)
1646
52.2k
{
1647
52.2k
    DECLARE_STATE_2D(tif, sp, "Fax4Decode");
1648
52.2k
    (void)s;
1649
52.2k
    if (occ % sp->b.rowbytes)
1650
0
    {
1651
0
        TIFFErrorExtR(tif, module, "Fractional scanlines cannot be read");
1652
0
        return (-1);
1653
0
    }
1654
52.2k
    if (CheckReachedCounters(tif, module, sp))
1655
0
        return (-1);
1656
52.2k
    CACHE_STATE(tif, sp);
1657
52.2k
    int start = sp->line;
1658
1.28M
    while (occ > 0)
1659
1.28M
    {
1660
1.28M
        a0 = 0;
1661
1.28M
        RunLength = 0;
1662
1.28M
        pa = thisrun = sp->curruns;
1663
1.28M
        pb = sp->refruns;
1664
1.28M
        b1 = (int)*pb++;
1665
#ifdef FAX3_DEBUG
1666
        printf("\nBitAcc=%08" PRIX32 ", BitsAvail = %d\n", BitAcc, BitsAvail);
1667
        printf("-------------------- %d\n", tif->tif_dir.td_row);
1668
        fflush(stdout);
1669
#endif
1670
1.28M
        EXPAND2D(EOFG4);
1671
1.27M
        if (EOLcnt)
1672
38.8k
            goto EOFG4;
1673
1.23M
        if (((lastx + 7) >> 3) > (int)occ) /* check for buffer overrun */
1674
0
        {
1675
0
            TIFFErrorExtR(tif, module,
1676
0
                          "Buffer overrun detected : %" TIFF_SSIZE_FORMAT
1677
0
                          " bytes available, %d bits needed",
1678
0
                          occ, lastx);
1679
0
            return -1;
1680
0
        }
1681
1.23M
        (*sp->fill)(buf, thisrun, pa, (uint32_t)lastx);
1682
1.23M
        SETVALUE(0); /* imaginary change for reference */
1683
1.23M
        SWAP(uint32_t *, sp->curruns, sp->refruns);
1684
1.23M
        buf += sp->b.rowbytes;
1685
1.23M
        occ -= sp->b.rowbytes;
1686
1.23M
        sp->line++;
1687
1.23M
        continue;
1688
46.3k
    EOFG4:
1689
46.3k
        NeedBits16(13, BADG4);
1690
46.3k
    BADG4:
1691
#ifdef FAX3_DEBUG
1692
        if (GetBits(13) != 0x1001)
1693
            fputs("Bad EOFB\n", stderr);
1694
#endif
1695
46.3k
        ClrBits(13);
1696
46.3k
        if (((lastx + 7) >> 3) > (int)occ) /* check for buffer overrun */
1697
0
        {
1698
0
            TIFFErrorExtR(tif, module,
1699
0
                          "Buffer overrun detected : %" TIFF_SSIZE_FORMAT
1700
0
                          " bytes available, %d bits needed",
1701
0
                          occ, lastx);
1702
0
            return -1;
1703
0
        }
1704
46.3k
        (*sp->fill)(buf, thisrun, pa, (uint32_t)lastx);
1705
46.3k
        UNCACHE_STATE(tif, sp);
1706
46.3k
        return (sp->line != start
1707
46.3k
                    ? 1
1708
46.3k
                    : -1); /* don't error on badly-terminated strips */
1709
46.3k
    }
1710
5.07k
    UNCACHE_STATE(tif, sp);
1711
5.07k
    return (1);
1712
52.2k
}
1713
#undef SWAP
1714
1715
/*
1716
 * Encode the requested amount of data.
1717
 */
1718
static int Fax4Encode(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
1719
509
{
1720
509
    static const char module[] = "Fax4Encode";
1721
509
    Fax3CodecState *sp = EncoderState(tif);
1722
509
    (void)s;
1723
509
    if (cc % sp->b.rowbytes)
1724
0
    {
1725
0
        TIFFErrorExtR(tif, module, "Fractional scanlines cannot be written");
1726
0
        return (0);
1727
0
    }
1728
1.01k
    while (cc > 0)
1729
509
    {
1730
509
        if (!Fax3Encode2DRow(tif, bp, sp->refline, sp->b.rowpixels))
1731
0
            return (0);
1732
509
        _TIFFmemcpy(sp->refline, bp, sp->b.rowbytes);
1733
509
        bp += sp->b.rowbytes;
1734
509
        cc -= sp->b.rowbytes;
1735
509
    }
1736
509
    return (1);
1737
509
}
1738
1739
static int Fax4PostEncode(TIFF *tif)
1740
18
{
1741
18
    Fax3CodecState *sp = EncoderState(tif);
1742
1743
    /* terminate strip w/ EOFB */
1744
18
    Fax3PutBits(tif, EOL, 12);
1745
18
    Fax3PutBits(tif, EOL, 12);
1746
18
    if (sp->bit != 8)
1747
18
        Fax3FlushBits(tif, sp);
1748
18
    return (1);
1749
18
}
1750
1751
static uint64_t Fax4GetMaxCompressionRatio(TIFF *tif)
1752
0
{
1753
    /* FAX4 can compress up to almost one byte per line, so the compression
1754
     * ratio can be up to the tile/strip width.
1755
     * See README_for_libtiff_developpers.md for raw data
1756
     */
1757
0
    return isTiled(tif) ? tif->tif_dir.td_tilewidth
1758
0
                        : tif->tif_dir.td_imagewidth;
1759
0
}
1760
1761
int TIFFInitCCITTFax4(TIFF *tif, int scheme)
1762
2.82k
{
1763
2.82k
    (void)scheme;
1764
2.82k
    if (InitCCITTFax3(tif))
1765
2.82k
    { /* reuse G3 support */
1766
        /*
1767
         * Merge codec-specific tag information.
1768
         */
1769
2.82k
        if (!_TIFFMergeFields(tif, fax4Fields, TIFFArrayCount(fax4Fields)))
1770
0
        {
1771
0
            TIFFErrorExtR(tif, "TIFFInitCCITTFax4",
1772
0
                          "Merging CCITT Fax 4 codec-specific tags failed");
1773
0
            return 0;
1774
0
        }
1775
1776
2.82k
        tif->tif_decoderow = Fax4Decode;
1777
2.82k
        tif->tif_decodestrip = Fax4Decode;
1778
2.82k
        tif->tif_decodetile = Fax4Decode;
1779
2.82k
        tif->tif_encoderow = Fax4Encode;
1780
2.82k
        tif->tif_encodestrip = Fax4Encode;
1781
2.82k
        tif->tif_encodetile = Fax4Encode;
1782
2.82k
        tif->tif_postencode = Fax4PostEncode;
1783
2.82k
        tif->tif_getmaxcompressionratio = Fax4GetMaxCompressionRatio;
1784
        /*
1785
         * Suppress RTC at the end of each strip.
1786
         */
1787
2.82k
        return TIFFSetField(tif, TIFFTAG_FAXMODE, FAXMODE_NORTC);
1788
2.82k
    }
1789
0
    else
1790
0
        return (0);
1791
2.82k
}
1792
1793
/*
1794
 * CCITT Group 3 1-D Modified Huffman RLE Compression Support.
1795
 * (Compression algorithms 2 and 32771)
1796
 */
1797
1798
/*
1799
 * Decode the requested amount of RLE-encoded data.
1800
 */
1801
static int Fax3DecodeRLE(TIFF *tif, uint8_t *buf, tmsize_t occ, uint16_t s)
1802
9.53k
{
1803
9.53k
    DECLARE_STATE(tif, sp, "Fax3DecodeRLE");
1804
9.53k
    int mode = sp->b.mode;
1805
9.53k
    (void)s;
1806
9.53k
    if (occ % sp->b.rowbytes)
1807
0
    {
1808
0
        TIFFErrorExtR(tif, module, "Fractional scanlines cannot be read");
1809
0
        return (-1);
1810
0
    }
1811
9.53k
    if (CheckReachedCounters(tif, module, sp))
1812
0
        return (-1);
1813
9.53k
    CACHE_STATE(tif, sp);
1814
9.53k
    thisrun = sp->curruns;
1815
533k
    while (occ > 0)
1816
528k
    {
1817
528k
        a0 = 0;
1818
528k
        RunLength = 0;
1819
528k
        pa = thisrun;
1820
#ifdef FAX3_DEBUG
1821
        printf("\nBitAcc=%08" PRIX32 ", BitsAvail = %d\n", BitAcc, BitsAvail);
1822
        printf("-------------------- %" PRIu32 "\n", tif->tif_dir.td_row);
1823
        fflush(stdout);
1824
#endif
1825
528k
        EXPAND1D(EOFRLE);
1826
524k
        (*sp->fill)(buf, thisrun, pa, (uint32_t)lastx);
1827
        /*
1828
         * Cleanup at the end of the row.
1829
         */
1830
524k
        if (mode & FAXMODE_BYTEALIGN)
1831
457k
        {
1832
457k
            int n = BitsAvail - (BitsAvail & ~7);
1833
457k
            ClrBits(n);
1834
457k
        }
1835
67.2k
        else if (mode & FAXMODE_WORDALIGN)
1836
67.2k
        {
1837
67.2k
            int n = BitsAvail - (BitsAvail & ~15);
1838
67.2k
            ClrBits(n);
1839
67.2k
            if (BitsAvail == 0 && !isAligned(cp, uint16_t))
1840
13.5k
                cp++;
1841
67.2k
        }
1842
524k
        buf += sp->b.rowbytes;
1843
524k
        occ -= sp->b.rowbytes;
1844
524k
        sp->line++;
1845
524k
        continue;
1846
4.16k
    EOFRLE: /* premature EOF */
1847
4.16k
        (*sp->fill)(buf, thisrun, pa, (uint32_t)lastx);
1848
4.16k
        UNCACHE_STATE(tif, sp);
1849
4.16k
        return (-1);
1850
528k
    }
1851
5.37k
    UNCACHE_STATE(tif, sp);
1852
5.37k
    return (1);
1853
9.53k
}
1854
1855
static uint64_t Fax3RLEGetMaxCompressionRatio(TIFF *tif)
1856
5
{
1857
5
    (void)tif;
1858
    /* See README_for_libtiff_developpers.md for raw data used to estimate
1859
     * the maximum compression rate. */
1860
1861
    /* 1024x1024: 43 */
1862
    /* 4096x4096: 128 */
1863
    /* 16383x16383: 171 */
1864
    /* 65536x65536: 205 */
1865
    /* 200000x200000: 211 */
1866
1867
5
    return 250;
1868
5
}
1869
1870
int TIFFInitCCITTRLE(TIFF *tif, int scheme)
1871
629
{
1872
629
    (void)scheme;
1873
629
    if (InitCCITTFax3(tif))
1874
629
    { /* reuse G3 support */
1875
629
        tif->tif_decoderow = Fax3DecodeRLE;
1876
629
        tif->tif_decodestrip = Fax3DecodeRLE;
1877
629
        tif->tif_decodetile = Fax3DecodeRLE;
1878
629
        tif->tif_getmaxcompressionratio = Fax3RLEGetMaxCompressionRatio;
1879
        /*
1880
         * Suppress RTC+EOLs when encoding and byte-align data.
1881
         */
1882
629
        return TIFFSetField(tif, TIFFTAG_FAXMODE,
1883
629
                            FAXMODE_NORTC | FAXMODE_NOEOL | FAXMODE_BYTEALIGN);
1884
629
    }
1885
0
    else
1886
0
        return (0);
1887
629
}
1888
1889
int TIFFInitCCITTRLEW(TIFF *tif, int scheme)
1890
427
{
1891
427
    (void)scheme;
1892
427
    if (InitCCITTFax3(tif))
1893
427
    { /* reuse G3 support */
1894
427
        tif->tif_decoderow = Fax3DecodeRLE;
1895
427
        tif->tif_decodestrip = Fax3DecodeRLE;
1896
427
        tif->tif_decodetile = Fax3DecodeRLE;
1897
427
        tif->tif_getmaxcompressionratio = Fax3RLEGetMaxCompressionRatio;
1898
        /*
1899
         * Suppress RTC+EOLs when encoding and word-align data.
1900
         */
1901
427
        return TIFFSetField(tif, TIFFTAG_FAXMODE,
1902
427
                            FAXMODE_NORTC | FAXMODE_NOEOL | FAXMODE_WORDALIGN);
1903
427
    }
1904
0
    else
1905
0
        return (0);
1906
427
}
1907
#endif /* CCITT_SUPPORT */