1 /* $Header: /usr/people/sam/tiff/libtiff/RCS/tif_lzw.c,v 1.55 1994/09/28 00:54:41 sam Exp $ */
2
3 /*
4 * Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994 Sam Leffler
5 * Copyright (c) 1991, 1992, 1993, 1994 Silicon Graphics, Inc.
6 *
7 * Permission to use, copy, modify, distribute, and sell this software and
8 * its documentation for any purpose is hereby granted without fee, provided
9 * that (i) the above copyright notices and this permission notice appear in
10 * all copies of the software and related documentation, and (ii) the names of
11 * Sam Leffler and Silicon Graphics may not be used in any advertising or
12 * publicity relating to the software without the specific, prior written
13 * permission of Sam Leffler and Silicon Graphics.
14 *
15 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
17 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
18 *
19 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
20 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
21 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
22 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
23 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
24 * OF THIS SOFTWARE.
25 */
26
27 /*
28 * TIFF Library.
29 * Rev 5.0 Lempel-Ziv & Welch Compression Support
30 *
31 * This code is derived from the compress program whose code is
32 * derived from software contributed to Berkeley by James A. Woods,
33 * derived from original work by Spencer Thomas and Joseph Orost.
34 *
35 * The original Berkeley copyright notice appears below in its entirety.
36 */
37 #include "tiffiop.h"
38 #include <assert.h>
39 #include <stdio.h>
40
41 /*
42 * NB: The 5.0 spec describes a different algorithm than Aldus
43 * implements. Specifically, Aldus does code length transitions
44 * one code earlier than should be done (for real LZW).
45 * Earlier versions of this library implemented the correct
46 * LZW algorithm, but emitted codes in a bit order opposite
47 * to the TIFF spec. Thus, to maintain compatibility w/ Aldus
48 * we interpret MSB-LSB ordered codes to be images written w/
49 * old versions of this library, but otherwise adhere to the
50 * Aldus "off by one" algorithm.
51 *
52 * Future revisions to the TIFF spec are expected to "clarify this issue".
53 */
54 #define LZW_COMPAT /* include backwards compatibility code */
55 /*
56 * Each strip of data is supposed to be terminated by a CODE_EOI.
57 * If the following #define is included, the decoder will also
58 * check for end-of-strip w/o seeing this code. This makes the
59 * library more robust, but also slower.
60 */
61 #define LZW_CHECKEOS /* include checks for strips w/o EOI code */
62
63 #define MAXCODE(n) ((1L<<(n))-1)
64 /*
65 * The TIFF spec specifies that encoded bit
66 * strings range from 9 to 12 bits.
67 */
68 #define BITS_MIN 9 /* start with 9 bits */
69 #define BITS_MAX 12 /* max of 12 bit strings */
70 /* predefined codes */
71 #define CODE_CLEAR 256 /* code to clear string table */
72 #define CODE_EOI 257 /* end-of-information code */
73 #define CODE_FIRST 258 /* first free code entry */
74 #define CODE_MAX MAXCODE(BITS_MAX)
75 #define HSIZE 9001L /* 91% occupancy */
76 #define HSHIFT (13-8)
77 #ifdef LZW_COMPAT
78 /* NB: +1024 is for compatibility with old files */
79 #define CSIZE (MAXCODE(BITS_MAX)+1024)
80 #else
81 #define CSIZE (MAXCODE(BITS_MAX)+1)
82 #endif
83
84 typedef void (*predictorFunc)(tidata_t data, tsize_t nbytes, u_int stride);
85
86 /*
87 * State block for each open TIFF
88 * file using LZW compression/decompression.
89 */
90 typedef struct {
91 predictorFunc hordiff; /* horizontal differencing method */
92 u_long rowsize; /* width of tile/strip/row */
93 u_short stride; /* horizontal diferencing stride */
94 u_short nbits; /* # of bits/code */
95 u_short maxcode; /* maximum code for lzw_nbits */
96 u_short free_ent; /* next free entry in hash table */
97 long nextdata; /* next bits of i/o */
98 long nextbits; /* # of valid bits in lzw_nextdata */
99 } LZWState;
100
101 #define lzw_hordiff base.hordiff
102 #define lzw_rowsize base.rowsize
103 #define lzw_stride base.stride
104 #define lzw_nbits base.nbits
105 #define lzw_maxcode base.maxcode
106 #define lzw_free_ent base.free_ent
107 #define lzw_nextdata base.nextdata
108 #define lzw_nextbits base.nextbits
109
110 /*
111 * Decoding-specific state.
112 */
113 typedef struct code_ent {
114 struct code_ent *next;
115 u_short length; /* string len, including this token */
116 u_char value; /* data value */
117 u_char firstchar; /* first token of string */
118 } code_t;
119
120 typedef int (*decodeFunc)(TIFF*, tidata_t, tsize_t, tsample_t);
121
122 typedef struct {
123 LZWState base;
124 long dec_nbitsmask; /* lzw_nbits 1 bits, right adjusted */
125 long dec_restart; /* restart count */
126 #ifdef LZW_CHECKEOS
127 long dec_bitsleft; /* available bits in raw data */
128 #endif
129 decodeFunc dec_decode; /* regular or backwards compatible */
130 code_t *dec_codep; /* current recognized code */
131 code_t *dec_oldcodep; /* previously recognized code */
132 code_t *dec_free_entp; /* next free entry */
133 code_t *dec_maxcodep; /* max available entry */
134 code_t *dec_codetab; /* kept separate for small machines */
135 } LZWDecodeState;
136
137 /*
138 * Encoding-specific state.
139 */
140 typedef uint16 hcode_t; /* codes fit in 16 bits */
141 typedef struct {
142 long hash;
143 hcode_t code;
144 } hash_t;
145
146 typedef struct {
147 LZWState base;
148 int enc_oldcode; /* last code encountered */
149 long enc_checkpoint; /* point at which to clear table */
150 #define CHECK_GAP 10000 /* enc_ratio check interval */
151 long enc_ratio; /* current compression ratio */
152 long enc_incount; /* (input) data bytes encoded */
153 long enc_outcount; /* encoded (output) bytes */
154 tidata_t enc_rawlimit; /* bound on tif_rawdata buffer */
155 hash_t *enc_hashtab; /* kept separate for small machines */
156 } LZWEncodeState;
157
158 #define DecoderState(tif) ((LZWDecodeState*)(tif)->tif_data)
159 #define EncoderState(tif) ((LZWEncodeState*)(tif)->tif_data)
160
161 static int LZWEncodePredRow(TIFF*, tidata_t, tsize_t, tsample_t);
162 static int LZWEncodePredTile(TIFF*, tidata_t, tsize_t, tsample_t);
163 static int LZWDecode(TIFF*, tidata_t, tsize_t, tsample_t);
164 #ifdef LZW_COMPAT
165 static int LZWDecodeCompat(TIFF*, tidata_t, tsize_t, tsample_t);
166 #endif
167 static int LZWDecodePredRow(TIFF*, tidata_t, tsize_t, tsample_t);
168 static int LZWDecodePredTile(TIFF*, tidata_t, tsize_t, tsample_t);
169 static void cl_hash(LZWEncodeState*);
170
171 static int
LZWCheckPredictor(TIFF * tif,LZWState * sp,predictorFunc pred8bit,predictorFunc pred16bit)172 LZWCheckPredictor(TIFF* tif,
173 LZWState* sp, predictorFunc pred8bit, predictorFunc pred16bit)
174 {
175 TIFFDirectory *td = &tif->tif_dir;
176
177 sp->hordiff = NULL;
178 switch (td->td_predictor) {
179 case 1:
180 break;
181 case 2:
182 sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ?
183 td->td_samplesperpixel : 1);
184 switch (td->td_bitspersample) {
185 case 8:
186 sp->hordiff = pred8bit;
187 break;
188 case 16:
189 sp->hordiff = pred16bit;
190 break;
191 default:
192 TIFFError(tif->tif_name,
193 "Horizontal differencing \"Predictor\" not supported with %d-bit samples",
194 td->td_bitspersample);
195 return (0);
196 }
197 break;
198 default:
199 TIFFError(tif->tif_name, "\"Predictor\" value %d not supported",
200 td->td_predictor);
201 return (0);
202 }
203 if (sp->hordiff != NULL) {
204 /*
205 * Calculate the scanline/tile-width size in bytes.
206 */
207 if (isTiled(tif))
208 sp->rowsize = TIFFTileRowSize(tif);
209 else
210 sp->rowsize = TIFFScanlineSize(tif);
211 } else
212 sp->rowsize = 0;
213 return (1);
214 }
215
216 /*
217 * LZW Decoder.
218 */
219
220 #ifdef LZW_CHECKEOS
221 /*
222 * This check shouldn't be necessary because each
223 * strip is suppose to be terminated with CODE_EOI.
224 */
225 #define NextCode(tif, sp, bp, code, get) { \
226 if ((sp)->dec_bitsleft < nbits) { \
227 TIFFWarning(tif->tif_name, \
228 "LZWDecode: Strip %d not terminated with EOI code", \
229 tif->tif_curstrip); \
230 code = CODE_EOI; \
231 } else { \
232 get(sp, bp, code); \
233 (sp)->dec_bitsleft -= nbits; \
234 } \
235 }
236 #else
237 #define NextCode(tif, sp, bp, code, get) get(sp, bp, code)
238 #endif
239
240 #define REPEAT4(n, op) \
241 switch (n) { \
242 default: { int i; for (i = n-4; i > 0; i--) { op; } } \
243 case 4: op; \
244 case 3: op; \
245 case 2: op; \
246 case 1: op; \
247 case 0: ; \
248 }
249 #define XREPEAT4(n, op) \
250 switch (n) { \
251 default: { int i; for (i = n-4; i > 0; i--) { op; } } \
252 case 2: op; \
253 case 1: op; \
254 case 0: ; \
255 }
256
257 static void
horAcc8(tidata_t cp0,tsize_t cc,u_int stride)258 horAcc8(tidata_t cp0, tsize_t cc, u_int stride)
259 {
260 char* cp = (char*) cp0;
261 if (cc > stride) {
262 cc -= stride;
263 /*
264 * Pipeline the most common cases.
265 */
266 if (stride == 3) {
267 u_int cr = cp[0];
268 u_int cg = cp[1];
269 u_int cb = cp[2];
270 do {
271 cc -= 3, cp += 3;
272 cp[0] = (cr += cp[0]);
273 cp[1] = (cg += cp[1]);
274 cp[2] = (cb += cp[2]);
275 } while ((int32) cc > 0);
276 } else if (stride == 4) {
277 u_int cr = cp[0];
278 u_int cg = cp[1];
279 u_int cb = cp[2];
280 u_int ca = cp[3];
281 do {
282 cc -= 4, cp += 4;
283 cp[0] = (cr += cp[0]);
284 cp[1] = (cg += cp[1]);
285 cp[2] = (cb += cp[2]);
286 cp[3] = (ca += cp[3]);
287 } while ((int32) cc > 0);
288 } else {
289 do {
290 XREPEAT4(stride, cp[stride] += *cp; cp++)
291 cc -= stride;
292 } while ((int32) cc > 0);
293 }
294 }
295 }
296
297 static void
swabHorAcc16(tidata_t cp0,tsize_t cc,u_int stride)298 swabHorAcc16(tidata_t cp0, tsize_t cc, u_int stride)
299 {
300 uint16* wp = (uint16*) cp0;
301 tsize_t wc = cc / 2;
302
303 if (wc > stride) {
304 TIFFSwabArrayOfShort(wp, wc);
305 wc -= stride;
306 do {
307 REPEAT4(stride, wp[stride] += wp[0]; wp++)
308 wc -= stride;
309 } while ((int32) wc > 0);
310 }
311 }
312
313 static void
horAcc16(tidata_t cp0,tsize_t cc,u_int stride)314 horAcc16(tidata_t cp0, tsize_t cc, u_int stride)
315 {
316 uint16* wp = (uint16*) cp0;
317 tsize_t wc = cc / 2;
318
319 if (wc > stride) {
320 wc -= stride;
321 do {
322 REPEAT4(stride, wp[stride] += wp[0]; wp++)
323 wc -= stride;
324 } while ((int32) wc > 0);
325 }
326 }
327
328 /*
329 * Setup state for decoding a strip.
330 */
331 static int
LZWPreDecode(TIFF * tif)332 LZWPreDecode(TIFF* tif)
333 {
334 LZWDecodeState *sp = DecoderState(tif);
335 static char module[] = " LZWPreDecode";
336
337 if (sp == NULL) {
338 tif->tif_data = (tidata_t)_TIFFmalloc(sizeof (LZWDecodeState));
339 if (tif->tif_data == NULL) {
340 TIFFError(module, "No space for LZW state block");
341 return (0);
342 }
343 sp = DecoderState(tif);
344 sp->dec_codetab = (code_t*)_TIFFmalloc(CSIZE*sizeof (code_t));
345 if (sp->dec_codetab == NULL) {
346 TIFFError(module, "No space for LZW code table");
347 return (0);
348 }
349 sp->dec_decode = NULL;
350 if (!LZWCheckPredictor(tif, &sp->base, horAcc8, horAcc16))
351 return (0);
352 if (sp->lzw_hordiff) {
353 /*
354 * Override default decoding method with
355 * one that does the predictor stuff.
356 */
357 tif->tif_decoderow = LZWDecodePredRow;
358 tif->tif_decodestrip = LZWDecodePredTile;
359 tif->tif_decodetile = LZWDecodePredTile;
360 /*
361 * If the data is horizontally differenced
362 * 16-bit data that requires byte-swapping,
363 * then it must be byte swapped before the
364 * accumulation step. We do this with a
365 * special-purpose routine and override the
366 * normal post decoding logic that the library
367 * setup when the directory was read.
368 */
369 if (tif->tif_flags&TIFF_SWAB) {
370 if (sp->lzw_hordiff == horAcc16) {
371 sp->lzw_hordiff = swabHorAcc16;
372 tif->tif_postdecode = TIFFNoPostDecode;
373 } /* else handle 32-bit case... */
374 }
375 }
376 /*
377 * Pre-load the table.
378 */
379 { int code;
380 for (code = 255; code >= 0; code--) {
381 sp->dec_codetab[code].value = code;
382 sp->dec_codetab[code].firstchar = code;
383 sp->dec_codetab[code].length = 1;
384 sp->dec_codetab[code].next = NULL;
385 }
386 }
387 }
388 /*
389 * Check for old bit-reversed codes.
390 */
391 if (tif->tif_rawdata[0] == 0 && (tif->tif_rawdata[1] & 0x1)) {
392 #ifdef LZW_COMPAT
393 if (!sp->dec_decode) {
394 if (sp->lzw_hordiff == NULL) {
395 /*
396 * Override default decoding methods with
397 * ones that deal with the old coding.
398 * Otherwise the predictor versions set
399 * above will call the compatibility routines
400 * through the dec_decode method.
401 */
402 tif->tif_decoderow = LZWDecodeCompat;
403 tif->tif_decodestrip = LZWDecodeCompat;
404 tif->tif_decodetile = LZWDecodeCompat;
405 }
406 TIFFWarning(tif->tif_name,
407 "Old-style LZW codes, convert file");
408 }
409 sp->lzw_maxcode = MAXCODE(BITS_MIN);
410 sp->dec_decode = LZWDecodeCompat;
411 #else /* !LZW_COMPAT */
412 if (!sp->dec_decode) {
413 TIFFError(tif->tif_name,
414 "Old-style LZW codes not supported");
415 sp->dec_decode = LZWDecode;
416 }
417 return (0);
418 #endif/* !LZW_COMPAT */
419 } else {
420 sp->lzw_maxcode = MAXCODE(BITS_MIN)-1;
421 sp->dec_decode = LZWDecode;
422 }
423 sp->lzw_nbits = BITS_MIN;
424 sp->lzw_nextbits = 0;
425 sp->lzw_nextdata = 0;
426
427 sp->dec_restart = 0;
428 sp->dec_nbitsmask = MAXCODE(BITS_MIN);
429 #ifdef LZW_CHECKEOS
430 sp->dec_bitsleft = tif->tif_rawdatasize << 3;
431 #endif
432 sp->dec_free_entp = sp->dec_codetab + CODE_FIRST;
433 sp->dec_oldcodep = &sp->dec_codetab[-1];
434 sp->dec_maxcodep = &sp->dec_codetab[sp->dec_nbitsmask-1];
435 return (1);
436 }
437
438 /*
439 * Decode a "hunk of data".
440 */
441 #define GetNextCode(sp, bp, code) { \
442 nextdata = (nextdata<<8) | *(bp)++; \
443 nextbits += 8; \
444 if (nextbits < nbits) { \
445 nextdata = (nextdata<<8) | *(bp)++; \
446 nextbits += 8; \
447 } \
448 code = (hcode_t)((nextdata >> (nextbits-nbits)) & nbitsmask); \
449 nextbits -= nbits; \
450 }
451
452 static void
codeLoop(TIFF * tif)453 codeLoop(TIFF* tif)
454 {
455 TIFFError(tif->tif_name,
456 "LZWDecode: Bogus encoding, loop in the code table; scanline %d",
457 tif->tif_row);
458 }
459
460 static int
LZWDecode(TIFF * tif,tidata_t op0,tsize_t occ0,tsample_t s)461 LZWDecode(TIFF* tif, tidata_t op0, tsize_t occ0, tsample_t s)
462 {
463 LZWDecodeState *sp = DecoderState(tif);
464 char *op = (char*) op0;
465 long occ = (long) occ0;
466 char *tp;
467 u_char *bp;
468 hcode_t code;
469 int len;
470 long nbits, nextbits, nextdata, nbitsmask;
471 code_t *codep, *free_entp, *maxcodep, *oldcodep;
472
473 assert(sp != NULL);
474 /*
475 * Restart interrupted output operation.
476 */
477 if (sp->dec_restart) {
478 long residue;
479
480 codep = sp->dec_codep;
481 residue = codep->length - sp->dec_restart;
482 if (residue > occ) {
483 /*
484 * Residue from previous decode is sufficient
485 * to satisfy decode request. Skip to the
486 * start of the decoded string, place decoded
487 * values in the output buffer, and return.
488 */
489 sp->dec_restart += occ;
490 do {
491 codep = codep->next;
492 } while (--residue > occ && codep);
493 if (codep) {
494 tp = op + occ;
495 do {
496 *--tp = codep->value;
497 codep = codep->next;
498 } while (--occ && codep);
499 }
500 return (1);
501 }
502 /*
503 * Residue satisfies only part of the decode request.
504 */
505 op += residue, occ -= residue;
506 tp = op;
507 do {
508 int t;
509 --tp;
510 t = codep->value;
511 codep = codep->next;
512 *tp = t;
513 } while (--residue && codep);
514 sp->dec_restart = 0;
515 }
516
517 bp = (u_char *)tif->tif_rawcp;
518 nbits = sp->lzw_nbits;
519 nextdata = sp->lzw_nextdata;
520 nextbits = sp->lzw_nextbits;
521 nbitsmask = sp->dec_nbitsmask;
522 oldcodep = sp->dec_oldcodep;
523 free_entp = sp->dec_free_entp;
524 maxcodep = sp->dec_maxcodep;
525
526 while (occ > 0) {
527 NextCode(tif, sp, bp, code, GetNextCode);
528 if (code == CODE_EOI)
529 break;
530 if (code == CODE_CLEAR) {
531 free_entp = sp->dec_codetab + CODE_FIRST;
532 nbits = BITS_MIN;
533 nbitsmask = MAXCODE(BITS_MIN);
534 maxcodep = sp->dec_codetab + nbitsmask-1;
535 NextCode(tif, sp, bp, code, GetNextCode);
536 if (code == CODE_EOI)
537 break;
538 *op++ = code, occ--;
539 oldcodep = sp->dec_codetab + code;
540 continue;
541 }
542 codep = sp->dec_codetab + code;
543
544 /*
545 * Add the new entry to the code table.
546 */
547 assert(&sp->dec_codetab[0] <= free_entp && free_entp < &sp->dec_codetab[CSIZE]);
548 free_entp->next = oldcodep;
549 free_entp->firstchar = free_entp->next->firstchar;
550 free_entp->length = free_entp->next->length+1;
551 free_entp->value = (codep < free_entp) ?
552 codep->firstchar : free_entp->firstchar;
553 if (++free_entp > maxcodep) {
554 if (++nbits > BITS_MAX) /* should not happen */
555 nbits = BITS_MAX;
556 nbitsmask = MAXCODE(nbits);
557 maxcodep = sp->dec_codetab + nbitsmask-1;
558 }
559 oldcodep = codep;
560 if (code >= 256) {
561 /*
562 * Code maps to a string, copy string
563 * value to output (written in reverse).
564 */
565 if (codep->length > occ) {
566 /*
567 * String is too long for decode buffer,
568 * locate portion that will fit, copy to
569 * the decode buffer, and setup restart
570 * logic for the next decoding call.
571 */
572 sp->dec_codep = codep;
573 do {
574 codep = codep->next;
575 } while (codep && codep->length > occ);
576 if (codep) {
577 sp->dec_restart = occ;
578 tp = op + occ;
579 do {
580 *--tp = codep->value;
581 codep = codep->next;
582 } while (--occ && codep);
583 if (codep)
584 codeLoop(tif);
585 }
586 break;
587 }
588 len = codep->length;
589 tp = op + len;
590 do {
591 int t;
592 --tp;
593 t = codep->value;
594 codep = codep->next;
595 *tp = t;
596 } while (codep && tp > op);
597 if (codep) {
598 codeLoop(tif);
599 break;
600 }
601 op += len, occ -= len;
602 } else
603 *op++ = code, occ--;
604 }
605
606 tif->tif_rawcp = (tidata_t) bp;
607 sp->lzw_nbits = (u_short) nbits;
608 sp->lzw_nextdata = nextdata;
609 sp->lzw_nextbits = nextbits;
610 sp->dec_nbitsmask = nbitsmask;
611 sp->dec_oldcodep = oldcodep;
612 sp->dec_free_entp = free_entp;
613 sp->dec_maxcodep = maxcodep;
614
615 if (occ > 0) {
616 TIFFError(tif->tif_name,
617 "LZWDecode: Not enough data at scanline %d (short %d bytes)",
618 tif->tif_row, occ);
619 return (0);
620 }
621 return (1);
622 }
623
624 #ifdef LZW_COMPAT
625 /*
626 * Decode a "hunk of data" for old images.
627 */
628 #define GetNextCodeCompat(sp, bp, code) { \
629 nextdata |= *(bp)++ << nextbits; \
630 nextbits += 8; \
631 if (nextbits < nbits) { \
632 nextdata |= *(bp)++ << nextbits; \
633 nextbits += 8; \
634 } \
635 code = (hcode_t)(nextdata & nbitsmask); \
636 nextdata >>= nbits; \
637 nextbits -= nbits; \
638 }
639
640 static int
LZWDecodeCompat(TIFF * tif,tidata_t op0,tsize_t occ0,tsample_t s)641 LZWDecodeCompat(TIFF* tif, tidata_t op0, tsize_t occ0, tsample_t s)
642 {
643 LZWDecodeState *sp = DecoderState(tif);
644 char *op = (char*) op0;
645 long occ = (long) occ0;
646 char *tp;
647 u_char *bp;
648 int code, nbits;
649 long nextbits, nextdata, nbitsmask;
650 code_t *codep, *free_entp, *maxcodep, *oldcodep;
651
652 assert(sp != NULL);
653 /*
654 * Restart interrupted output operation.
655 */
656 if (sp->dec_restart) {
657 long residue;
658
659 codep = sp->dec_codep;
660 residue = codep->length - sp->dec_restart;
661 if (residue > occ) {
662 /*
663 * Residue from previous decode is sufficient
664 * to satisfy decode request. Skip to the
665 * start of the decoded string, place decoded
666 * values in the output buffer, and return.
667 */
668 sp->dec_restart += occ;
669 do {
670 codep = codep->next;
671 } while (--residue > occ);
672 tp = op + occ;
673 do {
674 *--tp = codep->value;
675 codep = codep->next;
676 } while (--occ);
677 return (1);
678 }
679 /*
680 * Residue satisfies only part of the decode request.
681 */
682 op += residue, occ -= residue;
683 tp = op;
684 do {
685 *--tp = codep->value;
686 codep = codep->next;
687 } while (--residue);
688 sp->dec_restart = 0;
689 }
690
691 bp = (u_char *)tif->tif_rawcp;
692 nbits = sp->lzw_nbits;
693 nextdata = sp->lzw_nextdata;
694 nextbits = sp->lzw_nextbits;
695 nbitsmask = sp->dec_nbitsmask;
696 oldcodep = sp->dec_oldcodep;
697 free_entp = sp->dec_free_entp;
698 maxcodep = sp->dec_maxcodep;
699
700 while (occ > 0) {
701 NextCode(tif, sp, bp, code, GetNextCodeCompat);
702 if (code == CODE_EOI)
703 break;
704 if (code == CODE_CLEAR) {
705 free_entp = sp->dec_codetab + CODE_FIRST;
706 nbits = BITS_MIN;
707 nbitsmask = MAXCODE(BITS_MIN);
708 maxcodep = sp->dec_codetab + nbitsmask;
709 NextCode(tif, sp, bp, code, GetNextCodeCompat);
710 if (code == CODE_EOI)
711 break;
712 *op++ = code, occ--;
713 oldcodep = sp->dec_codetab + code;
714 continue;
715 }
716 codep = sp->dec_codetab + code;
717
718 /*
719 * Add the new entry to the code table.
720 */
721 assert(&sp->dec_codetab[0] <= free_entp && free_entp < &sp->dec_codetab[CSIZE]);
722 free_entp->next = oldcodep;
723 free_entp->firstchar = free_entp->next->firstchar;
724 free_entp->length = free_entp->next->length+1;
725 free_entp->value = (codep < free_entp) ?
726 codep->firstchar : free_entp->firstchar;
727 if (++free_entp > maxcodep) {
728 if (++nbits > BITS_MAX) /* should not happen */
729 nbits = BITS_MAX;
730 nbitsmask = MAXCODE(nbits);
731 maxcodep = sp->dec_codetab + nbitsmask;
732 }
733 oldcodep = codep;
734 if (code >= 256) {
735 /*
736 * Code maps to a string, copy string
737 * value to output (written in reverse).
738 */
739 if (codep->length > occ) {
740 /*
741 * String is too long for decode buffer,
742 * locate portion that will fit, copy to
743 * the decode buffer, and setup restart
744 * logic for the next decoding call.
745 */
746 sp->dec_codep = codep;
747 do {
748 codep = codep->next;
749 } while (codep->length > occ);
750 sp->dec_restart = occ;
751 tp = op + occ;
752 do {
753 *--tp = codep->value;
754 codep = codep->next;
755 } while (--occ);
756 break;
757 }
758 op += codep->length, occ -= codep->length;
759 tp = op;
760 do {
761 *--tp = codep->value;
762 } while (codep = codep->next);
763 } else
764 *op++ = code, occ--;
765 }
766
767 tif->tif_rawcp = (tidata_t) bp;
768 sp->lzw_nbits = nbits;
769 sp->lzw_nextdata = nextdata;
770 sp->lzw_nextbits = nextbits;
771 sp->dec_nbitsmask = nbitsmask;
772 sp->dec_oldcodep = oldcodep;
773 sp->dec_free_entp = free_entp;
774 sp->dec_maxcodep = maxcodep;
775
776 if (occ > 0) {
777 TIFFError(tif->tif_name,
778 "LZWDecodeCompat: Not enough data at scanline %d (short %d bytes)",
779 tif->tif_row, occ);
780 return (0);
781 }
782 return (1);
783 }
784 #endif /* LZW_COMPAT */
785
786 /*
787 * Decode a scanline and apply the predictor routine.
788 */
789 static int
LZWDecodePredRow(TIFF * tif,tidata_t op0,tsize_t occ0,tsample_t s)790 LZWDecodePredRow(TIFF* tif, tidata_t op0, tsize_t occ0, tsample_t s)
791 {
792 LZWDecodeState *sp = DecoderState(tif);
793
794 assert(sp != NULL);
795 assert(sp->dec_decode != NULL);
796 if ((*sp->dec_decode)(tif, op0, occ0, s)) {
797 (*sp->lzw_hordiff)(op0, occ0, sp->lzw_stride);
798 return (1);
799 } else
800 return (0);
801 }
802
803 /*
804 * Decode a tile/strip and apply the predictor routine.
805 * Note that horizontal differencing must be done on a
806 * row-by-row basis. The width of a "row" has already
807 * been calculated at pre-decode time according to the
808 * strip/tile dimensions.
809 */
810 static int
LZWDecodePredTile(TIFF * tif,tidata_t op0,tsize_t occ0,tsample_t s)811 LZWDecodePredTile(TIFF* tif, tidata_t op0, tsize_t occ0, tsample_t s)
812 {
813 LZWDecodeState *sp = DecoderState(tif);
814 u_long rowsize;
815
816 assert(sp != NULL);
817 assert(sp->dec_decode != NULL);
818 if (!(*sp->dec_decode)(tif, op0, occ0, s))
819 return (0);
820 rowsize = sp->lzw_rowsize;
821 assert(rowsize > 0);
822 while ((long)occ0 > 0) {
823 (*sp->lzw_hordiff)(op0, (tsize_t) rowsize, sp->lzw_stride);
824 occ0 -= rowsize;
825 op0 += rowsize;
826 }
827 return (1);
828 }
829
830 /*
831 * LZW Encoding.
832 */
833
834 static void
horDiff8(tidata_t cp0,tsize_t cc,u_int stride)835 horDiff8(tidata_t cp0, tsize_t cc, u_int stride)
836 {
837 char* cp = (char*) cp0;
838 if (cc > stride) {
839 cc -= stride;
840 /*
841 * Pipeline the most common cases.
842 */
843 if (stride == 3) {
844 int r1, g1, b1;
845 int r2 = cp[0];
846 int g2 = cp[1];
847 int b2 = cp[2];
848 do {
849 r1 = cp[3]; cp[3] = r1-r2; r2 = r1;
850 g1 = cp[4]; cp[4] = g1-g2; g2 = g1;
851 b1 = cp[5]; cp[5] = b1-b2; b2 = b1;
852 cp += 3;
853 } while ((int32)(cc -= 3) > 0);
854 } else if (stride == 4) {
855 int r1, g1, b1, a1;
856 int r2 = cp[0];
857 int g2 = cp[1];
858 int b2 = cp[2];
859 int a2 = cp[3];
860 do {
861 r1 = cp[4]; cp[4] = r1-r2; r2 = r1;
862 g1 = cp[5]; cp[5] = g1-g2; g2 = g1;
863 b1 = cp[6]; cp[6] = b1-b2; b2 = b1;
864 a1 = cp[7]; cp[7] = a1-a2; a2 = a1;
865 cp += 4;
866 } while ((int32)(cc -= 4) > 0);
867 } else {
868 cp += cc - 1;
869 do {
870 REPEAT4(stride, cp[stride] -= cp[0]; cp--)
871 } while ((int32)(cc -= stride) > 0);
872 }
873 }
874 }
875
876 static void
horDiff16(tidata_t cp0,tsize_t cc,u_int stride)877 horDiff16(tidata_t cp0, tsize_t cc, u_int stride)
878 {
879 int16 *wp = (int16*) cp0;
880 tsize_t wc = cc/2;
881
882 if (wc > stride) {
883 wc -= stride;
884 wp += wc - 1;
885 do {
886 REPEAT4(stride, wp[stride] -= wp[0]; wp--)
887 wc -= stride;
888 } while ((int32) wc > 0);
889 }
890 }
891
892 /*
893 * Reset encoding state at the start of a strip.
894 */
895 static int
LZWPreEncode(TIFF * tif)896 LZWPreEncode(TIFF* tif)
897 {
898 LZWEncodeState *sp = EncoderState(tif);
899 static char module[] = "LZWPreEncode";
900
901 if (sp == NULL) {
902 tif->tif_data = (tidata_t)_TIFFmalloc(sizeof (LZWEncodeState));
903 if (tif->tif_data == NULL) {
904 TIFFError(module, "No space for LZW state block");
905 return (0);
906 }
907 sp = EncoderState(tif);
908 sp->enc_hashtab = (hash_t*)_TIFFmalloc(HSIZE*sizeof (hash_t));
909 if (sp->enc_hashtab == NULL) {
910 TIFFError(module, "No space for LZW hash table");
911 return (0);
912 }
913 if (!LZWCheckPredictor(tif, &sp->base, horDiff8, horDiff16))
914 return (0);
915 if (sp->lzw_hordiff != NULL) {
916 tif->tif_encoderow = LZWEncodePredRow;
917 tif->tif_encodestrip = LZWEncodePredTile;
918 tif->tif_encodetile = LZWEncodePredTile;
919 }
920 }
921 sp->lzw_nbits = BITS_MIN;
922 sp->lzw_maxcode = MAXCODE(BITS_MIN);
923 sp->lzw_free_ent = CODE_FIRST;
924 sp->lzw_nextbits = 0;
925 sp->lzw_nextdata = 0;
926 sp->enc_checkpoint = CHECK_GAP;
927 sp->enc_ratio = 0;
928 sp->enc_incount = 0;
929 sp->enc_outcount = 0;
930 /*
931 * The 4 here insures there is space for 2 max-sized
932 * codes in LZWEncode and LZWPostDecode.
933 */
934 sp->enc_rawlimit = tif->tif_rawdata + tif->tif_rawdatasize-1 - 4;
935 cl_hash(sp); /* clear hash table */
936 sp->enc_oldcode = (hcode_t) -1; /* generates CODE_CLEAR in LZWEncode */
937 return (1);
938 }
939
940 #define CALCRATIO(sp, rat) { \
941 if (incount > 0x007fffff) { /* NB: shift will overflow */\
942 rat = outcount >> 8; \
943 rat = (rat == 0 ? 0x7fffffff : incount/rat); \
944 } else \
945 rat = (incount<<8) / outcount; \
946 }
947 #define PutNextCode(op, c) { \
948 nextdata = (nextdata << nbits) | c; \
949 nextbits += nbits; \
950 *op++ = (u_char)(nextdata >> (nextbits-8)); \
951 nextbits -= 8; \
952 if (nextbits >= 8) { \
953 *op++ = (u_char)(nextdata >> (nextbits-8)); \
954 nextbits -= 8; \
955 } \
956 outcount += nbits; \
957 }
958
959 /*
960 * Encode a chunk of pixels.
961 *
962 * Uses an open addressing double hashing (no chaining) on the
963 * prefix code/next character combination. We do a variant of
964 * Knuth's algorithm D (vol. 3, sec. 6.4) along with G. Knott's
965 * relatively-prime secondary probe. Here, the modular division
966 * first probe is gives way to a faster exclusive-or manipulation.
967 * Also do block compression with an adaptive reset, whereby the
968 * code table is cleared when the compression ratio decreases,
969 * but after the table fills. The variable-length output codes
970 * are re-sized at this point, and a CODE_CLEAR is generated
971 * for the decoder.
972 */
973 static int
LZWEncode(TIFF * tif,tidata_t bp,tsize_t cc,tsample_t s)974 LZWEncode(TIFF* tif, tidata_t bp, tsize_t cc, tsample_t s)
975 {
976 register LZWEncodeState *sp = EncoderState(tif);
977 register long fcode;
978 register hash_t *hp;
979 register int h, c;
980 hcode_t ent;
981 long disp;
982 long incount, outcount, checkpoint;
983 long nextdata, nextbits;
984 int free_ent, maxcode, nbits;
985 tidata_t op, limit;
986
987 if (sp == NULL)
988 return (0);
989 /*
990 * Load local state.
991 */
992 incount = sp->enc_incount;
993 outcount = sp->enc_outcount;
994 checkpoint = sp->enc_checkpoint;
995 nextdata = sp->lzw_nextdata;
996 nextbits = sp->lzw_nextbits;
997 free_ent = sp->lzw_free_ent;
998 maxcode = sp->lzw_maxcode;
999 nbits = sp->lzw_nbits;
1000 op = tif->tif_rawcp;
1001 limit = sp->enc_rawlimit;
1002 ent = sp->enc_oldcode;
1003
1004 if (ent == (hcode_t) -1 && cc > 0) {
1005 /*
1006 * NB: This is safe because it can only happen
1007 * at the start of a strip where we know there
1008 * is space in the data buffer.
1009 */
1010 PutNextCode(op, CODE_CLEAR);
1011 ent = *bp++; cc--; incount++;
1012 }
1013 while (cc > 0) {
1014 c = *bp++; cc--; incount++;
1015 fcode = ((long)c << BITS_MAX) + ent;
1016 h = (c << HSHIFT) ^ ent; /* xor hashing */
1017 #ifdef _WINDOWS
1018 /*
1019 * Check hash index for an overflow.
1020 */
1021 if (h >= HSIZE)
1022 h -= HSIZE;
1023 #endif
1024 hp = &sp->enc_hashtab[h];
1025 if (hp->hash == fcode) {
1026 ent = hp->code;
1027 continue;
1028 }
1029 if (hp->hash >= 0) {
1030 /*
1031 * Primary hash failed, check secondary hash.
1032 */
1033 disp = HSIZE - h;
1034 if (h == 0)
1035 disp = 1;
1036 do {
1037 #ifndef _WINDOWS
1038 if ((hp -= disp) < sp->enc_hashtab)
1039 hp += HSIZE;
1040 #else
1041 /*
1042 * Avoid pointer arithmetic 'cuz of
1043 * wraparound problems with segments.
1044 */
1045 if ((h -= disp) < 0)
1046 h += HSIZE;
1047 hp = &sp->enc_hashtab[h];
1048 #endif
1049 if (hp->hash == fcode) {
1050 ent = hp->code;
1051 goto hit;
1052 }
1053 } while (hp->hash >= 0);
1054 }
1055 /*
1056 * New entry, emit code and add to table.
1057 */
1058 /*
1059 * Verify there is space in the buffer for the code
1060 * and any potential Clear code that might be emitted
1061 * below. The value of limit is setup so that there
1062 * are at least 4 bytes free--room for 2 codes.
1063 */
1064 if (op > limit) {
1065 tif->tif_rawcc = (tsize_t)(op - tif->tif_rawdata);
1066 TIFFFlushData1(tif);
1067 op = tif->tif_rawdata;
1068 }
1069 PutNextCode(op, ent);
1070 ent = c;
1071 hp->code = free_ent++;
1072 hp->hash = fcode;
1073 if (free_ent == CODE_MAX-1) {
1074 /* table is full, emit clear code and reset */
1075 cl_hash(sp);
1076 sp->enc_ratio = 0;
1077 incount = 0;
1078 outcount = 0;
1079 free_ent = CODE_FIRST;
1080 PutNextCode(op, CODE_CLEAR);
1081 nbits = BITS_MIN;
1082 maxcode = MAXCODE(BITS_MIN);
1083 } else {
1084 /*
1085 * If the next entry is going to be too big for
1086 * the code size, then increase it, if possible.
1087 */
1088 if (free_ent > maxcode) {
1089 nbits++;
1090 assert(nbits <= BITS_MAX);
1091 maxcode = (int) MAXCODE(nbits);
1092 } else if (incount >= checkpoint) {
1093 long rat;
1094 /*
1095 * Check compression ratio and, if things seem
1096 * to be slipping, clear the hash table and
1097 * reset state. The compression ratio is a
1098 * 24+8-bit fractional number.
1099 */
1100 checkpoint = incount+CHECK_GAP;
1101 CALCRATIO(sp, rat);
1102 if (rat <= sp->enc_ratio) {
1103 cl_hash(sp);
1104 sp->enc_ratio = 0;
1105 incount = 0;
1106 outcount = 0;
1107 free_ent = CODE_FIRST;
1108 PutNextCode(op, CODE_CLEAR);
1109 nbits = BITS_MIN;
1110 maxcode = MAXCODE(BITS_MIN);
1111 } else
1112 sp->enc_ratio = rat;
1113 }
1114 }
1115 hit:
1116 ;
1117 }
1118
1119 /*
1120 * Restore global state.
1121 */
1122 sp->enc_incount = incount;
1123 sp->enc_outcount = outcount;
1124 sp->enc_checkpoint = checkpoint;
1125 sp->enc_oldcode = ent;
1126 sp->lzw_nextdata = nextdata;
1127 sp->lzw_nextbits = nextbits;
1128 sp->lzw_free_ent = free_ent;
1129 sp->lzw_maxcode = maxcode;
1130 sp->lzw_nbits = nbits;
1131 tif->tif_rawcp = op;
1132 return (1);
1133 }
1134
1135 static int
LZWEncodePredRow(TIFF * tif,tidata_t bp,tsize_t cc,tsample_t s)1136 LZWEncodePredRow(TIFF* tif, tidata_t bp, tsize_t cc, tsample_t s)
1137 {
1138 LZWEncodeState *sp = EncoderState(tif);
1139
1140 assert(sp != NULL);
1141 assert(sp->lzw_hordiff != NULL);
1142 /* XXX horizontal differencing alters user's data XXX */
1143 (*sp->lzw_hordiff)(bp, cc, sp->lzw_stride);
1144 return (LZWEncode(tif, bp, cc, s));
1145 }
1146
1147 static int
LZWEncodePredTile(TIFF * tif,tidata_t bp0,tsize_t cc0,tsample_t s)1148 LZWEncodePredTile(TIFF* tif, tidata_t bp0, tsize_t cc0, tsample_t s)
1149 {
1150 LZWEncodeState *sp = EncoderState(tif);
1151 u_long cc = cc0, rowsize;
1152 u_char *bp = bp0;
1153
1154 assert(sp != NULL);
1155 assert(sp->lzw_hordiff != NULL);
1156 rowsize = sp->lzw_rowsize;
1157 assert(rowsize > 0);
1158 while ((long)cc > 0) {
1159 (*sp->lzw_hordiff)(bp, (tsize_t) rowsize, sp->lzw_stride);
1160 cc -= rowsize;
1161 bp += rowsize;
1162 }
1163 return (LZWEncode(tif, bp0, cc0, s));
1164 }
1165
1166 /*
1167 * Finish off an encoded strip by flushing the last
1168 * string and tacking on an End Of Information code.
1169 */
1170 static int
LZWPostEncode(TIFF * tif)1171 LZWPostEncode(TIFF* tif)
1172 {
1173 register LZWEncodeState *sp = EncoderState(tif);
1174 tidata_t op = tif->tif_rawcp;
1175 long nextbits = sp->lzw_nextbits;
1176 long nextdata = sp->lzw_nextdata;
1177 long outcount = sp->enc_outcount;
1178 int nbits = sp->lzw_nbits;
1179
1180 if (op > sp->enc_rawlimit) {
1181 tif->tif_rawcc = (tsize_t)(op - tif->tif_rawdata);
1182 TIFFFlushData1(tif);
1183 op = tif->tif_rawdata;
1184 }
1185 if (sp->enc_oldcode != (hcode_t) -1) {
1186 PutNextCode(op, sp->enc_oldcode);
1187 sp->enc_oldcode = (hcode_t) -1;
1188 }
1189 PutNextCode(op, CODE_EOI);
1190 if (nextbits > 0)
1191 *op++ = (u_char)(nextdata << (8-nextbits));
1192 tif->tif_rawcc = (tsize_t)(op - tif->tif_rawdata);
1193 return (1);
1194 }
1195
1196 /*
1197 * Reset encoding hash table.
1198 */
1199 static void
cl_hash(LZWEncodeState * sp)1200 cl_hash(LZWEncodeState* sp)
1201 {
1202 register hash_t *hp = &sp->enc_hashtab[HSIZE-1];
1203 register long i = HSIZE-8;
1204
1205 do {
1206 i -= 8;
1207 hp[-7].hash = -1;
1208 hp[-6].hash = -1;
1209 hp[-5].hash = -1;
1210 hp[-4].hash = -1;
1211 hp[-3].hash = -1;
1212 hp[-2].hash = -1;
1213 hp[-1].hash = -1;
1214 hp[ 0].hash = -1;
1215 hp -= 8;
1216 } while (i >= 0);
1217 for (i += 8; i > 0; i--, hp--)
1218 hp->hash = -1;
1219 }
1220
1221 static void
LZWCleanup(TIFF * tif)1222 LZWCleanup(TIFF* tif)
1223 {
1224 if (tif->tif_data) {
1225 if (tif->tif_mode == O_RDONLY)
1226 _TIFFfree(DecoderState(tif)->dec_codetab);
1227 else
1228 _TIFFfree(EncoderState(tif)->enc_hashtab);
1229 _TIFFfree(tif->tif_data);
1230 tif->tif_data = NULL;
1231 }
1232 }
1233
1234 int
TIFFInitLZW(TIFF * tif)1235 TIFFInitLZW(TIFF* tif)
1236 {
1237 tif->tif_predecode = LZWPreDecode;
1238 tif->tif_decoderow = LZWDecode;
1239 tif->tif_decodestrip = LZWDecode;
1240 tif->tif_decodetile = LZWDecode;
1241 tif->tif_preencode = LZWPreEncode;
1242 tif->tif_postencode = LZWPostEncode;
1243 tif->tif_encoderow = LZWEncode;
1244 tif->tif_encodestrip = LZWEncode;
1245 tif->tif_encodetile = LZWEncode;
1246 tif->tif_cleanup = LZWCleanup;
1247 return (1);
1248 }
1249
1250 /*
1251 * Copyright (c) 1985, 1986 The Regents of the University of California.
1252 * All rights reserved.
1253 *
1254 * This code is derived from software contributed to Berkeley by
1255 * James A. Woods, derived from original work by Spencer Thomas
1256 * and Joseph Orost.
1257 *
1258 * Redistribution and use in source and binary forms are permitted
1259 * provided that the above copyright notice and this paragraph are
1260 * duplicated in all such forms and that any documentation,
1261 * advertising materials, and other materials related to such
1262 * distribution and use acknowledge that the software was developed
1263 * by the University of California, Berkeley. The name of the
1264 * University may not be used to endorse or promote products derived
1265 * from this software without specific prior written permission.
1266 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
1267 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
1268 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
1269 */
1270