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