Coverage Report

Created: 2025-06-10 07:27

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