1 /* $Id: tif_lzw.c,v 1.57 2017-07-11 10:54:29 erouault Exp $ */
4 * Copyright (c) 1988-1997 Sam Leffler
5 * Copyright (c) 1991-1997 Silicon Graphics, Inc.
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.
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.
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
31 * Rev 5.0 Lempel-Ziv & Welch Compression Support
33 * This code is derived from the compress program whose code is
34 * derived from software contributed to Berkeley by James A. Woods,
35 * derived from original work by Spencer Thomas and Joseph Orost.
37 * The original Berkeley copyright notice appears below in its entirety.
39 #include "tif_predict.h"
44 * NB: The 5.0 spec describes a different algorithm than Aldus
45 * implements. Specifically, Aldus does code length transitions
46 * one code earlier than should be done (for real LZW).
47 * Earlier versions of this library implemented the correct
48 * LZW algorithm, but emitted codes in a bit order opposite
49 * to the TIFF spec. Thus, to maintain compatibility w/ Aldus
50 * we interpret MSB-LSB ordered codes to be images written w/
51 * old versions of this library, but otherwise adhere to the
52 * Aldus "off by one" algorithm.
54 * Future revisions to the TIFF spec are expected to "clarify this issue".
56 #define LZW_COMPAT /* include backwards compatibility code */
58 * Each strip of data is supposed to be terminated by a CODE_EOI.
59 * If the following #define is included, the decoder will also
60 * check for end-of-strip w/o seeing this code. This makes the
61 * library more robust, but also slower.
63 #define LZW_CHECKEOS /* include checks for strips w/o EOI code */
65 #define MAXCODE(n) ((1L<<(n))-1)
67 * The TIFF spec specifies that encoded bit
68 * strings range from 9 to 12 bits.
70 #define BITS_MIN 9 /* start with 9 bits */
71 #define BITS_MAX 12 /* max of 12 bit strings */
72 /* predefined codes */
73 #define CODE_CLEAR 256 /* code to clear string table */
74 #define CODE_EOI 257 /* end-of-information code */
75 #define CODE_FIRST 258 /* first free code entry */
76 #define CODE_MAX MAXCODE(BITS_MAX)
77 #define HSIZE 9001L /* 91% occupancy */
80 /* NB: +1024 is for compatibility with old files */
81 #define CSIZE (MAXCODE(BITS_MAX)+1024L)
83 #define CSIZE (MAXCODE(BITS_MAX)+1L)
87 * State block for each open TIFF file using LZW
88 * compression/decompression. Note that the predictor
89 * state block must be first in this data structure.
92 TIFFPredictorState predict; /* predictor super class */
94 unsigned short nbits; /* # of bits/code */
95 unsigned short maxcode; /* maximum code for lzw_nbits */
96 unsigned short free_ent; /* next free entry in hash table */
97 unsigned long nextdata; /* next bits of i/o */
98 long nextbits; /* # of valid bits in lzw_nextdata */
100 int rw_mode; /* preserve rw_mode from init */
103 #define lzw_nbits base.nbits
104 #define lzw_maxcode base.maxcode
105 #define lzw_free_ent base.free_ent
106 #define lzw_nextdata base.nextdata
107 #define lzw_nextbits base.nextbits
110 * Encoding-specific state.
112 typedef uint16 hcode_t; /* codes fit in 16 bits */
119 * Decoding-specific state.
121 typedef struct code_ent {
122 struct code_ent *next;
123 unsigned short length; /* string len, including this token */
124 unsigned char value; /* data value */
125 unsigned char firstchar; /* first token of string */
128 typedef int (*decodeFunc)(TIFF*, uint8*, tmsize_t, uint16);
133 /* Decoding specific data */
134 long dec_nbitsmask; /* lzw_nbits 1 bits, right adjusted */
135 long dec_restart; /* restart count */
137 uint64 dec_bitsleft; /* available bits in raw data */
139 decodeFunc dec_decode; /* regular or backwards compatible */
140 code_t* dec_codep; /* current recognized code */
141 code_t* dec_oldcodep; /* previously recognized code */
142 code_t* dec_free_entp; /* next free entry */
143 code_t* dec_maxcodep; /* max available entry */
144 code_t* dec_codetab; /* kept separate for small machines */
146 /* Encoding specific data */
147 int enc_oldcode; /* last code encountered */
148 long enc_checkpoint; /* point at which to clear table */
149 #define CHECK_GAP 10000 /* enc_ratio check interval */
150 long enc_ratio; /* current compression ratio */
151 long enc_incount; /* (input) data bytes encoded */
152 long enc_outcount; /* encoded (output) bytes */
153 uint8* enc_rawlimit; /* bound on tif_rawdata buffer */
154 hash_t* enc_hashtab; /* kept separate for small machines */
157 #define LZWState(tif) ((LZWBaseState*) (tif)->tif_data)
158 #define DecoderState(tif) ((LZWCodecState*) LZWState(tif))
159 #define EncoderState(tif) ((LZWCodecState*) LZWState(tif))
161 static int LZWDecode(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s);
163 static int LZWDecodeCompat(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s);
165 static void cl_hash(LZWCodecState*);
173 * This check shouldn't be necessary because each
174 * strip is suppose to be terminated with CODE_EOI.
176 #define NextCode(_tif, _sp, _bp, _code, _get) { \
177 if ((_sp)->dec_bitsleft < (uint64)nbits) { \
178 TIFFWarningExt(_tif->tif_clientdata, module, \
179 "LZWDecode: Strip %d not terminated with EOI code", \
180 _tif->tif_curstrip); \
183 _get(_sp,_bp,_code); \
184 (_sp)->dec_bitsleft -= nbits; \
188 #define NextCode(tif, sp, bp, code, get) get(sp, bp, code)
192 LZWFixupTags(TIFF* tif)
199 LZWSetupDecode(TIFF* tif)
201 static const char module[] = "LZWSetupDecode";
202 LZWCodecState* sp = DecoderState(tif);
208 * Allocate state block so tag methods have storage to record
211 tif->tif_data = (uint8*) _TIFFmalloc(sizeof(LZWCodecState));
212 if (tif->tif_data == NULL)
214 TIFFErrorExt(tif->tif_clientdata, module, "No space for LZW state block");
218 DecoderState(tif)->dec_codetab = NULL;
219 DecoderState(tif)->dec_decode = NULL;
222 * Setup predictor setup.
224 (void) TIFFPredictorInit(tif);
226 sp = DecoderState(tif);
231 if (sp->dec_codetab == NULL) {
232 sp->dec_codetab = (code_t*)_TIFFmalloc(CSIZE*sizeof (code_t));
233 if (sp->dec_codetab == NULL) {
234 TIFFErrorExt(tif->tif_clientdata, module,
235 "No space for LZW code table");
239 * Pre-load the table.
243 sp->dec_codetab[code].value = (unsigned char)code;
244 sp->dec_codetab[code].firstchar = (unsigned char)code;
245 sp->dec_codetab[code].length = 1;
246 sp->dec_codetab[code].next = NULL;
249 * Zero-out the unused entries
251 _TIFFmemset(&sp->dec_codetab[CODE_CLEAR], 0,
252 (CODE_FIRST - CODE_CLEAR) * sizeof (code_t));
258 * Setup state for decoding a strip.
261 LZWPreDecode(TIFF* tif, uint16 s)
263 static const char module[] = "LZWPreDecode";
264 LZWCodecState *sp = DecoderState(tif);
268 if( sp->dec_codetab == NULL )
270 tif->tif_setupdecode( tif );
271 if( sp->dec_codetab == NULL )
276 * Check for old bit-reversed codes.
278 if (tif->tif_rawcc >= 2 &&
279 tif->tif_rawdata[0] == 0 && (tif->tif_rawdata[1] & 0x1)) {
281 if (!sp->dec_decode) {
282 TIFFWarningExt(tif->tif_clientdata, module,
283 "Old-style LZW codes, convert file");
285 * Override default decoding methods with
286 * ones that deal with the old coding.
287 * Otherwise the predictor versions set
288 * above will call the compatibility routines
289 * through the dec_decode method.
291 tif->tif_decoderow = LZWDecodeCompat;
292 tif->tif_decodestrip = LZWDecodeCompat;
293 tif->tif_decodetile = LZWDecodeCompat;
295 * If doing horizontal differencing, must
296 * re-setup the predictor logic since we
297 * switched the basic decoder methods...
299 (*tif->tif_setupdecode)(tif);
300 sp->dec_decode = LZWDecodeCompat;
302 sp->lzw_maxcode = MAXCODE(BITS_MIN);
303 #else /* !LZW_COMPAT */
304 if (!sp->dec_decode) {
305 TIFFErrorExt(tif->tif_clientdata, module,
306 "Old-style LZW codes not supported");
307 sp->dec_decode = LZWDecode;
310 #endif/* !LZW_COMPAT */
312 sp->lzw_maxcode = MAXCODE(BITS_MIN)-1;
313 sp->dec_decode = LZWDecode;
315 sp->lzw_nbits = BITS_MIN;
316 sp->lzw_nextbits = 0;
317 sp->lzw_nextdata = 0;
320 sp->dec_nbitsmask = MAXCODE(BITS_MIN);
322 sp->dec_bitsleft = 0;
324 sp->dec_free_entp = sp->dec_codetab + CODE_FIRST;
326 * Zero entries that are not yet filled in. We do
327 * this to guard against bogus input data that causes
328 * us to index into undefined entries. If you can
329 * come up with a way to safely bounds-check input codes
330 * while decoding then you can remove this operation.
332 _TIFFmemset(sp->dec_free_entp, 0, (CSIZE-CODE_FIRST)*sizeof (code_t));
333 sp->dec_oldcodep = &sp->dec_codetab[-1];
334 sp->dec_maxcodep = &sp->dec_codetab[sp->dec_nbitsmask-1];
339 * Decode a "hunk of data".
341 #define GetNextCode(sp, bp, code) { \
342 nextdata = (nextdata<<8) | *(bp)++; \
344 if (nextbits < nbits) { \
345 nextdata = (nextdata<<8) | *(bp)++; \
348 code = (hcode_t)((nextdata >> (nextbits-nbits)) & nbitsmask); \
353 codeLoop(TIFF* tif, const char* module)
355 TIFFErrorExt(tif->tif_clientdata, module,
356 "Bogus encoding, loop in the code table; scanline %d",
361 LZWDecode(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s)
363 static const char module[] = "LZWDecode";
364 LZWCodecState *sp = DecoderState(tif);
365 char *op = (char*) op0;
366 long occ = (long) occ0;
371 long nbits, nextbits, nbitsmask;
372 unsigned long nextdata;
373 code_t *codep, *free_entp, *maxcodep, *oldcodep;
377 assert(sp->dec_codetab != NULL);
380 Fail if value does not fit in long.
382 if ((tmsize_t) occ != occ0)
385 * Restart interrupted output operation.
387 if (sp->dec_restart) {
390 codep = sp->dec_codep;
391 residue = codep->length - sp->dec_restart;
394 * Residue from previous decode is sufficient
395 * to satisfy decode request. Skip to the
396 * start of the decoded string, place decoded
397 * values in the output buffer, and return.
399 sp->dec_restart += occ;
402 } while (--residue > occ && codep);
406 *--tp = codep->value;
408 } while (--occ && codep);
413 * Residue satisfies only part of the decode request.
424 } while (--residue && codep);
428 bp = (unsigned char *)tif->tif_rawcp;
430 sp->dec_bitsleft = (((uint64)tif->tif_rawcc) << 3);
432 nbits = sp->lzw_nbits;
433 nextdata = sp->lzw_nextdata;
434 nextbits = sp->lzw_nextbits;
435 nbitsmask = sp->dec_nbitsmask;
436 oldcodep = sp->dec_oldcodep;
437 free_entp = sp->dec_free_entp;
438 maxcodep = sp->dec_maxcodep;
441 NextCode(tif, sp, bp, code, GetNextCode);
442 if (code == CODE_EOI)
444 if (code == CODE_CLEAR) {
446 free_entp = sp->dec_codetab + CODE_FIRST;
447 _TIFFmemset(free_entp, 0,
448 (CSIZE - CODE_FIRST) * sizeof (code_t));
450 nbitsmask = MAXCODE(BITS_MIN);
451 maxcodep = sp->dec_codetab + nbitsmask-1;
452 NextCode(tif, sp, bp, code, GetNextCode);
453 } while (code == CODE_CLEAR); /* consecutive CODE_CLEAR codes */
454 if (code == CODE_EOI)
456 if (code > CODE_CLEAR) {
457 TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
458 "LZWDecode: Corrupted LZW table at scanline %d",
464 oldcodep = sp->dec_codetab + code;
467 codep = sp->dec_codetab + code;
470 * Add the new entry to the code table.
472 if (free_entp < &sp->dec_codetab[0] ||
473 free_entp >= &sp->dec_codetab[CSIZE]) {
474 TIFFErrorExt(tif->tif_clientdata, module,
475 "Corrupted LZW table at scanline %d",
480 free_entp->next = oldcodep;
481 if (free_entp->next < &sp->dec_codetab[0] ||
482 free_entp->next >= &sp->dec_codetab[CSIZE]) {
483 TIFFErrorExt(tif->tif_clientdata, module,
484 "Corrupted LZW table at scanline %d",
488 free_entp->firstchar = free_entp->next->firstchar;
489 free_entp->length = free_entp->next->length+1;
490 free_entp->value = (codep < free_entp) ?
491 codep->firstchar : free_entp->firstchar;
492 if (++free_entp > maxcodep) {
493 if (++nbits > BITS_MAX) /* should not happen */
495 nbitsmask = MAXCODE(nbits);
496 maxcodep = sp->dec_codetab + nbitsmask-1;
501 * Code maps to a string, copy string
502 * value to output (written in reverse).
504 if(codep->length == 0) {
505 TIFFErrorExt(tif->tif_clientdata, module,
506 "Wrong length of decoded string: "
507 "data probably corrupted at scanline %d",
511 if (codep->length > occ) {
513 * String is too long for decode buffer,
514 * locate portion that will fit, copy to
515 * the decode buffer, and setup restart
516 * logic for the next decoding call.
518 sp->dec_codep = codep;
521 } while (codep && codep->length > occ);
523 sp->dec_restart = (long)occ;
526 *--tp = codep->value;
528 } while (--occ && codep);
530 codeLoop(tif, module);
542 } while (codep && tp > op);
544 codeLoop(tif, module);
556 tif->tif_rawcc -= (tmsize_t)( (uint8*) bp - tif->tif_rawcp );
557 tif->tif_rawcp = (uint8*) bp;
558 sp->lzw_nbits = (unsigned short) nbits;
559 sp->lzw_nextdata = nextdata;
560 sp->lzw_nextbits = nextbits;
561 sp->dec_nbitsmask = nbitsmask;
562 sp->dec_oldcodep = oldcodep;
563 sp->dec_free_entp = free_entp;
564 sp->dec_maxcodep = maxcodep;
567 #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
568 TIFFErrorExt(tif->tif_clientdata, module,
569 "Not enough data at scanline %d (short %I64d bytes)",
570 tif->tif_row, (unsigned __int64) occ);
572 TIFFErrorExt(tif->tif_clientdata, module,
573 "Not enough data at scanline %d (short %llu bytes)",
574 tif->tif_row, (unsigned long long) occ);
583 * Decode a "hunk of data" for old images.
585 #define GetNextCodeCompat(sp, bp, code) { \
586 nextdata |= (unsigned long) *(bp)++ << nextbits; \
588 if (nextbits < nbits) { \
589 nextdata |= (unsigned long) *(bp)++ << nextbits;\
592 code = (hcode_t)(nextdata & nbitsmask); \
593 nextdata >>= nbits; \
598 LZWDecodeCompat(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s)
600 static const char module[] = "LZWDecodeCompat";
601 LZWCodecState *sp = DecoderState(tif);
602 char *op = (char*) op0;
603 long occ = (long) occ0;
607 long nextbits, nextdata, nbitsmask;
608 code_t *codep, *free_entp, *maxcodep, *oldcodep;
614 Fail if value does not fit in long.
616 if ((tmsize_t) occ != occ0)
620 * Restart interrupted output operation.
622 if (sp->dec_restart) {
625 codep = sp->dec_codep;
626 residue = codep->length - sp->dec_restart;
629 * Residue from previous decode is sufficient
630 * to satisfy decode request. Skip to the
631 * start of the decoded string, place decoded
632 * values in the output buffer, and return.
634 sp->dec_restart += occ;
637 } while (--residue > occ);
640 *--tp = codep->value;
646 * Residue satisfies only part of the decode request.
652 *--tp = codep->value;
658 bp = (unsigned char *)tif->tif_rawcp;
660 sp->dec_bitsleft = (((uint64)tif->tif_rawcc) << 3);
662 nbits = sp->lzw_nbits;
663 nextdata = sp->lzw_nextdata;
664 nextbits = sp->lzw_nextbits;
665 nbitsmask = sp->dec_nbitsmask;
666 oldcodep = sp->dec_oldcodep;
667 free_entp = sp->dec_free_entp;
668 maxcodep = sp->dec_maxcodep;
671 NextCode(tif, sp, bp, code, GetNextCodeCompat);
672 if (code == CODE_EOI)
674 if (code == CODE_CLEAR) {
676 free_entp = sp->dec_codetab + CODE_FIRST;
677 _TIFFmemset(free_entp, 0,
678 (CSIZE - CODE_FIRST) * sizeof (code_t));
680 nbitsmask = MAXCODE(BITS_MIN);
681 maxcodep = sp->dec_codetab + nbitsmask;
682 NextCode(tif, sp, bp, code, GetNextCodeCompat);
683 } while (code == CODE_CLEAR); /* consecutive CODE_CLEAR codes */
684 if (code == CODE_EOI)
686 if (code > CODE_CLEAR) {
687 TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
688 "LZWDecode: Corrupted LZW table at scanline %d",
694 oldcodep = sp->dec_codetab + code;
697 codep = sp->dec_codetab + code;
700 * Add the new entry to the code table.
702 if (free_entp < &sp->dec_codetab[0] ||
703 free_entp >= &sp->dec_codetab[CSIZE]) {
704 TIFFErrorExt(tif->tif_clientdata, module,
705 "Corrupted LZW table at scanline %d", tif->tif_row);
709 free_entp->next = oldcodep;
710 if (free_entp->next < &sp->dec_codetab[0] ||
711 free_entp->next >= &sp->dec_codetab[CSIZE]) {
712 TIFFErrorExt(tif->tif_clientdata, module,
713 "Corrupted LZW table at scanline %d", tif->tif_row);
716 free_entp->firstchar = free_entp->next->firstchar;
717 free_entp->length = free_entp->next->length+1;
718 free_entp->value = (codep < free_entp) ?
719 codep->firstchar : free_entp->firstchar;
720 if (++free_entp > maxcodep) {
721 if (++nbits > BITS_MAX) /* should not happen */
723 nbitsmask = MAXCODE(nbits);
724 maxcodep = sp->dec_codetab + nbitsmask;
729 * Code maps to a string, copy string
730 * value to output (written in reverse).
732 if(codep->length == 0) {
733 TIFFErrorExt(tif->tif_clientdata, module,
734 "Wrong length of decoded "
735 "string: data probably corrupted at scanline %d",
739 if (codep->length > occ) {
741 * String is too long for decode buffer,
742 * locate portion that will fit, copy to
743 * the decode buffer, and setup restart
744 * logic for the next decoding call.
746 sp->dec_codep = codep;
749 } while (codep->length > occ);
750 sp->dec_restart = occ;
753 *--tp = codep->value;
758 assert(occ >= codep->length);
760 occ -= codep->length;
763 *--tp = codep->value;
764 } while( (codep = codep->next) != NULL );
771 tif->tif_rawcc -= (tmsize_t)( (uint8*) bp - tif->tif_rawcp );
772 tif->tif_rawcp = (uint8*) bp;
773 sp->lzw_nbits = (unsigned short)nbits;
774 sp->lzw_nextdata = nextdata;
775 sp->lzw_nextbits = nextbits;
776 sp->dec_nbitsmask = nbitsmask;
777 sp->dec_oldcodep = oldcodep;
778 sp->dec_free_entp = free_entp;
779 sp->dec_maxcodep = maxcodep;
782 #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
783 TIFFErrorExt(tif->tif_clientdata, module,
784 "Not enough data at scanline %d (short %I64d bytes)",
785 tif->tif_row, (unsigned __int64) occ);
787 TIFFErrorExt(tif->tif_clientdata, module,
788 "Not enough data at scanline %d (short %llu bytes)",
789 tif->tif_row, (unsigned long long) occ);
795 #endif /* LZW_COMPAT */
802 LZWSetupEncode(TIFF* tif)
804 static const char module[] = "LZWSetupEncode";
805 LZWCodecState* sp = EncoderState(tif);
808 sp->enc_hashtab = (hash_t*) _TIFFmalloc(HSIZE*sizeof (hash_t));
809 if (sp->enc_hashtab == NULL) {
810 TIFFErrorExt(tif->tif_clientdata, module,
811 "No space for LZW hash table");
818 * Reset encoding state at the start of a strip.
821 LZWPreEncode(TIFF* tif, uint16 s)
823 LZWCodecState *sp = EncoderState(tif);
828 if( sp->enc_hashtab == NULL )
830 tif->tif_setupencode( tif );
833 sp->lzw_nbits = BITS_MIN;
834 sp->lzw_maxcode = MAXCODE(BITS_MIN);
835 sp->lzw_free_ent = CODE_FIRST;
836 sp->lzw_nextbits = 0;
837 sp->lzw_nextdata = 0;
838 sp->enc_checkpoint = CHECK_GAP;
841 sp->enc_outcount = 0;
843 * The 4 here insures there is space for 2 max-sized
844 * codes in LZWEncode and LZWPostDecode.
846 sp->enc_rawlimit = tif->tif_rawdata + tif->tif_rawdatasize-1 - 4;
847 cl_hash(sp); /* clear hash table */
848 sp->enc_oldcode = (hcode_t) -1; /* generates CODE_CLEAR in LZWEncode */
852 #define CALCRATIO(sp, rat) { \
853 if (incount > 0x007fffff) { /* NB: shift will overflow */\
854 rat = outcount >> 8; \
855 rat = (rat == 0 ? 0x7fffffff : incount/rat); \
857 rat = (incount<<8) / outcount; \
860 /* Explicit 0xff masking to make icc -check=conversions happy */
861 #define PutNextCode(op, c) { \
862 nextdata = (nextdata << nbits) | c; \
864 *op++ = (unsigned char)((nextdata >> (nextbits-8))&0xff); \
866 if (nextbits >= 8) { \
867 *op++ = (unsigned char)((nextdata >> (nextbits-8))&0xff); \
874 * Encode a chunk of pixels.
876 * Uses an open addressing double hashing (no chaining) on the
877 * prefix code/next character combination. We do a variant of
878 * Knuth's algorithm D (vol. 3, sec. 6.4) along with G. Knott's
879 * relatively-prime secondary probe. Here, the modular division
880 * first probe is gives way to a faster exclusive-or manipulation.
881 * Also do block compression with an adaptive reset, whereby the
882 * code table is cleared when the compression ratio decreases,
883 * but after the table fills. The variable-length output codes
884 * are re-sized at this point, and a CODE_CLEAR is generated
888 LZWEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
890 register LZWCodecState *sp = EncoderState(tif);
896 long incount, outcount, checkpoint;
897 unsigned long nextdata;
899 int free_ent, maxcode, nbits;
907 assert(sp->enc_hashtab != NULL);
912 incount = sp->enc_incount;
913 outcount = sp->enc_outcount;
914 checkpoint = sp->enc_checkpoint;
915 nextdata = sp->lzw_nextdata;
916 nextbits = sp->lzw_nextbits;
917 free_ent = sp->lzw_free_ent;
918 maxcode = sp->lzw_maxcode;
919 nbits = sp->lzw_nbits;
921 limit = sp->enc_rawlimit;
922 ent = (hcode_t)sp->enc_oldcode;
924 if (ent == (hcode_t) -1 && cc > 0) {
926 * NB: This is safe because it can only happen
927 * at the start of a strip where we know there
928 * is space in the data buffer.
930 PutNextCode(op, CODE_CLEAR);
931 ent = *bp++; cc--; incount++;
934 c = *bp++; cc--; incount++;
935 fcode = ((long)c << BITS_MAX) + ent;
936 h = (c << HSHIFT) ^ ent; /* xor hashing */
939 * Check hash index for an overflow.
944 hp = &sp->enc_hashtab[h];
945 if (hp->hash == fcode) {
951 * Primary hash failed, check secondary hash.
958 * Avoid pointer arithmetic because of
959 * wraparound problems with segments.
963 hp = &sp->enc_hashtab[h];
964 if (hp->hash == fcode) {
968 } while (hp->hash >= 0);
971 * New entry, emit code and add to table.
974 * Verify there is space in the buffer for the code
975 * and any potential Clear code that might be emitted
976 * below. The value of limit is setup so that there
977 * are at least 4 bytes free--room for 2 codes.
980 tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata);
981 if( !TIFFFlushData1(tif) )
983 op = tif->tif_rawdata;
985 PutNextCode(op, ent);
987 hp->code = (hcode_t)(free_ent++);
989 if (free_ent == CODE_MAX-1) {
990 /* table is full, emit clear code and reset */
995 free_ent = CODE_FIRST;
996 PutNextCode(op, CODE_CLEAR);
998 maxcode = MAXCODE(BITS_MIN);
1001 * If the next entry is going to be too big for
1002 * the code size, then increase it, if possible.
1004 if (free_ent > maxcode) {
1006 assert(nbits <= BITS_MAX);
1007 maxcode = (int) MAXCODE(nbits);
1008 } else if (incount >= checkpoint) {
1011 * Check compression ratio and, if things seem
1012 * to be slipping, clear the hash table and
1013 * reset state. The compression ratio is a
1014 * 24+8-bit fractional number.
1016 checkpoint = incount+CHECK_GAP;
1018 if (rat <= sp->enc_ratio) {
1023 free_ent = CODE_FIRST;
1024 PutNextCode(op, CODE_CLEAR);
1026 maxcode = MAXCODE(BITS_MIN);
1028 sp->enc_ratio = rat;
1036 * Restore global state.
1038 sp->enc_incount = incount;
1039 sp->enc_outcount = outcount;
1040 sp->enc_checkpoint = checkpoint;
1041 sp->enc_oldcode = ent;
1042 sp->lzw_nextdata = nextdata;
1043 sp->lzw_nextbits = nextbits;
1044 sp->lzw_free_ent = (unsigned short)free_ent;
1045 sp->lzw_maxcode = (unsigned short)maxcode;
1046 sp->lzw_nbits = (unsigned short)nbits;
1047 tif->tif_rawcp = op;
1052 * Finish off an encoded strip by flushing the last
1053 * string and tacking on an End Of Information code.
1056 LZWPostEncode(TIFF* tif)
1058 register LZWCodecState *sp = EncoderState(tif);
1059 uint8* op = tif->tif_rawcp;
1060 long nextbits = sp->lzw_nextbits;
1061 unsigned long nextdata = sp->lzw_nextdata;
1062 long outcount = sp->enc_outcount;
1063 int nbits = sp->lzw_nbits;
1065 if (op > sp->enc_rawlimit) {
1066 tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata);
1067 if( !TIFFFlushData1(tif) )
1069 op = tif->tif_rawdata;
1071 if (sp->enc_oldcode != (hcode_t) -1) {
1072 int free_ent = sp->lzw_free_ent;
1074 PutNextCode(op, sp->enc_oldcode);
1075 sp->enc_oldcode = (hcode_t) -1;
1078 if (free_ent == CODE_MAX-1) {
1079 /* table is full, emit clear code and reset */
1081 PutNextCode(op, CODE_CLEAR);
1085 * If the next entry is going to be too big for
1086 * the code size, then increase it, if possible.
1088 if (free_ent > sp->lzw_maxcode) {
1090 assert(nbits <= BITS_MAX);
1094 PutNextCode(op, CODE_EOI);
1095 /* Explicit 0xff masking to make icc -check=conversions happy */
1097 *op++ = (unsigned char)((nextdata << (8-nextbits))&0xff);
1098 tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata);
1103 * Reset encoding hash table.
1106 cl_hash(LZWCodecState* sp)
1108 register hash_t *hp = &sp->enc_hashtab[HSIZE-1];
1109 register long i = HSIZE-8;
1123 for (i += 8; i > 0; i--, hp--)
1128 LZWCleanup(TIFF* tif)
1130 (void)TIFFPredictorCleanup(tif);
1132 assert(tif->tif_data != 0);
1134 if (DecoderState(tif)->dec_codetab)
1135 _TIFFfree(DecoderState(tif)->dec_codetab);
1137 if (EncoderState(tif)->enc_hashtab)
1138 _TIFFfree(EncoderState(tif)->enc_hashtab);
1140 _TIFFfree(tif->tif_data);
1141 tif->tif_data = NULL;
1143 _TIFFSetDefaultCompressionState(tif);
1147 TIFFInitLZW(TIFF* tif, int scheme)
1149 static const char module[] = "TIFFInitLZW";
1150 assert(scheme == COMPRESSION_LZW);
1152 * Allocate state block so tag methods have storage to record values.
1154 tif->tif_data = (uint8*) _TIFFmalloc(sizeof (LZWCodecState));
1155 if (tif->tif_data == NULL)
1157 DecoderState(tif)->dec_codetab = NULL;
1158 DecoderState(tif)->dec_decode = NULL;
1159 EncoderState(tif)->enc_hashtab = NULL;
1160 LZWState(tif)->rw_mode = tif->tif_mode;
1163 * Install codec methods.
1165 tif->tif_fixuptags = LZWFixupTags;
1166 tif->tif_setupdecode = LZWSetupDecode;
1167 tif->tif_predecode = LZWPreDecode;
1168 tif->tif_decoderow = LZWDecode;
1169 tif->tif_decodestrip = LZWDecode;
1170 tif->tif_decodetile = LZWDecode;
1171 tif->tif_setupencode = LZWSetupEncode;
1172 tif->tif_preencode = LZWPreEncode;
1173 tif->tif_postencode = LZWPostEncode;
1174 tif->tif_encoderow = LZWEncode;
1175 tif->tif_encodestrip = LZWEncode;
1176 tif->tif_encodetile = LZWEncode;
1177 tif->tif_cleanup = LZWCleanup;
1179 * Setup predictor setup.
1181 (void) TIFFPredictorInit(tif);
1184 TIFFErrorExt(tif->tif_clientdata, module,
1185 "No space for LZW state block");
1190 * Copyright (c) 1985, 1986 The Regents of the University of California.
1191 * All rights reserved.
1193 * This code is derived from software contributed to Berkeley by
1194 * James A. Woods, derived from original work by Spencer Thomas
1197 * Redistribution and use in source and binary forms are permitted
1198 * provided that the above copyright notice and this paragraph are
1199 * duplicated in all such forms and that any documentation,
1200 * advertising materials, and other materials related to such
1201 * distribution and use acknowledge that the software was developed
1202 * by the University of California, Berkeley. The name of the
1203 * University may not be used to endorse or promote products derived
1204 * from this software without specific prior written permission.
1205 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
1206 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
1207 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
1209 #endif /* LZW_SUPPORT */
1211 /* vim: set ts=8 sts=8 sw=8 noet: */