1 /* pts_lzw.c -- a real, effective implementation of PostScript
2  *   LanguageLevel2 and PDF /LZWEncode and /LZWDecode filters (same as the LZW
3  *   compression used in TIFF raster image files)
4  *
5  * based on tif_lzw.c in libtiff-v3.4beta037 by Sam Leffler and Silicon Graphics.
6  * by pts@fazekas.hu at Sun Dec 30 15:04:19 CET 2001
7  * encoding and decoding works at Sun Dec 30 17:05:23 CET 2001
8  * modified for sam2p at Mon Mar  4 00:21:59 CET 2002
9  *
10  * Note that the LZW compression (but not uncompression) is patented by
11  * Unisys (patent number #4,558,302), so use this program at your own legal
12  * risk!
13  *
14  * Predictors and PostScript LanguageLevel3 filter options are not supported.
15  *
16  * Test: linux-2.2.8.tar.gz
17  * -- uncompressed:              58 388 480 bytes
18  * -- LZWEncode (lzw_codec.c):   26 518 397 bytes (uncompression OK)
19  * -- FlateEncode (almost gzip): 13 808 890 bytes (uncompression: zcat)
20  *
21  * This program is free software; you can redistribute it and/or modify
22  * it under the terms of the GNU General Public License as published by
23  * the Free Software Foundation; either version 2 of the License, or
24  * (at your option) any later version.
25  *
26  * This program is distributed in the hope that it will be useful,
27  * but WITHOUT ANY WARRANTY; without even the implied warranty of
28  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
29  * GNU General Public License for more details.
30  *
31  * You should have received a copy of the GNU General Public License
32  * along with this program; if not, write to the Free Software
33  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
34  */
35 /* Imp: check #ifdef _WINDOWS */
36 /* Dat: a strip is an interval of rows. Each strip -- probably except for the
37  *      last -- has a same number of rows. Strips are useful for TIFF writers
38  *      to better organize data in memory or disk.
39  */
40 
41 #ifdef __GNUC__
42 #ifndef __clang__
43 #pragma implementation
44 #endif
45 #endif
46 
47 #if _MSC_VER > 1000
48 # undef  __PROTOTYPES__
49 # define __PROTOTYPES__ 1
50 # pragma warning(disable: 4127) /* conditional expression is constant */
51 # pragma warning(disable: 4244) /* =' : conversion from 'int ' to 'unsigned char ', possible loss of data */
52 #endif
53 
54 
55 /* Original: /d1/sam/tiff/libtiff/RCS/tif_lzw.c,v 1.73 1997/08/29 21:45:54 sam Exp */
56 
57 /*
58  * Copyright (c) 1988-1997 Sam Leffler
59  * Copyright (c) 1991-1997 Silicon Graphics, Inc.
60  *
61  * Permission to use, copy, modify, distribute, and sell this software and
62  * its documentation for any purpose is hereby granted without fee, provided
63  * that (i) the above copyright notices and this permission notice appear in
64  * all copies of the software and related documentation, and (ii) the names of
65  * Sam Leffler and Silicon Graphics may not be used in any advertising or
66  * publicity relating to the software without the specific, prior written
67  * permission of Sam Leffler and Silicon Graphics.
68  *
69  * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
70  * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
71  * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
72  *
73  * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
74  * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
75  * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
76  * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
77  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
78  * OF THIS SOFTWARE.
79  */
80 
81 /**** pts ****/
82 #if OBJDEP
83 #  warning PROVIDES: pts_lzw
84 #endif
85 #define LZW_SUPPORT 1
86 #if 0 /* conflicts with some system defs */
87 typedef unsigned short u_short;
88 typedef unsigned char u_char;
89 typedef unsigned long u_long;
90 #endif
91 #define TO_RDONLY 1
92 #define _TIFFmalloc malloc
93 #define _TIFFfree free
94 #define _TIFFmemset memset
95 #include <stdlib.h>
96 #include <string.h>
97 
98 /*
99  * ``Library-private'' definitions.
100  */
101 
102 /*
103  * TIFF I/O Library Definitions.
104  */
105 /*
106  * Tag Image File Format (TIFF)
107  *
108  * Based on Rev 6.0 from:
109  *    Developer's Desk
110  *    Aldus Corporation
111  *    411 First Ave. South
112  *    Suite 200
113  *    Seattle, WA  98104
114  *    206-622-5500
115  */
116 #define	TIFF_VERSION	42
117 
118 /*
119  * NB: In the comments below,
120  *  - items marked with a + are obsoleted by revision 5.0,
121  *  - items marked with a ! are introduced in revision 6.0.
122  *  - items marked with a % are introduced post revision 6.0.
123  *  - items marked with a $ are obsoleted by revision 6.0.
124  */
125 
126 /* --- */
127 
128 /*
129  * This define can be used in code that requires
130  * compilation-related definitions specific to a
131  * version or versions of the library.  Runtime
132  * version checking should be done based on the
133  * string returned by TIFFGetVersion.
134  */
135 #define	TIFFLIB_VERSION	19970127	/* January 27, 1997 */
136 
137 /*
138  * The following typedefs define the intrinsic size of
139  * data types used in the *exported* interfaces.  These
140  * definitions depend on the proper definition of types
141  * in tiff.h.  Note also that the varargs interface used
142  * to pass tag types and values uses the types defined in
143  * tiff.h directly.
144  *
145  * NB: ttag_t is unsigned int and not unsigned short because
146  *     ANSI C requires that the type before the ellipsis be a
147  *     promoted type (i.e. one of int, unsigned int, pointer,
148  *     or double) and because we defined pseudo-tags that are
149  *     outside the range of legal Aldus-assigned tags.
150  * NB: tsize_t is int32 and not uint32 because some functions
151  *     return -1.
152  * NB: toff_t is not off_t for many reasons; TIFFs max out at
153  *     32-bit file offsets being the most important
154  */
155 
156 #ifndef NULL
157 #define	NULL	0
158 #endif
159 
160 typedef struct pts_lzw_state TIFF;
161 #include "pts_lzw.h"
162 
163 /**** pts ****/
164 static	int TIFFInitLZW(TIFF*);
165 static void TIFFError(char const*a, char const*b);
166 #if 0 /**** pts ****/
167 static void TIFFWarning(char const*a, char const*b, int c);
168 void TIFFWarning(char const*a, char const*b, int c) {
169   fprintf(stderr, "Warning: %s: ", a);
170   fprintf(stderr, b, c);
171   fprintf(stderr, "\n");
172 }
173 #endif
174 static  int TIFFAppendTo(TIFF*, tidataval_t*, tsize_t); /* tif_write.h */
175 #if 0
176 static void TIFFReverseBits(unsigned char *, unsigned long);
177 #endif
178 
179 #ifdef LZW_SUPPORT
180 /*
181  * TIFF Library.
182  * Rev 5.0 Lempel-Ziv & Welch Compression Support
183  *
184  * This code is derived from the compress program whose code is
185  * derived from software contributed to Berkeley by James A. Woods,
186  * derived from original work by Spencer Thomas and Joseph Orost.
187  *
188  * The original Berkeley copyright notice appears below in its entirety.
189  */
190 
191 #include <assert.h>
192 /* #include <stdio.h> */
193 
194 /*
195  * Internal version of TIFFFlushData that can be
196  * called by ``encodestrip routines'' w/o concern
197  * for infinite recursion.
198  */
199 static int
TIFFFlushData1(TIFF * tif)200 TIFFFlushData1(TIFF* tif)
201 {
202         if (tif->tif_rawcc > 0) {
203 #if 0
204 		if (tif->tif_revbits_p)
205                         TIFFReverseBits((unsigned char *)tif->tif_rawdata,
206                             tif->tif_rawcc);
207 #endif
208                 if (!TIFFAppendTo(tif,
209                     /* isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip, */
210                     tif->tif_rawdata, tif->tif_rawcc))
211                         return (0);
212                 tif->tif_rawcc = 0;
213                 tif->tif_rawcp = tif->tif_rawdata;
214         }
215         return (1);
216 }
217 
218 
219 
220 /*
221  * NB: The 5.0 spec describes a different algorithm than Aldus
222  *     implements.  Specifically, Aldus does code length transitions
223  *     one code earlier than should be done (for real LZW).
224  *     Earlier versions of this library implemented the correct
225  *     LZW algorithm, but emitted codes in a bit order opposite
226  *     to the TIFF spec.  Thus, to maintain compatibility w/ Aldus
227  *     we interpret MSB-LSB ordered codes to be images written w/
228  *     old versions of this library, but otherwise adhere to the
229  *     Aldus "off by one" algorithm.
230  *
231  * Future revisions to the TIFF spec are expected to "clarify this issue".
232  */
233 #define	LZW_COMPAT		/* include backwards compatibility code */
234 /*
235  * Each strip of data is supposed to be terminated by a CODE_EOI.
236  * If the following #define is included, the decoder will also
237  * check for end-of-strip w/o seeing this code.  This makes the
238  * library more robust, but also slower.
239  */
240 #define	LZW_CHECKEOS		/* include checks for strips w/o EOI code */
241 #undef LZW_CHECKEOS /**** pts ****/
242 
243 #define MAXCODE(n)	((1L<<(n))-1)
244 /*
245  * The TIFF spec specifies that encoded bit
246  * strings range from 9 to 12 bits.
247  */
248 #define	BITS_MIN	9		/* start with 9 bits */
249 #define	BITS_MAX	12		/* max of 12 bit strings */
250 /* predefined codes */
251 #define	CODE_CLEAR	256		/* code to clear string table */
252 #define	CODE_EOI	257		/* end-of-information code */
253 #define CODE_FIRST	258		/* first free code entry */
254 #define	CODE_MAX	MAXCODE(BITS_MAX)
255 #define	HSIZE		9001L		/* 91% occupancy */
256 #define	HSHIFT		(13-8)
257 #ifdef LZW_COMPAT
258 /* NB: +1024 is for compatibility with old files */
259 #define	CSIZE		(MAXCODE(BITS_MAX)+1024L)
260 #else
261 #define	CSIZE		(MAXCODE(BITS_MAX)+1L)
262 #endif
263 
264 /*
265  * State block for each open TIFF file using LZW
266  * compression/decompression.  Note that the predictor
267  * state block must be first in this data structure.
268  */
269 typedef	struct {
270 #if 0 /****pts****/
271 	TIFFPredictorState predict;	/* predictor super class */
272 #endif
273 
274 	unsigned short		nbits;		/* # of bits/code */
275 	unsigned short		maxcode;	/* maximum code for lzw_nbits */
276 	unsigned short		free_ent;	/* next free entry in hash table */
277 	long		nextdata;	/* next bits of i/o */
278 	long		nextbits;	/* # of valid bits in lzw_nextdata */
279 } LZWBaseState;
280 
281 #define	lzw_nbits	base.nbits
282 #define	lzw_maxcode	base.maxcode
283 #define	lzw_free_ent	base.free_ent
284 #define	lzw_nextdata	base.nextdata
285 #define	lzw_nextbits	base.nextbits
286 
287 /*
288  * Decoding-specific state.
289  */
290 typedef struct code_ent {
291 	struct code_ent *next;
292 	unsigned short	length;			/* string len, including this token */
293 	unsigned char	value;			/* data value */
294 	unsigned char	firstchar;		/* first token of string */
295 } code_t;
296 
297 typedef	int (*decodeFunc)(TIFF*, tidataval_t*, tsize_t);
298 
299 typedef struct {
300 	LZWBaseState base;
301 	long	dec_nbitsmask;		/* lzw_nbits 1 bits, right adjusted */
302 	long	dec_restart;		/* restart count */
303 #ifdef LZW_CHECKEOS
304 	long	dec_bitsleft;		/* available bits in raw data */
305 #endif
306 	decodeFunc dec_decode;		/* regular or backwards compatible */
307 	code_t*	dec_codep;		/* current recognized code */
308 	code_t*	dec_oldcodep;		/* previously recognized code */
309 	code_t*	dec_free_entp;		/* next free entry */
310 	code_t*	dec_maxcodep;		/* max available entry */
311 	code_t*	dec_codetab;		/* kept separate for small machines */
312 } LZWDecodeState;
313 
314 /*
315  * Encoding-specific state.
316  */
317 typedef unsigned short hcode_t;			/* codes fit in 16 bits */
318 typedef struct {
319 	long	hash;
320 	hcode_t	code;
321 } hash_t;
322 
323 typedef struct {
324 	LZWBaseState base;
325 	int	enc_oldcode;		/* last code encountered */
326 	long	enc_checkpoint;		/* point at which to clear table */
327 #define CHECK_GAP	10000		/* enc_ratio check interval */
328 	long	enc_ratio;		/* current compression ratio */
329 	long	enc_incount;		/* (input) data bytes encoded */
330 	long	enc_outcount;		/* encoded (output) bytes */
331 	tidataval_t* enc_rawlimit;	/* bound on tif_rawdata buffer */
332 	hash_t*	enc_hashtab;		/* kept separate for small machines */
333 } LZWEncodeState;
334 
335 #define	LZWState(tif)		((LZWBaseState*)  (void*) (tif)->tif_data)
336 #define	DecoderState(tif)	((LZWDecodeState*)(void*) LZWState(tif))
337 #define	EncoderState(tif)	((LZWEncodeState*)(void*) LZWState(tif))
338 /* ^^^ Dat: (void*) -> suppress gcc warning from -Wcast-align */
339 
340 static	void cl_hash(LZWEncodeState*);
341 
342 #if 0 /**** pts ****/ /* LZW decoder is not needed */
343 
344 static	int LZWDecode(TIFF*, tidataval_t*, tsize_t);
345 #ifdef LZW_COMPAT
346 static	int LZWDecodeCompat(TIFF*, tidataval_t*, tsize_t);
347 #endif
348 
349 /*
350  * LZW Decoder.
351  */
352 
353 #ifdef LZW_CHECKEOS
354 /*
355  * This check shouldn't be necessary because each
356  * strip is suppose to be terminated with CODE_EOI.
357  */
358 #define	NextCode(_tif, _sp, _bp, _code, _get) {				\
359 	if ((_sp)->dec_bitsleft < nbits) {				\
360 		TIFFWarning(_tif->tif_name,				\
361 		    "LZWDecode: Strip %d not terminated with EOI code", \
362 		    /*_tif->tif_curstrip*/ 0);				\
363 		_code = CODE_EOI;					\
364 	} else {							\
365 		_get(_sp,_bp,_code);					\
366 		(_sp)->dec_bitsleft -= nbits;				\
367 	}								\
368 }
369 #else
370 #define	NextCode(tif, sp, bp, code, get) get(sp, bp, code)
371 #endif
372 
373 static int
374 LZWSetupDecode(TIFF* tif)
375 {
376 	LZWDecodeState* sp = DecoderState(tif);
377 	static const char module[] = " LZWSetupDecode";
378 	int code;
379 
380 	assert(sp != NULL);
381 	if (sp->dec_codetab == NULL) {
382 		sp->dec_codetab = (code_t*)_TIFFmalloc(CSIZE*sizeof (code_t));
383 		if (sp->dec_codetab == NULL) {
384 			TIFFError(module, "No space for LZW code table");
385 			return (0);
386 		}
387 		/*
388 		 * Pre-load the table.
389 		 */
390 		for (code = 255; code >= 0; code--) {
391 			sp->dec_codetab[code].value = code;
392 			sp->dec_codetab[code].firstchar = code;
393 			sp->dec_codetab[code].length = 1;
394 			sp->dec_codetab[code].next = NULL;
395 		}
396 	}
397 	return (1);
398 }
399 
400 /*
401  * Setup state for decoding a strip.
402  */
403 static int
404 LZWPreDecode(TIFF* tif)
405 {
406 	LZWDecodeState *sp = DecoderState(tif);
407 
408 	assert(sp != NULL);
409 	/*
410 	 * Check for old bit-reversed codes.
411 	 */
412 	if (tif->tif_rawdata[0] == 0 && (tif->tif_rawdata[1] & 0x1)) {
413 #ifdef LZW_COMPAT
414 		if (!sp->dec_decode) {
415 			TIFFWarning(tif->tif_name,
416 			    "Old-style LZW codes, convert file %d", 0);
417 #if 0 /**** pts ****/
418 			/*
419 			 * Override default decoding methods with
420 			 * ones that deal with the old coding.
421 			 * Otherwise the predictor versions set
422 			 * above will call the compatibility routines
423 			 * through the dec_decode method.
424 			 */
425 			tif->tif_decoderow = LZWDecodeCompat;
426 			tif->tif_decodestrip = LZWDecodeCompat;
427 			tif->tif_decodetile = LZWDecodeCompat;
428 			/*
429 			 * If doing horizontal differencing, must
430 			 * re-setup the predictor logic since we
431 			 * switched the basic decoder methods...
432 			 */
433 			(*tif->tif_setupdecode)(tif);
434 #endif
435 			LZWSetupDecode(tif);
436 			sp->dec_decode = LZWDecodeCompat;
437 		}
438 		sp->lzw_maxcode = MAXCODE(BITS_MIN);
439 #else /* !LZW_COMPAT */
440 		if (!sp->dec_decode) {
441 			TIFFError(tif->tif_name,
442 			    "Old-style LZW codes not supported");
443 			sp->dec_decode = LZWDecode;
444 		}
445 		return (0);
446 #endif/* !LZW_COMPAT */
447 	} else {
448 		sp->lzw_maxcode = MAXCODE(BITS_MIN)-1;
449 		sp->dec_decode = LZWDecode;
450 	}
451 	sp->lzw_nbits = BITS_MIN;
452 	sp->lzw_nextbits = 0;
453 	sp->lzw_nextdata = 0;
454 
455 	sp->dec_restart = 0;
456 	sp->dec_nbitsmask = MAXCODE(BITS_MIN);
457 #ifdef LZW_CHECKEOS
458 	sp->dec_bitsleft = tif->tif_rawcc << 3;
459 #endif
460 	sp->dec_free_entp = sp->dec_codetab + CODE_FIRST;
461 	/*
462 	 * Zero entries that are not yet filled in.  We do
463 	 * this to guard against bogus input data that causes
464 	 * us to index into undefined entries.  If you can
465 	 * come up with a way to safely bounds-check input codes
466 	 * while decoding then you can remove this operation.
467 	 */
468 	_TIFFmemset(sp->dec_free_entp, 0, (CSIZE-CODE_FIRST)*sizeof (code_t));
469 	sp->dec_oldcodep = &sp->dec_codetab[-1];
470 	sp->dec_maxcodep = &sp->dec_codetab[sp->dec_nbitsmask-1];
471 	return (1);
472 }
473 
474 /*
475  * Decode a "hunk of data".
476  */
477 #define	GetNextCode(sp, bp, code) {				\
478 	nextdata = (nextdata<<8) | *(bp)++;			\
479 	nextbits += 8;						\
480 	if (nextbits < nbits) {					\
481 		nextdata = (nextdata<<8) | *(bp)++;		\
482 		nextbits += 8;					\
483 	}							\
484 	code = (hcode_t)((nextdata >> (nextbits-nbits)) & nbitsmask);	\
485 	nextbits -= nbits;					\
486 }
487 
488 static void
489 codeLoop(TIFF* tif)
490 {
491 	TIFFError(tif->tif_name,
492 	    "LZWDecode: Bogus encoding, loop in the code table; scanline %d"
493 	    /*,tif->tif_row*/);
494 }
495 
496 static int
497 LZWDecode(TIFF* tif, tidataval_t* op0, tsize_t occ0)
498 {
499 	LZWDecodeState *sp = DecoderState(tif);
500 	char *op = (char*) op0;
501 	long occ = (long) occ0;
502 	char *tp;
503 	unsigned char *bp;
504 	hcode_t code;
505 	int len;
506 	long nbits, nextbits, nextdata, nbitsmask;
507 	code_t *codep, *free_entp, *maxcodep, *oldcodep;
508 
509 	assert(sp != NULL);
510 	/*
511 	 * Restart interrupted output operation.
512 	 */
513 	if (sp->dec_restart) {
514 		long residue;
515 
516 		codep = sp->dec_codep;
517 		residue = codep->length - sp->dec_restart;
518 		if (residue > occ) {
519 			/*
520 			 * Residue from previous decode is sufficient
521 			 * to satisfy decode request.  Skip to the
522 			 * start of the decoded string, place decoded
523 			 * values in the output buffer, and return.
524 			 */
525 			sp->dec_restart += occ;
526 			do {
527 				codep = codep->next;
528 			} while (--residue > occ && codep);
529 			if (codep) {
530 				tp = op + occ;
531 				do {
532 					*--tp = codep->value;
533 					codep = codep->next;
534 				} while (--occ && codep);
535 			}
536 			return occ0-occ;
537 		}
538 		/*
539 		 * Residue satisfies only part of the decode request.
540 		 */
541 		op += residue, occ -= residue;
542 		tp = op;
543 		do {
544 			int t;
545 			--tp;
546 			t = codep->value;
547 			codep = codep->next;
548 			*tp = t;
549 		} while (--residue && codep);
550 		sp->dec_restart = 0;
551 	}
552 
553 	bp = (unsigned char *)tif->tif_rawcp; /* reading from here */
554 	nbits = sp->lzw_nbits;
555 	nextdata = sp->lzw_nextdata;
556 	nextbits = sp->lzw_nextbits;
557 	nbitsmask = sp->dec_nbitsmask;
558 	oldcodep = sp->dec_oldcodep;
559 	free_entp = sp->dec_free_entp;
560 	maxcodep = sp->dec_maxcodep;
561 
562 	while (occ > 0 && bp<tif->tif_rawend /**** pts ****/) {
563 		NextCode(tif, sp, bp, code, GetNextCode);
564 		#if 0
565 		  if (bp>tif->tif_rawend) fprintf(stderr, "over %d\n", tif->tif_rawend-bp);
566 		  assert(bp<=tif->tif_rawend);
567 		#endif
568 		if (code == CODE_EOI)
569 			break;
570 		if (code == CODE_CLEAR) {
571 			free_entp = sp->dec_codetab + CODE_FIRST;
572 			nbits = BITS_MIN;
573 			nbitsmask = MAXCODE(BITS_MIN);
574 			maxcodep = sp->dec_codetab + nbitsmask-1;
575 
576 #if 1 /**** pts ****/
577 			NextCode(tif, sp, bp, code, GetNextCode);
578 			if (code == CODE_EOI)
579 				break;
580 			*op++ = code, occ--;
581 			oldcodep = sp->dec_codetab + code; /* ! */
582 #endif
583 			continue;
584 		}
585 		codep = sp->dec_codetab + code;
586 
587 		/*
588 	 	 * Add the new entry to the code table.
589 	 	 */
590 		assert(&sp->dec_codetab[0] <= free_entp && free_entp < &sp->dec_codetab[CSIZE]);
591 		free_entp->next = oldcodep;
592 		free_entp->firstchar = free_entp->next->firstchar;
593 		free_entp->length = free_entp->next->length+1;
594 		free_entp->value = (codep < free_entp) ?
595 		    codep->firstchar : free_entp->firstchar;
596 		if (++free_entp > maxcodep) {
597 			if (++nbits > BITS_MAX)		/* should not happen */
598 				nbits = BITS_MAX;
599 			nbitsmask = MAXCODE(nbits);
600 			maxcodep = sp->dec_codetab + nbitsmask-1;
601 		}
602 		oldcodep = codep;
603 		if (code >= 256) {
604 			/*
605 		 	 * Code maps to a string, copy string
606 			 * value to output (written in reverse).
607 		 	 */
608 			if (codep->length > occ) {
609 				/*
610 				 * String is too long for decode buffer,
611 				 * locate portion that will fit, copy to
612 				 * the decode buffer, and setup restart
613 				 * logic for the next decoding call.
614 				 */
615 				sp->dec_codep = codep;
616 				do {
617 					codep = codep->next;
618 				} while (codep && codep->length > occ);
619 				if (codep) {
620 					sp->dec_restart = occ;
621 					tp = op + occ;
622 					do  {
623 						*--tp = codep->value;
624 						codep = codep->next;
625 					}  while (--occ && codep);
626 					if (codep) {
627 						codeLoop(tif);
628 						return -1;
629 					}
630 				}
631 				break;
632 			}
633 			len = codep->length;
634 			tp = op + len;
635 			do {
636 				int t;
637 				--tp;
638 				t = codep->value;
639 				codep = codep->next;
640 				*tp = t;
641 			} while (codep && tp > op);
642 			if (codep) {
643 			    codeLoop(tif);
644 			    return -1;
645 			    /* break; */
646 			}
647 			op += len, occ -= len;
648 		} else
649 			*op++ = code, occ--;
650 	}
651 
652 	tif->tif_rawcp = (tidataval_t*) bp;
653 	sp->lzw_nbits = (unsigned short) nbits;
654 	sp->lzw_nextdata = nextdata;
655 	sp->lzw_nextbits = nextbits;
656 	sp->dec_nbitsmask = nbitsmask;
657 	sp->dec_oldcodep = oldcodep;
658 	sp->dec_free_entp = free_entp;
659 	sp->dec_maxcodep = maxcodep;
660 
661 #if 0 /**** pts ****/
662 	if (occ > 0) {
663 		TIFFError(tif->tif_name,
664 		"LZWDecode: Not enough data at scanline %d (short %d bytes)"
665 		    /*,tif->tif_row, occ*/);
666 		return (0);
667 	}
668 #endif
669 	return occ0-occ;
670 }
671 
672 #ifdef LZW_COMPAT
673 /*
674  * Decode a "hunk of data" for old images.
675  */
676 #define	GetNextCodeCompat(sp, bp, code) {			\
677 	nextdata |= (unsigned long) *(bp)++ << nextbits;		\
678 	nextbits += 8;						\
679 	if (nextbits < nbits) {					\
680 		nextdata |= (unsigned long) *(bp)++ << nextbits;	\
681 		nextbits += 8;					\
682 	}							\
683 	code = (hcode_t)(nextdata & nbitsmask);			\
684 	nextdata >>= nbits;					\
685 	nextbits -= nbits;					\
686 }
687 
688 static int
689 LZWDecodeCompat(TIFF* tif, tidataval_t* op0, tsize_t occ0)
690 {
691 	LZWDecodeState *sp = DecoderState(tif);
692 	char *op = (char*) op0;
693 	long occ = (long) occ0;
694 	char *tp;
695 	unsigned char *bp;
696 	int code, nbits;
697 	long nextbits, nextdata, nbitsmask;
698 	code_t *codep, *free_entp, *maxcodep, *oldcodep;
699 
700 	assert(0);
701 	assert(sp != NULL);
702 	/*
703 	 * Restart interrupted output operation.
704 	 */
705 	if (sp->dec_restart) {
706 		long residue;
707 
708 		codep = sp->dec_codep;
709 		residue = codep->length - sp->dec_restart;
710 		if (residue > occ) {
711 			/*
712 			 * Residue from previous decode is sufficient
713 			 * to satisfy decode request.  Skip to the
714 			 * start of the decoded string, place decoded
715 			 * values in the output buffer, and return.
716 			 */
717 			sp->dec_restart += occ;
718 			do {
719 				codep = codep->next;
720 			} while (--residue > occ);
721 			tp = op + occ;
722 			do {
723 				*--tp = codep->value;
724 				codep = codep->next;
725 			} while (--occ);
726 			return occ0-occ;
727 		}
728 		/*
729 		 * Residue satisfies only part of the decode request.
730 		 */
731 		op += residue, occ -= residue;
732 		tp = op;
733 		do {
734 			*--tp = codep->value;
735 			codep = codep->next;
736 		} while (--residue);
737 		sp->dec_restart = 0;
738 	}
739 
740 	bp = (unsigned char *)tif->tif_rawcp;
741 	nbits = sp->lzw_nbits;
742 	nextdata = sp->lzw_nextdata;
743 	nextbits = sp->lzw_nextbits;
744 	nbitsmask = sp->dec_nbitsmask;
745 	oldcodep = sp->dec_oldcodep;
746 	free_entp = sp->dec_free_entp;
747 	maxcodep = sp->dec_maxcodep;
748 
749 	while (occ > 0 && bp<tif->tif_rawend) {
750 		NextCode(tif, sp, bp, code, GetNextCodeCompat);
751 		if (code == CODE_EOI)
752 			break;
753 		if (code == CODE_CLEAR) {
754 			free_entp = sp->dec_codetab + CODE_FIRST;
755 			nbits = BITS_MIN;
756 			nbitsmask = MAXCODE(BITS_MIN);
757 			maxcodep = sp->dec_codetab + nbitsmask;
758 			NextCode(tif, sp, bp, code, GetNextCodeCompat);
759 			if (code == CODE_EOI)
760 				break;
761 			*op++ = code, occ--;
762 			oldcodep = sp->dec_codetab + code;
763 			continue;
764 		}
765 		codep = sp->dec_codetab + code;
766 
767 		/*
768 	 	 * Add the new entry to the code table.
769 	 	 */
770 		assert(&sp->dec_codetab[0] <= free_entp && free_entp < &sp->dec_codetab[CSIZE]);
771 		free_entp->next = oldcodep;
772 		free_entp->firstchar = free_entp->next->firstchar;
773 		free_entp->length = free_entp->next->length+1;
774 		free_entp->value = (codep < free_entp) ?
775 		    codep->firstchar : free_entp->firstchar;
776 		if (++free_entp > maxcodep) {
777 			if (++nbits > BITS_MAX)		/* should not happen */
778 				nbits = BITS_MAX;
779 			nbitsmask = MAXCODE(nbits);
780 			maxcodep = sp->dec_codetab + nbitsmask;
781 		}
782 		oldcodep = codep;
783 		if (code >= 256) {
784 			/*
785 		 	 * Code maps to a string, copy string
786 			 * value to output (written in reverse).
787 		 	 */
788 			if (codep->length > occ) {
789 				/*
790 				 * String is too long for decode buffer,
791 				 * locate portion that will fit, copy to
792 				 * the decode buffer, and setup restart
793 				 * logic for the next decoding call.
794 				 */
795 				sp->dec_codep = codep;
796 				do {
797 					codep = codep->next;
798 				} while (codep->length > occ);
799 				sp->dec_restart = occ;
800 				tp = op + occ;
801 				do  {
802 					*--tp = codep->value;
803 					codep = codep->next;
804 				}  while (--occ);
805 				break;
806 			}
807 			op += codep->length, occ -= codep->length;
808 			tp = op;
809 			do {
810 				*--tp = codep->value;
811 			} while (0!=(codep = codep->next));
812 		} else
813 			*op++ = code, occ--;
814 	}
815 
816 	tif->tif_rawcp = (tidataval_t*) bp;
817 	sp->lzw_nbits = nbits;
818 	sp->lzw_nextdata = nextdata;
819 	sp->lzw_nextbits = nextbits;
820 	sp->dec_nbitsmask = nbitsmask;
821 	sp->dec_oldcodep = oldcodep;
822 	sp->dec_free_entp = free_entp;
823 	sp->dec_maxcodep = maxcodep;
824 
825 #if 0 /**** pts ****/
826 	if (occ > 0) {
827 		TIFFError(tif->tif_name,
828 		    "LZWDecodeCompat: Not enough data at scanline %d (short %d bytes)"
829 		    /*,tif->tif_row, occ*/);
830 		return (0);
831 	}
832 #endif
833 	return occ0-occ;
834 }
835 #endif /* LZW_COMPAT */
836 
837 #endif /**** pts ****/
838 
839 /* --- */
840 
841 /*
842  * LZW Encoding.
843  */
844 
845 static int
LZWSetupEncode(TIFF * tif)846 LZWSetupEncode(TIFF* tif)
847 {
848 	LZWEncodeState* sp = EncoderState(tif);
849 	static const char module[] = "LZWSetupEncode";
850 
851 	assert(sp != NULL);
852 	sp->enc_hashtab = (hash_t*) _TIFFmalloc(HSIZE*sizeof (hash_t));
853 	if (sp->enc_hashtab == NULL) {
854 		TIFFError(module, "No space for LZW hash table");
855 		return (0);
856 	}
857 	return (1);
858 }
859 
860 /*
861  * Reset encoding state at the start of a strip.
862  */
863 static int
LZWPreEncode(TIFF * tif)864 LZWPreEncode(TIFF* tif)
865 {
866 	LZWEncodeState *sp = EncoderState(tif);
867 
868 	assert(sp != NULL);
869 	sp->lzw_nbits = BITS_MIN;
870 	sp->lzw_maxcode = MAXCODE(BITS_MIN);
871 	sp->lzw_free_ent = CODE_FIRST;
872 	sp->lzw_nextbits = 0;
873 	sp->lzw_nextdata = 0;
874 	sp->enc_checkpoint = CHECK_GAP;
875 	sp->enc_ratio = 0;
876 	sp->enc_incount = 0;
877 	sp->enc_outcount = 0;
878 	/*
879 	 * The 4 here insures there is space for 2 max-sized
880 	 * codes in LZWEncode and LZWPostDecode.
881 	 */
882 	sp->enc_rawlimit = tif->tif_rawdata + tif->tif_rawdatasize-1 - 4;
883 	cl_hash(sp);		/* clear hash table */
884 	sp->enc_oldcode = (hcode_t) -1;	/* generates CODE_CLEAR in LZWEncode */
885 	return (1);
886 }
887 
888 #define	CALCRATIO(sp, rat) {					\
889 	if (incount > 0x007fffff) { /* NB: shift will overflow */\
890 		rat = outcount >> 8;				\
891 		rat = (rat == 0 ? 0x7fffffff : incount/rat);	\
892 	} else							\
893 		rat = (incount<<8) / outcount;			\
894 }
895 #define	PutNextCode(op, c) {					\
896 	nextdata = (nextdata << nbits) | c;			\
897 	nextbits += nbits;					\
898 	*op++ = (unsigned char)(nextdata >> (nextbits-8));		\
899 	nextbits -= 8;						\
900 	if (nextbits >= 8) {					\
901 		*op++ = (unsigned char)(nextdata >> (nextbits-8));	\
902 		nextbits -= 8;					\
903 	}							\
904 	outcount += nbits;					\
905 }
906 
907 /*
908  * Encode a chunk of pixels.
909  *
910  * Uses an open addressing double hashing (no chaining) on the
911  * prefix code/next character combination.  We do a variant of
912  * Knuth's algorithm D (vol. 3, sec. 6.4) along with G. Knott's
913  * relatively-prime secondary probe.  Here, the modular division
914  * first probe is gives way to a faster exclusive-or manipulation.
915  * Also do block compression with an adaptive reset, whereby the
916  * code table is cleared when the compression ratio decreases,
917  * but after the table fills.  The variable-length output codes
918  * are re-sized at this point, and a CODE_CLEAR is generated
919  * for the decoder.
920  */
921 static int
LZWEncode(TIFF * tif,tidataval_t * bp,tsize_t cc)922 LZWEncode(TIFF* tif, tidataval_t* bp, tsize_t cc)
923 {
924 	register LZWEncodeState *sp = EncoderState(tif);
925 	register long fcode;
926 	register hash_t *hp;
927 	register int h, c;
928 	hcode_t ent;
929 	long disp;
930 	long incount, outcount, checkpoint;
931 	long nextdata, nextbits;
932 	int free_ent, maxcode, nbits;
933 	tidataval_t* op, *limit;
934 
935 	if (sp == NULL)
936 		return (0);
937 	/*
938 	 * Load local state.
939 	 */
940 	incount = sp->enc_incount;
941 	outcount = sp->enc_outcount;
942 	checkpoint = sp->enc_checkpoint;
943 	nextdata = sp->lzw_nextdata;
944 	nextbits = sp->lzw_nextbits;
945 	free_ent = sp->lzw_free_ent;
946 	maxcode = sp->lzw_maxcode;
947 	nbits = sp->lzw_nbits;
948 	op = tif->tif_rawcp;
949 	limit = sp->enc_rawlimit;
950 	ent = sp->enc_oldcode;
951 
952 	if (ent == (hcode_t) -1 && cc > 0) {
953 		/*
954 		 * NB: This is safe because it can only happen
955 		 *     at the start of a strip where we know there
956 		 *     is space in the data buffer.
957 		 */
958 		PutNextCode(op, CODE_CLEAR);
959 		ent = *bp++; cc--; incount++;
960 	}
961 	while (cc > 0) {
962 		c = *bp++; cc--; incount++;
963 		fcode = ((long)c << BITS_MAX) + ent;
964 		h = (c << HSHIFT) ^ ent;	/* xor hashing */
965 #ifdef _WINDOWS /* ?? */
966 		/*
967 		 * Check hash index for an overflow.
968 		 */
969 		if (h >= HSIZE)
970 			h -= HSIZE;
971 #endif
972 		hp = &sp->enc_hashtab[h];
973 		if (hp->hash == fcode) {
974 			ent = hp->code;
975 			continue;
976 		}
977 		if (hp->hash >= 0) {
978 			/*
979 			 * Primary hash failed, check secondary hash.
980 			 */
981 			disp = HSIZE - h;
982 			if (h == 0)
983 				disp = 1;
984 			do {
985 				/*
986 				 * Avoid pointer arithmetic 'cuz of
987 				 * wraparound problems with segments.
988 				 */
989 				if ((h -= disp) < 0)
990 					h += HSIZE;
991 				hp = &sp->enc_hashtab[h];
992 				if (hp->hash == fcode) {
993 					ent = hp->code;
994 					goto hit;
995 				}
996 			} while (hp->hash >= 0);
997 		}
998 		/*
999 		 * New entry, emit code and add to table.
1000 		 */
1001 		/*
1002 		 * Verify there is space in the buffer for the code
1003 		 * and any potential Clear code that might be emitted
1004 		 * below.  The value of limit is setup so that there
1005 		 * are at least 4 bytes free--room for 2 codes.
1006 		 */
1007 		if (op > limit) {
1008 			tif->tif_rawcc = (tsize_t)(op - tif->tif_rawdata);
1009 			TIFFFlushData1(tif);
1010 			op = tif->tif_rawdata;
1011 		}
1012 		PutNextCode(op, ent);
1013 		ent = c;
1014 		hp->code = free_ent++;
1015 		hp->hash = fcode;
1016 		if (free_ent == CODE_MAX-1) {
1017 			/* table is full, emit clear code and reset */
1018 			cl_hash(sp);
1019 			sp->enc_ratio = 0;
1020 			incount = 0;
1021 			outcount = 0;
1022 			free_ent = CODE_FIRST;
1023 			PutNextCode(op, CODE_CLEAR);
1024 			nbits = BITS_MIN;
1025 			maxcode = MAXCODE(BITS_MIN);
1026 		} else {
1027 			/*
1028 			 * If the next entry is going to be too big for
1029 			 * the code size, then increase it, if possible.
1030 			 */
1031 			if (free_ent > maxcode) {
1032 				nbits++;
1033 				assert(nbits <= BITS_MAX);
1034 				maxcode = (int) MAXCODE(nbits);
1035 			} else if (incount >= checkpoint) {
1036 				long rat;
1037 				/*
1038 				 * Check compression ratio and, if things seem
1039 				 * to be slipping, clear the hash table and
1040 				 * reset state.  The compression ratio is a
1041 				 * 24+8-bit fractional number.
1042 				 */
1043 				checkpoint = incount+CHECK_GAP;
1044 				CALCRATIO(sp, rat);
1045 				if (rat <= sp->enc_ratio) {
1046 					cl_hash(sp);
1047 					sp->enc_ratio = 0;
1048 					incount = 0;
1049 					outcount = 0;
1050 					free_ent = CODE_FIRST;
1051 					PutNextCode(op, CODE_CLEAR);
1052 					nbits = BITS_MIN;
1053 					maxcode = MAXCODE(BITS_MIN);
1054 				} else
1055 					sp->enc_ratio = rat;
1056 			}
1057 		}
1058 	hit:
1059 		;
1060 	}
1061 
1062 	/*
1063 	 * Restore global state.
1064 	 */
1065 	sp->enc_incount = incount;
1066 	sp->enc_outcount = outcount;
1067 	sp->enc_checkpoint = checkpoint;
1068 	sp->enc_oldcode = ent;
1069 	sp->lzw_nextdata = nextdata;
1070 	sp->lzw_nextbits = nextbits;
1071 	sp->lzw_free_ent = free_ent;
1072 	sp->lzw_maxcode = maxcode;
1073 	sp->lzw_nbits = nbits;
1074 	tif->tif_rawcp = op;
1075 	return (1);
1076 }
1077 
1078 /*
1079  * Finish off an encoded strip by flushing the last
1080  * string and tacking on an End Of Information code.
1081  */
1082 static int
LZWPostEncode(TIFF * tif)1083 LZWPostEncode(TIFF* tif)
1084 {
1085 	register LZWEncodeState *sp = EncoderState(tif);
1086 	tidataval_t* op = tif->tif_rawcp;
1087 	long nextbits = sp->lzw_nextbits;
1088 	long nextdata = sp->lzw_nextdata;
1089 	long outcount = sp->enc_outcount;
1090 	int nbits = sp->lzw_nbits;
1091 
1092 	if (op > sp->enc_rawlimit) {
1093 		/* fprintf(stderr, "Yupp!\n"); */
1094 		tif->tif_rawcc = (tsize_t)(op - tif->tif_rawdata);
1095 		TIFFFlushData1(tif);
1096 		op = tif->tif_rawdata;
1097 	}
1098 	if (sp->enc_oldcode != (hcode_t) -1) {
1099 		/* fprintf(stderr, "EIK\n"); */
1100 		PutNextCode(op, sp->enc_oldcode);
1101 		sp->enc_oldcode = (hcode_t) -1;
1102 	}
1103 	PutNextCode(op, CODE_EOI);
1104 	if (nextbits > 0)
1105 		*op++ = (unsigned char)(nextdata << (8-nextbits));
1106 	tif->tif_rawcc = (tsize_t)(op - tif->tif_rawdata);
1107 	return (1);
1108 }
1109 
1110 /*
1111  * Reset encoding hash table.
1112  */
1113 static void
cl_hash(LZWEncodeState * sp)1114 cl_hash(LZWEncodeState* sp)
1115 {
1116 	register hash_t *hp = &sp->enc_hashtab[HSIZE-1];
1117 	register long i = HSIZE-8;
1118 
1119  	do {
1120 		i -= 8;
1121 		hp[-7].hash = -1;
1122 		hp[-6].hash = -1;
1123 		hp[-5].hash = -1;
1124 		hp[-4].hash = -1;
1125 		hp[-3].hash = -1;
1126 		hp[-2].hash = -1;
1127 		hp[-1].hash = -1;
1128 		hp[ 0].hash = -1;
1129 		hp -= 8;
1130 	} while (i >= 0);
1131     	for (i += 8; i > 0; i--, hp--)
1132 		hp->hash = -1;
1133 }
1134 
1135 static void
LZWCleanup(TIFF * tif)1136 LZWCleanup(TIFF* tif)
1137 {
1138 	if (tif->tif_data) {
1139 		if (tif->tif_reading_p) {
1140 			if (DecoderState(tif)->dec_codetab)
1141 				_TIFFfree(DecoderState(tif)->dec_codetab);
1142 		} else {
1143 			if (EncoderState(tif)->enc_hashtab)
1144 				_TIFFfree(EncoderState(tif)->enc_hashtab);
1145 		}
1146 		_TIFFfree(tif->tif_data);
1147 		tif->tif_data = NULL;
1148 	}
1149 	_TIFFfree(tif->tif_rawdata);
1150 }
1151 
1152 static int
TIFFInitLZW(TIFF * tif)1153 TIFFInitLZW(TIFF* tif)
1154 {
1155 	/* assert(scheme == COMPRESSION_LZW); */
1156 	/*
1157 	 * Allocate state block so tag methods have storage to record values.
1158 	 */
1159 	if (tif->tif_reading_p) {
1160 		tif->tif_data = (tidataval_t*) _TIFFmalloc(sizeof (LZWDecodeState));
1161 		if (tif->tif_data == NULL)
1162 			goto bad;
1163 		DecoderState(tif)->dec_codetab = NULL;
1164 		DecoderState(tif)->dec_decode = NULL;
1165 	} else {
1166 		tif->tif_data = (tidataval_t*) _TIFFmalloc(sizeof (LZWEncodeState));
1167 		if (tif->tif_data == NULL)
1168 			goto bad;
1169 		EncoderState(tif)->enc_hashtab = NULL;
1170 	}
1171 #if 0 /**** pts ****/
1172 	/*
1173 	 * Install codec methods.
1174 	 */
1175 	tif->tif_setupdecode = LZWSetupDecode;
1176 	tif->tif_predecode = LZWPreDecode;
1177 	tif->tif_decoderow = LZWDecode;
1178 	tif->tif_decodestrip = LZWDecode;
1179 	tif->tif_decodetile = LZWDecode;
1180 	tif->tif_setupencode = LZWSetupEncode;
1181 	tif->tif_preencode = LZWPreEncode;
1182 	tif->tif_postencode = LZWPostEncode;
1183 	tif->tif_encoderow = LZWEncode;
1184 	tif->tif_encodestrip = LZWEncode;
1185 	tif->tif_encodetile = LZWEncode;
1186 	tif->tif_cleanup = LZWCleanup;
1187 #endif
1188 #if 0 /**** pts ****/
1189 	/*
1190 	 * Setup predictor setup.
1191 	 */
1192 	(void) TIFFPredictorInit(tif);
1193 #endif
1194 	return (1);
1195 bad:
1196 	TIFFError("TIFFInitLZW", "No space for LZW state block");
1197 	return (0);
1198 }
1199 
1200 /*
1201  * Copyright (c) 1985, 1986 The Regents of the University of California.
1202  * All rights reserved.
1203  *
1204  * This code is derived from software contributed to Berkeley by
1205  * James A. Woods, derived from original work by Spencer Thomas
1206  * and Joseph Orost.
1207  *
1208  * Redistribution and use in source and binary forms are permitted
1209  * provided that the above copyright notice and this paragraph are
1210  * duplicated in all such forms and that any documentation,
1211  * advertising materials, and other materials related to such
1212  * distribution and use acknowledge that the software was developed
1213  * by the University of California, Berkeley.  The name of the
1214  * University may not be used to endorse or promote products derived
1215  * from this software without specific prior written permission.
1216  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
1217  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
1218  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
1219  */
1220 #endif /* LZW_SUPPORT */
1221 
1222 #if 0
1223 #ifdef __cplusplus
1224 extern "C"
1225 #else
1226 extern
1227 #endif
1228 FILE *fdopen (int fildes, const char *mode); /* POSIX, but not ANSI */
1229 #else
1230 #undef  _POSIX_SOURCE
1231 #define _POSIX_SOURCE 1
1232 #undef  _POSIX_C_SOURCE /* Sat Jun  1 14:25:53 CEST 2002 */
1233 #define _POSIX_C_SOURCE 2
1234 #include <stdio.h>
1235 #endif
1236 
1237 #if 0 /**** pts: never needed, because output FillOrder is always 1 */
1238 void
1239 TIFFReverseBits(register unsigned char* cp, register unsigned long n)
1240 {
1241         char *TIFFBitRevTable=...; /**** pts ****/
1242         for (; n > 8; n -= 8) {
1243                 cp[0] = TIFFBitRevTable[cp[0]];
1244                 cp[1] = TIFFBitRevTable[cp[1]];
1245                 cp[2] = TIFFBitRevTable[cp[2]];
1246                 cp[3] = TIFFBitRevTable[cp[3]];
1247                 cp[4] = TIFFBitRevTable[cp[4]];
1248                 cp[5] = TIFFBitRevTable[cp[5]];
1249                 cp[6] = TIFFBitRevTable[cp[6]];
1250                 cp[7] = TIFFBitRevTable[cp[7]];
1251                 cp += 8;
1252         }
1253         while (n-- > 0)
1254                 *cp = TIFFBitRevTable[*cp], cp++;
1255 }
1256 #endif
1257 
TIFFError(char const * a,char const * b)1258 static void TIFFError(char const*a, char const*b) {
1259   fprintf(stderr, "%s: %s\n", a, b);
1260 }
TIFFAppendTo(TIFF * tif,tidataval_t * data,tsize_t cc)1261 static int TIFFAppendTo(TIFF*tif, tidataval_t* data, tsize_t cc) {
1262    (void)tif;
1263    (void)data;
1264    (void)cc;
1265    /* fwrite(data, 1, cc, (FILE*)tif->tif_sout);
1266       if (ferror((FILE*)tif->tif_sout)) return 0; */
1267    if (-1==tif->tif_writer((char*)data, cc, tif->tif_sout)) return 0;
1268 #if 0 /**** pts ****/ /* tif_write.h */
1269    (void)strip;
1270         TIFFDirectory *td = &tif->tif_dir;
1271         static const char module[] = "TIFFAppendToStrip";
1272 
1273         if (td->td_stripoffset[strip] == 0 || tif->tif_curoff == 0) {
1274                 /*
1275                  * No current offset, set the current strip.
1276                  */
1277                 if (td->td_stripoffset[strip] != 0) {
1278                         if (!SeekOK(tif, td->td_stripoffset[strip])) {
1279                                 TIFFError(module,
1280                                     "%s: Seek error at scanline %lu",
1281                                     tif->tif_name, (unsigned long) tif->tif_row);
1282                                 return (0);
1283                         }
1284                 } else
1285                         td->td_stripoffset[strip] =
1286                             TIFFSeekFile(tif, (toff_t) 0, SEEK_END);
1287                 tif->tif_curoff = td->td_stripoffset[strip];
1288         }
1289         if (!WriteOK(tif, data, cc)) {
1290                 TIFFError(module, "%s: Write error at scanline %lu",
1291                     tif->tif_name, (unsigned long) tif->tif_row);
1292                 return (0);
1293         }
1294         tif->tif_curoff += cc;
1295         td->td_stripbytecount[strip] += cc;
1296 #endif
1297         return (1);
1298 }
1299 
1300 #if 0
1301 static tidataval_t readbuf[4096];
1302 unsigned int readlen;
1303 static char *inname;
1304 typedef int (*filter_t)(FILE *sin, FILE*sout);
1305 /** /LZWEncode filter, STDIN -> STDOUT */
1306 static int lzw_encode(FILE *sin, FILE *sout) {
1307   TIFF tif;
1308   tif.tif_sout=sout;
1309   tif.tif_reading_p=0;
1310 #if 0
1311   tif.tif_revbits_p=0;
1312 #endif
1313   tif.tif_name=inname;
1314   tif.tif_rawdata=(tidataval_t*)_TIFFmalloc(tif.tif_rawdatasize=4096); /* Imp: check */
1315   tif.tif_rawcp=tif.tif_rawdata;
1316   tif.tif_rawcc=0;
1317   if (TIFFInitLZW(&tif) &&
1318       LZWSetupEncode(&tif) &&
1319       LZWPreEncode(&tif) /* for each strip */) {
1320     while ((readlen=fread(readbuf, 1, sizeof(readbuf), sin))!=0) {
1321       if (!LZWEncode(&tif, readbuf, readlen)) goto err;
1322       /* fprintf(stderr, "readlen=%d\n", readlen); */
1323     }
1324     if (!LZWPostEncode(&tif)) goto err; /* for each strip */
1325     LZWCleanup(&tif);
1326     if (!TIFFFlushData1(&tif)) { _TIFFfree(tif.tif_rawdata); fflush(sout); return 0; }
1327     fflush(sout);
1328   } else { err:
1329     fflush(sout);
1330     LZWCleanup(&tif);
1331     _TIFFfree(tif.tif_rawdata);
1332     return 0;
1333   }
1334   return 1;
1335 }
1336 /** /LZWEncode filter, STDIN -> STDOUT */
1337 static int lzw_decode(FILE *sin, FILE *sout) {
1338   TIFF tif;
1339   /* tidataval_t *rawend0; */
1340   /* char *xbuf; */
1341   int got;
1342   unsigned int left;
1343   tif.tif_reading_p=1;
1344 #if 0
1345   tif.tif_revbits_p=0;
1346 #endif
1347   tif.tif_name=inname;
1348   tif.tif_rawdata=(tidataval_t*)_TIFFmalloc(tif.tif_rawdatasize=4096); /* Imp: check */
1349   tif.tif_rawcc=0;
1350   left=0;
1351   if (TIFFInitLZW(&tif) &&
1352       LZWSetupDecode(&tif) &&
1353       LZWPreDecode(&tif) /* for each strip */) {
1354     /* vvv Dat: fread returns >=0 ! */
1355     while ((readlen=left+fread(tif.tif_rawdata+left, 1, tif.tif_rawdatasize-left, sin))!=0) {
1356      #if DEBUGMSG
1357       fprintf(stderr, "readlen+=%d\n", readlen);
1358      #endif
1359       while (readlen<=3) {
1360         if ((got=fread(tif.tif_rawdata+readlen, 1, tif.tif_rawdatasize-readlen, sin))==0) {
1361           tif.tif_rawend=tif.tif_rawdata+readlen;
1362           goto star;
1363         }
1364         readlen+=got;
1365       }
1366       tif.tif_rawend=tif.tif_rawdata+readlen-3;
1367      star:
1368       tif.tif_rawcp=tif.tif_rawdata;
1369      #if DEBUGMSG
1370       fprintf(stderr, "readlen:=%d\n", readlen);
1371      #endif
1372       while (1) {
1373         if (-1==(got=(DecoderState(&tif)->dec_decode)(&tif, readbuf, sizeof(readbuf)))) goto err;
1374        #if DEBUGMSG
1375         fprintf(stderr, "OK, written: %d %d\n", got, tif.tif_rawend-tif.tif_rawcp);
1376        #endif
1377         if (0==got) break;
1378         fwrite(readbuf, 1, got, sout);
1379       }
1380       left=tif.tif_rawdata+readlen-tif.tif_rawcp;
1381       got=left;
1382      #if DEBUGMSG
1383       fprintf(stderr, "left=%d\n", left); fflush(stderr);
1384      #endif
1385       while (got--!=0) { tif.tif_rawdata[got]=tif.tif_rawcp[got]; }
1386     }
1387 #if 0
1388     if (!LZWPostDecode(&tif)) { LZWCleanup(&tif); return 0; } /* for each strip */
1389 #endif
1390     LZWCleanup(&tif);
1391     fflush(sout);
1392   } else { err:
1393     fflush(sout);
1394     LZWCleanup(&tif);
1395     _TIFFfree(tif.tif_rawdata);
1396     return 0;
1397   }
1398   return 1;
1399 }
1400 #endif
1401 
feeder(char * readbuf,unsigned readlen,TIFF * tif)1402 static int feeder(char *readbuf, unsigned readlen, TIFF *tif) {
1403   /*(void)LZWPreDecode;*/ /* Imp: better avoid gcc warning... */
1404   if (readlen!=0) {
1405     if (!LZWEncode(tif, (tidataval_t*)readbuf, readlen)) { e1:
1406       LZWCleanup(tif); e2:
1407       _TIFFfree(tif->tif_rawdata);
1408       return 0;
1409     }
1410   } else {
1411     if (!LZWPostEncode(tif)) goto e1;
1412     if (!TIFFFlushData1(tif)) goto e2;
1413     LZWCleanup(tif);
1414   }
1415   return 1;
1416 }
1417 
1418 /** /LZWEncode filter, STDIN -> STDOUT */
pts_lzw_init(TIFF * tif)1419 int pts_lzw_init(TIFF *tif) {
1420   /* tif_sout and tif_writer are already filled */
1421   tif->tif_feeder=feeder;
1422   tif->tif_reading_p=0;
1423 #if 0
1424   tif->tif_revbits_p=0;
1425 #endif
1426   tif->tif_name="//.filter";/*inname;*/
1427   tif->tif_rawdata=(tidataval_t*)_TIFFmalloc(tif->tif_rawdatasize=4096); /* Imp: check */
1428   tif->tif_rawcp=tif->tif_rawdata;
1429   tif->tif_rawcc=0;
1430   if (TIFFInitLZW(tif) &&
1431       LZWSetupEncode(tif) &&
1432       LZWPreEncode(tif) /* for each strip */) {
1433     return 1;
1434   }
1435   LZWCleanup(tif);
1436   _TIFFfree(tif->tif_rawdata);
1437   return 0;
1438 }
1439 
1440 
1441 #if 0
1442 /**** pts ****/
1443 int main(int argc, char **argv) {
1444   filter_t filter;
1445   FILE *sin, *sout;
1446   inname="STDIN";
1447 
1448   if (argc>=2 && argc<=4 && argv[1][0]=='e') {
1449     filter=lzw_encode;
1450   } else if (argc>=2 && argc<=4 && argv[1][0]=='d') {
1451     filter=lzw_decode;
1452   } else {
1453     fprintf(stderr,
1454       "This is PotterSoftware LZW codec v0.1, (C) pts@fazekas.hu in Late Dec 2001\n"
1455       "THIS SOFTWARE COMES WITH ABSOLUTELY NO WARRANTY! USE AT YOUR OWN RISK!\n"
1456       "This program is free software, covered by the GNU GPL.\n"
1457       "  Derived from code Copyright (c) 1988-1997 Sam Leffler\n"
1458       "  Derived from code Copyright (c) 1991-1997 Silicon Graphics, Inc.\n\n"
1459       "Usage: %s encode|decode [INFILE] [OUTFILE]\n\n"
1460       "Unspecified file names mean STDIN or STDOUT.\n"
1461       "Encoding is /LZWEncode compression, decoding is /LZWDecode uncompression.\n\n"
1462       "Note that the LZW compression (but not uncompression) is patented by\n"
1463       "Unisys (patent number #4,558,302), so use this program at your own legal\n"
1464       "risk!\n"
1465       ,argv[0]);
1466     return 2;
1467   }
1468   if (argc>=3) sin= fopen(inname=argv[2],"rb");
1469           else sin= fdopen(0, "rb");
1470   if (sin==0) {
1471     fprintf(stderr, "%s: error opening infile\n", argv[0]);
1472     return 3;
1473   }
1474   if (argc>=4) sout=fopen(inname=argv[3],"wb");
1475           else sout=fdopen(1, "wb");
1476   if (sout==0) {
1477     fprintf(stderr, "%s: error opening outfile\n", argv[0]);
1478     return 4;
1479   }
1480   return !filter(sin, sout);
1481   /* fclose(sout); fclose(sin); */
1482 }
1483 #endif
1484