Coverage Report

Created: 2025-12-03 07:28

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