roentgen b75cab
/* $Id: tif_lzw.c,v 1.45 2011-04-02 20:54:09 bfriesen Exp $ */
roentgen b75cab
roentgen b75cab
/*
roentgen b75cab
 * Copyright (c) 1988-1997 Sam Leffler
roentgen b75cab
 * Copyright (c) 1991-1997 Silicon Graphics, Inc.
roentgen b75cab
 *
roentgen b75cab
 * Permission to use, copy, modify, distribute, and sell this software and 
roentgen b75cab
 * its documentation for any purpose is hereby granted without fee, provided
roentgen b75cab
 * that (i) the above copyright notices and this permission notice appear in
roentgen b75cab
 * all copies of the software and related documentation, and (ii) the names of
roentgen b75cab
 * Sam Leffler and Silicon Graphics may not be used in any advertising or
roentgen b75cab
 * publicity relating to the software without the specific, prior written
roentgen b75cab
 * permission of Sam Leffler and Silicon Graphics.
roentgen b75cab
 * 
roentgen b75cab
 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, 
roentgen b75cab
 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY 
roentgen b75cab
 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  
roentgen b75cab
 * 
roentgen b75cab
 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
roentgen b75cab
 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
roentgen b75cab
 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
roentgen b75cab
 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF 
roentgen b75cab
 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
roentgen b75cab
 * OF THIS SOFTWARE.
roentgen b75cab
 */
roentgen b75cab
roentgen b75cab
#include "tiffiop.h"
roentgen b75cab
#ifdef LZW_SUPPORT
roentgen b75cab
/*
roentgen b75cab
 * TIFF Library.  
roentgen b75cab
 * Rev 5.0 Lempel-Ziv & Welch Compression Support
roentgen b75cab
 *
roentgen b75cab
 * This code is derived from the compress program whose code is
roentgen b75cab
 * derived from software contributed to Berkeley by James A. Woods,
roentgen b75cab
 * derived from original work by Spencer Thomas and Joseph Orost.
roentgen b75cab
 *
roentgen b75cab
 * The original Berkeley copyright notice appears below in its entirety.
roentgen b75cab
 */
roentgen b75cab
#include "tif_predict.h"
roentgen b75cab
roentgen b75cab
#include <stdio.h></stdio.h>
roentgen b75cab
roentgen b75cab
/*
roentgen b75cab
 * NB: The 5.0 spec describes a different algorithm than Aldus
roentgen b75cab
 *     implements.  Specifically, Aldus does code length transitions
roentgen b75cab
 *     one code earlier than should be done (for real LZW).
roentgen b75cab
 *     Earlier versions of this library implemented the correct
roentgen b75cab
 *     LZW algorithm, but emitted codes in a bit order opposite
roentgen b75cab
 *     to the TIFF spec.  Thus, to maintain compatibility w/ Aldus
roentgen b75cab
 *     we interpret MSB-LSB ordered codes to be images written w/
roentgen b75cab
 *     old versions of this library, but otherwise adhere to the
roentgen b75cab
 *     Aldus "off by one" algorithm.
roentgen b75cab
 *
roentgen b75cab
 * Future revisions to the TIFF spec are expected to "clarify this issue".
roentgen b75cab
 */
roentgen b75cab
#define LZW_COMPAT              /* include backwards compatibility code */
roentgen b75cab
/*
roentgen b75cab
 * Each strip of data is supposed to be terminated by a CODE_EOI.
roentgen b75cab
 * If the following #define is included, the decoder will also
roentgen b75cab
 * check for end-of-strip w/o seeing this code.  This makes the
roentgen b75cab
 * library more robust, but also slower.
roentgen b75cab
 */
roentgen b75cab
#define LZW_CHECKEOS            /* include checks for strips w/o EOI code */
roentgen b75cab
roentgen b75cab
#define MAXCODE(n)	((1L<<(n))-1)
roentgen b75cab
/*
roentgen b75cab
 * The TIFF spec specifies that encoded bit
roentgen b75cab
 * strings range from 9 to 12 bits.
roentgen b75cab
 */
roentgen b75cab
#define BITS_MIN        9               /* start with 9 bits */
roentgen b75cab
#define BITS_MAX        12              /* max of 12 bit strings */
roentgen b75cab
/* predefined codes */
roentgen b75cab
#define CODE_CLEAR      256             /* code to clear string table */
roentgen b75cab
#define CODE_EOI        257             /* end-of-information code */
roentgen b75cab
#define CODE_FIRST      258             /* first free code entry */
roentgen b75cab
#define CODE_MAX        MAXCODE(BITS_MAX)
roentgen b75cab
#define HSIZE           9001L           /* 91% occupancy */
roentgen b75cab
#define HSHIFT          (13-8)
roentgen b75cab
#ifdef LZW_COMPAT
roentgen b75cab
/* NB: +1024 is for compatibility with old files */
roentgen b75cab
#define CSIZE           (MAXCODE(BITS_MAX)+1024L)
roentgen b75cab
#else
roentgen b75cab
#define CSIZE           (MAXCODE(BITS_MAX)+1L)
roentgen b75cab
#endif
roentgen b75cab
roentgen b75cab
/*
roentgen b75cab
 * State block for each open TIFF file using LZW
roentgen b75cab
 * compression/decompression.  Note that the predictor
roentgen b75cab
 * state block must be first in this data structure.
roentgen b75cab
 */
roentgen b75cab
typedef struct {
roentgen b75cab
	TIFFPredictorState predict;     /* predictor super class */
roentgen b75cab
roentgen b75cab
	unsigned short  nbits;          /* # of bits/code */
roentgen b75cab
	unsigned short  maxcode;        /* maximum code for lzw_nbits */
roentgen b75cab
	unsigned short  free_ent;       /* next free entry in hash table */
roentgen b75cab
	long            nextdata;       /* next bits of i/o */
roentgen b75cab
	long            nextbits;       /* # of valid bits in lzw_nextdata */
roentgen b75cab
roentgen b75cab
	int             rw_mode;        /* preserve rw_mode from init */
roentgen b75cab
} LZWBaseState;
roentgen b75cab
roentgen b75cab
#define lzw_nbits       base.nbits
roentgen b75cab
#define lzw_maxcode     base.maxcode
roentgen b75cab
#define lzw_free_ent    base.free_ent
roentgen b75cab
#define lzw_nextdata    base.nextdata
roentgen b75cab
#define lzw_nextbits    base.nextbits
roentgen b75cab
roentgen b75cab
/*
roentgen b75cab
 * Encoding-specific state.
roentgen b75cab
 */
roentgen b75cab
typedef uint16 hcode_t;			/* codes fit in 16 bits */
roentgen b75cab
typedef struct {
roentgen b75cab
	long	hash;
roentgen b75cab
	hcode_t	code;
roentgen b75cab
} hash_t;
roentgen b75cab
roentgen b75cab
/*
roentgen b75cab
 * Decoding-specific state.
roentgen b75cab
 */
roentgen b75cab
typedef struct code_ent {
roentgen b75cab
	struct code_ent *next;
roentgen b75cab
	unsigned short	length;		/* string len, including this token */
roentgen b75cab
	unsigned char	value;		/* data value */
roentgen b75cab
	unsigned char	firstchar;	/* first token of string */
roentgen b75cab
} code_t;
roentgen b75cab
roentgen b75cab
typedef int (*decodeFunc)(TIFF*, uint8*, tmsize_t, uint16);
roentgen b75cab
roentgen b75cab
typedef struct {
roentgen b75cab
	LZWBaseState base;
roentgen b75cab
roentgen b75cab
	/* Decoding specific data */
roentgen b75cab
	long    dec_nbitsmask;		/* lzw_nbits 1 bits, right adjusted */
roentgen b75cab
	long    dec_restart;		/* restart count */
roentgen b75cab
#ifdef LZW_CHECKEOS
roentgen b75cab
	uint64  dec_bitsleft;		/* available bits in raw data */
roentgen b75cab
#endif
roentgen b75cab
	decodeFunc dec_decode;		/* regular or backwards compatible */
roentgen b75cab
	code_t* dec_codep;		/* current recognized code */
roentgen b75cab
	code_t* dec_oldcodep;		/* previously recognized code */
roentgen b75cab
	code_t* dec_free_entp;		/* next free entry */
roentgen b75cab
	code_t* dec_maxcodep;		/* max available entry */
roentgen b75cab
	code_t* dec_codetab;		/* kept separate for small machines */
roentgen b75cab
roentgen b75cab
	/* Encoding specific data */
roentgen b75cab
	int     enc_oldcode;		/* last code encountered */
roentgen b75cab
	long    enc_checkpoint;		/* point at which to clear table */
roentgen b75cab
#define CHECK_GAP	10000		/* enc_ratio check interval */
roentgen b75cab
	long    enc_ratio;		/* current compression ratio */
roentgen b75cab
	long    enc_incount;		/* (input) data bytes encoded */
roentgen b75cab
	long    enc_outcount;		/* encoded (output) bytes */
roentgen b75cab
	uint8*  enc_rawlimit;		/* bound on tif_rawdata buffer */
roentgen b75cab
	hash_t* enc_hashtab;		/* kept separate for small machines */
roentgen b75cab
} LZWCodecState;
roentgen b75cab
roentgen b75cab
#define LZWState(tif)		((LZWBaseState*) (tif)->tif_data)
roentgen b75cab
#define DecoderState(tif)	((LZWCodecState*) LZWState(tif))
roentgen b75cab
#define EncoderState(tif)	((LZWCodecState*) LZWState(tif))
roentgen b75cab
roentgen b75cab
static int LZWDecode(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s);
roentgen b75cab
#ifdef LZW_COMPAT
roentgen b75cab
static int LZWDecodeCompat(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s);
roentgen b75cab
#endif
roentgen b75cab
static void cl_hash(LZWCodecState*);
roentgen b75cab
roentgen b75cab
/*
roentgen b75cab
 * LZW Decoder.
roentgen b75cab
 */
roentgen b75cab
roentgen b75cab
#ifdef LZW_CHECKEOS
roentgen b75cab
/*
roentgen b75cab
 * This check shouldn't be necessary because each
roentgen b75cab
 * strip is suppose to be terminated with CODE_EOI.
roentgen b75cab
 */
roentgen b75cab
#define	NextCode(_tif, _sp, _bp, _code, _get) {				\
roentgen b75cab
	if ((_sp)->dec_bitsleft < (uint64)nbits) {			\
roentgen b75cab
		TIFFWarningExt(_tif->tif_clientdata, module,		\
roentgen b75cab
		    "LZWDecode: Strip %d not terminated with EOI code", \
roentgen b75cab
		    _tif->tif_curstrip);				\
roentgen b75cab
		_code = CODE_EOI;					\
roentgen b75cab
	} else {							\
roentgen b75cab
		_get(_sp,_bp,_code);					\
roentgen b75cab
		(_sp)->dec_bitsleft -= nbits;				\
roentgen b75cab
	}								\
roentgen b75cab
}
roentgen b75cab
#else
roentgen b75cab
#define	NextCode(tif, sp, bp, code, get) get(sp, bp, code)
roentgen b75cab
#endif
roentgen b75cab
roentgen b75cab
static int
roentgen b75cab
LZWFixupTags(TIFF* tif)
roentgen b75cab
{
roentgen b75cab
	(void) tif;
roentgen b75cab
	return (1);
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
static int
roentgen b75cab
LZWSetupDecode(TIFF* tif)
roentgen b75cab
{
roentgen b75cab
	static const char module[] = "LZWSetupDecode";
roentgen b75cab
	LZWCodecState* sp = DecoderState(tif);
roentgen b75cab
	int code;
roentgen b75cab
roentgen b75cab
	if( sp == NULL )
roentgen b75cab
	{
roentgen b75cab
		/*
roentgen b75cab
		 * Allocate state block so tag methods have storage to record
roentgen b75cab
		 * values.
roentgen b75cab
		*/
roentgen b75cab
		tif->tif_data = (uint8*) _TIFFmalloc(sizeof(LZWCodecState));
roentgen b75cab
		if (tif->tif_data == NULL)
roentgen b75cab
		{
roentgen b75cab
			TIFFErrorExt(tif->tif_clientdata, module, "No space for LZW state block");
roentgen b75cab
			return (0);
roentgen b75cab
		}
roentgen b75cab
roentgen b75cab
		DecoderState(tif)->dec_codetab = NULL;
roentgen b75cab
		DecoderState(tif)->dec_decode = NULL;
roentgen b75cab
roentgen b75cab
		/*
roentgen b75cab
		 * Setup predictor setup.
roentgen b75cab
		 */
roentgen b75cab
		(void) TIFFPredictorInit(tif);
roentgen b75cab
roentgen b75cab
		sp = DecoderState(tif);
roentgen b75cab
	}
roentgen b75cab
roentgen b75cab
	assert(sp != NULL);
roentgen b75cab
roentgen b75cab
	if (sp->dec_codetab == NULL) {
roentgen b75cab
		sp->dec_codetab = (code_t*)_TIFFmalloc(CSIZE*sizeof (code_t));
roentgen b75cab
		if (sp->dec_codetab == NULL) {
roentgen b75cab
			TIFFErrorExt(tif->tif_clientdata, module,
roentgen b75cab
				     "No space for LZW code table");
roentgen b75cab
			return (0);
roentgen b75cab
		}
roentgen b75cab
		/*
roentgen b75cab
		 * Pre-load the table.
roentgen b75cab
		 */
roentgen b75cab
		code = 255;
roentgen b75cab
		do {
roentgen b75cab
			sp->dec_codetab[code].value = code;
roentgen b75cab
			sp->dec_codetab[code].firstchar = code;
roentgen b75cab
			sp->dec_codetab[code].length = 1;
roentgen b75cab
			sp->dec_codetab[code].next = NULL;
roentgen b75cab
		} while (code--);
roentgen b75cab
		/*
roentgen b75cab
		 * Zero-out the unused entries
roentgen b75cab
                 */
roentgen b75cab
                 _TIFFmemset(&sp->dec_codetab[CODE_CLEAR], 0,
roentgen b75cab
			     (CODE_FIRST - CODE_CLEAR) * sizeof (code_t));
roentgen b75cab
	}
roentgen b75cab
	return (1);
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
/*
roentgen b75cab
 * Setup state for decoding a strip.
roentgen b75cab
 */
roentgen b75cab
static int
roentgen b75cab
LZWPreDecode(TIFF* tif, uint16 s)
roentgen b75cab
{
roentgen b75cab
	static const char module[] = "LZWPreDecode";
roentgen b75cab
	LZWCodecState *sp = DecoderState(tif);
roentgen b75cab
roentgen b75cab
	(void) s;
roentgen b75cab
	assert(sp != NULL);
roentgen b75cab
	if( sp->dec_codetab == NULL )
roentgen b75cab
        {
roentgen b75cab
            tif->tif_setupdecode( tif );
roentgen b75cab
        }
roentgen b75cab
roentgen b75cab
	/*
roentgen b75cab
	 * Check for old bit-reversed codes.
roentgen b75cab
	 */
roentgen b75cab
	if (tif->tif_rawdata[0] == 0 && (tif->tif_rawdata[1] & 0x1)) {
roentgen b75cab
#ifdef LZW_COMPAT
roentgen b75cab
		if (!sp->dec_decode) {
roentgen b75cab
			TIFFWarningExt(tif->tif_clientdata, module,
roentgen b75cab
			    "Old-style LZW codes, convert file");
roentgen b75cab
			/*
roentgen b75cab
			 * Override default decoding methods with
roentgen b75cab
			 * ones that deal with the old coding.
roentgen b75cab
			 * Otherwise the predictor versions set
roentgen b75cab
			 * above will call the compatibility routines
roentgen b75cab
			 * through the dec_decode method.
roentgen b75cab
			 */
roentgen b75cab
			tif->tif_decoderow = LZWDecodeCompat;
roentgen b75cab
			tif->tif_decodestrip = LZWDecodeCompat;
roentgen b75cab
			tif->tif_decodetile = LZWDecodeCompat;
roentgen b75cab
			/*
roentgen b75cab
			 * If doing horizontal differencing, must
roentgen b75cab
			 * re-setup the predictor logic since we
roentgen b75cab
			 * switched the basic decoder methods...
roentgen b75cab
			 */
roentgen b75cab
			(*tif->tif_setupdecode)(tif);
roentgen b75cab
			sp->dec_decode = LZWDecodeCompat;
roentgen b75cab
		}
roentgen b75cab
		sp->lzw_maxcode = MAXCODE(BITS_MIN);
roentgen b75cab
#else /* !LZW_COMPAT */
roentgen b75cab
		if (!sp->dec_decode) {
roentgen b75cab
			TIFFErrorExt(tif->tif_clientdata, module,
roentgen b75cab
			    "Old-style LZW codes not supported");
roentgen b75cab
			sp->dec_decode = LZWDecode;
roentgen b75cab
		}
roentgen b75cab
		return (0);
roentgen b75cab
#endif/* !LZW_COMPAT */
roentgen b75cab
	} else {
roentgen b75cab
		sp->lzw_maxcode = MAXCODE(BITS_MIN)-1;
roentgen b75cab
		sp->dec_decode = LZWDecode;
roentgen b75cab
	}
roentgen b75cab
	sp->lzw_nbits = BITS_MIN;
roentgen b75cab
	sp->lzw_nextbits = 0;
roentgen b75cab
	sp->lzw_nextdata = 0;
roentgen b75cab
roentgen b75cab
	sp->dec_restart = 0;
roentgen b75cab
	sp->dec_nbitsmask = MAXCODE(BITS_MIN);
roentgen b75cab
#ifdef LZW_CHECKEOS
roentgen b75cab
	sp->dec_bitsleft = ((uint64)tif->tif_rawcc) << 3;
roentgen b75cab
#endif
roentgen b75cab
	sp->dec_free_entp = sp->dec_codetab + CODE_FIRST;
roentgen b75cab
	/*
roentgen b75cab
	 * Zero entries that are not yet filled in.  We do
roentgen b75cab
	 * this to guard against bogus input data that causes
roentgen b75cab
	 * us to index into undefined entries.  If you can
roentgen b75cab
	 * come up with a way to safely bounds-check input codes
roentgen b75cab
	 * while decoding then you can remove this operation.
roentgen b75cab
	 */
roentgen b75cab
	_TIFFmemset(sp->dec_free_entp, 0, (CSIZE-CODE_FIRST)*sizeof (code_t));
roentgen b75cab
	sp->dec_oldcodep = &sp->dec_codetab[-1];
roentgen b75cab
	sp->dec_maxcodep = &sp->dec_codetab[sp->dec_nbitsmask-1];
roentgen b75cab
	return (1);
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
/*
roentgen b75cab
 * Decode a "hunk of data".
roentgen b75cab
 */
roentgen b75cab
#define	GetNextCode(sp, bp, code) {				\
roentgen b75cab
	nextdata = (nextdata<<8) | *(bp)++;			\
roentgen b75cab
	nextbits += 8;						\
roentgen b75cab
	if (nextbits < nbits) {					\
roentgen b75cab
		nextdata = (nextdata<<8) | *(bp)++;		\
roentgen b75cab
		nextbits += 8;					\
roentgen b75cab
	}							\
roentgen b75cab
	code = (hcode_t)((nextdata >> (nextbits-nbits)) & nbitsmask);	\
roentgen b75cab
	nextbits -= nbits;					\
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
static void
roentgen b75cab
codeLoop(TIFF* tif, const char* module)
roentgen b75cab
{
roentgen b75cab
	TIFFErrorExt(tif->tif_clientdata, module,
roentgen b75cab
	    "Bogus encoding, loop in the code table; scanline %d",
roentgen b75cab
	    tif->tif_row);
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
static int
roentgen b75cab
LZWDecode(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s)
roentgen b75cab
{
roentgen b75cab
	static const char module[] = "LZWDecode";
roentgen b75cab
	LZWCodecState *sp = DecoderState(tif);
roentgen b75cab
	char *op = (char*) op0;
roentgen b75cab
	long occ = (long) occ0;
roentgen b75cab
	char *tp;
roentgen b75cab
	unsigned char *bp;
roentgen b75cab
	hcode_t code;
roentgen b75cab
	int len;
roentgen b75cab
	long nbits, nextbits, nextdata, nbitsmask;
roentgen b75cab
	code_t *codep, *free_entp, *maxcodep, *oldcodep;
roentgen b75cab
roentgen b75cab
	(void) s;
roentgen b75cab
	assert(sp != NULL);
roentgen b75cab
        assert(sp->dec_codetab != NULL);
roentgen b75cab
roentgen b75cab
	/*
roentgen b75cab
	  Fail if value does not fit in long.
roentgen b75cab
	*/
roentgen b75cab
	if ((tmsize_t) occ != occ0)
roentgen b75cab
	        return (0);
roentgen b75cab
	/*
roentgen b75cab
	 * Restart interrupted output operation.
roentgen b75cab
	 */
roentgen b75cab
	if (sp->dec_restart) {
roentgen b75cab
		long residue;
roentgen b75cab
roentgen b75cab
		codep = sp->dec_codep;
roentgen b75cab
		residue = codep->length - sp->dec_restart;
roentgen b75cab
		if (residue > occ) {
roentgen b75cab
			/*
roentgen b75cab
			 * Residue from previous decode is sufficient
roentgen b75cab
			 * to satisfy decode request.  Skip to the
roentgen b75cab
			 * start of the decoded string, place decoded
roentgen b75cab
			 * values in the output buffer, and return.
roentgen b75cab
			 */
roentgen b75cab
			sp->dec_restart += occ;
roentgen b75cab
			do {
roentgen b75cab
				codep = codep->next;
roentgen b75cab
			} while (--residue > occ && codep);
roentgen b75cab
			if (codep) {
roentgen b75cab
				tp = op + occ;
roentgen b75cab
				do {
roentgen b75cab
					*--tp = codep->value;
roentgen b75cab
					codep = codep->next;
roentgen b75cab
				} while (--occ && codep);
roentgen b75cab
			}
roentgen b75cab
			return (1);
roentgen b75cab
		}
roentgen b75cab
		/*
roentgen b75cab
		 * Residue satisfies only part of the decode request.
roentgen b75cab
		 */
roentgen b75cab
		op += residue, occ -= residue;
roentgen b75cab
		tp = op;
roentgen b75cab
		do {
roentgen b75cab
			int t;
roentgen b75cab
			--tp;
roentgen b75cab
			t = codep->value;
roentgen b75cab
			codep = codep->next;
roentgen b75cab
			*tp = t;
roentgen b75cab
		} while (--residue && codep);
roentgen b75cab
		sp->dec_restart = 0;
roentgen b75cab
	}
roentgen b75cab
roentgen b75cab
	bp = (unsigned char *)tif->tif_rawcp;
roentgen b75cab
	nbits = sp->lzw_nbits;
roentgen b75cab
	nextdata = sp->lzw_nextdata;
roentgen b75cab
	nextbits = sp->lzw_nextbits;
roentgen b75cab
	nbitsmask = sp->dec_nbitsmask;
roentgen b75cab
	oldcodep = sp->dec_oldcodep;
roentgen b75cab
	free_entp = sp->dec_free_entp;
roentgen b75cab
	maxcodep = sp->dec_maxcodep;
roentgen b75cab
roentgen b75cab
	while (occ > 0) {
roentgen b75cab
		NextCode(tif, sp, bp, code, GetNextCode);
roentgen b75cab
		if (code == CODE_EOI)
roentgen b75cab
			break;
roentgen b75cab
		if (code == CODE_CLEAR) {
roentgen b75cab
			free_entp = sp->dec_codetab + CODE_FIRST;
roentgen b75cab
			_TIFFmemset(free_entp, 0,
roentgen b75cab
				    (CSIZE - CODE_FIRST) * sizeof (code_t));
roentgen b75cab
			nbits = BITS_MIN;
roentgen b75cab
			nbitsmask = MAXCODE(BITS_MIN);
roentgen b75cab
			maxcodep = sp->dec_codetab + nbitsmask-1;
roentgen b75cab
			NextCode(tif, sp, bp, code, GetNextCode);
roentgen b75cab
			if (code == CODE_EOI)
roentgen b75cab
				break;
roentgen b75cab
			if (code >= CODE_CLEAR) {
roentgen b75cab
				TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
roentgen b75cab
				"LZWDecode: Corrupted LZW table at scanline %d",
roentgen b75cab
					     tif->tif_row);
roentgen b75cab
				return (0);
roentgen b75cab
			}
roentgen b75cab
			*op++ = (char)code, occ--;
roentgen b75cab
			oldcodep = sp->dec_codetab + code;
roentgen b75cab
			continue;
roentgen b75cab
		}
roentgen b75cab
		codep = sp->dec_codetab + code;
roentgen b75cab
roentgen b75cab
		/*
roentgen b75cab
		 * Add the new entry to the code table.
roentgen b75cab
		 */
roentgen b75cab
		if (free_entp < &sp->dec_codetab[0] ||
roentgen b75cab
		    free_entp >= &sp->dec_codetab[CSIZE]) {
roentgen b75cab
			TIFFErrorExt(tif->tif_clientdata, module,
roentgen b75cab
			    "Corrupted LZW table at scanline %d",
roentgen b75cab
			    tif->tif_row);
roentgen b75cab
			return (0);
roentgen b75cab
		}
roentgen b75cab
roentgen b75cab
		free_entp->next = oldcodep;
roentgen b75cab
		if (free_entp->next < &sp->dec_codetab[0] ||
roentgen b75cab
		    free_entp->next >= &sp->dec_codetab[CSIZE]) {
roentgen b75cab
			TIFFErrorExt(tif->tif_clientdata, module,
roentgen b75cab
			    "Corrupted LZW table at scanline %d",
roentgen b75cab
			    tif->tif_row);
roentgen b75cab
			return (0);
roentgen b75cab
		}
roentgen b75cab
		free_entp->firstchar = free_entp->next->firstchar;
roentgen b75cab
		free_entp->length = free_entp->next->length+1;
roentgen b75cab
		free_entp->value = (codep < free_entp) ?
roentgen b75cab
		    codep->firstchar : free_entp->firstchar;
roentgen b75cab
		if (++free_entp > maxcodep) {
roentgen b75cab
			if (++nbits > BITS_MAX)		/* should not happen */
roentgen b75cab
				nbits = BITS_MAX;
roentgen b75cab
			nbitsmask = MAXCODE(nbits);
roentgen b75cab
			maxcodep = sp->dec_codetab + nbitsmask-1;
roentgen b75cab
		}
roentgen b75cab
		oldcodep = codep;
roentgen b75cab
		if (code >= 256) {
roentgen b75cab
			/*
roentgen b75cab
			 * Code maps to a string, copy string
roentgen b75cab
			 * value to output (written in reverse).
roentgen b75cab
			 */
roentgen b75cab
			if(codep->length == 0) {
roentgen b75cab
				TIFFErrorExt(tif->tif_clientdata, module,
roentgen b75cab
				    "Wrong length of decoded string: "
roentgen b75cab
				    "data probably corrupted at scanline %d",
roentgen b75cab
				    tif->tif_row);
roentgen b75cab
				return (0);
roentgen b75cab
			}
roentgen b75cab
			if (codep->length > occ) {
roentgen b75cab
				/*
roentgen b75cab
				 * String is too long for decode buffer,
roentgen b75cab
				 * locate portion that will fit, copy to
roentgen b75cab
				 * the decode buffer, and setup restart
roentgen b75cab
				 * logic for the next decoding call.
roentgen b75cab
				 */
roentgen b75cab
				sp->dec_codep = codep;
roentgen b75cab
				do {
roentgen b75cab
					codep = codep->next;
roentgen b75cab
				} while (codep && codep->length > occ);
roentgen b75cab
				if (codep) {
roentgen b75cab
					sp->dec_restart = (long)occ;
roentgen b75cab
					tp = op + occ;
roentgen b75cab
					do  {
roentgen b75cab
						*--tp = codep->value;
roentgen b75cab
						codep = codep->next;
roentgen b75cab
					}  while (--occ && codep);
roentgen b75cab
					if (codep)
roentgen b75cab
						codeLoop(tif, module);
roentgen b75cab
				}
roentgen b75cab
				break;
roentgen b75cab
			}
roentgen b75cab
			len = codep->length;
roentgen b75cab
			tp = op + len;
roentgen b75cab
			do {
roentgen b75cab
				int t;
roentgen b75cab
				--tp;
roentgen b75cab
				t = codep->value;
roentgen b75cab
				codep = codep->next;
roentgen b75cab
				*tp = t;
roentgen b75cab
			} while (codep && tp > op);
roentgen b75cab
			if (codep) {
roentgen b75cab
			    codeLoop(tif, module);
roentgen b75cab
			    break;
roentgen b75cab
			}
roentgen b75cab
			assert(occ >= len);
roentgen b75cab
			op += len, occ -= len;
roentgen b75cab
		} else
roentgen b75cab
			*op++ = (char)code, occ--;
roentgen b75cab
	}
roentgen b75cab
roentgen b75cab
	tif->tif_rawcp = (uint8*) bp;
roentgen b75cab
	sp->lzw_nbits = (unsigned short) nbits;
roentgen b75cab
	sp->lzw_nextdata = nextdata;
roentgen b75cab
	sp->lzw_nextbits = nextbits;
roentgen b75cab
	sp->dec_nbitsmask = nbitsmask;
roentgen b75cab
	sp->dec_oldcodep = oldcodep;
roentgen b75cab
	sp->dec_free_entp = free_entp;
roentgen b75cab
	sp->dec_maxcodep = maxcodep;
roentgen b75cab
roentgen b75cab
	if (occ > 0) {
roentgen b75cab
#if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
roentgen b75cab
		TIFFErrorExt(tif->tif_clientdata, module,
roentgen b75cab
			"Not enough data at scanline %d (short %I64d bytes)",
roentgen b75cab
			     tif->tif_row, (unsigned __int64) occ);
roentgen b75cab
#else
roentgen b75cab
		TIFFErrorExt(tif->tif_clientdata, module,
roentgen b75cab
			"Not enough data at scanline %d (short %llu bytes)",
roentgen b75cab
			     tif->tif_row, (unsigned long long) occ);
roentgen b75cab
#endif
roentgen b75cab
		return (0);
roentgen b75cab
	}
roentgen b75cab
	return (1);
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
#ifdef LZW_COMPAT
roentgen b75cab
/*
roentgen b75cab
 * Decode a "hunk of data" for old images.
roentgen b75cab
 */
roentgen b75cab
#define	GetNextCodeCompat(sp, bp, code) {			\
roentgen b75cab
	nextdata |= (unsigned long) *(bp)++ << nextbits;	\
roentgen b75cab
	nextbits += 8;						\
roentgen b75cab
	if (nextbits < nbits) {					\
roentgen b75cab
		nextdata |= (unsigned long) *(bp)++ << nextbits;\
roentgen b75cab
		nextbits += 8;					\
roentgen b75cab
	}							\
roentgen b75cab
	code = (hcode_t)(nextdata & nbitsmask);			\
roentgen b75cab
	nextdata >>= nbits;					\
roentgen b75cab
	nextbits -= nbits;					\
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
static int
roentgen b75cab
LZWDecodeCompat(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s)
roentgen b75cab
{
roentgen b75cab
	static const char module[] = "LZWDecodeCompat";
roentgen b75cab
	LZWCodecState *sp = DecoderState(tif);
roentgen b75cab
	char *op = (char*) op0;
roentgen b75cab
	long occ = (long) occ0;
roentgen b75cab
	char *tp;
roentgen b75cab
	unsigned char *bp;
roentgen b75cab
	int code, nbits;
roentgen b75cab
	long nextbits, nextdata, nbitsmask;
roentgen b75cab
	code_t *codep, *free_entp, *maxcodep, *oldcodep;
roentgen b75cab
roentgen b75cab
	(void) s;
roentgen b75cab
	assert(sp != NULL);
roentgen b75cab
roentgen b75cab
	/*
roentgen b75cab
	  Fail if value does not fit in long.
roentgen b75cab
	*/
roentgen b75cab
	if ((tmsize_t) occ != occ0)
roentgen b75cab
	        return (0);
roentgen b75cab
roentgen b75cab
	/*
roentgen b75cab
	 * Restart interrupted output operation.
roentgen b75cab
	 */
roentgen b75cab
	if (sp->dec_restart) {
roentgen b75cab
		long residue;
roentgen b75cab
roentgen b75cab
		codep = sp->dec_codep;
roentgen b75cab
		residue = codep->length - sp->dec_restart;
roentgen b75cab
		if (residue > occ) {
roentgen b75cab
			/*
roentgen b75cab
			 * Residue from previous decode is sufficient
roentgen b75cab
			 * to satisfy decode request.  Skip to the
roentgen b75cab
			 * start of the decoded string, place decoded
roentgen b75cab
			 * values in the output buffer, and return.
roentgen b75cab
			 */
roentgen b75cab
			sp->dec_restart += occ;
roentgen b75cab
			do {
roentgen b75cab
				codep = codep->next;
roentgen b75cab
			} while (--residue > occ);
roentgen b75cab
			tp = op + occ;
roentgen b75cab
			do {
roentgen b75cab
				*--tp = codep->value;
roentgen b75cab
				codep = codep->next;
roentgen b75cab
			} while (--occ);
roentgen b75cab
			return (1);
roentgen b75cab
		}
roentgen b75cab
		/*
roentgen b75cab
		 * Residue satisfies only part of the decode request.
roentgen b75cab
		 */
roentgen b75cab
		op += residue, occ -= residue;
roentgen b75cab
		tp = op;
roentgen b75cab
		do {
roentgen b75cab
			*--tp = codep->value;
roentgen b75cab
			codep = codep->next;
roentgen b75cab
		} while (--residue);
roentgen b75cab
		sp->dec_restart = 0;
roentgen b75cab
	}
roentgen b75cab
roentgen b75cab
	bp = (unsigned char *)tif->tif_rawcp;
roentgen b75cab
	nbits = sp->lzw_nbits;
roentgen b75cab
	nextdata = sp->lzw_nextdata;
roentgen b75cab
	nextbits = sp->lzw_nextbits;
roentgen b75cab
	nbitsmask = sp->dec_nbitsmask;
roentgen b75cab
	oldcodep = sp->dec_oldcodep;
roentgen b75cab
	free_entp = sp->dec_free_entp;
roentgen b75cab
	maxcodep = sp->dec_maxcodep;
roentgen b75cab
roentgen b75cab
	while (occ > 0) {
roentgen b75cab
		NextCode(tif, sp, bp, code, GetNextCodeCompat);
roentgen b75cab
		if (code == CODE_EOI)
roentgen b75cab
			break;
roentgen b75cab
		if (code == CODE_CLEAR) {
roentgen b75cab
			free_entp = sp->dec_codetab + CODE_FIRST;
roentgen b75cab
			_TIFFmemset(free_entp, 0,
roentgen b75cab
				    (CSIZE - CODE_FIRST) * sizeof (code_t));
roentgen b75cab
			nbits = BITS_MIN;
roentgen b75cab
			nbitsmask = MAXCODE(BITS_MIN);
roentgen b75cab
			maxcodep = sp->dec_codetab + nbitsmask;
roentgen b75cab
			NextCode(tif, sp, bp, code, GetNextCodeCompat);
roentgen b75cab
			if (code == CODE_EOI)
roentgen b75cab
				break;
roentgen b75cab
			if (code >= CODE_CLEAR) {
roentgen b75cab
				TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
roentgen b75cab
				"LZWDecode: Corrupted LZW table at scanline %d",
roentgen b75cab
					     tif->tif_row);
roentgen b75cab
				return (0);
roentgen b75cab
			}
roentgen b75cab
			*op++ = code, occ--;
roentgen b75cab
			oldcodep = sp->dec_codetab + code;
roentgen b75cab
			continue;
roentgen b75cab
		}
roentgen b75cab
		codep = sp->dec_codetab + code;
roentgen b75cab
roentgen b75cab
		/*
roentgen b75cab
		 * Add the new entry to the code table.
roentgen b75cab
		 */
roentgen b75cab
		if (free_entp < &sp->dec_codetab[0] ||
roentgen b75cab
		    free_entp >= &sp->dec_codetab[CSIZE]) {
roentgen b75cab
			TIFFErrorExt(tif->tif_clientdata, module,
roentgen b75cab
			    "Corrupted LZW table at scanline %d", tif->tif_row);
roentgen b75cab
			return (0);
roentgen b75cab
		}
roentgen b75cab
roentgen b75cab
		free_entp->next = oldcodep;
roentgen b75cab
		if (free_entp->next < &sp->dec_codetab[0] ||
roentgen b75cab
		    free_entp->next >= &sp->dec_codetab[CSIZE]) {
roentgen b75cab
			TIFFErrorExt(tif->tif_clientdata, module,
roentgen b75cab
			    "Corrupted LZW table at scanline %d", tif->tif_row);
roentgen b75cab
			return (0);
roentgen b75cab
		}
roentgen b75cab
		free_entp->firstchar = free_entp->next->firstchar;
roentgen b75cab
		free_entp->length = free_entp->next->length+1;
roentgen b75cab
		free_entp->value = (codep < free_entp) ?
roentgen b75cab
		    codep->firstchar : free_entp->firstchar;
roentgen b75cab
		if (++free_entp > maxcodep) {
roentgen b75cab
			if (++nbits > BITS_MAX)		/* should not happen */
roentgen b75cab
				nbits = BITS_MAX;
roentgen b75cab
			nbitsmask = MAXCODE(nbits);
roentgen b75cab
			maxcodep = sp->dec_codetab + nbitsmask;
roentgen b75cab
		}
roentgen b75cab
		oldcodep = codep;
roentgen b75cab
		if (code >= 256) {
roentgen b75cab
			/*
roentgen b75cab
			 * Code maps to a string, copy string
roentgen b75cab
			 * value to output (written in reverse).
roentgen b75cab
			 */
roentgen b75cab
			if(codep->length == 0) {
roentgen b75cab
				TIFFErrorExt(tif->tif_clientdata, module,
roentgen b75cab
				    "Wrong length of decoded "
roentgen b75cab
				    "string: data probably corrupted at scanline %d",
roentgen b75cab
				    tif->tif_row);
roentgen b75cab
				return (0);
roentgen b75cab
			}
roentgen b75cab
			if (codep->length > occ) {
roentgen b75cab
				/*
roentgen b75cab
				 * String is too long for decode buffer,
roentgen b75cab
				 * locate portion that will fit, copy to
roentgen b75cab
				 * the decode buffer, and setup restart
roentgen b75cab
				 * logic for the next decoding call.
roentgen b75cab
				 */
roentgen b75cab
				sp->dec_codep = codep;
roentgen b75cab
				do {
roentgen b75cab
					codep = codep->next;
roentgen b75cab
				} while (codep->length > occ);
roentgen b75cab
				sp->dec_restart = occ;
roentgen b75cab
				tp = op + occ;
roentgen b75cab
				do  {
roentgen b75cab
					*--tp = codep->value;
roentgen b75cab
					codep = codep->next;
roentgen b75cab
				}  while (--occ);
roentgen b75cab
				break;
roentgen b75cab
			}
roentgen b75cab
			assert(occ >= codep->length);
roentgen b75cab
			op += codep->length, occ -= codep->length;
roentgen b75cab
			tp = op;
roentgen b75cab
			do {
roentgen b75cab
				*--tp = codep->value;
roentgen b75cab
			} while( (codep = codep->next) != NULL );
roentgen b75cab
		} else
roentgen b75cab
			*op++ = code, occ--;
roentgen b75cab
	}
roentgen b75cab
roentgen b75cab
	tif->tif_rawcp = (uint8*) bp;
roentgen b75cab
	sp->lzw_nbits = nbits;
roentgen b75cab
	sp->lzw_nextdata = nextdata;
roentgen b75cab
	sp->lzw_nextbits = nextbits;
roentgen b75cab
	sp->dec_nbitsmask = nbitsmask;
roentgen b75cab
	sp->dec_oldcodep = oldcodep;
roentgen b75cab
	sp->dec_free_entp = free_entp;
roentgen b75cab
	sp->dec_maxcodep = maxcodep;
roentgen b75cab
roentgen b75cab
	if (occ > 0) {
roentgen b75cab
#if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
roentgen b75cab
		TIFFErrorExt(tif->tif_clientdata, module,
roentgen b75cab
			"Not enough data at scanline %d (short %I64d bytes)",
roentgen b75cab
			     tif->tif_row, (unsigned __int64) occ);
roentgen b75cab
#else
roentgen b75cab
		TIFFErrorExt(tif->tif_clientdata, module,
roentgen b75cab
			"Not enough data at scanline %d (short %llu bytes)",
roentgen b75cab
			     tif->tif_row, (unsigned long long) occ);
roentgen b75cab
#endif
roentgen b75cab
		return (0);
roentgen b75cab
	}
roentgen b75cab
	return (1);
roentgen b75cab
}
roentgen b75cab
#endif /* LZW_COMPAT */
roentgen b75cab
roentgen b75cab
/*
roentgen b75cab
 * LZW Encoding.
roentgen b75cab
 */
roentgen b75cab
roentgen b75cab
static int
roentgen b75cab
LZWSetupEncode(TIFF* tif)
roentgen b75cab
{
roentgen b75cab
	static const char module[] = "LZWSetupEncode";
roentgen b75cab
	LZWCodecState* sp = EncoderState(tif);
roentgen b75cab
roentgen b75cab
	assert(sp != NULL);
roentgen b75cab
	sp->enc_hashtab = (hash_t*) _TIFFmalloc(HSIZE*sizeof (hash_t));
roentgen b75cab
	if (sp->enc_hashtab == NULL) {
roentgen b75cab
		TIFFErrorExt(tif->tif_clientdata, module,
roentgen b75cab
			     "No space for LZW hash table");
roentgen b75cab
		return (0);
roentgen b75cab
	}
roentgen b75cab
	return (1);
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
/*
roentgen b75cab
 * Reset encoding state at the start of a strip.
roentgen b75cab
 */
roentgen b75cab
static int
roentgen b75cab
LZWPreEncode(TIFF* tif, uint16 s)
roentgen b75cab
{
roentgen b75cab
	LZWCodecState *sp = EncoderState(tif);
roentgen b75cab
roentgen b75cab
	(void) s;
roentgen b75cab
	assert(sp != NULL);
roentgen b75cab
roentgen b75cab
	if( sp->enc_hashtab == NULL )
roentgen b75cab
        {
roentgen b75cab
            tif->tif_setupencode( tif );
roentgen b75cab
        }
roentgen b75cab
roentgen b75cab
	sp->lzw_nbits = BITS_MIN;
roentgen b75cab
	sp->lzw_maxcode = MAXCODE(BITS_MIN);
roentgen b75cab
	sp->lzw_free_ent = CODE_FIRST;
roentgen b75cab
	sp->lzw_nextbits = 0;
roentgen b75cab
	sp->lzw_nextdata = 0;
roentgen b75cab
	sp->enc_checkpoint = CHECK_GAP;
roentgen b75cab
	sp->enc_ratio = 0;
roentgen b75cab
	sp->enc_incount = 0;
roentgen b75cab
	sp->enc_outcount = 0;
roentgen b75cab
	/*
roentgen b75cab
	 * The 4 here insures there is space for 2 max-sized
roentgen b75cab
	 * codes in LZWEncode and LZWPostDecode.
roentgen b75cab
	 */
roentgen b75cab
	sp->enc_rawlimit = tif->tif_rawdata + tif->tif_rawdatasize-1 - 4;
roentgen b75cab
	cl_hash(sp);		/* clear hash table */
roentgen b75cab
	sp->enc_oldcode = (hcode_t) -1;	/* generates CODE_CLEAR in LZWEncode */
roentgen b75cab
	return (1);
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
#define	CALCRATIO(sp, rat) {					\
roentgen b75cab
	if (incount > 0x007fffff) { /* NB: shift will overflow */\
roentgen b75cab
		rat = outcount >> 8;				\
roentgen b75cab
		rat = (rat == 0 ? 0x7fffffff : incount/rat);	\
roentgen b75cab
	} else							\
roentgen b75cab
		rat = (incount<<8) / outcount;			\
roentgen b75cab
}
roentgen b75cab
#define	PutNextCode(op, c) {					\
roentgen b75cab
	nextdata = (nextdata << nbits) | c;			\
roentgen b75cab
	nextbits += nbits;					\
roentgen b75cab
	*op++ = (unsigned char)(nextdata >> (nextbits-8));		\
roentgen b75cab
	nextbits -= 8;						\
roentgen b75cab
	if (nextbits >= 8) {					\
roentgen b75cab
		*op++ = (unsigned char)(nextdata >> (nextbits-8));	\
roentgen b75cab
		nextbits -= 8;					\
roentgen b75cab
	}							\
roentgen b75cab
	outcount += nbits;					\
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
/*
roentgen b75cab
 * Encode a chunk of pixels.
roentgen b75cab
 *
roentgen b75cab
 * Uses an open addressing double hashing (no chaining) on the 
roentgen b75cab
 * prefix code/next character combination.  We do a variant of
roentgen b75cab
 * Knuth's algorithm D (vol. 3, sec. 6.4) along with G. Knott's
roentgen b75cab
 * relatively-prime secondary probe.  Here, the modular division
roentgen b75cab
 * first probe is gives way to a faster exclusive-or manipulation. 
roentgen b75cab
 * Also do block compression with an adaptive reset, whereby the
roentgen b75cab
 * code table is cleared when the compression ratio decreases,
roentgen b75cab
 * but after the table fills.  The variable-length output codes
roentgen b75cab
 * are re-sized at this point, and a CODE_CLEAR is generated
roentgen b75cab
 * for the decoder. 
roentgen b75cab
 */
roentgen b75cab
static int
roentgen b75cab
LZWEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
roentgen b75cab
{
roentgen b75cab
	register LZWCodecState *sp = EncoderState(tif);
roentgen b75cab
	register long fcode;
roentgen b75cab
	register hash_t *hp;
roentgen b75cab
	register int h, c;
roentgen b75cab
	hcode_t ent;
roentgen b75cab
	long disp;
roentgen b75cab
	long incount, outcount, checkpoint;
roentgen b75cab
	long nextdata, nextbits;
roentgen b75cab
	int free_ent, maxcode, nbits;
roentgen b75cab
	uint8* op;
roentgen b75cab
	uint8* limit;
roentgen b75cab
roentgen b75cab
	(void) s;
roentgen b75cab
	if (sp == NULL)
roentgen b75cab
		return (0);
roentgen b75cab
roentgen b75cab
        assert(sp->enc_hashtab != NULL);
roentgen b75cab
roentgen b75cab
	/*
roentgen b75cab
	 * Load local state.
roentgen b75cab
	 */
roentgen b75cab
	incount = sp->enc_incount;
roentgen b75cab
	outcount = sp->enc_outcount;
roentgen b75cab
	checkpoint = sp->enc_checkpoint;
roentgen b75cab
	nextdata = sp->lzw_nextdata;
roentgen b75cab
	nextbits = sp->lzw_nextbits;
roentgen b75cab
	free_ent = sp->lzw_free_ent;
roentgen b75cab
	maxcode = sp->lzw_maxcode;
roentgen b75cab
	nbits = sp->lzw_nbits;
roentgen b75cab
	op = tif->tif_rawcp;
roentgen b75cab
	limit = sp->enc_rawlimit;
roentgen b75cab
	ent = sp->enc_oldcode;
roentgen b75cab
roentgen b75cab
	if (ent == (hcode_t) -1 && cc > 0) {
roentgen b75cab
		/*
roentgen b75cab
		 * NB: This is safe because it can only happen
roentgen b75cab
		 *     at the start of a strip where we know there
roentgen b75cab
		 *     is space in the data buffer.
roentgen b75cab
		 */
roentgen b75cab
		PutNextCode(op, CODE_CLEAR);
roentgen b75cab
		ent = *bp++; cc--; incount++;
roentgen b75cab
	}
roentgen b75cab
	while (cc > 0) {
roentgen b75cab
		c = *bp++; cc--; incount++;
roentgen b75cab
		fcode = ((long)c << BITS_MAX) + ent;
roentgen b75cab
		h = (c << HSHIFT) ^ ent;	/* xor hashing */
roentgen b75cab
#ifdef _WINDOWS
roentgen b75cab
		/*
roentgen b75cab
		 * Check hash index for an overflow.
roentgen b75cab
		 */
roentgen b75cab
		if (h >= HSIZE)
roentgen b75cab
			h -= HSIZE;
roentgen b75cab
#endif
roentgen b75cab
		hp = &sp->enc_hashtab[h];
roentgen b75cab
		if (hp->hash == fcode) {
roentgen b75cab
			ent = hp->code;
roentgen b75cab
			continue;
roentgen b75cab
		}
roentgen b75cab
		if (hp->hash >= 0) {
roentgen b75cab
			/*
roentgen b75cab
			 * Primary hash failed, check secondary hash.
roentgen b75cab
			 */
roentgen b75cab
			disp = HSIZE - h;
roentgen b75cab
			if (h == 0)
roentgen b75cab
				disp = 1;
roentgen b75cab
			do {
roentgen b75cab
				/*
roentgen b75cab
				 * Avoid pointer arithmetic 'cuz of
roentgen b75cab
				 * wraparound problems with segments.
roentgen b75cab
				 */
roentgen b75cab
				if ((h -= disp) < 0)
roentgen b75cab
					h += HSIZE;
roentgen b75cab
				hp = &sp->enc_hashtab[h];
roentgen b75cab
				if (hp->hash == fcode) {
roentgen b75cab
					ent = hp->code;
roentgen b75cab
					goto hit;
roentgen b75cab
				}
roentgen b75cab
			} while (hp->hash >= 0);
roentgen b75cab
		}
roentgen b75cab
		/*
roentgen b75cab
		 * New entry, emit code and add to table.
roentgen b75cab
		 */
roentgen b75cab
		/*
roentgen b75cab
		 * Verify there is space in the buffer for the code
roentgen b75cab
		 * and any potential Clear code that might be emitted
roentgen b75cab
		 * below.  The value of limit is setup so that there
roentgen b75cab
		 * are at least 4 bytes free--room for 2 codes.
roentgen b75cab
		 */
roentgen b75cab
		if (op > limit) {
roentgen b75cab
			tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata);
roentgen b75cab
			TIFFFlushData1(tif);
roentgen b75cab
			op = tif->tif_rawdata;
roentgen b75cab
		}
roentgen b75cab
		PutNextCode(op, ent);
roentgen b75cab
		ent = c;
roentgen b75cab
		hp->code = free_ent++;
roentgen b75cab
		hp->hash = fcode;
roentgen b75cab
		if (free_ent == CODE_MAX-1) {
roentgen b75cab
			/* table is full, emit clear code and reset */
roentgen b75cab
			cl_hash(sp);
roentgen b75cab
			sp->enc_ratio = 0;
roentgen b75cab
			incount = 0;
roentgen b75cab
			outcount = 0;
roentgen b75cab
			free_ent = CODE_FIRST;
roentgen b75cab
			PutNextCode(op, CODE_CLEAR);
roentgen b75cab
			nbits = BITS_MIN;
roentgen b75cab
			maxcode = MAXCODE(BITS_MIN);
roentgen b75cab
		} else {
roentgen b75cab
			/*
roentgen b75cab
			 * If the next entry is going to be too big for
roentgen b75cab
			 * the code size, then increase it, if possible.
roentgen b75cab
			 */
roentgen b75cab
			if (free_ent > maxcode) {
roentgen b75cab
				nbits++;
roentgen b75cab
				assert(nbits <= BITS_MAX);
roentgen b75cab
				maxcode = (int) MAXCODE(nbits);
roentgen b75cab
			} else if (incount >= checkpoint) {
roentgen b75cab
				long rat;
roentgen b75cab
				/*
roentgen b75cab
				 * Check compression ratio and, if things seem
roentgen b75cab
				 * to be slipping, clear the hash table and
roentgen b75cab
				 * reset state.  The compression ratio is a
roentgen b75cab
				 * 24+8-bit fractional number.
roentgen b75cab
				 */
roentgen b75cab
				checkpoint = incount+CHECK_GAP;
roentgen b75cab
				CALCRATIO(sp, rat);
roentgen b75cab
				if (rat <= sp->enc_ratio) {
roentgen b75cab
					cl_hash(sp);
roentgen b75cab
					sp->enc_ratio = 0;
roentgen b75cab
					incount = 0;
roentgen b75cab
					outcount = 0;
roentgen b75cab
					free_ent = CODE_FIRST;
roentgen b75cab
					PutNextCode(op, CODE_CLEAR);
roentgen b75cab
					nbits = BITS_MIN;
roentgen b75cab
					maxcode = MAXCODE(BITS_MIN);
roentgen b75cab
				} else
roentgen b75cab
					sp->enc_ratio = rat;
roentgen b75cab
			}
roentgen b75cab
		}
roentgen b75cab
	hit:
roentgen b75cab
		;
roentgen b75cab
	}
roentgen b75cab
roentgen b75cab
	/*
roentgen b75cab
	 * Restore global state.
roentgen b75cab
	 */
roentgen b75cab
	sp->enc_incount = incount;
roentgen b75cab
	sp->enc_outcount = outcount;
roentgen b75cab
	sp->enc_checkpoint = checkpoint;
roentgen b75cab
	sp->enc_oldcode = ent;
roentgen b75cab
	sp->lzw_nextdata = nextdata;
roentgen b75cab
	sp->lzw_nextbits = nextbits;
roentgen b75cab
	sp->lzw_free_ent = free_ent;
roentgen b75cab
	sp->lzw_maxcode = maxcode;
roentgen b75cab
	sp->lzw_nbits = nbits;
roentgen b75cab
	tif->tif_rawcp = op;
roentgen b75cab
	return (1);
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
/*
roentgen b75cab
 * Finish off an encoded strip by flushing the last
roentgen b75cab
 * string and tacking on an End Of Information code.
roentgen b75cab
 */
roentgen b75cab
static int
roentgen b75cab
LZWPostEncode(TIFF* tif)
roentgen b75cab
{
roentgen b75cab
	register LZWCodecState *sp = EncoderState(tif);
roentgen b75cab
	uint8* op = tif->tif_rawcp;
roentgen b75cab
	long nextbits = sp->lzw_nextbits;
roentgen b75cab
	long nextdata = sp->lzw_nextdata;
roentgen b75cab
	long outcount = sp->enc_outcount;
roentgen b75cab
	int nbits = sp->lzw_nbits;
roentgen b75cab
roentgen b75cab
	if (op > sp->enc_rawlimit) {
roentgen b75cab
		tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata);
roentgen b75cab
		TIFFFlushData1(tif);
roentgen b75cab
		op = tif->tif_rawdata;
roentgen b75cab
	}
roentgen b75cab
	if (sp->enc_oldcode != (hcode_t) -1) {
roentgen b75cab
		PutNextCode(op, sp->enc_oldcode);
roentgen b75cab
		sp->enc_oldcode = (hcode_t) -1;
roentgen b75cab
	}
roentgen b75cab
	PutNextCode(op, CODE_EOI);
roentgen b75cab
	if (nextbits > 0) 
roentgen b75cab
		*op++ = (unsigned char)(nextdata << (8-nextbits));
roentgen b75cab
	tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata);
roentgen b75cab
	return (1);
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
/*
roentgen b75cab
 * Reset encoding hash table.
roentgen b75cab
 */
roentgen b75cab
static void
roentgen b75cab
cl_hash(LZWCodecState* sp)
roentgen b75cab
{
roentgen b75cab
	register hash_t *hp = &sp->enc_hashtab[HSIZE-1];
roentgen b75cab
	register long i = HSIZE-8;
roentgen b75cab
roentgen b75cab
	do {
roentgen b75cab
		i -= 8;
roentgen b75cab
		hp[-7].hash = -1;
roentgen b75cab
		hp[-6].hash = -1;
roentgen b75cab
		hp[-5].hash = -1;
roentgen b75cab
		hp[-4].hash = -1;
roentgen b75cab
		hp[-3].hash = -1;
roentgen b75cab
		hp[-2].hash = -1;
roentgen b75cab
		hp[-1].hash = -1;
roentgen b75cab
		hp[ 0].hash = -1;
roentgen b75cab
		hp -= 8;
roentgen b75cab
	} while (i >= 0);
roentgen b75cab
	for (i += 8; i > 0; i--, hp--)
roentgen b75cab
		hp->hash = -1;
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
static void
roentgen b75cab
LZWCleanup(TIFF* tif)
roentgen b75cab
{
roentgen b75cab
	(void)TIFFPredictorCleanup(tif);
roentgen b75cab
roentgen b75cab
	assert(tif->tif_data != 0);
roentgen b75cab
roentgen b75cab
	if (DecoderState(tif)->dec_codetab)
roentgen b75cab
		_TIFFfree(DecoderState(tif)->dec_codetab);
roentgen b75cab
roentgen b75cab
	if (EncoderState(tif)->enc_hashtab)
roentgen b75cab
		_TIFFfree(EncoderState(tif)->enc_hashtab);
roentgen b75cab
roentgen b75cab
	_TIFFfree(tif->tif_data);
roentgen b75cab
	tif->tif_data = NULL;
roentgen b75cab
roentgen b75cab
	_TIFFSetDefaultCompressionState(tif);
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
int
roentgen b75cab
TIFFInitLZW(TIFF* tif, int scheme)
roentgen b75cab
{
roentgen b75cab
	static const char module[] = "TIFFInitLZW";
roentgen b75cab
	assert(scheme == COMPRESSION_LZW);
roentgen b75cab
	/*
roentgen b75cab
	 * Allocate state block so tag methods have storage to record values.
roentgen b75cab
	 */
roentgen b75cab
	tif->tif_data = (uint8*) _TIFFmalloc(sizeof (LZWCodecState));
roentgen b75cab
	if (tif->tif_data == NULL)
roentgen b75cab
		goto bad;
roentgen b75cab
	DecoderState(tif)->dec_codetab = NULL;
roentgen b75cab
	DecoderState(tif)->dec_decode = NULL;
roentgen b75cab
	EncoderState(tif)->enc_hashtab = NULL;
roentgen b75cab
        LZWState(tif)->rw_mode = tif->tif_mode;
roentgen b75cab
roentgen b75cab
	/*
roentgen b75cab
	 * Install codec methods.
roentgen b75cab
	 */
roentgen b75cab
	tif->tif_fixuptags = LZWFixupTags; 
roentgen b75cab
	tif->tif_setupdecode = LZWSetupDecode;
roentgen b75cab
	tif->tif_predecode = LZWPreDecode;
roentgen b75cab
	tif->tif_decoderow = LZWDecode;
roentgen b75cab
	tif->tif_decodestrip = LZWDecode;
roentgen b75cab
	tif->tif_decodetile = LZWDecode;
roentgen b75cab
	tif->tif_setupencode = LZWSetupEncode;
roentgen b75cab
	tif->tif_preencode = LZWPreEncode;
roentgen b75cab
	tif->tif_postencode = LZWPostEncode;
roentgen b75cab
	tif->tif_encoderow = LZWEncode;
roentgen b75cab
	tif->tif_encodestrip = LZWEncode;
roentgen b75cab
	tif->tif_encodetile = LZWEncode;
roentgen b75cab
	tif->tif_cleanup = LZWCleanup;
roentgen b75cab
	/*
roentgen b75cab
	 * Setup predictor setup.
roentgen b75cab
	 */
roentgen b75cab
	(void) TIFFPredictorInit(tif);
roentgen b75cab
	return (1);
roentgen b75cab
bad:
roentgen b75cab
	TIFFErrorExt(tif->tif_clientdata, module, 
roentgen b75cab
		     "No space for LZW state block");
roentgen b75cab
	return (0);
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
/*
roentgen b75cab
 * Copyright (c) 1985, 1986 The Regents of the University of California.
roentgen b75cab
 * All rights reserved.
roentgen b75cab
 *
roentgen b75cab
 * This code is derived from software contributed to Berkeley by
roentgen b75cab
 * James A. Woods, derived from original work by Spencer Thomas
roentgen b75cab
 * and Joseph Orost.
roentgen b75cab
 *
roentgen b75cab
 * Redistribution and use in source and binary forms are permitted
roentgen b75cab
 * provided that the above copyright notice and this paragraph are
roentgen b75cab
 * duplicated in all such forms and that any documentation,
roentgen b75cab
 * advertising materials, and other materials related to such
roentgen b75cab
 * distribution and use acknowledge that the software was developed
roentgen b75cab
 * by the University of California, Berkeley.  The name of the
roentgen b75cab
 * University may not be used to endorse or promote products derived
roentgen b75cab
 * from this software without specific prior written permission.
roentgen b75cab
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
roentgen b75cab
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
roentgen b75cab
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
roentgen b75cab
 */
roentgen b75cab
#endif /* LZW_SUPPORT */
roentgen b75cab
roentgen b75cab
/* vim: set ts=8 sts=8 sw=8 noet: */
roentgen b75cab
/*
roentgen b75cab
 * Local Variables:
roentgen b75cab
 * mode: c
roentgen b75cab
 * c-basic-offset: 8
roentgen b75cab
 * fill-column: 78
roentgen b75cab
 * End:
roentgen b75cab
 */