ReactOS Fundraising Campaign 2012
 
€ 4,410 / € 30,000

Information | Donate

Home | Info | Community | Development | myReactOS | Contact Us

  1. Home
  2. Community
  3. Development
  4. myReactOS
  5. Fundraiser 2012

  1. Main Page
  2. Alphabetical List
  3. Data Structures
  4. Directories
  5. File List
  6. Data Fields
  7. Globals
  8. Related Pages

ReactOS Development > Doxygen

tif_lzw.c
Go to the documentation of this file.
00001 /* $Id: tif_lzw.c,v 1.29.2.6 2010-06-08 18:50:42 bfriesen Exp $ */
00002 
00003 /*
00004  * Copyright (c) 1988-1997 Sam Leffler
00005  * Copyright (c) 1991-1997 Silicon Graphics, Inc.
00006  *
00007  * Permission to use, copy, modify, distribute, and sell this software and 
00008  * its documentation for any purpose is hereby granted without fee, provided
00009  * that (i) the above copyright notices and this permission notice appear in
00010  * all copies of the software and related documentation, and (ii) the names of
00011  * Sam Leffler and Silicon Graphics may not be used in any advertising or
00012  * publicity relating to the software without the specific, prior written
00013  * permission of Sam Leffler and Silicon Graphics.
00014  * 
00015  * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, 
00016  * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY 
00017  * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  
00018  * 
00019  * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
00020  * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
00021  * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
00022  * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF 
00023  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
00024  * OF THIS SOFTWARE.
00025  */
00026 
00027 #include "tiffiop.h"
00028 #ifdef LZW_SUPPORT
00029 /*
00030  * TIFF Library.
00031  * Rev 5.0 Lempel-Ziv & Welch Compression Support
00032  *
00033  * This code is derived from the compress program whose code is
00034  * derived from software contributed to Berkeley by James A. Woods,
00035  * derived from original work by Spencer Thomas and Joseph Orost.
00036  *
00037  * The original Berkeley copyright notice appears below in its entirety.
00038  */
00039 #include "tif_predict.h"
00040 
00041 #include <stdio.h>
00042 
00043 /*
00044  * NB: The 5.0 spec describes a different algorithm than Aldus
00045  *     implements.  Specifically, Aldus does code length transitions
00046  *     one code earlier than should be done (for real LZW).
00047  *     Earlier versions of this library implemented the correct
00048  *     LZW algorithm, but emitted codes in a bit order opposite
00049  *     to the TIFF spec.  Thus, to maintain compatibility w/ Aldus
00050  *     we interpret MSB-LSB ordered codes to be images written w/
00051  *     old versions of this library, but otherwise adhere to the
00052  *     Aldus "off by one" algorithm.
00053  *
00054  * Future revisions to the TIFF spec are expected to "clarify this issue".
00055  */
00056 #define LZW_COMPAT      /* include backwards compatibility code */
00057 /*
00058  * Each strip of data is supposed to be terminated by a CODE_EOI.
00059  * If the following #define is included, the decoder will also
00060  * check for end-of-strip w/o seeing this code.  This makes the
00061  * library more robust, but also slower.
00062  */
00063 #define LZW_CHECKEOS        /* include checks for strips w/o EOI code */
00064 
00065 #define MAXCODE(n)  ((1L<<(n))-1)
00066 /*
00067  * The TIFF spec specifies that encoded bit
00068  * strings range from 9 to 12 bits.
00069  */
00070 #define BITS_MIN    9       /* start with 9 bits */
00071 #define BITS_MAX    12      /* max of 12 bit strings */
00072 /* predefined codes */
00073 #define CODE_CLEAR  256     /* code to clear string table */
00074 #define CODE_EOI    257     /* end-of-information code */
00075 #define CODE_FIRST  258     /* first free code entry */
00076 #define CODE_MAX    MAXCODE(BITS_MAX)
00077 #define HSIZE       9001L       /* 91% occupancy */
00078 #define HSHIFT      (13-8)
00079 #ifdef LZW_COMPAT
00080 /* NB: +1024 is for compatibility with old files */
00081 #define CSIZE       (MAXCODE(BITS_MAX)+1024L)
00082 #else
00083 #define CSIZE       (MAXCODE(BITS_MAX)+1L)
00084 #endif
00085 
00086 /*
00087  * State block for each open TIFF file using LZW
00088  * compression/decompression.  Note that the predictor
00089  * state block must be first in this data structure.
00090  */
00091 typedef struct {
00092     TIFFPredictorState predict; /* predictor super class */
00093 
00094     unsigned short  nbits;      /* # of bits/code */
00095     unsigned short  maxcode;    /* maximum code for lzw_nbits */
00096     unsigned short  free_ent;   /* next free entry in hash table */
00097     long        nextdata;   /* next bits of i/o */
00098     long        nextbits;   /* # of valid bits in lzw_nextdata */
00099 
00100         int             rw_mode;        /* preserve rw_mode from init */
00101 } LZWBaseState;
00102 
00103 #define lzw_nbits   base.nbits
00104 #define lzw_maxcode base.maxcode
00105 #define lzw_free_ent    base.free_ent
00106 #define lzw_nextdata    base.nextdata
00107 #define lzw_nextbits    base.nextbits
00108 
00109 /*
00110  * Encoding-specific state.
00111  */
00112 typedef uint16 hcode_t;         /* codes fit in 16 bits */
00113 typedef struct {
00114     long    hash;
00115     hcode_t code;
00116 } hash_t;
00117 
00118 /*
00119  * Decoding-specific state.
00120  */
00121 typedef struct code_ent {
00122     struct code_ent *next;
00123     unsigned short  length;     /* string len, including this token */
00124     unsigned char   value;      /* data value */
00125     unsigned char   firstchar;  /* first token of string */
00126 } code_t;
00127 
00128 typedef int (*decodeFunc)(TIFF*, tidata_t, tsize_t, tsample_t);
00129 
00130 typedef struct {
00131     LZWBaseState base;
00132 
00133     /* Decoding specific data */
00134     long    dec_nbitsmask;      /* lzw_nbits 1 bits, right adjusted */
00135     long    dec_restart;        /* restart count */
00136 #ifdef LZW_CHECKEOS
00137     long    dec_bitsleft;       /* available bits in raw data */
00138 #endif
00139     decodeFunc dec_decode;      /* regular or backwards compatible */
00140     code_t* dec_codep;      /* current recognized code */
00141     code_t* dec_oldcodep;       /* previously recognized code */
00142     code_t* dec_free_entp;      /* next free entry */
00143     code_t* dec_maxcodep;       /* max available entry */
00144     code_t* dec_codetab;        /* kept separate for small machines */
00145 
00146     /* Encoding specific data */
00147     int enc_oldcode;        /* last code encountered */
00148     long    enc_checkpoint;     /* point at which to clear table */
00149 #define CHECK_GAP   10000       /* enc_ratio check interval */
00150     long    enc_ratio;      /* current compression ratio */
00151     long    enc_incount;        /* (input) data bytes encoded */
00152     long    enc_outcount;       /* encoded (output) bytes */
00153     tidata_t enc_rawlimit;      /* bound on tif_rawdata buffer */
00154     hash_t* enc_hashtab;        /* kept separate for small machines */
00155 } LZWCodecState;
00156 
00157 #define LZWState(tif)       ((LZWBaseState*) (tif)->tif_data)
00158 #define DecoderState(tif)   ((LZWCodecState*) LZWState(tif))
00159 #define EncoderState(tif)   ((LZWCodecState*) LZWState(tif))
00160 
00161 static  int LZWDecode(TIFF*, tidata_t, tsize_t, tsample_t);
00162 #ifdef LZW_COMPAT
00163 static  int LZWDecodeCompat(TIFF*, tidata_t, tsize_t, tsample_t);
00164 #endif
00165 static  void cl_hash(LZWCodecState*);
00166 
00167 /*
00168  * LZW Decoder.
00169  */
00170 
00171 #ifdef LZW_CHECKEOS
00172 /*
00173  * This check shouldn't be necessary because each
00174  * strip is suppose to be terminated with CODE_EOI.
00175  */
00176 #define NextCode(_tif, _sp, _bp, _code, _get) {             \
00177     if ((_sp)->dec_bitsleft < nbits) {              \
00178         TIFFWarningExt(_tif->tif_clientdata, _tif->tif_name,                \
00179             "LZWDecode: Strip %d not terminated with EOI code", \
00180             _tif->tif_curstrip);                \
00181         _code = CODE_EOI;                   \
00182     } else {                            \
00183         _get(_sp,_bp,_code);                    \
00184         (_sp)->dec_bitsleft -= nbits;               \
00185     }                               \
00186 }
00187 #else
00188 #define NextCode(tif, sp, bp, code, get) get(sp, bp, code)
00189 #endif
00190 
00191 static int
00192 LZWSetupDecode(TIFF* tif)
00193 {
00194     LZWCodecState* sp = DecoderState(tif);
00195     static const char module[] = " LZWSetupDecode";
00196     int code;
00197 
00198         if( sp == NULL )
00199         {
00200             /*
00201              * Allocate state block so tag methods have storage to record 
00202              * values.
00203              */
00204             tif->tif_data = (tidata_t) _TIFFmalloc(sizeof(LZWCodecState));
00205             if (tif->tif_data == NULL)
00206             {
00207                 TIFFErrorExt(tif->tif_clientdata, "LZWPreDecode", "No space for LZW state block");
00208                 return (0);
00209             }
00210 
00211             DecoderState(tif)->dec_codetab = NULL;
00212             DecoderState(tif)->dec_decode = NULL;
00213             
00214             /*
00215              * Setup predictor setup.
00216              */
00217             (void) TIFFPredictorInit(tif);
00218 
00219             sp = DecoderState(tif);
00220         }
00221             
00222     assert(sp != NULL);
00223 
00224     if (sp->dec_codetab == NULL) {
00225         sp->dec_codetab = (code_t*)_TIFFmalloc(CSIZE*sizeof (code_t));
00226         if (sp->dec_codetab == NULL) {
00227             TIFFErrorExt(tif->tif_clientdata, module,
00228                      "No space for LZW code table");
00229             return (0);
00230         }
00231         /*
00232          * Pre-load the table.
00233          */
00234                 code = 255;
00235                 do {
00236                     sp->dec_codetab[code].value = code;
00237                     sp->dec_codetab[code].firstchar = code;
00238                     sp->dec_codetab[code].length = 1;
00239                     sp->dec_codetab[code].next = NULL;
00240                 } while (code--);
00241         /*
00242          * Zero-out the unused entries
00243                  */
00244                  _TIFFmemset(&sp->dec_codetab[CODE_CLEAR], 0,
00245                  (CODE_FIRST - CODE_CLEAR) * sizeof (code_t));
00246     }
00247     return (1);
00248 }
00249 
00250 /*
00251  * Setup state for decoding a strip.
00252  */
00253 static int
00254 LZWPreDecode(TIFF* tif, tsample_t s)
00255 {
00256     LZWCodecState *sp = DecoderState(tif);
00257 
00258     (void) s;
00259     assert(sp != NULL);
00260         if( sp->dec_codetab == NULL )
00261         {
00262             tif->tif_setupdecode( tif );
00263         }
00264 
00265     /*
00266      * Check for old bit-reversed codes.
00267      */
00268     if (tif->tif_rawdata[0] == 0 && (tif->tif_rawdata[1] & 0x1)) {
00269 #ifdef LZW_COMPAT
00270         if (!sp->dec_decode) {
00271             TIFFWarningExt(tif->tif_clientdata, tif->tif_name,
00272                 "Old-style LZW codes, convert file");
00273             /*
00274              * Override default decoding methods with
00275              * ones that deal with the old coding.
00276              * Otherwise the predictor versions set
00277              * above will call the compatibility routines
00278              * through the dec_decode method.
00279              */
00280             tif->tif_decoderow = LZWDecodeCompat;
00281             tif->tif_decodestrip = LZWDecodeCompat;
00282             tif->tif_decodetile = LZWDecodeCompat;
00283             /*
00284              * If doing horizontal differencing, must
00285              * re-setup the predictor logic since we
00286              * switched the basic decoder methods...
00287              */
00288             (*tif->tif_setupdecode)(tif);
00289             sp->dec_decode = LZWDecodeCompat;
00290         }
00291         sp->lzw_maxcode = MAXCODE(BITS_MIN);
00292 #else /* !LZW_COMPAT */
00293         if (!sp->dec_decode) {
00294             TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
00295                 "Old-style LZW codes not supported");
00296             sp->dec_decode = LZWDecode;
00297         }
00298         return (0);
00299 #endif/* !LZW_COMPAT */
00300     } else {
00301         sp->lzw_maxcode = MAXCODE(BITS_MIN)-1;
00302         sp->dec_decode = LZWDecode;
00303     }
00304     sp->lzw_nbits = BITS_MIN;
00305     sp->lzw_nextbits = 0;
00306     sp->lzw_nextdata = 0;
00307 
00308     sp->dec_restart = 0;
00309     sp->dec_nbitsmask = MAXCODE(BITS_MIN);
00310 #ifdef LZW_CHECKEOS
00311     sp->dec_bitsleft = tif->tif_rawcc << 3;
00312 #endif
00313     sp->dec_free_entp = sp->dec_codetab + CODE_FIRST;
00314     /*
00315      * Zero entries that are not yet filled in.  We do
00316      * this to guard against bogus input data that causes
00317      * us to index into undefined entries.  If you can
00318      * come up with a way to safely bounds-check input codes
00319      * while decoding then you can remove this operation.
00320      */
00321     _TIFFmemset(sp->dec_free_entp, 0, (CSIZE-CODE_FIRST)*sizeof (code_t));
00322     sp->dec_oldcodep = &sp->dec_codetab[-1];
00323     sp->dec_maxcodep = &sp->dec_codetab[sp->dec_nbitsmask-1];
00324     return (1);
00325 }
00326 
00327 /*
00328  * Decode a "hunk of data".
00329  */
00330 #define GetNextCode(sp, bp, code) {             \
00331     nextdata = (nextdata<<8) | *(bp)++;         \
00332     nextbits += 8;                      \
00333     if (nextbits < nbits) {                 \
00334         nextdata = (nextdata<<8) | *(bp)++;     \
00335         nextbits += 8;                  \
00336     }                           \
00337     code = (hcode_t)((nextdata >> (nextbits-nbits)) & nbitsmask);   \
00338     nextbits -= nbits;                  \
00339 }
00340 
00341 static void
00342 codeLoop(TIFF* tif)
00343 {
00344     TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
00345         "LZWDecode: Bogus encoding, loop in the code table; scanline %d",
00346         tif->tif_row);
00347 }
00348 
00349 static int
00350 LZWDecode(TIFF* tif, tidata_t op0, tsize_t occ0, tsample_t s)
00351 {
00352     LZWCodecState *sp = DecoderState(tif);
00353     char *op = (char*) op0;
00354     long occ = (long) occ0;
00355     char *tp;
00356     unsigned char *bp;
00357     hcode_t code;
00358     int len;
00359     long nbits, nextbits, nextdata, nbitsmask;
00360     code_t *codep, *free_entp, *maxcodep, *oldcodep;
00361 
00362     (void) s;
00363     assert(sp != NULL);
00364         assert(sp->dec_codetab != NULL);
00365     /*
00366      * Restart interrupted output operation.
00367      */
00368     if (sp->dec_restart) {
00369         long residue;
00370 
00371         codep = sp->dec_codep;
00372         residue = codep->length - sp->dec_restart;
00373         if (residue > occ) {
00374             /*
00375              * Residue from previous decode is sufficient
00376              * to satisfy decode request.  Skip to the
00377              * start of the decoded string, place decoded
00378              * values in the output buffer, and return.
00379              */
00380             sp->dec_restart += occ;
00381             do {
00382                 codep = codep->next;
00383             } while (--residue > occ && codep);
00384             if (codep) {
00385                 tp = op + occ;
00386                 do {
00387                     *--tp = codep->value;
00388                     codep = codep->next;
00389                 } while (--occ && codep);
00390             }
00391             return (1);
00392         }
00393         /*
00394          * Residue satisfies only part of the decode request.
00395          */
00396         op += residue, occ -= residue;
00397         tp = op;
00398         do {
00399             int t;
00400             --tp;
00401             t = codep->value;
00402             codep = codep->next;
00403             *tp = t;
00404         } while (--residue && codep);
00405         sp->dec_restart = 0;
00406     }
00407 
00408     bp = (unsigned char *)tif->tif_rawcp;
00409     nbits = sp->lzw_nbits;
00410     nextdata = sp->lzw_nextdata;
00411     nextbits = sp->lzw_nextbits;
00412     nbitsmask = sp->dec_nbitsmask;
00413     oldcodep = sp->dec_oldcodep;
00414     free_entp = sp->dec_free_entp;
00415     maxcodep = sp->dec_maxcodep;
00416 
00417     while (occ > 0) {
00418         NextCode(tif, sp, bp, code, GetNextCode);
00419         if (code == CODE_EOI)
00420             break;
00421         if (code == CODE_CLEAR) {
00422             free_entp = sp->dec_codetab + CODE_FIRST;
00423             _TIFFmemset(free_entp, 0,
00424                     (CSIZE - CODE_FIRST) * sizeof (code_t));
00425             nbits = BITS_MIN;
00426             nbitsmask = MAXCODE(BITS_MIN);
00427             maxcodep = sp->dec_codetab + nbitsmask-1;
00428             NextCode(tif, sp, bp, code, GetNextCode);
00429             if (code == CODE_EOI)
00430                 break;
00431             if (code == CODE_CLEAR) {
00432                 TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
00433                 "LZWDecode: Corrupted LZW table at scanline %d",
00434                          tif->tif_row);
00435                 return (0);
00436             }
00437             *op++ = (char)code, occ--;
00438             oldcodep = sp->dec_codetab + code;
00439             continue;
00440         }
00441         codep = sp->dec_codetab + code;
00442 
00443         /*
00444          * Add the new entry to the code table.
00445          */
00446         if (free_entp < &sp->dec_codetab[0] ||
00447             free_entp >= &sp->dec_codetab[CSIZE]) {
00448             TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
00449             "LZWDecode: Corrupted LZW table at scanline %d",
00450             tif->tif_row);
00451             return (0);
00452         }
00453 
00454         free_entp->next = oldcodep;
00455         if (free_entp->next < &sp->dec_codetab[0] ||
00456             free_entp->next >= &sp->dec_codetab[CSIZE]) {
00457             TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
00458             "LZWDecode: Corrupted LZW table at scanline %d",
00459             tif->tif_row);
00460             return (0);
00461         }
00462         free_entp->firstchar = free_entp->next->firstchar;
00463         free_entp->length = free_entp->next->length+1;
00464         free_entp->value = (codep < free_entp) ?
00465             codep->firstchar : free_entp->firstchar;
00466         if (++free_entp > maxcodep) {
00467             if (++nbits > BITS_MAX)     /* should not happen */
00468                 nbits = BITS_MAX;
00469             nbitsmask = MAXCODE(nbits);
00470             maxcodep = sp->dec_codetab + nbitsmask-1;
00471         }
00472         oldcodep = codep;
00473         if (code >= 256) {
00474             /*
00475              * Code maps to a string, copy string
00476              * value to output (written in reverse).
00477              */
00478             if(codep->length == 0) {
00479                 TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
00480                     "LZWDecode: Wrong length of decoded string: "
00481                 "data probably corrupted at scanline %d",
00482                 tif->tif_row);  
00483                 return (0);
00484             }
00485             if (codep->length > occ) {
00486                 /*
00487                  * String is too long for decode buffer,
00488                  * locate portion that will fit, copy to
00489                  * the decode buffer, and setup restart
00490                  * logic for the next decoding call.
00491                  */
00492                 sp->dec_codep = codep;
00493                 do {
00494                     codep = codep->next;
00495                 } while (codep && codep->length > occ);
00496                 if (codep) {
00497                     sp->dec_restart = occ;
00498                     tp = op + occ;
00499                     do  {
00500                         *--tp = codep->value;
00501                         codep = codep->next;
00502                     }  while (--occ && codep);
00503                     if (codep)
00504                         codeLoop(tif);
00505                 }
00506                 break;
00507             }
00508             len = codep->length;
00509             tp = op + len;
00510             do {
00511                 int t;
00512                 --tp;
00513                 t = codep->value;
00514                 codep = codep->next;
00515                 *tp = t;
00516             } while (codep && tp > op);
00517             if (codep) {
00518                 codeLoop(tif);
00519                 break;
00520             }
00521             op += len, occ -= len;
00522         } else
00523             *op++ = (char)code, occ--;
00524     }
00525 
00526     tif->tif_rawcp = (tidata_t) bp;
00527     sp->lzw_nbits = (unsigned short) nbits;
00528     sp->lzw_nextdata = nextdata;
00529     sp->lzw_nextbits = nextbits;
00530     sp->dec_nbitsmask = nbitsmask;
00531     sp->dec_oldcodep = oldcodep;
00532     sp->dec_free_entp = free_entp;
00533     sp->dec_maxcodep = maxcodep;
00534 
00535     if (occ > 0) {
00536         TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
00537         "LZWDecode: Not enough data at scanline %d (short %ld bytes)",
00538             tif->tif_row, occ);
00539         return (0);
00540     }
00541     return (1);
00542 }
00543 
00544 #ifdef LZW_COMPAT
00545 /*
00546  * Decode a "hunk of data" for old images.
00547  */
00548 #define GetNextCodeCompat(sp, bp, code) {           \
00549     nextdata |= (unsigned long) *(bp)++ << nextbits;    \
00550     nextbits += 8;                      \
00551     if (nextbits < nbits) {                 \
00552         nextdata |= (unsigned long) *(bp)++ << nextbits;\
00553         nextbits += 8;                  \
00554     }                           \
00555     code = (hcode_t)(nextdata & nbitsmask);         \
00556     nextdata >>= nbits;                 \
00557     nextbits -= nbits;                  \
00558 }
00559 
00560 static int
00561 LZWDecodeCompat(TIFF* tif, tidata_t op0, tsize_t occ0, tsample_t s)
00562 {
00563     LZWCodecState *sp = DecoderState(tif);
00564     char *op = (char*) op0;
00565     long occ = (long) occ0;
00566     char *tp;
00567     unsigned char *bp;
00568     int code, nbits;
00569     long nextbits, nextdata, nbitsmask;
00570     code_t *codep, *free_entp, *maxcodep, *oldcodep;
00571 
00572     (void) s;
00573     assert(sp != NULL);
00574     /*
00575      * Restart interrupted output operation.
00576      */
00577     if (sp->dec_restart) {
00578         long residue;
00579 
00580         codep = sp->dec_codep;
00581         residue = codep->length - sp->dec_restart;
00582         if (residue > occ) {
00583             /*
00584              * Residue from previous decode is sufficient
00585              * to satisfy decode request.  Skip to the
00586              * start of the decoded string, place decoded
00587              * values in the output buffer, and return.
00588              */
00589             sp->dec_restart += occ;
00590             do {
00591                 codep = codep->next;
00592             } while (--residue > occ);
00593             tp = op + occ;
00594             do {
00595                 *--tp = codep->value;
00596                 codep = codep->next;
00597             } while (--occ);
00598             return (1);
00599         }
00600         /*
00601          * Residue satisfies only part of the decode request.
00602          */
00603         op += residue, occ -= residue;
00604         tp = op;
00605         do {
00606             *--tp = codep->value;
00607             codep = codep->next;
00608         } while (--residue);
00609         sp->dec_restart = 0;
00610     }
00611 
00612     bp = (unsigned char *)tif->tif_rawcp;
00613     nbits = sp->lzw_nbits;
00614     nextdata = sp->lzw_nextdata;
00615     nextbits = sp->lzw_nextbits;
00616     nbitsmask = sp->dec_nbitsmask;
00617     oldcodep = sp->dec_oldcodep;
00618     free_entp = sp->dec_free_entp;
00619     maxcodep = sp->dec_maxcodep;
00620 
00621     while (occ > 0) {
00622         NextCode(tif, sp, bp, code, GetNextCodeCompat);
00623         if (code == CODE_EOI)
00624             break;
00625         if (code == CODE_CLEAR) {
00626             free_entp = sp->dec_codetab + CODE_FIRST;
00627             _TIFFmemset(free_entp, 0,
00628                     (CSIZE - CODE_FIRST) * sizeof (code_t));
00629             nbits = BITS_MIN;
00630             nbitsmask = MAXCODE(BITS_MIN);
00631             maxcodep = sp->dec_codetab + nbitsmask;
00632             NextCode(tif, sp, bp, code, GetNextCodeCompat);
00633             if (code == CODE_EOI)
00634                 break;
00635             if (code == CODE_CLEAR) {
00636                 TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
00637                 "LZWDecode: Corrupted LZW table at scanline %d",
00638                          tif->tif_row);
00639                 return (0);
00640             }
00641             *op++ = code, occ--;
00642             oldcodep = sp->dec_codetab + code;
00643             continue;
00644         }
00645         codep = sp->dec_codetab + code;
00646 
00647         /*
00648          * Add the new entry to the code table.
00649          */
00650         if (free_entp < &sp->dec_codetab[0] ||
00651             free_entp >= &sp->dec_codetab[CSIZE]) {
00652             TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
00653             "LZWDecodeCompat: Corrupted LZW table at scanline %d",
00654             tif->tif_row);
00655             return (0);
00656         }
00657 
00658         free_entp->next = oldcodep;
00659         if (free_entp->next < &sp->dec_codetab[0] ||
00660             free_entp->next >= &sp->dec_codetab[CSIZE]) {
00661             TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
00662             "LZWDecodeCompat: Corrupted LZW table at scanline %d",
00663             tif->tif_row);
00664             return (0);
00665         }
00666         free_entp->firstchar = free_entp->next->firstchar;
00667         free_entp->length = free_entp->next->length+1;
00668         free_entp->value = (codep < free_entp) ?
00669             codep->firstchar : free_entp->firstchar;
00670         if (++free_entp > maxcodep) {
00671             if (++nbits > BITS_MAX)     /* should not happen */
00672                 nbits = BITS_MAX;
00673             nbitsmask = MAXCODE(nbits);
00674             maxcodep = sp->dec_codetab + nbitsmask;
00675         }
00676         oldcodep = codep;
00677         if (code >= 256) {
00678             char *op_orig = op;
00679             /*
00680              * Code maps to a string, copy string
00681              * value to output (written in reverse).
00682              */
00683             if(codep->length == 0) {
00684                 TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
00685                     "LZWDecodeCompat: Wrong length of decoded "
00686                 "string: data probably corrupted at scanline %d",
00687                 tif->tif_row);  
00688                 return (0);
00689             }
00690             if (codep->length > occ) {
00691                 /*
00692                  * String is too long for decode buffer,
00693                  * locate portion that will fit, copy to
00694                  * the decode buffer, and setup restart
00695                  * logic for the next decoding call.
00696                  */
00697                 sp->dec_codep = codep;
00698                 do {
00699                     codep = codep->next;
00700                 } while (codep->length > occ);
00701                 sp->dec_restart = occ;
00702                 tp = op + occ;
00703                 do  {
00704                     *--tp = codep->value;
00705                     codep = codep->next;
00706                 }  while (--occ);
00707                 break;
00708             }
00709             op += codep->length, occ -= codep->length;
00710             tp = op;
00711             do {
00712                 *--tp = codep->value;
00713             } while( (codep = codep->next) != NULL && tp > op_orig);
00714         } else
00715             *op++ = code, occ--;
00716     }
00717 
00718     tif->tif_rawcp = (tidata_t) bp;
00719     sp->lzw_nbits = nbits;
00720     sp->lzw_nextdata = nextdata;
00721     sp->lzw_nextbits = nextbits;
00722     sp->dec_nbitsmask = nbitsmask;
00723     sp->dec_oldcodep = oldcodep;
00724     sp->dec_free_entp = free_entp;
00725     sp->dec_maxcodep = maxcodep;
00726 
00727     if (occ > 0) {
00728         TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
00729         "LZWDecodeCompat: Not enough data at scanline %d (short %ld bytes)",
00730             tif->tif_row, occ);
00731         return (0);
00732     }
00733     return (1);
00734 }
00735 #endif /* LZW_COMPAT */
00736 
00737 /*
00738  * LZW Encoding.
00739  */
00740 
00741 static int
00742 LZWSetupEncode(TIFF* tif)
00743 {
00744     LZWCodecState* sp = EncoderState(tif);
00745     static const char module[] = "LZWSetupEncode";
00746 
00747     assert(sp != NULL);
00748     sp->enc_hashtab = (hash_t*) _TIFFmalloc(HSIZE*sizeof (hash_t));
00749     if (sp->enc_hashtab == NULL) {
00750         TIFFErrorExt(tif->tif_clientdata, module, "No space for LZW hash table");
00751         return (0);
00752     }
00753     return (1);
00754 }
00755 
00756 /*
00757  * Reset encoding state at the start of a strip.
00758  */
00759 static int
00760 LZWPreEncode(TIFF* tif, tsample_t s)
00761 {
00762     LZWCodecState *sp = EncoderState(tif);
00763 
00764     (void) s;
00765     assert(sp != NULL);
00766         
00767         if( sp->enc_hashtab == NULL )
00768         {
00769             tif->tif_setupencode( tif );
00770         }
00771 
00772     sp->lzw_nbits = BITS_MIN;
00773     sp->lzw_maxcode = MAXCODE(BITS_MIN);
00774     sp->lzw_free_ent = CODE_FIRST;
00775     sp->lzw_nextbits = 0;
00776     sp->lzw_nextdata = 0;
00777     sp->enc_checkpoint = CHECK_GAP;
00778     sp->enc_ratio = 0;
00779     sp->enc_incount = 0;
00780     sp->enc_outcount = 0;
00781     /*
00782      * The 4 here insures there is space for 2 max-sized
00783      * codes in LZWEncode and LZWPostDecode.
00784      */
00785     sp->enc_rawlimit = tif->tif_rawdata + tif->tif_rawdatasize-1 - 4;
00786     cl_hash(sp);        /* clear hash table */
00787     sp->enc_oldcode = (hcode_t) -1; /* generates CODE_CLEAR in LZWEncode */
00788     return (1);
00789 }
00790 
00791 #define CALCRATIO(sp, rat) {                    \
00792     if (incount > 0x007fffff) { /* NB: shift will overflow */\
00793         rat = outcount >> 8;                \
00794         rat = (rat == 0 ? 0x7fffffff : incount/rat);    \
00795     } else                          \
00796         rat = (incount<<8) / outcount;          \
00797 }
00798 #define PutNextCode(op, c) {                    \
00799     nextdata = (nextdata << nbits) | c;         \
00800     nextbits += nbits;                  \
00801     *op++ = (unsigned char)(nextdata >> (nextbits-8));      \
00802     nextbits -= 8;                      \
00803     if (nextbits >= 8) {                    \
00804         *op++ = (unsigned char)(nextdata >> (nextbits-8));  \
00805         nextbits -= 8;                  \
00806     }                           \
00807     outcount += nbits;                  \
00808 }
00809 
00810 /*
00811  * Encode a chunk of pixels.
00812  *
00813  * Uses an open addressing double hashing (no chaining) on the 
00814  * prefix code/next character combination.  We do a variant of
00815  * Knuth's algorithm D (vol. 3, sec. 6.4) along with G. Knott's
00816  * relatively-prime secondary probe.  Here, the modular division
00817  * first probe is gives way to a faster exclusive-or manipulation. 
00818  * Also do block compression with an adaptive reset, whereby the
00819  * code table is cleared when the compression ratio decreases,
00820  * but after the table fills.  The variable-length output codes
00821  * are re-sized at this point, and a CODE_CLEAR is generated
00822  * for the decoder. 
00823  */
00824 static int
00825 LZWEncode(TIFF* tif, tidata_t bp, tsize_t cc, tsample_t s)
00826 {
00827     register LZWCodecState *sp = EncoderState(tif);
00828     register long fcode;
00829     register hash_t *hp;
00830     register int h, c;
00831     hcode_t ent;
00832     long disp;
00833     long incount, outcount, checkpoint;
00834     long nextdata, nextbits;
00835     int free_ent, maxcode, nbits;
00836     tidata_t op, limit;
00837 
00838     (void) s;
00839     if (sp == NULL)
00840         return (0);
00841 
00842         assert(sp->enc_hashtab != NULL);
00843 
00844     /*
00845      * Load local state.
00846      */
00847     incount = sp->enc_incount;
00848     outcount = sp->enc_outcount;
00849     checkpoint = sp->enc_checkpoint;
00850     nextdata = sp->lzw_nextdata;
00851     nextbits = sp->lzw_nextbits;
00852     free_ent = sp->lzw_free_ent;
00853     maxcode = sp->lzw_maxcode;
00854     nbits = sp->lzw_nbits;
00855     op = tif->tif_rawcp;
00856     limit = sp->enc_rawlimit;
00857     ent = sp->enc_oldcode;
00858 
00859     if (ent == (hcode_t) -1 && cc > 0) {
00860         /*
00861          * NB: This is safe because it can only happen
00862          *     at the start of a strip where we know there
00863          *     is space in the data buffer.
00864          */
00865         PutNextCode(op, CODE_CLEAR);
00866         ent = *bp++; cc--; incount++;
00867     }
00868     while (cc > 0) {
00869         c = *bp++; cc--; incount++;
00870         fcode = ((long)c << BITS_MAX) + ent;
00871         h = (c << HSHIFT) ^ ent;    /* xor hashing */
00872 #ifdef _WINDOWS
00873         /*
00874          * Check hash index for an overflow.
00875          */
00876         if (h >= HSIZE)
00877             h -= HSIZE;
00878 #endif
00879         hp = &sp->enc_hashtab[h];
00880         if (hp->hash == fcode) {
00881             ent = hp->code;
00882             continue;
00883         }
00884         if (hp->hash >= 0) {
00885             /*
00886              * Primary hash failed, check secondary hash.
00887              */
00888             disp = HSIZE - h;
00889             if (h == 0)
00890                 disp = 1;
00891             do {
00892                 /*
00893                  * Avoid pointer arithmetic 'cuz of
00894                  * wraparound problems with segments.
00895                  */
00896                 if ((h -= disp) < 0)
00897                     h += HSIZE;
00898                 hp = &sp->enc_hashtab[h];
00899                 if (hp->hash == fcode) {
00900                     ent = hp->code;
00901                     goto hit;
00902                 }
00903             } while (hp->hash >= 0);
00904         }
00905         /*
00906          * New entry, emit code and add to table.
00907          */
00908         /*
00909          * Verify there is space in the buffer for the code
00910          * and any potential Clear code that might be emitted
00911          * below.  The value of limit is setup so that there
00912          * are at least 4 bytes free--room for 2 codes.
00913          */
00914         if (op > limit) {
00915             tif->tif_rawcc = (tsize_t)(op - tif->tif_rawdata);
00916             TIFFFlushData1(tif);
00917             op = tif->tif_rawdata;
00918         }
00919         PutNextCode(op, ent);
00920         ent = c;
00921         hp->code = free_ent++;
00922         hp->hash = fcode;
00923         if (free_ent == CODE_MAX-1) {
00924             /* table is full, emit clear code and reset */
00925             cl_hash(sp);
00926             sp->enc_ratio = 0;
00927             incount = 0;
00928             outcount = 0;
00929             free_ent = CODE_FIRST;
00930             PutNextCode(op, CODE_CLEAR);
00931             nbits = BITS_MIN;
00932             maxcode = MAXCODE(BITS_MIN);
00933         } else {
00934             /*
00935              * If the next entry is going to be too big for
00936              * the code size, then increase it, if possible.
00937              */
00938             if (free_ent > maxcode) {
00939                 nbits++;
00940                 assert(nbits <= BITS_MAX);
00941                 maxcode = (int) MAXCODE(nbits);
00942             } else if (incount >= checkpoint) {
00943                 long rat;
00944                 /*
00945                  * Check compression ratio and, if things seem
00946                  * to be slipping, clear the hash table and
00947                  * reset state.  The compression ratio is a
00948                  * 24+8-bit fractional number.
00949                  */
00950                 checkpoint = incount+CHECK_GAP;
00951                 CALCRATIO(sp, rat);
00952                 if (rat <= sp->enc_ratio) {
00953                     cl_hash(sp);
00954                     sp->enc_ratio = 0;
00955                     incount = 0;
00956                     outcount = 0;
00957                     free_ent = CODE_FIRST;
00958                     PutNextCode(op, CODE_CLEAR);
00959                     nbits = BITS_MIN;
00960                     maxcode = MAXCODE(BITS_MIN);
00961                 } else
00962                     sp->enc_ratio = rat;
00963             }
00964         }
00965     hit:
00966         ;
00967     }
00968 
00969     /*
00970      * Restore global state.
00971      */
00972     sp->enc_incount = incount;
00973     sp->enc_outcount = outcount;
00974     sp->enc_checkpoint = checkpoint;
00975     sp->enc_oldcode = ent;
00976     sp->lzw_nextdata = nextdata;
00977     sp->lzw_nextbits = nextbits;
00978     sp->lzw_free_ent = free_ent;
00979     sp->lzw_maxcode = maxcode;
00980     sp->lzw_nbits = nbits;
00981     tif->tif_rawcp = op;
00982     return (1);
00983 }
00984 
00985 /*
00986  * Finish off an encoded strip by flushing the last
00987  * string and tacking on an End Of Information code.
00988  */
00989 static int
00990 LZWPostEncode(TIFF* tif)
00991 {
00992     register LZWCodecState *sp = EncoderState(tif);
00993     tidata_t op = tif->tif_rawcp;
00994     long nextbits = sp->lzw_nextbits;
00995     long nextdata = sp->lzw_nextdata;
00996     long outcount = sp->enc_outcount;
00997     int nbits = sp->lzw_nbits;
00998 
00999     if (op > sp->enc_rawlimit) {
01000         tif->tif_rawcc = (tsize_t)(op - tif->tif_rawdata);
01001         TIFFFlushData1(tif);
01002         op = tif->tif_rawdata;
01003     }
01004     if (sp->enc_oldcode != (hcode_t) -1) {
01005         PutNextCode(op, sp->enc_oldcode);
01006         sp->enc_oldcode = (hcode_t) -1;
01007     }
01008     PutNextCode(op, CODE_EOI);
01009     if (nextbits > 0) 
01010         *op++ = (unsigned char)(nextdata << (8-nextbits));
01011     tif->tif_rawcc = (tsize_t)(op - tif->tif_rawdata);
01012     return (1);
01013 }
01014 
01015 /*
01016  * Reset encoding hash table.
01017  */
01018 static void
01019 cl_hash(LZWCodecState* sp)
01020 {
01021     register hash_t *hp = &sp->enc_hashtab[HSIZE-1];
01022     register long i = HSIZE-8;
01023 
01024     do {
01025         i -= 8;
01026         hp[-7].hash = -1;
01027         hp[-6].hash = -1;
01028         hp[-5].hash = -1;
01029         hp[-4].hash = -1;
01030         hp[-3].hash = -1;
01031         hp[-2].hash = -1;
01032         hp[-1].hash = -1;
01033         hp[ 0].hash = -1;
01034         hp -= 8;
01035     } while (i >= 0);
01036         for (i += 8; i > 0; i--, hp--)
01037         hp->hash = -1;
01038 }
01039 
01040 static void
01041 LZWCleanup(TIFF* tif)
01042 {
01043     (void)TIFFPredictorCleanup(tif);
01044 
01045     assert(tif->tif_data != 0);
01046 
01047     if (DecoderState(tif)->dec_codetab)
01048         _TIFFfree(DecoderState(tif)->dec_codetab);
01049 
01050     if (EncoderState(tif)->enc_hashtab)
01051         _TIFFfree(EncoderState(tif)->enc_hashtab);
01052 
01053     _TIFFfree(tif->tif_data);
01054     tif->tif_data = NULL;
01055 
01056     _TIFFSetDefaultCompressionState(tif);
01057 }
01058 
01059 int
01060 TIFFInitLZW(TIFF* tif, int scheme)
01061 {
01062     assert(scheme == COMPRESSION_LZW);
01063     /*
01064      * Allocate state block so tag methods have storage to record values.
01065      */
01066     tif->tif_data = (tidata_t) _TIFFmalloc(sizeof (LZWCodecState));
01067     if (tif->tif_data == NULL)
01068         goto bad;
01069     DecoderState(tif)->dec_codetab = NULL;
01070     DecoderState(tif)->dec_decode = NULL;
01071     EncoderState(tif)->enc_hashtab = NULL;
01072         LZWState(tif)->rw_mode = tif->tif_mode;
01073 
01074     /*
01075      * Install codec methods.
01076      */
01077     tif->tif_setupdecode = LZWSetupDecode;
01078     tif->tif_predecode = LZWPreDecode;
01079     tif->tif_decoderow = LZWDecode;
01080     tif->tif_decodestrip = LZWDecode;
01081     tif->tif_decodetile = LZWDecode;
01082     tif->tif_setupencode = LZWSetupEncode;
01083     tif->tif_preencode = LZWPreEncode;
01084     tif->tif_postencode = LZWPostEncode;
01085     tif->tif_encoderow = LZWEncode;
01086     tif->tif_encodestrip = LZWEncode;
01087     tif->tif_encodetile = LZWEncode;
01088     tif->tif_cleanup = LZWCleanup;
01089     /*
01090      * Setup predictor setup.
01091      */
01092     (void) TIFFPredictorInit(tif);
01093     return (1);
01094 bad:
01095     TIFFErrorExt(tif->tif_clientdata, "TIFFInitLZW", 
01096              "No space for LZW state block");
01097     return (0);
01098 }
01099 
01100 /*
01101  * Copyright (c) 1985, 1986 The Regents of the University of California.
01102  * All rights reserved.
01103  *
01104  * This code is derived from software contributed to Berkeley by
01105  * James A. Woods, derived from original work by Spencer Thomas
01106  * and Joseph Orost.
01107  *
01108  * Redistribution and use in source and binary forms are permitted
01109  * provided that the above copyright notice and this paragraph are
01110  * duplicated in all such forms and that any documentation,
01111  * advertising materials, and other materials related to such
01112  * distribution and use acknowledge that the software was developed
01113  * by the University of California, Berkeley.  The name of the
01114  * University may not be used to endorse or promote products derived
01115  * from this software without specific prior written permission.
01116  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
01117  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
01118  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
01119  */
01120 #endif /* LZW_SUPPORT */
01121 
01122 /* vim: set ts=8 sts=8 sw=8 noet: */
01123 /*
01124  * Local Variables:
01125  * mode: c
01126  * c-basic-offset: 8
01127  * fill-column: 78
01128  * End:
01129  */

Generated on Sun May 27 2012 04:19:34 for ReactOS by doxygen 1.7.6.1

ReactOS is a registered trademark or a trademark of ReactOS Foundation in the United States and other countries.