Coverage Report

Created: 2025-06-13 06:29

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