Coverage Report

Created: 2025-11-16 06:25

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