Coverage Report

Created: 2026-07-25 07:06

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
3.32M
#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
25.3M
#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
1.25M
#define DecoderState(tif) ((Fax3CodecState *)Fax3State(tif))
109
23.5M
#define EncoderState(tif) ((Fax3CodecState *)Fax3State(tif))
110
111
2.17M
#define is2DEncoding(sp) (sp->b.groupoptions & GROUP3OPT_2DENCODING)
112
51.0M
#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
1.10M
    static const char module[] = mod;                                          \
124
1.10M
    Fax3CodecState *sp = DecoderState(tif);                                    \
125
1.10M
    int a0;                                   /* reference element */          \
126
1.10M
    int lastx = (int)sp->b.rowpixels;         /* last element in row */        \
127
1.10M
    uint32_t BitAcc;                          /* bit accumulator */            \
128
1.10M
    int BitsAvail;                            /* # valid bits in BitAcc */     \
129
1.10M
    int RunLength;                            /* length of current run */      \
130
1.10M
    unsigned char *cp;                        /* next byte of input data */    \
131
1.10M
    unsigned char *ep;                        /* end of input data */          \
132
1.10M
    uint32_t *pa;                             /* place to stuff next run */    \
133
1.10M
    uint32_t *thisrun;                        /* current row's run array */    \
134
1.10M
    int EOLcnt;                               /* # EOL codes recognized */     \
135
1.10M
    const unsigned char *bitmap = sp->bitmap; /* input data bit reverser */    \
136
1.10M
    const TIFFFaxTabEnt *TabEnt
137
138
#define DECLARE_STATE_2D(tif, sp, mod)                                         \
139
166k
    DECLARE_STATE(tif, sp, mod);                                               \
140
166k
    int b1; /* next change on prev line */                                     \
141
166k
    uint32_t                                                                   \
142
166k
        *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
1.11M
    do                                                                         \
148
1.11M
    {                                                                          \
149
1.11M
        BitAcc = sp->data;                                                     \
150
1.11M
        BitsAvail = sp->bit;                                                   \
151
1.11M
        EOLcnt = sp->EOLcnt;                                                   \
152
1.11M
        cp = (unsigned char *)tif->tif_rawcp;                                  \
153
1.11M
        ep = cp + tif->tif_rawcc;                                              \
154
1.11M
    } while (0)
155
/*
156
 * Save state possibly changed during decoding.
157
 */
158
#define UNCACHE_STATE(tif, sp)                                                 \
159
1.10M
    do                                                                         \
160
1.10M
    {                                                                          \
161
1.10M
        sp->bit = BitsAvail;                                                   \
162
1.10M
        sp->data = BitAcc;                                                     \
163
1.10M
        sp->EOLcnt = EOLcnt;                                                   \
164
1.10M
        tif->tif_rawcc -= (tmsize_t)((uint8_t *)cp - tif->tif_rawcp);          \
165
1.10M
        tif->tif_rawcp = (uint8_t *)cp;                                        \
166
1.10M
    } while (0)
167
168
/*
169
 * Setup state for decoding a strip.
170
 */
171
static int Fax3PreDecode(TIFF *tif, uint16_t s)
172
21.7k
{
173
21.7k
    Fax3CodecState *sp = DecoderState(tif);
174
175
21.7k
    (void)s;
176
21.7k
    assert(sp != NULL);
177
21.7k
    sp->bit = 0; /* force initial read */
178
21.7k
    sp->data = 0;
179
21.7k
    sp->EOLcnt = 0; /* force initial scan for EOL */
180
21.7k
    sp->eofReachedCount = 0;
181
21.7k
    sp->eolReachedCount = 0;
182
21.7k
    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
21.7k
    sp->bitmap =
191
21.7k
        TIFFGetBitRevTable(tif->tif_dir.td_fillorder != FILLORDER_LSB2MSB);
192
21.7k
    sp->curruns = sp->runs;
193
21.7k
    if (sp->refruns)
194
14.7k
    { /* init reference line to white */
195
14.7k
        sp->refruns = sp->runs + sp->nruns;
196
14.7k
        sp->refruns[0] = (uint32_t)sp->b.rowpixels;
197
14.7k
        sp->refruns[1] = 0;
198
14.7k
    }
199
21.7k
    sp->line = 0;
200
21.7k
    return (1);
201
21.7k
}
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.18M
{
212
1.18M
    TIFFErrorExtR(
213
1.18M
        tif, module,
214
1.18M
        "Bad code word at line %" PRIu32 " of %s %" PRIu32 " (x %" PRIu32 ")",
215
1.18M
        line, isTiled(tif) ? "tile" : "strip",
216
1.18M
        (isTiled(tif) ? tif->tif_dir.td_curtile : tif->tif_dir.td_curstrip),
217
1.18M
        a0);
218
1.18M
}
219
#define unexpected(table, a0)                                                  \
220
1.18M
    do                                                                         \
221
1.18M
    {                                                                          \
222
1.18M
        Fax3Unexpected(module, tif, (uint32_t)sp->line, (uint32_t)(a0));       \
223
1.18M
        ++sp->unexpectedReachedCount;                                          \
224
1.18M
    } while (0)
225
226
static void Fax3Extension(const char *module, TIFF *tif, uint32_t line,
227
                          uint32_t a0)
228
36.3k
{
229
36.3k
    TIFFErrorExtR(
230
36.3k
        tif, module,
231
36.3k
        "Uncompressed data (not supported) at line %" PRIu32 " of %s %" PRIu32
232
36.3k
        " (x %" PRIu32 ")",
233
36.3k
        line, isTiled(tif) ? "tile" : "strip",
234
36.3k
        (isTiled(tif) ? tif->tif_dir.td_curtile : tif->tif_dir.td_curstrip),
235
36.3k
        a0);
236
36.3k
}
237
#define extension(a0)                                                          \
238
36.3k
    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
3.34M
{
243
3.34M
    TIFFWarningExtR(
244
3.34M
        tif, module,
245
3.34M
        "%s at line %" PRIu32 " of %s %" PRIu32 " (got %" PRIu32
246
3.34M
        ", expected %" PRIu32 ")",
247
3.34M
        a0 < lastx ? "Premature EOL" : "Line length mismatch", line,
248
3.34M
        isTiled(tif) ? "tile" : "strip",
249
3.34M
        (isTiled(tif) ? tif->tif_dir.td_curtile : tif->tif_dir.td_curstrip), a0,
250
3.34M
        lastx);
251
3.34M
}
252
#define badlength(a0, lastx)                                                   \
253
3.34M
    do                                                                         \
254
3.34M
    {                                                                          \
255
3.34M
        Fax3BadLength(module, tif, (uint32_t)sp->line, (uint32_t)(a0),         \
256
3.34M
                      (uint32_t)(lastx));                                      \
257
3.34M
        ++sp->eolReachedCount;                                                 \
258
3.34M
    } while (0)
259
260
static void Fax3PrematureEOF(const char *module, TIFF *tif, uint32_t line,
261
                             uint32_t a0)
262
7.94k
{
263
7.94k
    TIFFWarningExtR(
264
7.94k
        tif, module,
265
7.94k
        "Premature EOF at line %" PRIu32 " of %s %" PRIu32 " (x %" PRIu32 ")",
266
7.94k
        line, isTiled(tif) ? "tile" : "strip",
267
7.94k
        (isTiled(tif) ? tif->tif_dir.td_curtile : tif->tif_dir.td_curstrip),
268
7.94k
        a0);
269
7.94k
}
270
#define prematureEOF(a0)                                                       \
271
7.94k
    do                                                                         \
272
7.94k
    {                                                                          \
273
7.94k
        Fax3PrematureEOF(module, tif, (uint32_t)sp->line, (uint32_t)(a0));     \
274
7.94k
        ++sp->eofReachedCount;                                                 \
275
7.94k
    } while (0)
276
277
static void Fax3TryG3WithoutEOL(const char *module, TIFF *tif, uint32_t line,
278
                                uint32_t a0)
279
3.25k
{
280
3.25k
    TIFFWarningExtR(
281
3.25k
        tif, module,
282
3.25k
        "Try to decode (read) fax Group 3 data without EOL at line %" PRIu32
283
3.25k
        " of %s %" PRIu32 " (x %" PRIu32 "). Please check result",
284
3.25k
        line, isTiled(tif) ? "tile" : "strip",
285
3.25k
        (isTiled(tif) ? tif->tif_dir.td_curtile : tif->tif_dir.td_curstrip),
286
3.25k
        a0);
287
3.25k
}
288
#define tryG3WithoutEOL(a0)                                                    \
289
3.25k
    do                                                                         \
290
3.25k
    {                                                                          \
291
3.25k
        Fax3TryG3WithoutEOL(module, tif, (uint32_t)sp->line, (uint32_t)(a0));  \
292
3.25k
    } while (0)
293
294
static int CheckReachedCounters(TIFF *tif, const char *module,
295
                                Fax3CodecState *sp)
296
1.10M
{
297
1.10M
    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
1.10M
    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
1.10M
    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
1.10M
    return (0);
323
1.10M
}
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
912k
{
334
912k
    DECLARE_STATE(tif, sp, "Fax3Decode1D");
335
912k
    (void)s;
336
912k
    if (occ % sp->b.rowbytes)
337
0
    {
338
0
        TIFFErrorExtR(tif, module, "Fractional scanlines cannot be read");
339
0
        return (-1);
340
0
    }
341
912k
    if (CheckReachedCounters(tif, module, sp))
342
0
        return (-1);
343
913k
RETRY_WITHOUT_EOL_1D:
344
913k
    CACHE_STATE(tif, sp);
345
913k
    thisrun = sp->curruns;
346
3.11M
    while (occ > 0)
347
2.19M
    {
348
2.19M
        a0 = 0;
349
2.19M
        RunLength = 0;
350
2.19M
        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
2.19M
        SYNC_EOL(EOF1D, RETRY_WITHOUT_EOL_1D);
357
2.19M
        EXPAND1D(EOF1Da);
358
2.19M
        (*sp->fill)(buf, thisrun, pa, (uint32_t)lastx);
359
2.19M
        buf += sp->b.rowbytes;
360
2.19M
        occ -= sp->b.rowbytes;
361
2.19M
        sp->line++;
362
2.19M
        continue;
363
0
    EOF1D: /* premature EOF */
364
0
        CLEANUP_RUNS();
365
354
    EOF1Da: /* premature EOF */
366
354
        (*sp->fill)(buf, thisrun, pa, (uint32_t)lastx);
367
354
        UNCACHE_STATE(tif, sp);
368
354
        return (-1);
369
0
    }
370
911k
    UNCACHE_STATE(tif, sp);
371
911k
    return (1);
372
913k
}
373
374
#define SWAP(t, a, b)                                                          \
375
573k
    {                                                                          \
376
573k
        t x;                                                                   \
377
573k
        x = (a);                                                               \
378
573k
        (a) = (b);                                                             \
379
573k
        (b) = x;                                                               \
380
573k
    }
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
6.91k
{
386
6.91k
    DECLARE_STATE_2D(tif, sp, "Fax3Decode2D");
387
6.91k
    int is1D; /* current line is 1d/2d-encoded */
388
6.91k
    (void)s;
389
6.91k
    if (occ % sp->b.rowbytes)
390
0
    {
391
0
        TIFFErrorExtR(tif, module, "Fractional scanlines cannot be read");
392
0
        return (-1);
393
0
    }
394
6.91k
    if (CheckReachedCounters(tif, module, sp))
395
0
        return (-1);
396
8.78k
RETRY_WITHOUT_EOL_2D:
397
8.78k
    CACHE_STATE(tif, sp);
398
582k
    while (occ > 0)
399
577k
    {
400
577k
        a0 = 0;
401
577k
        RunLength = 0;
402
577k
        pa = thisrun = sp->curruns;
403
#ifdef FAX3_DEBUG
404
        printf("\nBitAcc=%08" PRIX32 ", BitsAvail = %d EOLcnt = %d", BitAcc,
405
               BitsAvail, EOLcnt);
406
#endif
407
577k
        SYNC_EOL(EOF2D, RETRY_WITHOUT_EOL_2D);
408
575k
        NeedBits8(1, EOF2D);
409
575k
        is1D = GetBits(1); /* 1D/2D-encoding tag bit */
410
575k
        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
575k
        pb = sp->refruns;
417
575k
        b1 = (int)*pb++;
418
575k
        if (is1D)
419
141k
            EXPAND1D(EOF2Da);
420
434k
        else
421
434k
            EXPAND2D(EOF2Da);
422
573k
        (*sp->fill)(buf, thisrun, pa, (uint32_t)lastx);
423
573k
        if (pa < thisrun + sp->nruns)
424
573k
        {
425
573k
            SETVALUE(0); /* imaginary change for reference */
426
573k
        }
427
573k
        SWAP(uint32_t *, sp->curruns, sp->refruns);
428
573k
        buf += sp->b.rowbytes;
429
573k
        occ -= sp->b.rowbytes;
430
573k
        sp->line++;
431
573k
        continue;
432
373
    EOF2D: /* premature EOF */
433
373
        CLEANUP_RUNS();
434
2.22k
    EOF2Da: /* premature EOF */
435
2.22k
        (*sp->fill)(buf, thisrun, pa, (uint32_t)lastx);
436
2.22k
        UNCACHE_STATE(tif, sp);
437
2.22k
        return (-1);
438
373
    }
439
4.65k
    UNCACHE_STATE(tif, sp);
440
4.65k
    return (1);
441
8.78k
}
442
#undef SWAP
443
444
#define FILL(n, cp)                                                            \
445
4.57M
    for (int32_t ifill = 0; ifill < (n); ++ifill)                              \
446
3.34M
    {                                                                          \
447
3.34M
        (cp)[ifill] = 0xff;                                                    \
448
3.34M
    }                                                                          \
449
1.23M
    (cp) += (n);
450
451
#define ZERO(n, cp)                                                            \
452
29.4M
    for (int32_t izero = 0; izero < (n); ++izero)                              \
453
22.2M
    {                                                                          \
454
22.2M
        (cp)[izero] = 0;                                                       \
455
22.2M
    }                                                                          \
456
7.20M
    (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
4.11M
{
465
4.11M
    static const unsigned char _fillmasks[] = {0x00, 0x80, 0xc0, 0xe0, 0xf0,
466
4.11M
                                               0xf8, 0xfc, 0xfe, 0xff};
467
4.11M
    unsigned char *cp;
468
4.11M
    uint32_t x, bx, run;
469
4.11M
    int32_t n, nw;
470
4.11M
    int64_t *lp;
471
472
4.11M
    if ((erun - runs) & 1)
473
3.73M
        *erun++ = 0;
474
4.11M
    x = 0;
475
16.2M
    for (; runs < erun; runs += 2)
476
12.1M
    {
477
12.1M
        run = runs[0];
478
12.1M
        if (x + run > lastx || run > lastx)
479
265k
            run = runs[0] = (uint32_t)(lastx - x);
480
12.1M
        if (run)
481
11.7M
        {
482
11.7M
            cp = buf + (x >> 3);
483
11.7M
            bx = x & 7;
484
11.7M
            if (run > 8 - bx)
485
9.65M
            {
486
9.65M
                if (bx)
487
5.50M
                { /* align to byte boundary */
488
5.50M
                    *cp++ &= (unsigned char)(0xff << (8 - bx));
489
5.50M
                    run -= 8 - bx;
490
5.50M
                }
491
9.65M
                if ((n = (int32_t)(run >> 3)) != 0)
492
7.20M
                { /* multiple bytes to fill */
493
7.20M
                    if (((size_t)n / sizeof(int64_t)) > 1)
494
2.40M
                    {
495
                        /*
496
                         * Align to int64_tword boundary and fill.
497
                         */
498
6.03M
                        for (; n && !isAligned(cp, int64_t); n--)
499
3.63M
                            *cp++ = 0x00;
500
2.40M
                        lp = (int64_t *)cp;
501
2.40M
                        nw = (int32_t)((size_t)n / sizeof(int64_t));
502
2.40M
                        n -= (int32_t)((size_t)nw * sizeof(int64_t));
503
2.40M
                        do
504
35.0M
                        {
505
35.0M
                            *lp++ = 0L;
506
35.0M
                        } while (--nw);
507
2.40M
                        cp = (unsigned char *)lp;
508
2.40M
                    }
509
7.20M
                    ZERO(n, cp);
510
7.20M
                    run &= 7;
511
7.20M
                }
512
9.65M
                if (run)
513
8.52M
                    cp[0] &= (unsigned char)(0xff >> run);
514
9.65M
            }
515
2.10M
            else
516
2.10M
                cp[0] &= (unsigned char)~(_fillmasks[run] >> bx);
517
11.7M
            x += runs[0];
518
11.7M
        }
519
12.1M
        run = runs[1];
520
12.1M
        if (x + run > lastx || run > lastx)
521
0
            run = runs[1] = lastx - x;
522
12.1M
        if (run)
523
7.66M
        {
524
7.66M
            cp = buf + (x >> 3);
525
7.66M
            bx = x & 7;
526
7.66M
            if (run > 8 - bx)
527
3.02M
            {
528
3.02M
                if (bx)
529
2.83M
                { /* align to byte boundary */
530
2.83M
                    *cp++ |= (unsigned char)(0xff >> bx);
531
2.83M
                    run -= 8 - bx;
532
2.83M
                }
533
3.02M
                if ((n = (int32_t)(run >> 3)) != 0)
534
1.23M
                { /* multiple bytes to fill */
535
1.23M
                    if (((size_t)n / sizeof(int64_t)) > 1)
536
185k
                    {
537
                        /*
538
                         * Align to int64_t boundary and fill.
539
                         */
540
860k
                        for (; n && !isAligned(cp, int64_t); n--)
541
675k
                            *cp++ = 0xff;
542
185k
                        lp = (int64_t *)cp;
543
185k
                        nw = (int32_t)((size_t)n / sizeof(int64_t));
544
185k
                        n -= (int32_t)((size_t)nw * sizeof(int64_t));
545
185k
                        do
546
1.54M
                        {
547
1.54M
                            *lp++ = -1L;
548
1.54M
                        } while (--nw);
549
185k
                        cp = (unsigned char *)lp;
550
185k
                    }
551
1.23M
                    FILL(n, cp);
552
1.23M
                    run &= 7;
553
1.23M
                }
554
                /* Explicit 0xff masking to make icc -check=conversions happy */
555
3.02M
                if (run)
556
2.81M
                    cp[0] = (unsigned char)((cp[0] | (0xff00 >> run)) & 0xff);
557
3.02M
            }
558
4.63M
            else
559
4.63M
                cp[0] |= (unsigned char)(_fillmasks[run] >> bx);
560
7.66M
            x += runs[1];
561
7.66M
        }
562
12.1M
    }
563
4.11M
    assert(x == lastx);
564
4.11M
}
565
#undef ZERO
566
#undef FILL
567
568
static int Fax3FixupTags(TIFF *tif)
569
12.6k
{
570
12.6k
    (void)tif;
571
12.6k
    return (1);
572
12.6k
}
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
15.6k
{
583
15.6k
    static const char module[] = "Fax3SetupState";
584
15.6k
    TIFFDirectory *td = &tif->tif_dir;
585
15.6k
    Fax3BaseState *sp = Fax3State(tif);
586
15.6k
    int needsRefLine;
587
15.6k
    Fax3CodecState *dsp = (Fax3CodecState *)Fax3State(tif);
588
15.6k
    tmsize_t rowbytes;
589
15.6k
    uint32_t rowpixels;
590
591
15.6k
    if (td->td_bitspersample != 1)
592
7
    {
593
7
        TIFFErrorExtR(tif, module,
594
7
                      "Bits/sample must be 1 for Group 3/4 encoding/decoding");
595
7
        return (0);
596
7
    }
597
15.6k
    if (td->td_samplesperpixel != 1 &&
598
134
        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
15.6k
    if (isTiled(tif))
610
1.75k
    {
611
1.75k
        rowbytes = TIFFTileRowSize(tif);
612
1.75k
        rowpixels = td->td_tilewidth;
613
1.75k
    }
614
13.8k
    else
615
13.8k
    {
616
13.8k
        rowbytes = TIFFScanlineSize(tif);
617
13.8k
        rowpixels = td->td_imagewidth;
618
13.8k
    }
619
15.6k
    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
15.6k
    sp->rowbytes = rowbytes;
628
15.6k
    sp->rowpixels = rowpixels;
629
    /*
630
     * Allocate any additional space required for decoding/encoding.
631
     */
632
15.6k
    needsRefLine = ((sp->groupoptions & GROUP3OPT_2DENCODING) ||
633
13.4k
                    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
15.6k
    if (dsp->runs != NULL)
641
0
    {
642
0
        _TIFFfreeExt(tif, dsp->runs);
643
0
        dsp->runs = (uint32_t *)NULL;
644
0
    }
645
15.6k
    dsp->nruns = TIFFroundup_32(rowpixels + 1, 32);
646
15.6k
    if (needsRefLine)
647
11.8k
    {
648
11.8k
        dsp->nruns = TIFFSafeMultiply(uint32_t, dsp->nruns, 2);
649
11.8k
    }
650
15.6k
    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
15.6k
    dsp->runs = (uint32_t *)_TIFFCheckMalloc(
658
15.6k
        tif, TIFFSafeMultiply(uint32_t, dsp->nruns, 2), sizeof(uint32_t),
659
15.6k
        "for Group 3/4 run arrays");
660
15.6k
    if (dsp->runs == NULL)
661
0
        return (0);
662
15.6k
    memset(dsp->runs, 0,
663
15.6k
           TIFFSafeMultiply(uint32_t, dsp->nruns, 2) * sizeof(uint32_t));
664
15.6k
    dsp->curruns = dsp->runs;
665
15.6k
    if (needsRefLine)
666
11.8k
        dsp->refruns = dsp->runs + dsp->nruns;
667
3.81k
    else
668
3.81k
        dsp->refruns = NULL;
669
15.6k
    if (td->td_compression == COMPRESSION_CCITTFAX3 && is2DEncoding(dsp))
670
2.16k
    { /* NB: default is 1D routine */
671
2.16k
        tif->tif_decoderow = Fax3Decode2D;
672
2.16k
        tif->tif_decodestrip = Fax3Decode2D;
673
2.16k
        tif->tif_decodetile = Fax3Decode2D;
674
2.16k
    }
675
676
15.6k
    if (needsRefLine)
677
11.8k
    { /* 2d encoding */
678
11.8k
        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
11.8k
        if (esp->refline != NULL)
687
0
        {
688
0
            _TIFFfreeExt(tif, esp->refline);
689
0
        }
690
11.8k
        esp->refline = (unsigned char *)_TIFFmallocExt(tif, rowbytes);
691
11.8k
        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
11.8k
    }
697
3.81k
    else /* 1d encoding */
698
3.81k
        EncoderState(tif)->refline = NULL;
699
700
15.6k
    return (1);
701
15.6k
}
702
703
/*
704
 * CCITT Group 3 FAX Encoding.
705
 */
706
707
#define Fax3FlushBits(tif, sp)                                                 \
708
5.50k
    {                                                                          \
709
5.50k
        if ((tif)->tif_rawcc >= (tif)->tif_rawdatasize)                        \
710
5.50k
        {                                                                      \
711
1
            if (!TIFFFlushData1(tif))                                          \
712
1
                return 0;                                                      \
713
1
        }                                                                      \
714
5.50k
        *(tif)->tif_rawcp++ = (uint8_t)(sp)->data;                             \
715
5.50k
        (tif)->tif_rawcc++;                                                    \
716
5.50k
        (sp)->data = 0, (sp)->bit = 8;                                         \
717
5.50k
    }
718
#define _FlushBits(tif)                                                        \
719
11.5M
    {                                                                          \
720
11.5M
        if ((tif)->tif_rawcc >= (tif)->tif_rawdatasize)                        \
721
11.5M
        {                                                                      \
722
19
            if (!TIFFFlushData1(tif))                                          \
723
19
                return 0;                                                      \
724
19
        }                                                                      \
725
11.5M
        *(tif)->tif_rawcp++ = (uint8_t)data;                                   \
726
11.5M
        (tif)->tif_rawcc++;                                                    \
727
11.5M
        data = 0, bit = 8;                                                     \
728
11.5M
    }
729
static const int _msbmask[9] = {0x00, 0x01, 0x03, 0x07, 0x0f,
730
                                0x1f, 0x3f, 0x7f, 0xff};
731
#define _PutBits(tif, bits, length)                                            \
732
21.7M
    {                                                                          \
733
28.8M
        while (length > bit)                                                   \
734
21.7M
        {                                                                      \
735
7.07M
            data |= (int)((unsigned int)bits >> (length - bit));               \
736
7.07M
            length -= bit;                                                     \
737
7.07M
            _FlushBits(tif);                                                   \
738
7.07M
        }                                                                      \
739
21.7M
        assert(length < 9);                                                    \
740
21.7M
        data |= (int)(((unsigned int)bits & (unsigned int)_msbmask[length])    \
741
21.7M
                      << (unsigned int)(bit - length));                        \
742
21.7M
        bit -= length;                                                         \
743
21.7M
        if (bit == 0)                                                          \
744
21.7M
            _FlushBits(tif);                                                   \
745
21.7M
    }
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
9.96M
{
754
9.96M
    Fax3CodecState *sp = EncoderState(tif);
755
9.96M
    unsigned int bit = (unsigned int)sp->bit;
756
9.96M
    int data = (int)sp->data;
757
758
9.96M
    _PutBits(tif, bits, length);
759
760
9.96M
    sp->data = (uint32_t)data;
761
9.96M
    sp->bit = (int)bit;
762
9.96M
    return 1;
763
19.9M
}
764
765
/*
766
 * Write a code to the output stream.
767
 */
768
9.95M
#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
8.40M
{
791
8.40M
    Fax3CodecState *sp = EncoderState(tif);
792
8.40M
    unsigned int bit = (unsigned int)sp->bit;
793
8.40M
    int data = (int)sp->data;
794
8.40M
    unsigned int code, length;
795
796
8.40M
    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
8.40M
    if (span >= 64)
808
1.28M
    {
809
1.28M
        const tableentry *te = &tab[63 + (span >> 6)];
810
1.28M
        assert(te->runlen == 64 * (span >> 6));
811
1.28M
        code = te->code;
812
1.28M
        length = te->length;
813
#ifdef FAX3_DEBUG
814
        DEBUG_PRINT("MakeUp", te->runlen);
815
#endif
816
3.86M
        _PutBits(tif, code, length);
817
3.86M
        span -= te->runlen;
818
3.86M
    }
819
8.40M
    code = tab[span].code;
820
8.40M
    length = tab[span].length;
821
#ifdef FAX3_DEBUG
822
    DEBUG_PRINT("  Term", tab[span].runlen);
823
#endif
824
8.40M
    _PutBits(tif, code, length);
825
826
8.40M
    sp->data = (uint32_t)data;
827
8.40M
    sp->bit = (int)bit;
828
829
8.40M
    return 1;
830
16.8M
}
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
1.08M
{
840
1.08M
    Fax3CodecState *sp = EncoderState(tif);
841
1.08M
    unsigned int bit = (unsigned int)sp->bit;
842
1.08M
    int data = (int)sp->data;
843
1.08M
    unsigned int code, length, tparm;
844
845
1.08M
    if (sp->b.groupoptions & GROUP3OPT_FILLBITS)
846
1.08M
    {
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
1.08M
        int align = 8 - 4;
853
1.08M
        if (align != sp->bit)
854
1.02M
        {
855
1.02M
            if (align > sp->bit)
856
255k
                align = sp->bit + (8 - align);
857
768k
            else
858
768k
                align = sp->bit - align;
859
1.02M
            tparm = (unsigned int)align;
860
3.07M
            _PutBits(tif, 0, tparm);
861
3.07M
        }
862
1.08M
    }
863
1.08M
    code = EOL;
864
1.08M
    length = 12;
865
1.08M
    if (is2DEncoding(sp))
866
0
    {
867
0
        code = (code << 1) | (sp->tag == G3_1D);
868
0
        length++;
869
0
    }
870
1.08M
    _PutBits(tif, code, length);
871
872
1.08M
    sp->data = (uint32_t)data;
873
1.08M
    sp->bit = (int)bit;
874
875
1.08M
    return 1;
876
2.16M
}
877
878
/*
879
 * Reset encoding state at the start of a strip.
880
 */
881
static int Fax3PreEncode(TIFF *tif, uint16_t s)
882
6.57k
{
883
6.57k
    Fax3CodecState *sp = EncoderState(tif);
884
885
6.57k
    (void)s;
886
6.57k
    assert(sp != NULL);
887
6.57k
    sp->bit = 8;
888
6.57k
    sp->data = 0;
889
6.57k
    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
6.57k
    if (sp->refline)
896
5.03k
        _TIFFmemset(sp->refline, 0x00, sp->b.rowbytes);
897
6.57k
    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
6.57k
    else
916
6.57k
        sp->k = sp->maxk = 0;
917
6.57k
    sp->line = 0;
918
6.57k
    return (1);
919
6.57k
}
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
22.8M
{
965
22.8M
    int32_t bits = be - bs;
966
22.8M
    int32_t n, span;
967
968
22.8M
    bp += bs >> 3;
969
    /*
970
     * Check partial byte on lhs.
971
     */
972
22.8M
    if (bits > 0 && (n = (bs & 7)) != 0)
973
15.5M
    {
974
15.5M
        span = zeroruns[(*bp << n) & 0xff];
975
15.5M
        if (span > 8 - n) /* table value too generous */
976
11.2M
            span = 8 - n;
977
15.5M
        if (span > bits) /* constrain span to bit range */
978
54.4k
            span = bits;
979
15.5M
        if (n + span < 8) /* doesn't extend to edge of byte */
980
4.36M
            return (span);
981
11.1M
        bits -= span;
982
11.1M
        bp++;
983
11.1M
    }
984
7.26M
    else
985
7.26M
        span = 0;
986
18.4M
    if (bits >= (int32_t)(2 * 8 * sizeof(int64_t)))
987
16.8M
    {
988
16.8M
        int64_t *lp;
989
        /*
990
         * Align to int64_t boundary and check int64_t words.
991
         */
992
27.7M
        while (!isAligned(bp, int64_t))
993
20.1M
        {
994
20.1M
            if (*bp != 0x00)
995
9.21M
                return (span + zeroruns[*bp]);
996
10.9M
            span += 8;
997
10.9M
            bits -= 8;
998
10.9M
            bp++;
999
10.9M
        }
1000
7.59M
        lp = (int64_t *)bp;
1001
55.9M
        while ((bits >= (int32_t)(size_t)(8 * sizeof(int64_t))) && (0 == *lp))
1002
48.3M
        {
1003
48.3M
            span += (int32_t)(size_t)(8 * sizeof(int64_t));
1004
48.3M
            bits -= (int32_t)(size_t)(8 * sizeof(int64_t));
1005
48.3M
            lp++;
1006
48.3M
        }
1007
7.59M
        bp = (unsigned char *)lp;
1008
7.59M
    }
1009
    /*
1010
     * Scan full bytes for all 0's.
1011
     */
1012
27.7M
    while (bits >= 8)
1013
24.1M
    {
1014
24.1M
        if (*bp != 0x00) /* end of run */
1015
5.58M
            return (span + zeroruns[*bp]);
1016
18.5M
        span += 8;
1017
18.5M
        bits -= 8;
1018
18.5M
        bp++;
1019
18.5M
    }
1020
    /*
1021
     * Check partial byte on rhs.
1022
     */
1023
3.65M
    if (bits > 0)
1024
2.51M
    {
1025
2.51M
        n = zeroruns[*bp];
1026
2.51M
        span += (n > bits ? bits : n);
1027
2.51M
    }
1028
3.65M
    return (span);
1029
9.23M
}
1030
1031
static inline int32_t find1span(unsigned char *bp, int32_t bs, int32_t be)
1032
20.2M
{
1033
20.2M
    int32_t bits = be - bs;
1034
20.2M
    int32_t n, span;
1035
1036
20.2M
    bp += bs >> 3;
1037
    /*
1038
     * Check partial byte on lhs.
1039
     */
1040
20.2M
    if (bits > 0 && (n = (bs & 7)) != 0)
1041
16.3M
    {
1042
16.3M
        span = oneruns[(*bp << n) & 0xff];
1043
16.3M
        if (span > 8 - n) /* table value too generous */
1044
0
            span = 8 - n;
1045
16.3M
        if (span > bits) /* constrain span to bit range */
1046
0
            span = bits;
1047
16.3M
        if (n + span < 8) /* doesn't extend to edge of byte */
1048
8.53M
            return (span);
1049
7.82M
        bits -= span;
1050
7.82M
        bp++;
1051
7.82M
    }
1052
3.86M
    else
1053
3.86M
        span = 0;
1054
11.6M
    if (bits >= (int32_t)(2 * 8 * sizeof(int64_t)))
1055
10.4M
    {
1056
10.4M
        int64_t *lp;
1057
        /*
1058
         * Align to int64_t boundary and check int64_t words.
1059
         */
1060
16.3M
        while (!isAligned(bp, int64_t))
1061
12.8M
        {
1062
12.8M
            if (*bp != 0xff)
1063
6.96M
                return (span + oneruns[*bp]);
1064
5.85M
            span += 8;
1065
5.85M
            bits -= 8;
1066
5.85M
            bp++;
1067
5.85M
        }
1068
3.52M
        lp = (int64_t *)bp;
1069
22.7M
        while ((bits >= (int32_t)(size_t)(8 * sizeof(int64_t))) &&
1070
21.1M
               (~((uint64_t)0) == (uint64_t)*lp))
1071
19.1M
        {
1072
19.1M
            span += (int32_t)(size_t)(8 * sizeof(int64_t));
1073
19.1M
            bits -= (int32_t)(size_t)(8 * sizeof(int64_t));
1074
19.1M
            lp++;
1075
19.1M
        }
1076
3.52M
        bp = (unsigned char *)lp;
1077
3.52M
    }
1078
    /*
1079
     * Scan full bytes for all 1's.
1080
     */
1081
13.1M
    while (bits >= 8)
1082
11.2M
    {
1083
11.2M
        if (*bp != 0xff) /* end of run */
1084
2.79M
            return (span + oneruns[*bp]);
1085
8.45M
        span += 8;
1086
8.45M
        bits -= 8;
1087
8.45M
        bp++;
1088
8.45M
    }
1089
    /*
1090
     * Check partial byte on rhs.
1091
     */
1092
1.92M
    if (bits > 0)
1093
1.26M
    {
1094
1.26M
        n = oneruns[*bp];
1095
1.26M
        span += (n > bits ? bits : n);
1096
1.26M
    }
1097
1.92M
    return (span);
1098
4.72M
}
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
36.0M
    (_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
10.6M
    (_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
1.08M
{
1122
1.08M
    Fax3CodecState *sp = EncoderState(tif);
1123
1.08M
    int32_t span;
1124
1.08M
    uint32_t bs = 0;
1125
1126
1.08M
    for (;;)
1127
3.77M
    {
1128
3.77M
        span = find0span(bp, (int32_t)bs, (int32_t)bits); /* white span */
1129
3.77M
        if (!putspan(tif, span, TIFFFaxWhiteCodes))
1130
0
            return 0;
1131
3.77M
        bs += (uint32_t)span;
1132
3.77M
        if (bs >= bits)
1133
584k
            break;
1134
3.19M
        span = find1span(bp, (int32_t)bs, (int32_t)bits); /* black span */
1135
3.19M
        if (!putspan(tif, span, TIFFFaxBlackCodes))
1136
0
            return 0;
1137
3.19M
        bs += (uint32_t)span;
1138
3.19M
        if (bs >= bits)
1139
496k
            break;
1140
3.19M
    }
1141
1.08M
    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
1.08M
    return (1);
1150
1.08M
}
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
1.89M
{
1171
4.49M
#define PIXEL(buf, ix) ((((buf)[(ix) >> 3]) >> (7 - ((ix) & 7))) & 1)
1172
1.89M
    uint32_t a0 = 0;
1173
1.89M
    uint32_t a1 = (PIXEL(bp, 0) != 0
1174
1.89M
                       ? 0
1175
1.89M
                       : (uint32_t)finddiff(bp, (int32_t)0, (int32_t)bits, 0));
1176
1.89M
    uint32_t b1 = (PIXEL(rp, 0) != 0
1177
1.89M
                       ? 0
1178
1.89M
                       : (uint32_t)finddiff(rp, (int32_t)0, (int32_t)bits, 0));
1179
1.89M
    uint32_t a2, b2;
1180
1181
1.89M
    for (;;)
1182
9.95M
    {
1183
9.95M
        b2 = (uint32_t)finddiff2(rp, (int32_t)b1, (int32_t)bits,
1184
9.95M
                                 (int32_t)PIXEL(rp, b1));
1185
9.95M
        if (b2 >= a1)
1186
9.51M
        {
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
9.51M
            int32_t d = (b1 >= a1 && b1 - a1 <= 3U)  ? (int32_t)(b1 - a1)
1193
9.51M
                        : (b1 < a1 && a1 - b1 <= 3U) ? -(int32_t)(a1 - b1)
1194
985k
                                                     : 0x7FFFFFFF;
1195
9.51M
            if (!(-3 <= d && d <= 3))
1196
718k
            { /* horizontal mode */
1197
718k
                a2 = (uint32_t)finddiff2(bp, (int32_t)a1, (int32_t)bits,
1198
718k
                                         (int32_t)PIXEL(bp, a1));
1199
718k
                if (!putcode(tif, &horizcode))
1200
0
                    return 0;
1201
718k
                if (a0 + a1 == 0 || PIXEL(bp, a0) == 0)
1202
553k
                {
1203
553k
                    if (!putspan(tif, (int32_t)(a1 - a0), TIFFFaxWhiteCodes))
1204
0
                        return 0;
1205
553k
                    if (!putspan(tif, (int32_t)(a2 - a1), TIFFFaxBlackCodes))
1206
0
                        return 0;
1207
553k
                }
1208
165k
                else
1209
165k
                {
1210
165k
                    if (!putspan(tif, (int32_t)(a1 - a0), TIFFFaxBlackCodes))
1211
0
                        return 0;
1212
165k
                    if (!putspan(tif, (int32_t)(a2 - a1), TIFFFaxWhiteCodes))
1213
0
                        return 0;
1214
165k
                }
1215
718k
                a0 = a2;
1216
718k
            }
1217
8.79M
            else
1218
8.79M
            { /* vertical mode */
1219
8.79M
                if (!putcode(tif, &vcodes[d + 3]))
1220
0
                    return 0;
1221
8.79M
                a0 = a1;
1222
8.79M
            }
1223
9.51M
        }
1224
435k
        else
1225
435k
        { /* pass mode */
1226
435k
            if (!putcode(tif, &passcode))
1227
0
                return 0;
1228
435k
            a0 = b2;
1229
435k
        }
1230
9.95M
        if (a0 >= bits)
1231
1.89M
            break;
1232
8.06M
        a1 = (uint32_t)finddiff(bp, (int32_t)a0, (int32_t)bits,
1233
8.06M
                                (int32_t)PIXEL(bp, a0));
1234
8.06M
        b1 = (uint32_t)finddiff(rp, (int32_t)a0, (int32_t)bits,
1235
8.06M
                                (int32_t)!PIXEL(bp, a0));
1236
8.06M
        b1 = (uint32_t)finddiff(rp, (int32_t)b1, (int32_t)bits,
1237
8.06M
                                (int32_t)PIXEL(bp, a0));
1238
8.06M
    }
1239
1.89M
    return (1);
1240
1.89M
#undef PIXEL
1241
1.89M
}
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
1.08M
{
1248
1.08M
    static const char module[] = "Fax3Encode";
1249
1.08M
    Fax3CodecState *sp = EncoderState(tif);
1250
1.08M
    (void)s;
1251
1.08M
    if (cc % sp->b.rowbytes)
1252
0
    {
1253
0
        TIFFErrorExtR(tif, module, "Fractional scanlines cannot be written");
1254
0
        return (0);
1255
0
    }
1256
2.16M
    while (cc > 0)
1257
1.08M
    {
1258
1.08M
        if ((sp->b.mode & FAXMODE_NOEOL) == 0)
1259
1.08M
        {
1260
1.08M
            if (!Fax3PutEOL(tif))
1261
0
                return 0;
1262
1.08M
        }
1263
1.08M
        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
1.08M
        else
1286
1.08M
        {
1287
1.08M
            if (!Fax3Encode1DRow(tif, bp, sp->b.rowpixels))
1288
0
                return (0);
1289
1.08M
        }
1290
1.08M
        bp += sp->b.rowbytes;
1291
1.08M
        cc -= sp->b.rowbytes;
1292
1.08M
    }
1293
1.08M
    return (1);
1294
1.08M
}
1295
1296
static int Fax3PostEncode(TIFF *tif)
1297
1.54k
{
1298
1.54k
    Fax3CodecState *sp = EncoderState(tif);
1299
1300
1.54k
    if (sp->bit != 8)
1301
1.54k
        Fax3FlushBits(tif, sp);
1302
1.54k
    return (1);
1303
1.54k
}
1304
1305
static int _Fax3Close(TIFF *tif)
1306
6.57k
{
1307
6.57k
    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
6.57k
    return 1;
1324
6.57k
}
1325
1326
6.57k
static void Fax3Close(TIFF *tif) { _Fax3Close(tif); }
1327
1328
static void Fax3Cleanup(TIFF *tif)
1329
42.5k
{
1330
42.5k
    Fax3CodecState *sp = DecoderState(tif);
1331
1332
42.5k
    assert(sp != 0);
1333
1334
42.5k
    tif->tif_tagmethods.vgetfield = sp->b.vgetparent;
1335
42.5k
    tif->tif_tagmethods.vsetfield = sp->b.vsetparent;
1336
42.5k
    tif->tif_tagmethods.printdir = sp->b.printdir;
1337
1338
42.5k
    if (sp->runs)
1339
15.6k
        _TIFFfreeExt(tif, sp->runs);
1340
42.5k
    if (sp->refline)
1341
11.8k
        _TIFFfreeExt(tif, sp->refline);
1342
1343
42.5k
    _TIFFfreeExt(tif, tif->tif_data);
1344
42.5k
    tif->tif_data = NULL;
1345
1346
42.5k
    _TIFFSetDefaultCompressionState(tif);
1347
42.5k
}
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
272k
{
1377
272k
    Fax3BaseState *sp = Fax3State(tif);
1378
272k
    const TIFFField *fip;
1379
1380
272k
    assert(sp != 0);
1381
272k
    assert(sp->vsetparent != 0);
1382
1383
272k
    switch (tag)
1384
272k
    {
1385
42.5k
        case TIFFTAG_FAXMODE:
1386
42.5k
            sp->mode = (int)va_arg(ap, int);
1387
42.5k
            return 1; /* NB: pseudo tag */
1388
42.5k
        case TIFFTAG_FAXFILLFUNC:
1389
42.5k
            DecoderState(tif)->fill = va_arg(ap, TIFFFaxFillFunc);
1390
42.5k
            return 1; /* NB: pseudo tag */
1391
5.03k
        case TIFFTAG_GROUP3OPTIONS:
1392
            /* XXX: avoid reading options if compression mismatches. */
1393
5.03k
            if (tif->tif_dir.td_compression == COMPRESSION_CCITTFAX3)
1394
5.03k
                sp->groupoptions = (uint32_t)va_arg(ap, uint32_t);
1395
5.03k
            break;
1396
1.01k
        case TIFFTAG_GROUP4OPTIONS:
1397
            /* XXX: avoid reading options if compression mismatches. */
1398
1.01k
            if (tif->tif_dir.td_compression == COMPRESSION_CCITTFAX4)
1399
1.01k
                sp->groupoptions = (uint32_t)va_arg(ap, uint32_t);
1400
1.01k
            break;
1401
82
        case TIFFTAG_BADFAXLINES:
1402
82
            sp->badfaxlines = (uint32_t)va_arg(ap, uint32_t);
1403
82
            break;
1404
422
        case TIFFTAG_CLEANFAXDATA:
1405
422
            sp->cleanfaxdata = (uint16_t)va_arg(ap, uint16_vap);
1406
422
            break;
1407
1.75k
        case TIFFTAG_CONSECUTIVEBADFAXLINES:
1408
1.75k
            sp->badfaxrun = (uint32_t)va_arg(ap, uint32_t);
1409
1.75k
            break;
1410
178k
        default:
1411
178k
            return (*sp->vsetparent)(tif, tag, ap);
1412
272k
    }
1413
1414
8.31k
    if ((fip = TIFFFieldWithTag(tif, tag)) != NULL)
1415
8.31k
        TIFFSetFieldBit(tif, fip->field_bit);
1416
0
    else
1417
0
        return 0;
1418
1419
8.31k
    tif->tif_flags |= TIFF_DIRTYDIRECT;
1420
8.31k
    return 1;
1421
8.31k
}
1422
1423
static int Fax3VGetField(TIFF *tif, uint32_t tag, va_list ap)
1424
155k
{
1425
155k
    Fax3BaseState *sp = Fax3State(tif);
1426
1427
155k
    assert(sp != 0);
1428
1429
155k
    switch (tag)
1430
155k
    {
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
3.09k
        case TIFFTAG_GROUP3OPTIONS:
1438
3.09k
        case TIFFTAG_GROUP4OPTIONS:
1439
3.09k
            *va_arg(ap, uint32_t *) = sp->groupoptions;
1440
3.09k
            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
152k
        default:
1451
152k
            return (*sp->vgetparent)(tif, tag, ap);
1452
155k
    }
1453
3.09k
    return (1);
1454
155k
}
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
42.5k
{
1539
42.5k
    static const char module[] = "InitCCITTFax3";
1540
42.5k
    Fax3BaseState *sp;
1541
1542
    /*
1543
     * Merge codec-specific tag information.
1544
     */
1545
42.5k
    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
42.5k
    tif->tif_data = (uint8_t *)_TIFFmallocExt(tif, sizeof(Fax3CodecState));
1556
1557
42.5k
    if (tif->tif_data == NULL)
1558
0
    {
1559
0
        TIFFErrorExtR(tif, module, "No space for state block");
1560
0
        return (0);
1561
0
    }
1562
42.5k
    _TIFFmemset(tif->tif_data, 0, sizeof(Fax3CodecState));
1563
1564
42.5k
    sp = Fax3State(tif);
1565
42.5k
    sp->rw_mode = tif->tif_mode;
1566
1567
    /*
1568
     * Override parent get/set field methods.
1569
     */
1570
42.5k
    sp->vgetparent = tif->tif_tagmethods.vgetfield;
1571
42.5k
    tif->tif_tagmethods.vgetfield = Fax3VGetField; /* hook for codec tags */
1572
42.5k
    sp->vsetparent = tif->tif_tagmethods.vsetfield;
1573
42.5k
    tif->tif_tagmethods.vsetfield = Fax3VSetField; /* hook for codec tags */
1574
42.5k
    sp->printdir = tif->tif_tagmethods.printdir;
1575
42.5k
    tif->tif_tagmethods.printdir = Fax3PrintDir; /* hook for codec tags */
1576
42.5k
    sp->groupoptions = 0;
1577
1578
42.5k
    if (sp->rw_mode == O_RDONLY) /* FIXME: improve for in place update */
1579
36.0k
        tif->tif_flags |= TIFF_NOBITREV; /* decoder does bit reversal */
1580
42.5k
    DecoderState(tif)->runs = NULL;
1581
42.5k
    TIFFSetField(tif, TIFFTAG_FAXFILLFUNC, _TIFFFax3fillruns);
1582
42.5k
    EncoderState(tif)->refline = NULL;
1583
1584
    /*
1585
     * Install codec methods.
1586
     */
1587
42.5k
    tif->tif_fixuptags = Fax3FixupTags;
1588
42.5k
    tif->tif_setupdecode = Fax3SetupState;
1589
42.5k
    tif->tif_predecode = Fax3PreDecode;
1590
42.5k
    tif->tif_decoderow = Fax3Decode1D;
1591
42.5k
    tif->tif_decodestrip = Fax3Decode1D;
1592
42.5k
    tif->tif_decodetile = Fax3Decode1D;
1593
42.5k
    tif->tif_setupencode = Fax3SetupState;
1594
42.5k
    tif->tif_preencode = Fax3PreEncode;
1595
42.5k
    tif->tif_postencode = Fax3PostEncode;
1596
42.5k
    tif->tif_encoderow = Fax3Encode;
1597
42.5k
    tif->tif_encodestrip = Fax3Encode;
1598
42.5k
    tif->tif_encodetile = Fax3Encode;
1599
42.5k
    tif->tif_close = Fax3Close;
1600
42.5k
    tif->tif_cleanup = Fax3Cleanup;
1601
42.5k
    tif->tif_getmaxcompressionratio = Fax3GetMaxCompressionRatio;
1602
1603
42.5k
    return (1);
1604
42.5k
}
1605
1606
int TIFFInitCCITTFax3(TIFF *tif, int scheme)
1607
20.9k
{
1608
20.9k
    (void)scheme;
1609
20.9k
    if (InitCCITTFax3(tif))
1610
20.9k
    {
1611
        /*
1612
         * Merge codec-specific tag information.
1613
         */
1614
20.9k
        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
20.9k
        return TIFFSetField(tif, TIFFTAG_FAXMODE, FAXMODE_CLASSF);
1625
20.9k
    }
1626
0
    else
1627
0
        return 01;
1628
20.9k
}
1629
1630
/*
1631
 * CCITT Group 4 (T.6) Facsimile-compatible
1632
 * Compression Scheme Support.
1633
 */
1634
1635
#define SWAP(t, a, b)                                                          \
1636
995k
    {                                                                          \
1637
995k
        t x;                                                                   \
1638
995k
        x = (a);                                                               \
1639
995k
        (a) = (b);                                                             \
1640
995k
        (b) = x;                                                               \
1641
995k
    }
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
159k
{
1647
159k
    DECLARE_STATE_2D(tif, sp, "Fax4Decode");
1648
159k
    (void)s;
1649
159k
    if (occ % sp->b.rowbytes)
1650
0
    {
1651
0
        TIFFErrorExtR(tif, module, "Fractional scanlines cannot be read");
1652
0
        return (-1);
1653
0
    }
1654
159k
    if (CheckReachedCounters(tif, module, sp))
1655
0
        return (-1);
1656
159k
    CACHE_STATE(tif, sp);
1657
159k
    int start = sp->line;
1658
1.15M
    while (occ > 0)
1659
1.00M
    {
1660
1.00M
        a0 = 0;
1661
1.00M
        RunLength = 0;
1662
1.00M
        pa = thisrun = sp->curruns;
1663
1.00M
        pb = sp->refruns;
1664
1.00M
        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.00M
        EXPAND2D(EOFG4);
1671
1.00M
        if (EOLcnt)
1672
6.92k
            goto EOFG4;
1673
995k
        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
995k
        (*sp->fill)(buf, thisrun, pa, (uint32_t)lastx);
1682
995k
        SETVALUE(0); /* imaginary change for reference */
1683
995k
        SWAP(uint32_t *, sp->curruns, sp->refruns);
1684
995k
        buf += sp->b.rowbytes;
1685
995k
        occ -= sp->b.rowbytes;
1686
995k
        sp->line++;
1687
995k
        continue;
1688
11.0k
    EOFG4:
1689
11.0k
        NeedBits16(13, BADG4);
1690
11.0k
    BADG4:
1691
#ifdef FAX3_DEBUG
1692
        if (GetBits(13) != 0x1001)
1693
            fputs("Bad EOFB\n", stderr);
1694
#endif
1695
11.0k
        ClrBits(13);
1696
11.0k
        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
11.0k
        (*sp->fill)(buf, thisrun, pa, (uint32_t)lastx);
1705
11.0k
        UNCACHE_STATE(tif, sp);
1706
11.0k
        return (sp->line != start
1707
11.0k
                    ? 1
1708
11.0k
                    : -1); /* don't error on badly-terminated strips */
1709
11.0k
    }
1710
148k
    UNCACHE_STATE(tif, sp);
1711
148k
    return (1);
1712
159k
}
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
1.89M
{
1720
1.89M
    static const char module[] = "Fax4Encode";
1721
1.89M
    Fax3CodecState *sp = EncoderState(tif);
1722
1.89M
    (void)s;
1723
1.89M
    if (cc % sp->b.rowbytes)
1724
0
    {
1725
0
        TIFFErrorExtR(tif, module, "Fractional scanlines cannot be written");
1726
0
        return (0);
1727
0
    }
1728
3.78M
    while (cc > 0)
1729
1.89M
    {
1730
1.89M
        if (!Fax3Encode2DRow(tif, bp, sp->refline, sp->b.rowpixels))
1731
0
            return (0);
1732
1.89M
        _TIFFmemcpy(sp->refline, bp, sp->b.rowbytes);
1733
1.89M
        bp += sp->b.rowbytes;
1734
1.89M
        cc -= sp->b.rowbytes;
1735
1.89M
    }
1736
1.89M
    return (1);
1737
1.89M
}
1738
1739
static int Fax4PostEncode(TIFF *tif)
1740
5.03k
{
1741
5.03k
    Fax3CodecState *sp = EncoderState(tif);
1742
1743
    /* terminate strip w/ EOFB */
1744
5.03k
    Fax3PutBits(tif, EOL, 12);
1745
5.03k
    Fax3PutBits(tif, EOL, 12);
1746
5.03k
    if (sp->bit != 8)
1747
5.03k
        Fax3FlushBits(tif, sp);
1748
5.03k
    return (1);
1749
5.03k
}
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
15.4k
{
1763
15.4k
    (void)scheme;
1764
15.4k
    if (InitCCITTFax3(tif))
1765
15.4k
    { /* reuse G3 support */
1766
        /*
1767
         * Merge codec-specific tag information.
1768
         */
1769
15.4k
        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
15.4k
        tif->tif_decoderow = Fax4Decode;
1777
15.4k
        tif->tif_decodestrip = Fax4Decode;
1778
15.4k
        tif->tif_decodetile = Fax4Decode;
1779
15.4k
        tif->tif_encoderow = Fax4Encode;
1780
15.4k
        tif->tif_encodestrip = Fax4Encode;
1781
15.4k
        tif->tif_encodetile = Fax4Encode;
1782
15.4k
        tif->tif_postencode = Fax4PostEncode;
1783
15.4k
        tif->tif_getmaxcompressionratio = Fax4GetMaxCompressionRatio;
1784
        /*
1785
         * Suppress RTC at the end of each strip.
1786
         */
1787
15.4k
        return TIFFSetField(tif, TIFFTAG_FAXMODE, FAXMODE_NORTC);
1788
15.4k
    }
1789
0
    else
1790
0
        return (0);
1791
15.4k
}
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
29.1k
{
1803
29.1k
    DECLARE_STATE(tif, sp, "Fax3DecodeRLE");
1804
29.1k
    int mode = sp->b.mode;
1805
29.1k
    (void)s;
1806
29.1k
    if (occ % sp->b.rowbytes)
1807
0
    {
1808
0
        TIFFErrorExtR(tif, module, "Fractional scanlines cannot be read");
1809
0
        return (-1);
1810
0
    }
1811
29.1k
    if (CheckReachedCounters(tif, module, sp))
1812
0
        return (-1);
1813
29.1k
    CACHE_STATE(tif, sp);
1814
29.1k
    thisrun = sp->curruns;
1815
364k
    while (occ > 0)
1816
336k
    {
1817
336k
        a0 = 0;
1818
336k
        RunLength = 0;
1819
336k
        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
336k
        EXPAND1D(EOFRLE);
1826
334k
        (*sp->fill)(buf, thisrun, pa, (uint32_t)lastx);
1827
        /*
1828
         * Cleanup at the end of the row.
1829
         */
1830
334k
        if (mode & FAXMODE_BYTEALIGN)
1831
166k
        {
1832
166k
            int n = BitsAvail - (BitsAvail & ~7);
1833
166k
            ClrBits(n);
1834
166k
        }
1835
168k
        else if (mode & FAXMODE_WORDALIGN)
1836
168k
        {
1837
168k
            int n = BitsAvail - (BitsAvail & ~15);
1838
168k
            ClrBits(n);
1839
168k
            if (BitsAvail == 0 && !isAligned(cp, uint16_t))
1840
21.8k
                cp++;
1841
168k
        }
1842
334k
        buf += sp->b.rowbytes;
1843
334k
        occ -= sp->b.rowbytes;
1844
334k
        sp->line++;
1845
334k
        continue;
1846
1.61k
    EOFRLE: /* premature EOF */
1847
1.61k
        (*sp->fill)(buf, thisrun, pa, (uint32_t)lastx);
1848
1.61k
        UNCACHE_STATE(tif, sp);
1849
1.61k
        return (-1);
1850
336k
    }
1851
27.4k
    UNCACHE_STATE(tif, sp);
1852
27.4k
    return (1);
1853
29.1k
}
1854
1855
static uint64_t Fax3RLEGetMaxCompressionRatio(TIFF *tif)
1856
0
{
1857
0
    (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
0
    return 250;
1868
0
}
1869
1870
int TIFFInitCCITTRLE(TIFF *tif, int scheme)
1871
5.41k
{
1872
5.41k
    (void)scheme;
1873
5.41k
    if (InitCCITTFax3(tif))
1874
5.41k
    { /* reuse G3 support */
1875
5.41k
        tif->tif_decoderow = Fax3DecodeRLE;
1876
5.41k
        tif->tif_decodestrip = Fax3DecodeRLE;
1877
5.41k
        tif->tif_decodetile = Fax3DecodeRLE;
1878
5.41k
        tif->tif_getmaxcompressionratio = Fax3RLEGetMaxCompressionRatio;
1879
        /*
1880
         * Suppress RTC+EOLs when encoding and byte-align data.
1881
         */
1882
5.41k
        return TIFFSetField(tif, TIFFTAG_FAXMODE,
1883
5.41k
                            FAXMODE_NORTC | FAXMODE_NOEOL | FAXMODE_BYTEALIGN);
1884
5.41k
    }
1885
0
    else
1886
0
        return (0);
1887
5.41k
}
1888
1889
int TIFFInitCCITTRLEW(TIFF *tif, int scheme)
1890
731
{
1891
731
    (void)scheme;
1892
731
    if (InitCCITTFax3(tif))
1893
731
    { /* reuse G3 support */
1894
731
        tif->tif_decoderow = Fax3DecodeRLE;
1895
731
        tif->tif_decodestrip = Fax3DecodeRLE;
1896
731
        tif->tif_decodetile = Fax3DecodeRLE;
1897
731
        tif->tif_getmaxcompressionratio = Fax3RLEGetMaxCompressionRatio;
1898
        /*
1899
         * Suppress RTC+EOLs when encoding and word-align data.
1900
         */
1901
731
        return TIFFSetField(tif, TIFFTAG_FAXMODE,
1902
731
                            FAXMODE_NORTC | FAXMODE_NOEOL | FAXMODE_WORDALIGN);
1903
731
    }
1904
0
    else
1905
0
        return (0);
1906
731
}
1907
#endif /* CCITT_SUPPORT */