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