Coverage Report

Created: 2026-04-10 07:04

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