home *** CD-ROM | disk | FTP | other *** search
/ PC World 2002 February / PCWorld_2002-02_cd.bin / Software / Vyzkuste / pdflib / pdflib-4.0.1.sit / pdflib-4.0.1 / tiff / tif_fax3.c < prev    next >
Encoding:
C/C++ Source or Header  |  2001-07-04  |  31.8 KB  |  1,170 lines  |  [TEXT/CWIE]

  1. /*
  2.  * Copyright (c) 1990-1997 Sam Leffler
  3.  * Copyright (c) 1991-1997 Silicon Graphics, Inc.
  4.  *
  5.  * Permission to use, copy, modify, distribute, and sell this software and 
  6.  * its documentation for any purpose is hereby granted without fee, provided
  7.  * that (i) the above copyright notices and this permission notice appear in
  8.  * all copies of the software and related documentation, and (ii) the names of
  9.  * Sam Leffler and Silicon Graphics may not be used in any advertising or
  10.  * publicity relating to the software without the specific, prior written
  11.  * permission of Sam Leffler and Silicon Graphics.
  12.  * 
  13.  * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, 
  14.  * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY 
  15.  * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  
  16.  * 
  17.  * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
  18.  * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
  19.  * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
  20.  * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF 
  21.  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
  22.  * OF THIS SOFTWARE.
  23.  */
  24.  
  25.  
  26. /* $Id: tif_fax3.c,v 1.11 2001/04/05 15:58:17 tm Exp $ */
  27.  
  28. #include "tiffiop.h"
  29. #ifdef CCITT_SUPPORT
  30. /*
  31.  * TIFF Library.
  32.  *
  33.  * CCITT Group 3 (T.4) and Group 4 (T.6) Compression Support.
  34.  *
  35.  * This file contains support for decoding and encoding TIFF
  36.  * compression algorithms 2, 3, 4, and 32771.
  37.  *
  38.  * Decoder support is derived, with permission, from the code
  39.  * in Frank Cringle's viewfax program;
  40.  *      Copyright (C) 1990, 1995  Frank D. Cringle.
  41.  */
  42. #include "tif_fax3.h"
  43. #define    G3CODES
  44. #include "t4.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     rw_mode;                /* O_RDONLY for decode, else encode */
  59.     int    mode;            /* operating mode */
  60.     uint32    rowbytes;        /* bytes in a decoded scanline */
  61.     uint32    rowpixels;        /* pixels in a scanline */
  62.  
  63.     uint16    cleanfaxdata;        /* CleanFaxData tag */
  64.     uint32    badfaxrun;        /* BadFaxRun tag */
  65.     uint32    badfaxlines;        /* BadFaxLines tag */
  66.     uint32    groupoptions;        /* Group 3/4 options tag */
  67.     uint32    recvparams;        /* encoded Class 2 session params */
  68.     char*    subaddress;        /* subaddress string */
  69.     uint32    recvtime;        /* time spent receiving (secs) */
  70.     TIFFVGetMethod vgetparent;    /* super-class method */
  71.     TIFFVSetMethod vsetparent;    /* super-class method */
  72. } Fax3BaseState;
  73. #define    Fax3State(tif)        ((Fax3BaseState*) (tif)->tif_data)
  74.  
  75. typedef struct {
  76.     Fax3BaseState b;
  77.     const u_char* bitmap;        /* bit reversal table */
  78.     uint32    data;            /* current i/o byte/word */
  79.     int    bit;            /* current i/o bit in byte */
  80.     int    EOLcnt;            /* count of EOL codes recognized */
  81.     TIFFFaxFillFunc fill;        /* fill routine */
  82.     uint32*    runs;            /* b&w runs for current/previous row */
  83.     uint32*    refruns;        /* runs for reference line */
  84.     uint32*    curruns;        /* runs for current line */
  85. } Fax3DecodeState;
  86. #define    DecoderState(tif)    ((Fax3DecodeState*) Fax3State(tif))
  87.  
  88. typedef enum { G3_1D, G3_2D } Ttag;
  89. #define    is2DEncoding(sp) \
  90.     (sp->b.groupoptions & GROUP3OPT_2DENCODING)
  91. #define    isAligned(p,t)    ((((u_long)(p)) & (sizeof (t)-1)) == 0)
  92.  
  93. /*
  94.  * Group 3 and Group 4 Decoding.
  95.  */
  96.  
  97. /*
  98.  * These macros glue the TIFF library state to
  99.  * the state expected by Frank's decoder.
  100.  */
  101. #define    DECLARE_STATE(tif, sp, mod)                    \
  102.     static const char module[] = mod;                    \
  103.     Fax3DecodeState* sp = DecoderState(tif);                \
  104.     int a0;                /* reference element */        \
  105.     int lastx = sp->b.rowpixels;    /* last element in row */    \
  106.     uint32 BitAcc;            /* bit accumulator */        \
  107.     int BitsAvail;            /* # valid bits in BitAcc */    \
  108.     int RunLength;            /* length of current run */    \
  109.     u_char* cp;                /* next byte of input data */    \
  110.     u_char* ep;                /* end of input data */        \
  111.     uint32* pa;                /* place to stuff next run */    \
  112.     uint32* thisrun;            /* current row's run array */    \
  113.     int EOLcnt;                /* # EOL codes recognized */    \
  114.     const u_char* bitmap = sp->bitmap;    /* input data bit reverser */    \
  115.     const TIFFFaxTabEnt* TabEnt
  116. #define    DECLARE_STATE_2D(tif, sp, mod)                    \
  117.     DECLARE_STATE(tif, sp, mod);                    \
  118.     int b1;                /* next change on prev line */    \
  119.     uint32* pb                /* next run in reference line */\
  120. /*
  121.  * Load any state that may be changed during decoding.
  122.  */
  123. #define    CACHE_STATE(tif, sp) do {                    \
  124.     BitAcc = sp->data;                            \
  125.     BitsAvail = sp->bit;                        \
  126.     EOLcnt = sp->EOLcnt;                        \
  127.     cp = (unsigned char*) tif->tif_rawcp;                \
  128.     ep = cp + tif->tif_rawcc;                        \
  129. } while (0)
  130. /*
  131.  * Save state possibly changed during decoding.
  132.  */
  133. #define    UNCACHE_STATE(tif, sp) do {                    \
  134.     sp->bit = BitsAvail;                        \
  135.     sp->data = BitAcc;                            \
  136.     sp->EOLcnt = EOLcnt;                        \
  137.     tif->tif_rawcc -= (tidata_t) cp - tif->tif_rawcp;            \
  138.     tif->tif_rawcp = (tidata_t) cp;                    \
  139. } while (0)
  140.  
  141. /*
  142.  * Setup state for decoding a strip.
  143.  */
  144. static int
  145. Fax3PreDecode(TIFF* tif, tsample_t s)
  146. {
  147.     Fax3DecodeState* sp = DecoderState(tif);
  148.  
  149.     (void) s;
  150.     sp->bit = 0;            /* force initial read */
  151.     sp->data = 0;
  152.     sp->EOLcnt = 0;            /* force initial scan for EOL */
  153.     /*
  154.      * Decoder assumes lsb-to-msb bit order.  Note that we select
  155.      * this here rather than in Fax3SetupState so that viewers can
  156.      * hold the image open, fiddle with the FillOrder tag value,
  157.      * and then re-decode the image.  Otherwise they'd need to close
  158.      * and open the image to get the state reset.
  159.      */
  160.     sp->bitmap =
  161.         TIFFGetBitRevTable(tif->tif_dir.td_fillorder != FILLORDER_LSB2MSB);
  162.     if (sp->refruns) {        /* init reference line to white */
  163.         sp->refruns[0] = (uint32) sp->b.rowpixels;
  164.         sp->refruns[1] = 0;
  165.     }
  166.     return (1);
  167. }
  168.  
  169. /*
  170.  * Routine for handling various errors/conditions.
  171.  * Note how they are "glued into the decoder" by
  172.  * overriding the definitions used by the decoder.
  173.  */
  174.  
  175. static void
  176. Fax3Unexpected(const char* module, TIFF* tif, uint32 a0)
  177. {
  178.     TIFFError(module, "%s: Bad code word at scanline %d (x %lu)",
  179.         tif->tif_name, tif->tif_row, (u_long) a0);
  180. }
  181. #define    unexpected(table, a0)    Fax3Unexpected(module, tif, a0)
  182.  
  183. static void
  184. Fax3Extension(const char* module, TIFF* tif, uint32 a0)
  185. {
  186.     TIFFError(module,
  187.         "%s: Uncompressed data (not supported) at scanline %d (x %lu)",
  188.         tif->tif_name, tif->tif_row, (u_long) a0);
  189. }
  190. #define    extension(a0)    Fax3Extension(module, tif, a0)
  191.  
  192. static void
  193. Fax3BadLength(const char* module, TIFF* tif, uint32 a0, uint32 lastx)
  194. {
  195.     TIFFWarning(module, "%s: %s at scanline %d (got %lu, expected %lu)",
  196.         tif->tif_name,
  197.         a0 < lastx ? "Premature EOL" : "Line length mismatch",
  198.         tif->tif_row, (u_long) a0, (u_long) lastx);
  199. }
  200. #define    badlength(a0,lastx)    Fax3BadLength(module, tif, a0, lastx)
  201.  
  202. static void
  203. Fax3PrematureEOF(const char* module, TIFF* tif, uint32 a0)
  204. {
  205.     TIFFWarning(module, "%s: Premature EOF at scanline %d (x %lu)",
  206.         tif->tif_name, tif->tif_row, (u_long) a0);
  207. }
  208. #define    prematureEOF(a0)    Fax3PrematureEOF(module, tif, a0)
  209.  
  210. #define    Nop
  211.  
  212. /*
  213.  * Decode the requested amount of G3 1D-encoded data.
  214.  */
  215. static int
  216. Fax3Decode1D(TIFF* tif, tidata_t buf, tsize_t occ, tsample_t s)
  217. {
  218.     DECLARE_STATE(tif, sp, "Fax3Decode1D");
  219.  
  220.     (void) s;
  221.     CACHE_STATE(tif, sp);
  222.     thisrun = sp->curruns;
  223.     while ((long)occ > 0) {
  224.         a0 = 0;
  225.         RunLength = 0;
  226.         pa = thisrun;
  227. #ifdef FAX3_DEBUG
  228.         printf("\nBitAcc=%08X, BitsAvail = %d\n", BitAcc, BitsAvail);
  229.         printf("-------------------- %d\n", tif->tif_row);
  230.         fflush(stdout);
  231. #endif
  232.         SYNC_EOL(EOF1D);
  233.         EXPAND1D(EOF1Da);
  234.         (*sp->fill)(buf, thisrun, pa, lastx);
  235.         buf += sp->b.rowbytes;
  236.         occ -= sp->b.rowbytes;
  237.         if (occ != 0)
  238.             tif->tif_row++;
  239.         continue;
  240.     EOF1D:                /* premature EOF */
  241.         CLEANUP_RUNS();
  242.     EOF1Da:                /* premature EOF */
  243.         (*sp->fill)(buf, thisrun, pa, lastx);
  244.         UNCACHE_STATE(tif, sp);
  245.         return (-1);
  246.     }
  247.     UNCACHE_STATE(tif, sp);
  248.     return (1);
  249. }
  250.  
  251. #define    SWAP(t,a,b)    { t x; x = (a); (a) = (b); (b) = x; }
  252. /*
  253.  * Decode the requested amount of G3 2D-encoded data.
  254.  */
  255. static int
  256. Fax3Decode2D(TIFF* tif, tidata_t buf, tsize_t occ, tsample_t s)
  257. {
  258.     DECLARE_STATE_2D(tif, sp, "Fax3Decode2D");
  259.     int is1D;            /* current line is 1d/2d-encoded */
  260.  
  261.     (void) s;
  262.     CACHE_STATE(tif, sp);
  263.     while ((long)occ > 0) {
  264.         a0 = 0;
  265.         RunLength = 0;
  266.         pa = thisrun = sp->curruns;
  267. #ifdef FAX3_DEBUG
  268.         printf("\nBitAcc=%08X, BitsAvail = %d EOLcnt = %d",
  269.             BitAcc, BitsAvail, EOLcnt);
  270. #endif
  271.         SYNC_EOL(EOF2D);
  272.         NeedBits8(1, EOF2D);
  273.         is1D = GetBits(1);    /* 1D/2D-encoding tag bit */
  274.         ClrBits(1);
  275. #ifdef FAX3_DEBUG
  276.         printf(" %s\n-------------------- %d\n",
  277.             is1D ? "1D" : "2D", tif->tif_row);
  278.         fflush(stdout);
  279. #endif
  280.         pb = sp->refruns;
  281.         b1 = *pb++;
  282.         if (is1D)
  283.             EXPAND1D(EOF2Da);
  284.         else
  285.             EXPAND2D(EOF2Da);
  286.         (*sp->fill)(buf, thisrun, pa, lastx);
  287.         SETVAL(0);        /* imaginary change for reference */
  288.         SWAP(uint32*, sp->curruns, sp->refruns);
  289.         buf += sp->b.rowbytes;
  290.         occ -= sp->b.rowbytes;
  291.         if (occ != 0)
  292.             tif->tif_row++;
  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 defined(__alpha) || _MIPS_SZLONG == 64
  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(u_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.     u_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 = (u_char*) lp;
  389.             }
  390.             ZERO(n, cp);
  391.             run &= 7;
  392.             }
  393. #ifdef PURIFY
  394.             if (run)
  395.             cp[0] &= 0xff >> run;
  396. #else
  397.             cp[0] &= 0xff >> run;
  398. #endif
  399.         } else
  400.             cp[0] &= ~(_fillmasks[run]>>bx);
  401.         x += runs[0];
  402.         }
  403.         run = runs[1];
  404.         if (x+run > lastx || run > lastx )
  405.         run = runs[1] = lastx - x;
  406.         if (run) {
  407.         cp = buf + (x>>3);
  408.         bx = x&7;
  409.         if (run > 8-bx) {
  410.             if (bx) {            /* align to byte boundary */
  411.             *cp++ |= 0xff >> bx;
  412.             run -= 8-bx;
  413.             }
  414.             if( (n = run>>3) != 0 ) {    /* multiple bytes to fill */
  415.             if ((n/sizeof (long)) > 1) {
  416.                 /*
  417.                  * Align to longword boundary and fill.
  418.                  */
  419.                 for (; n && !isAligned(cp, long); n--)
  420.                 *cp++ = 0xff;
  421.                 lp = (long*) cp;
  422.                 nw = (int32)(n / sizeof (long));
  423.                 n -= nw * sizeof (long);
  424.                 do {
  425.                 *lp++ = -1L;
  426.                 } while (--nw);
  427.                 cp = (u_char*) lp;
  428.             }
  429.             FILL(n, cp);
  430.             run &= 7;
  431.             }
  432. #ifdef PURIFY
  433.             if (run)
  434.             cp[0] |= 0xff00 >> run;
  435. #else
  436.             cp[0] |= 0xff00 >> run;
  437. #endif
  438.         } else
  439.             cp[0] |= _fillmasks[run]>>bx;
  440.         x += runs[1];
  441.         }
  442.     }
  443. }
  444. #undef    ZERO
  445. #undef    FILL
  446.  
  447. /*
  448.  * Setup G3/G4-related compression/decompression state
  449.  * before data is processed.  This routine is called once
  450.  * per image -- it sets up different state based on whether
  451.  * or not decoding or encoding is being done and whether
  452.  * 1D- or 2D-encoded data is involved.
  453.  */
  454. static int
  455. Fax3SetupState(TIFF* tif)
  456. {
  457.     TIFFDirectory* td = &tif->tif_dir;
  458.     Fax3BaseState* sp = Fax3State(tif);
  459.     long rowbytes, rowpixels;
  460.     int needsRefLine;
  461.  
  462.     if (td->td_bitspersample != 1) {
  463.         TIFFError(tif->tif_name,
  464.             "Bits/sample must be 1 for Group 3/4 encoding/decoding");
  465.         return (0);
  466.     }
  467.     /*
  468.      * Calculate the scanline/tile widths.
  469.      */
  470.     if (isTiled(tif)) {
  471.         rowbytes = TIFFTileRowSize(tif);
  472.         rowpixels = td->td_tilewidth;
  473.     } else {
  474.         rowbytes = TIFFScanlineSize(tif);
  475.         rowpixels = td->td_imagewidth;
  476.     }
  477.     sp->rowbytes = (uint32) rowbytes;
  478.     sp->rowpixels = (uint32) rowpixels;
  479.     /*
  480.      * Allocate any additional space required for decoding/encoding.
  481.      */
  482.     needsRefLine = (
  483.         (sp->groupoptions & GROUP3OPT_2DENCODING) ||
  484.         td->td_compression == COMPRESSION_CCITTFAX4
  485.     );
  486.     if (sp->rw_mode == O_RDONLY) {    /* 1d/2d decoding */
  487.         Fax3DecodeState* dsp = DecoderState(tif);
  488.         uint32 nruns = needsRefLine ?
  489.              2*TIFFroundup(rowpixels,32) : rowpixels;
  490.  
  491.         dsp->runs = (uint32*)
  492.             _TIFFmalloc(tif, (2*nruns+3)*sizeof (uint32));
  493.         if (dsp->runs == NULL) {
  494.             TIFFError("Fax3SetupState",
  495.                 "%s: No space for Group 3/4 run arrays",
  496.                 tif->tif_name);
  497.             return (0);
  498.         }
  499.         dsp->curruns = dsp->runs;
  500.         if (needsRefLine)
  501.             dsp->refruns = dsp->runs + (nruns>>1);
  502.         else
  503.             dsp->refruns = NULL;
  504.         if (is2DEncoding(dsp)) {    /* NB: default is 1D routine */
  505.             tif->tif_decoderow = Fax3Decode2D;
  506.             tif->tif_decodestrip = Fax3Decode2D;
  507.             tif->tif_decodetile = Fax3Decode2D;
  508.         }
  509.     }
  510.     return (1);
  511. }
  512.  
  513. /*
  514.  * CCITT Group 3 FAX Encoding.
  515.  */
  516.  
  517. #define    Fax3FlushBits(tif, sp) {                \
  518.     if ((tif)->tif_rawcc >= (tif)->tif_rawdatasize)        \
  519.         (void) TIFFFlushData1(tif);            \
  520.     *(tif)->tif_rawcp++ = (sp)->data;            \
  521.     (tif)->tif_rawcc++;                    \
  522.     (sp)->data = 0, (sp)->bit = 8;                \
  523. }
  524. #define    _FlushBits(tif) {                    \
  525.     if ((tif)->tif_rawcc >= (tif)->tif_rawdatasize)        \
  526.         (void) TIFFFlushData1(tif);            \
  527.     *(tif)->tif_rawcp++ = data;                \
  528.     (tif)->tif_rawcc++;                    \
  529.     data = 0, bit = 8;                    \
  530. }
  531. static const int _msbmask[9] =
  532.     { 0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff };
  533. #define    _PutBits(tif, bits, length) {                \
  534.     while (length > bit) {                    \
  535.         data |= bits >> (length - bit);            \
  536.         length -= bit;                    \
  537.         _FlushBits(tif);                \
  538.     }                            \
  539.     data |= (bits & _msbmask[length]) << (bit - length);    \
  540.     bit -= length;                        \
  541.     if (bit == 0)                        \
  542.         _FlushBits(tif);                \
  543. }
  544.     
  545. /*
  546.  * Write a variable-length bit-value to
  547.  * the output stream.  Values are
  548.  * assumed to be at most 16 bits.
  549.  */
  550. static void
  551. Fax3PutBits(TIFF* tif, u_int bits, u_int length)
  552. {
  553.     (void) tif;
  554.     (void) bits;
  555.     (void) length;
  556. }
  557.  
  558. /*
  559.  * Write a code to the output stream.
  560.  */
  561. #define putcode(tif, te)    Fax3PutBits(tif, (te)->code, (te)->length)
  562.  
  563. #ifdef FAX3_DEBUG
  564. #define    DEBUG_COLOR(w) (tab == TIFFFaxWhiteCodes ? w "W" : w "B")
  565. #define    DEBUG_PRINT(what,len) {                        \
  566.     int t;                                \
  567.     printf("%08X/%-2d: %s%5d\t", data, bit, DEBUG_COLOR(what), len);    \
  568.     for (t = length-1; t >= 0; t--)                    \
  569.     putchar(code & (1<<t) ? '1' : '0');                \
  570.     putchar('\n');                            \
  571. }
  572. #endif
  573.  
  574. /*
  575.  * Write the sequence of codes that describes
  576.  * the specified span of zero's or one's.  The
  577.  * appropriate table that holds the make-up and
  578.  * terminating codes is supplied.
  579.  */
  580. static void
  581. putspan(TIFF* tif, int32 span, const tableentry* tab)
  582. {
  583.     (void) tif;
  584.     (void) span;
  585.     (void) tab;
  586. }
  587.  
  588. /*
  589.  * Write an EOL code to the output stream.  The zero-fill
  590.  * logic for byte-aligning encoded scanlines is handled
  591.  * here.  We also handle writing the tag bit for the next
  592.  * scanline when doing 2d encoding.
  593.  */
  594. static void
  595. Fax3PutEOL(TIFF* tif)
  596. {
  597.     (void) tif;
  598. }
  599.  
  600. static const u_char zeroruns[256] = {
  601.     8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,    /* 0x00 - 0x0f */
  602.     3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,    /* 0x10 - 0x1f */
  603.     2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,    /* 0x20 - 0x2f */
  604.     2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,    /* 0x30 - 0x3f */
  605.     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,    /* 0x40 - 0x4f */
  606.     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,    /* 0x50 - 0x5f */
  607.     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,    /* 0x60 - 0x6f */
  608.     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,    /* 0x70 - 0x7f */
  609.     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,    /* 0x80 - 0x8f */
  610.     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,    /* 0x90 - 0x9f */
  611.     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,    /* 0xa0 - 0xaf */
  612.     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,    /* 0xb0 - 0xbf */
  613.     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,    /* 0xc0 - 0xcf */
  614.     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,    /* 0xd0 - 0xdf */
  615.     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,    /* 0xe0 - 0xef */
  616.     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,    /* 0xf0 - 0xff */
  617. };
  618. static const u_char oneruns[256] = {
  619.     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,    /* 0x00 - 0x0f */
  620.     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,    /* 0x10 - 0x1f */
  621.     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,    /* 0x20 - 0x2f */
  622.     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,    /* 0x30 - 0x3f */
  623.     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,    /* 0x40 - 0x4f */
  624.     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,    /* 0x50 - 0x5f */
  625.     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,    /* 0x60 - 0x6f */
  626.     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,    /* 0x70 - 0x7f */
  627.     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,    /* 0x80 - 0x8f */
  628.     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,    /* 0x90 - 0x9f */
  629.     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,    /* 0xa0 - 0xaf */
  630.     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,    /* 0xb0 - 0xbf */
  631.     2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,    /* 0xc0 - 0xcf */
  632.     2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,    /* 0xd0 - 0xdf */
  633.     3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,    /* 0xe0 - 0xef */
  634.     4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 7, 8,    /* 0xf0 - 0xff */
  635. };
  636.  
  637. /*
  638.  * On certain systems it pays to inline
  639.  * the routines that find pixel spans.
  640.  */
  641. #ifdef VAXC
  642. static    int32 find0span(u_char*, int32, int32);
  643. static    int32 find1span(u_char*, int32, int32);
  644. #pragma inline(find0span,find1span)
  645. #endif
  646.  
  647. /*
  648.  * Find a span of ones or zeros using the supplied
  649.  * table.  The ``base'' of the bit string is supplied
  650.  * along with the start+end bit indices.
  651.  */
  652. INLINE static int32
  653. find0span(u_char* bp, int32 bs, int32 be)
  654. {
  655.     int32 bits = be - bs;
  656.     int32 n, span;
  657.  
  658.     bp += bs>>3;
  659.     /*
  660.      * Check partial byte on lhs.
  661.      */
  662.     if (bits > 0 && (n = (bs & 7))) {
  663.         span = zeroruns[(*bp << n) & 0xff];
  664.         if (span > 8-n)        /* table value too generous */
  665.             span = 8-n;
  666.         if (span > bits)    /* constrain span to bit range */
  667.             span = bits;
  668.         if (n+span < 8)        /* doesn't extend to edge of byte */
  669.             return (span);
  670.         bits -= span;
  671.         bp++;
  672.     } else
  673.         span = 0;
  674.     if (bits >= 2*8*sizeof (long)) {
  675.         long* lp;
  676.         /*
  677.          * Align to longword boundary and check longwords.
  678.          */
  679.         while (!isAligned(bp, long)) {
  680.             if (*bp != 0x00)
  681.                 return (span + zeroruns[*bp]);
  682.             span += 8, bits -= 8;
  683.             bp++;
  684.         }
  685.         lp = (long*) bp;
  686.         while (bits >= 8*sizeof (long) && *lp == 0) {
  687.             span += 8*sizeof (long), bits -= 8*sizeof (long);
  688.             lp++;
  689.         }
  690.         bp = (u_char*) lp;
  691.     }
  692.     /*
  693.      * Scan full bytes for all 0's.
  694.      */
  695.     while (bits >= 8) {
  696.         if (*bp != 0x00)    /* end of run */
  697.             return (span + zeroruns[*bp]);
  698.         span += 8, bits -= 8;
  699.         bp++;
  700.     }
  701.     /*
  702.      * Check partial byte on rhs.
  703.      */
  704.     if (bits > 0) {
  705.         n = zeroruns[*bp];
  706.         span += (n > bits ? bits : n);
  707.     }
  708.     return (span);
  709. }
  710.  
  711. INLINE static int32
  712. find1span(u_char* bp, int32 bs, int32 be)
  713. {
  714.     int32 bits = be - bs;
  715.     int32 n, span;
  716.  
  717.     bp += bs>>3;
  718.     /*
  719.      * Check partial byte on lhs.
  720.      */
  721.     if (bits > 0 && (n = (bs & 7))) {
  722.         span = oneruns[(*bp << n) & 0xff];
  723.         if (span > 8-n)        /* table value too generous */
  724.             span = 8-n;
  725.         if (span > bits)    /* constrain span to bit range */
  726.             span = bits;
  727.         if (n+span < 8)        /* doesn't extend to edge of byte */
  728.             return (span);
  729.         bits -= span;
  730.         bp++;
  731.     } else
  732.         span = 0;
  733.     if (bits >= 2*8*sizeof (long)) {
  734.         long* lp;
  735.         /*
  736.          * Align to longword boundary and check longwords.
  737.          */
  738.         while (!isAligned(bp, long)) {
  739.             if (*bp != 0xff)
  740.                 return (span + oneruns[*bp]);
  741.             span += 8, bits -= 8;
  742.             bp++;
  743.         }
  744.         lp = (long*) bp;
  745.         while (bits >= 8*sizeof (long) && *lp == ~0) {
  746.             span += 8*sizeof (long), bits -= 8*sizeof (long);
  747.             lp++;
  748.         }
  749.         bp = (u_char*) lp;
  750.     }
  751.     /*
  752.      * Scan full bytes for all 1's.
  753.      */
  754.     while (bits >= 8) {
  755.         if (*bp != 0xff)    /* end of run */
  756.             return (span + oneruns[*bp]);
  757.         span += 8, bits -= 8;
  758.         bp++;
  759.     }
  760.     /*
  761.      * Check partial byte on rhs.
  762.      */
  763.     if (bits > 0) {
  764.         n = oneruns[*bp];
  765.         span += (n > bits ? bits : n);
  766.     }
  767.     return (span);
  768. }
  769.  
  770. /*
  771.  * Return the offset of the next bit in the range
  772.  * [bs..be] that is different from the specified
  773.  * color.  The end, be, is returned if no such bit
  774.  * exists.
  775.  */
  776. #define    finddiff(_cp, _bs, _be, _color)    \
  777.     (_bs + (_color ? find1span(_cp,_bs,_be) : find0span(_cp,_bs,_be)))
  778. /*
  779.  * Like finddiff, but also check the starting bit
  780.  * against the end in case start > end.
  781.  */
  782. #define    finddiff2(_cp, _bs, _be, _color) \
  783.     (_bs < _be ? finddiff(_cp,_bs,_be,_color) : _be)
  784.  
  785. static void
  786. Fax3Close(TIFF* tif)
  787. {
  788.     (void) tif;
  789. }
  790.  
  791. static void
  792. Fax3Cleanup(TIFF* tif)
  793. {
  794.     if (tif->tif_data) {
  795.         if (Fax3State(tif)->rw_mode == O_RDONLY) {
  796.             Fax3DecodeState* sp = DecoderState(tif);
  797.             if (sp->runs)
  798.                 _TIFFfree(tif, sp->runs);
  799.         }
  800.         if (Fax3State(tif)->subaddress)
  801.             _TIFFfree(tif, Fax3State(tif)->subaddress);
  802.         _TIFFfree(tif, tif->tif_data);
  803.         tif->tif_data = NULL;
  804.     }
  805. }
  806.  
  807. #define    FIELD_BADFAXLINES    (FIELD_CODEC+0)
  808. #define    FIELD_CLEANFAXDATA    (FIELD_CODEC+1)
  809. #define    FIELD_BADFAXRUN        (FIELD_CODEC+2)
  810. #define    FIELD_RECVPARAMS    (FIELD_CODEC+3)
  811. #define    FIELD_SUBADDRESS    (FIELD_CODEC+4)
  812. #define    FIELD_RECVTIME        (FIELD_CODEC+5)
  813.  
  814. #define    FIELD_OPTIONS        (FIELD_CODEC+6)
  815.  
  816. static const TIFFFieldInfo faxFieldInfo[] = {
  817.     { TIFFTAG_FAXMODE,         0, 0,    TIFF_ANY,    FIELD_PSEUDO,
  818.       FALSE,    FALSE,    "FaxMode" },
  819.     { TIFFTAG_FAXFILLFUNC,     0, 0,    TIFF_ANY,    FIELD_PSEUDO,
  820.       FALSE,    FALSE,    "FaxFillFunc" },
  821.     { TIFFTAG_BADFAXLINES,     1, 1,    TIFF_LONG,    FIELD_BADFAXLINES,
  822.       TRUE,    FALSE,    "BadFaxLines" },
  823.     { TIFFTAG_BADFAXLINES,     1, 1,    TIFF_SHORT,    FIELD_BADFAXLINES,
  824.       TRUE,    FALSE,    "BadFaxLines" },
  825.     { TIFFTAG_CLEANFAXDATA,     1, 1,    TIFF_SHORT,    FIELD_CLEANFAXDATA,
  826.       TRUE,    FALSE,    "CleanFaxData" },
  827.     { TIFFTAG_CONSECUTIVEBADFAXLINES,1,1, TIFF_LONG,    FIELD_BADFAXRUN,
  828.       TRUE,    FALSE,    "ConsecutiveBadFaxLines" },
  829.     { TIFFTAG_CONSECUTIVEBADFAXLINES,1,1, TIFF_SHORT,    FIELD_BADFAXRUN,
  830.       TRUE,    FALSE,    "ConsecutiveBadFaxLines" },
  831.     { TIFFTAG_FAXRECVPARAMS,     1, 1, TIFF_LONG,    FIELD_RECVPARAMS,
  832.       TRUE,    FALSE,    "FaxRecvParams" },
  833.     { TIFFTAG_FAXSUBADDRESS,    -1,-1, TIFF_ASCII,    FIELD_SUBADDRESS,
  834.       TRUE,    FALSE,    "FaxSubAddress" },
  835.     { TIFFTAG_FAXRECVTIME,     1, 1, TIFF_LONG,    FIELD_RECVTIME,
  836.       TRUE,    FALSE,    "FaxRecvTime" },
  837. };
  838. static const TIFFFieldInfo fax3FieldInfo[] = {
  839.     { TIFFTAG_GROUP3OPTIONS,     1, 1,    TIFF_LONG,    FIELD_OPTIONS,
  840.       FALSE,    FALSE,    "Group3Options" },
  841. };
  842. static const TIFFFieldInfo fax4FieldInfo[] = {
  843.     { TIFFTAG_GROUP4OPTIONS,     1, 1,    TIFF_LONG,    FIELD_OPTIONS,
  844.       FALSE,    FALSE,    "Group4Options" },
  845. };
  846. #define    N(a)    (sizeof (a) / sizeof (a[0]))
  847.  
  848. static int
  849. Fax3VSetField(TIFF* tif, ttag_t tag, va_list ap)
  850. {
  851.     Fax3BaseState* sp = Fax3State(tif);
  852.  
  853.     switch (tag) {
  854.     case TIFFTAG_FAXMODE:
  855.         sp->mode = va_arg(ap, int);
  856.         return (1);            /* NB: pseudo tag */
  857.     case TIFFTAG_FAXFILLFUNC:
  858.         if (sp->rw_mode == O_RDONLY)
  859.             DecoderState(tif)->fill = va_arg(ap, TIFFFaxFillFunc);
  860.         return (1);            /* NB: pseudo tag */
  861.     case TIFFTAG_GROUP3OPTIONS:
  862.     case TIFFTAG_GROUP4OPTIONS:
  863.         sp->groupoptions = va_arg(ap, uint32);
  864.         break;
  865.     case TIFFTAG_BADFAXLINES:
  866.         sp->badfaxlines = va_arg(ap, uint32);
  867.         break;
  868.     case TIFFTAG_CLEANFAXDATA:
  869.         sp->cleanfaxdata = (uint16) va_arg(ap, int);
  870.         break;
  871.     case TIFFTAG_CONSECUTIVEBADFAXLINES:
  872.         sp->badfaxrun = va_arg(ap, uint32);
  873.         break;
  874.     case TIFFTAG_FAXRECVPARAMS:
  875.         sp->recvparams = va_arg(ap, uint32);
  876.         break;
  877.     case TIFFTAG_FAXSUBADDRESS:
  878.         _TIFFsetString(tif, &sp->subaddress, va_arg(ap, char*));
  879.         break;
  880.     case TIFFTAG_FAXRECVTIME:
  881.         sp->recvtime = va_arg(ap, uint32);
  882.         break;
  883.     default:
  884.         return (*sp->vsetparent)(tif, tag, ap);
  885.     }
  886.     TIFFSetFieldBit(tif, _TIFFFieldWithTag(tif, tag)->field_bit);
  887.     tif->tif_flags |= TIFF_DIRTYDIRECT;
  888.     return (1);
  889. }
  890.  
  891. static int
  892. Fax3VGetField(TIFF* tif, ttag_t tag, va_list ap)
  893. {
  894.     Fax3BaseState* sp = Fax3State(tif);
  895.  
  896.     switch (tag) {
  897.     case TIFFTAG_FAXMODE:
  898.         *va_arg(ap, int*) = sp->mode;
  899.         break;
  900.     case TIFFTAG_FAXFILLFUNC:
  901.         if (sp->rw_mode == O_RDONLY)
  902.             *va_arg(ap, TIFFFaxFillFunc*) = DecoderState(tif)->fill;
  903.         break;
  904.     case TIFFTAG_GROUP3OPTIONS:
  905.     case TIFFTAG_GROUP4OPTIONS:
  906.         *va_arg(ap, uint32*) = sp->groupoptions;
  907.         break;
  908.     case TIFFTAG_BADFAXLINES:
  909.         *va_arg(ap, uint32*) = sp->badfaxlines;
  910.         break;
  911.     case TIFFTAG_CLEANFAXDATA:
  912.         *va_arg(ap, uint16*) = sp->cleanfaxdata;
  913.         break;
  914.     case TIFFTAG_CONSECUTIVEBADFAXLINES:
  915.         *va_arg(ap, uint32*) = sp->badfaxrun;
  916.         break;
  917.     case TIFFTAG_FAXRECVPARAMS:
  918.         *va_arg(ap, uint32*) = sp->recvparams;
  919.         break;
  920.     case TIFFTAG_FAXSUBADDRESS:
  921.         *va_arg(ap, char**) = sp->subaddress;
  922.         break;
  923.     case TIFFTAG_FAXRECVTIME:
  924.         *va_arg(ap, uint32*) = sp->recvtime;
  925.         break;
  926.     default:
  927.         return (*sp->vgetparent)(tif, tag, ap);
  928.     }
  929.     return (1);
  930. }
  931.  
  932. static int
  933. InitCCITTFax3(TIFF* tif)
  934. {
  935.     Fax3BaseState* sp;
  936.  
  937.     /*
  938.      * Allocate state block so tag methods have storage to record values.
  939.      */
  940.     if (tif->tif_mode == O_RDONLY) {
  941.         if (tif->tif_data)
  942.             _TIFFfree(tif, tif->tif_data);
  943.             
  944.         tif->tif_data = (tidata_t)
  945.                     _TIFFmalloc(tif, sizeof (Fax3DecodeState));
  946.     }
  947.  
  948.     if (tif->tif_data == NULL) {
  949.         TIFFError("TIFFInitCCITTFax3",
  950.             "%s: No space for state block", tif->tif_name);
  951.         return (0);
  952.     }
  953.  
  954.     sp = Fax3State(tif);
  955.         sp->rw_mode = tif->tif_mode;
  956.  
  957.     /*
  958.      * Merge codec-specific tag information and
  959.      * override parent get/set field methods.
  960.      */
  961.     _TIFFMergeFieldInfo(tif, faxFieldInfo, N(faxFieldInfo));
  962.     sp->vgetparent = tif->tif_vgetfield;
  963.     tif->tif_vgetfield = Fax3VGetField;    /* hook for codec tags */
  964.     sp->vsetparent = tif->tif_vsetfield;
  965.     tif->tif_vsetfield = Fax3VSetField;    /* hook for codec tags */
  966.     sp->groupoptions = 0;    
  967.     sp->recvparams = 0;
  968.     sp->subaddress = NULL;
  969.  
  970.     if (sp->rw_mode == O_RDONLY) {
  971.         tif->tif_flags |= TIFF_NOBITREV;/* decoder does bit reversal */
  972.         DecoderState(tif)->runs = NULL;
  973.         TIFFSetField(tif, TIFFTAG_FAXFILLFUNC, _TIFFFax3fillruns);
  974.     } 
  975.  
  976.     /*
  977.      * Install codec methods.
  978.      */
  979.     tif->tif_setupdecode = Fax3SetupState;
  980.     tif->tif_predecode = Fax3PreDecode;
  981.     tif->tif_decoderow = Fax3Decode1D;
  982.     tif->tif_decodestrip = Fax3Decode1D;
  983.     tif->tif_decodetile = Fax3Decode1D;
  984.     tif->tif_setupencode = Fax3SetupState;
  985.     tif->tif_close = Fax3Close;
  986.     tif->tif_cleanup = Fax3Cleanup;
  987.     return (1);
  988. }
  989.  
  990. int
  991. TIFFInitCCITTFax3(TIFF* tif, int scheme)
  992. {
  993.     (void) scheme;
  994.  
  995.     if (InitCCITTFax3(tif)) {
  996.         _TIFFMergeFieldInfo(tif, fax3FieldInfo, N(fax3FieldInfo));
  997.  
  998.         /*
  999.          * The default format is Class/F-style w/o RTC.
  1000.          */
  1001.         return TIFFSetField(tif, TIFFTAG_FAXMODE, FAXMODE_CLASSF);
  1002.     } else
  1003.         return (0);
  1004. }
  1005.  
  1006. /*
  1007.  * CCITT Group 4 (T.6) Facsimile-compatible
  1008.  * Compression Scheme Support.
  1009.  */
  1010.  
  1011. #define    SWAP(t,a,b)    { t x; x = (a); (a) = (b); (b) = x; }
  1012. /*
  1013.  * Decode the requested amount of G4-encoded data.
  1014.  */
  1015. static int
  1016. Fax4Decode(TIFF* tif, tidata_t buf, tsize_t occ, tsample_t s)
  1017. {
  1018.     DECLARE_STATE_2D(tif, sp, "Fax4Decode");
  1019.  
  1020.     (void) s;
  1021.     CACHE_STATE(tif, sp);
  1022.     while ((long)occ > 0) {
  1023.         a0 = 0;
  1024.         RunLength = 0;
  1025.         pa = thisrun = sp->curruns;
  1026.         pb = sp->refruns;
  1027.         b1 = *pb++;
  1028. #ifdef FAX3_DEBUG
  1029.         printf("\nBitAcc=%08X, BitsAvail = %d\n", BitAcc, BitsAvail);
  1030.         printf("-------------------- %d\n", tif->tif_row);
  1031.         fflush(stdout);
  1032. #endif
  1033.         EXPAND2D(EOFG4);
  1034.                 if (EOLcnt)
  1035.                     goto EOFG4;
  1036.         (*sp->fill)(buf, thisrun, pa, lastx);
  1037.         SETVAL(0);        /* imaginary change for reference */
  1038.         SWAP(uint32*, sp->curruns, sp->refruns);
  1039.         buf += sp->b.rowbytes;
  1040.         occ -= sp->b.rowbytes;
  1041.         if (occ != 0)
  1042.             tif->tif_row++;
  1043.         continue;
  1044.     EOFG4:
  1045.                 NeedBits16( 13, BADG4 );
  1046.         BADG4:
  1047. #ifdef FAX3_DEBUG
  1048.                 if( GetBits(13) != 0x1001 )
  1049.                     fputs( "Bad RTC\n", stderr );
  1050. #endif                
  1051.                 ClrBits( 13 );
  1052.         (*sp->fill)(buf, thisrun, pa, lastx);
  1053.         UNCACHE_STATE(tif, sp);
  1054.         return (-1);
  1055.     }
  1056.     UNCACHE_STATE(tif, sp);
  1057.     return (1);
  1058. }
  1059. #undef    SWAP
  1060.  
  1061. int
  1062. TIFFInitCCITTFax4(TIFF* tif, int scheme)
  1063. {
  1064.     (void) scheme;
  1065.  
  1066.     if (InitCCITTFax3(tif)) {        /* reuse G3 support */
  1067.         _TIFFMergeFieldInfo(tif, fax4FieldInfo, N(fax4FieldInfo));
  1068.  
  1069.         tif->tif_decoderow = Fax4Decode;
  1070.         tif->tif_decodestrip = Fax4Decode;
  1071.         tif->tif_decodetile = Fax4Decode;
  1072.         /*
  1073.          * Suppress RTC at the end of each strip.
  1074.          */
  1075.         return TIFFSetField(tif, TIFFTAG_FAXMODE, FAXMODE_NORTC);
  1076.     } else
  1077.         return (0);
  1078. }
  1079.  
  1080. /*
  1081.  * CCITT Group 3 1-D Modified Huffman RLE Compression Support.
  1082.  * (Compression algorithms 2 and 32771)
  1083.  */
  1084.  
  1085. /*
  1086.  * Decode the requested amount of RLE-encoded data.
  1087.  */
  1088. static int
  1089. Fax3DecodeRLE(TIFF* tif, tidata_t buf, tsize_t occ, tsample_t s)
  1090. {
  1091.     DECLARE_STATE(tif, sp, "Fax3DecodeRLE");
  1092.     int mode = sp->b.mode;
  1093.  
  1094.     (void) s;
  1095.     CACHE_STATE(tif, sp);
  1096.     thisrun = sp->curruns;
  1097.     while ((long)occ > 0) {
  1098.         a0 = 0;
  1099.         RunLength = 0;
  1100.         pa = thisrun;
  1101. #ifdef FAX3_DEBUG
  1102.         printf("\nBitAcc=%08X, BitsAvail = %d\n", BitAcc, BitsAvail);
  1103.         printf("-------------------- %d\n", tif->tif_row);
  1104.         fflush(stdout);
  1105. #endif
  1106.         EXPAND1D(EOFRLE);
  1107.         (*sp->fill)(buf, thisrun, pa, lastx);
  1108.         /*
  1109.          * Cleanup at the end of the row.
  1110.          */
  1111.         if (mode & FAXMODE_BYTEALIGN) {
  1112.             int n = BitsAvail - (BitsAvail &~ 7);
  1113.             ClrBits(n);
  1114.         } else if (mode & FAXMODE_WORDALIGN) {
  1115.             int n = BitsAvail - (BitsAvail &~ 15);
  1116.             ClrBits(n);
  1117.             if (BitsAvail == 0 && !isAligned(cp, uint16))
  1118.                 cp++;
  1119.         }
  1120.         buf += sp->b.rowbytes;
  1121.         occ -= sp->b.rowbytes;
  1122.         if (occ != 0)
  1123.             tif->tif_row++;
  1124.         continue;
  1125.     EOFRLE:                /* premature EOF */
  1126.         (*sp->fill)(buf, thisrun, pa, lastx);
  1127.         UNCACHE_STATE(tif, sp);
  1128.         return (-1);
  1129.     }
  1130.     UNCACHE_STATE(tif, sp);
  1131.     return (1);
  1132. }
  1133.  
  1134. int
  1135. TIFFInitCCITTRLE(TIFF* tif, int scheme)
  1136. {
  1137.     (void) scheme;
  1138.  
  1139.     if (InitCCITTFax3(tif)) {        /* reuse G3 support */
  1140.         tif->tif_decoderow = Fax3DecodeRLE;
  1141.         tif->tif_decodestrip = Fax3DecodeRLE;
  1142.         tif->tif_decodetile = Fax3DecodeRLE;
  1143.         /*
  1144.          * Suppress RTC+EOLs when encoding and byte-align data.
  1145.          */
  1146.         return TIFFSetField(tif, TIFFTAG_FAXMODE,
  1147.             FAXMODE_NORTC|FAXMODE_NOEOL|FAXMODE_BYTEALIGN);
  1148.     } else
  1149.         return (0);
  1150. }
  1151.  
  1152. int
  1153. TIFFInitCCITTRLEW(TIFF* tif, int scheme)
  1154. {
  1155.     (void) scheme;
  1156.  
  1157.     if (InitCCITTFax3(tif)) {        /* reuse G3 support */
  1158.         tif->tif_decoderow = Fax3DecodeRLE;
  1159.         tif->tif_decodestrip = Fax3DecodeRLE;
  1160.         tif->tif_decodetile = Fax3DecodeRLE;
  1161.         /*
  1162.          * Suppress RTC+EOLs when encoding and word-align data.
  1163.          */
  1164.         return TIFFSetField(tif, TIFFTAG_FAXMODE,
  1165.             FAXMODE_NORTC|FAXMODE_NOEOL|FAXMODE_WORDALIGN);
  1166.     } else
  1167.         return (0);
  1168. }
  1169. #endif /* CCITT_SUPPORT */
  1170.