Coverage Report

Created: 2026-07-25 06:50

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