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