home *** CD-ROM | disk | FTP | other *** search
/ The Datafile PD-CD 4 / DATAFILE_PDCD4.iso / utilities / utilsf / libtiff / c / tif_fax3 < prev    next >
Encoding:
Text File  |  1995-10-12  |  39.8 KB  |  1,473 lines

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