LibTIFF 4.7.2
TIFF library public API and implementation reference
Loading...
Searching...
No Matches
tif_lzw.c
Go to the documentation of this file.
1/*
2 * Copyright (c) 1988-1997 Sam Leffler
3 * Copyright (c) 1991-1997 Silicon Graphics, Inc.
4 * Copyright (c) 2022 Even Rouault
5 *
6 * Permission to use, copy, modify, distribute, and sell this software and
7 * its documentation for any purpose is hereby granted without fee, provided
8 * that (i) the above copyright notices and this permission notice appear in
9 * all copies of the software and related documentation, and (ii) the names of
10 * Sam Leffler and Silicon Graphics may not be used in any advertising or
11 * publicity relating to the software without the specific, prior written
12 * permission of Sam Leffler and Silicon Graphics.
13 *
14 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
15 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
16 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
17 *
18 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
19 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
20 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
21 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
22 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
23 * OF THIS SOFTWARE.
24 */
25
31#include "tiffiop.h"
32#ifdef LZW_SUPPORT
33/*
34 * TIFF Library.
35 * Rev 5.0 Lempel-Ziv & Welch Compression Support
36 *
37 * This code is derived from the compress program whose code is
38 * derived from software contributed to Berkeley by James A. Woods,
39 * derived from original work by Spencer Thomas and Joseph Orost.
40 *
41 * The original Berkeley copyright notice appears below in its entirety.
42 */
43#include "tif_predict.h"
44
45#include <stdbool.h>
46#include <stdio.h>
47#include <stdlib.h>
48
49/* Select the plausible largest natural integer type for the architecture */
50#define SIZEOF_WORDTYPE SIZEOF_SIZE_T
55typedef size_t WordType;
56
57/*
58 * NB: The 5.0 spec describes a different algorithm than Aldus
59 * implements. Specifically, Aldus does code length transitions
60 * one code earlier than should be done (for real LZW).
61 * Earlier versions of this library implemented the correct
62 * LZW algorithm, but emitted codes in a bit order opposite
63 * to the TIFF spec. Thus, to maintain compatibility w/ Aldus
64 * we interpret MSB-LSB ordered codes to be images written w/
65 * old versions of this library, but otherwise adhere to the
66 * Aldus "off by one" algorithm.
67 *
68 * Future revisions to the TIFF spec are expected to "clarify this issue".
69 */
70#define LZW_COMPAT /* include backwards compatibility code */
71
72#define MAXCODE(n) ((1 << (n)) - 1)
73/*
74 * The TIFF spec specifies that encoded bit
75 * strings range from 9 to 12 bits.
76 */
77#define BITS_MIN 9 /* start with 9 bits */
78#define BITS_MAX 12 /* max of 12 bit strings */
79/* predefined codes */
80#define CODE_CLEAR 256 /* code to clear string table */
81#define CODE_EOI 257 /* end-of-information code */
82#define CODE_FIRST 258 /* first free code entry */
83#define CODE_MAX MAXCODE(BITS_MAX)
84#define HSIZE 9001 /* 91% occupancy */
85#define HSHIFT (13 - 8)
86#ifdef LZW_COMPAT
87/* NB: +1024 is for compatibility with old files */
88#define CSIZE (MAXCODE(BITS_MAX) + 1024L)
89#else
90#define CSIZE (MAXCODE(BITS_MAX) + 1L)
91#endif
92
93/*
94 * State block for each open TIFF file using LZW
95 * compression/decompression. Note that the predictor
96 * state block must be first in this data structure.
97 */
105typedef struct
106{
109
111 unsigned short nbits;
113 unsigned short maxcode;
115 unsigned short free_ent;
120
124
125#define lzw_nbits base.nbits
126#define lzw_maxcode base.maxcode
127#define lzw_free_ent base.free_ent
128#define lzw_nextdata base.nextdata
129#define lzw_nextbits base.nextbits
130
131/*
132 * Encoding-specific state.
133 */
138typedef uint16_t hcode_t; /* codes fit in 16 bits */
146typedef struct
147{
149 long hash;
152} hash_t;
153
154/*
155 * Decoding-specific state.
156 */
164typedef struct code_ent
165{
170 struct code_ent *next;
172 unsigned short length;
173
178 unsigned char firstchar;
180 unsigned char value;
184
200typedef int (*decodeFunc)(TIFF *tif, uint8_t *buf, tmsize_t size,
201 uint16_t sample);
202
259
260#define LZWState(tif) ((LZWBaseState *)(tif)->tif_data)
261#define LZWDecoderState(tif) ((LZWCodecState *)LZWState(tif))
262#define LZWEncoderState(tif) ((LZWCodecState *)LZWState(tif))
263
264static int LZWDecode(TIFF *tif, uint8_t *op0, tmsize_t occ0, uint16_t s);
265#ifdef LZW_COMPAT
266static int LZWDecodeCompat(TIFF *tif, uint8_t *op0, tmsize_t occ0, uint16_t s);
267#endif
268
269/*
270 * LZW Decoder.
271 */
272
282static int LZWFixupTags(TIFF *tif)
283{
284 (void)tif;
285 return (1);
286}
287
302static int LZWSetupDecode(TIFF *tif)
303{
304 static const char module[] = "LZWSetupDecode";
306 int code;
307
308 if (sp == NULL)
309 {
310 /*
311 * Allocate state block so tag methods have storage to record
312 * values.
313 */
314 tif->tif_data = (uint8_t *)_TIFFmallocExt(tif, sizeof(LZWCodecState));
315 if (tif->tif_data == NULL)
316 {
317 TIFFErrorExtR(tif, module, "No space for LZW state block");
318 return (0);
319 }
320
321 sp = LZWDecoderState(tif);
322 sp->dec_codetab = NULL;
323 sp->dec_decode = NULL;
324
325 /*
326 * Setup predictor setup.
327 */
328 (void)TIFFPredictorInit(tif);
329 }
330
331 if (sp->dec_codetab == NULL)
332 {
333 sp->dec_codetab = (code_t *)_TIFFmallocExt(tif, CSIZE * sizeof(code_t));
334 if (sp->dec_codetab == NULL)
335 {
336 TIFFErrorExtR(tif, module, "No space for LZW code table");
337 return (0);
338 }
339 /*
340 * Pre-load the table.
341 */
342 code = 255;
343 do
344 {
345 sp->dec_codetab[code].firstchar = (unsigned char)code;
346 sp->dec_codetab[code].value = (unsigned char)code;
347 sp->dec_codetab[code].repeated = true;
348 sp->dec_codetab[code].length = 1;
349 sp->dec_codetab[code].next = NULL;
350 } while (code--);
351 /*
352 * Zero-out the unused entries */
353 /* Silence false positive */
354 /* coverity[overrun-buffer-arg] */
355 memset(&sp->dec_codetab[CODE_CLEAR], 0,
356 (CODE_FIRST - CODE_CLEAR) * sizeof(code_t));
357 }
358 return (1);
359}
360
361/*
362 * Setup state for decoding a strip.
363 */
389static int LZWPreDecode(TIFF *tif, uint16_t s)
390{
391 static const char module[] = "LZWPreDecode";
393
394 (void)s;
395 assert(sp != NULL);
396 if (sp->dec_codetab == NULL)
397 {
398 tif->tif_setupdecode(tif);
399 if (sp->dec_codetab == NULL)
400 return (0);
401 }
402
403 /*
404 * Check for old bit-reversed codes.
405 */
406 if (tif->tif_rawcc >= 2 && tif->tif_rawdata[0] == 0 &&
407 (tif->tif_rawdata[1] & 0x1))
408 {
409#ifdef LZW_COMPAT
410 if (!sp->dec_decode)
411 {
412 TIFFWarningExtR(tif, module, "Old-style LZW codes, convert file");
413 /*
414 * Override default decoding methods with
415 * ones that deal with the old coding.
416 * Otherwise the predictor versions set
417 * above will call the compatibility routines
418 * through the dec_decode method.
419 */
423 /*
424 * If doing horizontal differencing, must
425 * re-setup the predictor logic since we
426 * switched the basic decoder methods...
427 */
428 (*tif->tif_setupdecode)(tif);
429 sp->dec_decode = LZWDecodeCompat;
430 }
431 sp->lzw_maxcode = MAXCODE(BITS_MIN);
432#else /* !LZW_COMPAT */
433 if (!sp->dec_decode)
434 {
435 TIFFErrorExtR(tif, module, "Old-style LZW codes not supported");
436 sp->dec_decode = LZWDecode;
437 }
438 return (0);
439#endif /* !LZW_COMPAT */
440 }
441 else
442 {
443 sp->lzw_maxcode = MAXCODE(BITS_MIN) - 1;
444 sp->dec_decode = LZWDecode;
445 }
446 sp->lzw_nbits = BITS_MIN;
447 sp->lzw_nextbits = 0;
448 sp->lzw_nextdata = 0;
449
450 sp->dec_restart = 0;
451 sp->dec_nbitsmask = MAXCODE(BITS_MIN);
452 sp->dec_bitsleft = 0;
453 sp->old_tif_rawcc = 0;
454 sp->dec_free_entp = sp->dec_codetab - 1; // + CODE_FIRST;
455 /*
456 * Zero entries that are not yet filled in. We do
457 * this to guard against bogus input data that causes
458 * us to index into undefined entries. If you can
459 * come up with a way to safely bounds-check input codes
460 * while decoding then you can remove this operation.
461 */
462 sp->dec_oldcodep = &sp->dec_codetab[0];
463 sp->dec_maxcodep = &sp->dec_codetab[sp->dec_nbitsmask - 1];
464 sp->read_error = 0;
465 return (1);
466}
467
468/*
469 * Decode a "hunk of data".
470 */
471
472/* Get the next 32 or 64-bit from the input data */
473#if WORDS_BIGENDIAN
474#define GetNextData(nextdata, bp) memcpy(&nextdata, bp, sizeof(nextdata))
475#elif SIZEOF_WORDTYPE == 8
476#if defined(_M_X64)
477#define GetNextData(nextdata, bp) nextdata = _byteswap_uint64(*(uint64_t *)(bp))
478#elif defined(__GNUC__)
479#define GetNextData(nextdata, bp) \
480 memcpy(&nextdata, bp, sizeof(nextdata)); \
481 nextdata = __builtin_bswap64(nextdata)
482#else
483#define GetNextData(nextdata, bp) \
484 nextdata = (((uint64_t)bp[0]) << 56) | (((uint64_t)bp[1]) << 48) | \
485 (((uint64_t)bp[2]) << 40) | (((uint64_t)bp[3]) << 32) | \
486 (((uint64_t)bp[4]) << 24) | (((uint64_t)bp[5]) << 16) | \
487 (((uint64_t)bp[6]) << 8) | (((uint64_t)bp[7]))
488#endif
489#elif SIZEOF_WORDTYPE == 4
490#if defined(_M_X86)
491#define GetNextData(nextdata, bp) \
492 nextdata = _byteswap_ulong(*(unsigned long *)(bp))
493#elif defined(__GNUC__)
494#define GetNextData(nextdata, bp) \
495 memcpy(&nextdata, bp, sizeof(nextdata)); \
496 nextdata = __builtin_bswap32(nextdata)
497#else
498#define GetNextData(nextdata, bp) \
499 nextdata = (((uint32_t)bp[0]) << 24) | (((uint32_t)bp[1]) << 16) | \
500 (((uint32_t)bp[2]) << 8) | (((uint32_t)bp[3]))
501#endif
502#else
503#error "Unhandled SIZEOF_WORDTYPE"
504#endif
505
506#define GetNextCodeLZW() \
507 do \
508 { \
509 nextbits -= nbits; \
510 if (nextbits < 0) \
511 { \
512 if (dec_bitsleft >= 8 * SIZEOF_WORDTYPE) \
513 { \
514 unsigned codetmp = (unsigned)(nextdata << (-nextbits)); \
515 GetNextData(nextdata, bp); \
516 bp += SIZEOF_WORDTYPE; \
517 nextbits += 8 * SIZEOF_WORDTYPE; \
518 dec_bitsleft -= 8 * SIZEOF_WORDTYPE; \
519 code = (WordType)((codetmp | (nextdata >> nextbits)) & \
520 (WordType)nbitsmask); \
521 break; \
522 } \
523 else \
524 { \
525 if (dec_bitsleft < 8) \
526 { \
527 goto no_eoi; \
528 } \
529 nextdata = (nextdata << 8) | *(bp)++; \
530 nextbits += 8; \
531 dec_bitsleft -= 8; \
532 if (nextbits < 0) \
533 { \
534 if (dec_bitsleft < 8) \
535 { \
536 goto no_eoi; \
537 } \
538 nextdata = (nextdata << 8) | *(bp)++; \
539 nextbits += 8; \
540 dec_bitsleft -= 8; \
541 } \
542 } \
543 } \
544 code = (WordType)((nextdata >> nextbits) & (WordType)nbitsmask); \
545 } while (0)
546
571static int LZWDecode(TIFF *tif, uint8_t *op0, tmsize_t occ0, uint16_t s)
572{
573 static const char module[] = "LZWDecode";
575 uint8_t *op = (uint8_t *)op0;
576 tmsize_t occ = occ0;
577 uint8_t *bp;
578 long nbits, nextbits, nbitsmask;
579 WordType nextdata;
580 code_t *free_entp, *maxcodep, *oldcodep;
581
582 (void)s;
583 assert(sp != NULL);
584 assert(sp->dec_codetab != NULL);
585
586 if (sp->read_error)
587 {
588 memset(op, 0, (size_t)occ);
589 TIFFErrorExtR(tif, module,
590 "LZWDecode: Scanline %" PRIu32 " cannot be read due to "
591 "previous error",
592 tif->tif_dir.td_row);
593 return 0;
594 }
595
596 /*
597 * Restart interrupted output operation.
598 */
599 if (sp->dec_restart)
600 {
601 tmsize_t residue;
602
603 code_t *codep = sp->dec_codep;
604 residue = codep->length - sp->dec_restart;
605 if (residue > occ)
606 {
607 /*
608 * Residue from previous decode is sufficient
609 * to satisfy decode request. Skip to the
610 * start of the decoded string, place decoded
611 * values in the output buffer, and return.
612 */
613 sp->dec_restart += occ;
614 do
615 {
616 codep = codep->next;
617 } while (--residue > occ && codep);
618 if (codep)
619 {
620 uint8_t *tp = op + occ;
621 do
622 {
623 *--tp = codep->value;
624 codep = codep->next;
625 } while (--occ && codep);
626 }
627 return (1);
628 }
629 /*
630 * Residue satisfies only part of the decode request.
631 */
632 op += residue;
633 occ -= residue;
634 uint8_t *tp = op;
635 do
636 {
637 *--tp = codep->value;
638 codep = codep->next;
639 } while (--residue && codep);
640 sp->dec_restart = 0;
641 }
642
643 bp = (uint8_t *)tif->tif_rawcp;
644 sp->dec_bitsleft +=
645 (((uint64_t)tif->tif_rawcc - (uint64_t)sp->old_tif_rawcc) << 3);
646 uint64_t dec_bitsleft = sp->dec_bitsleft;
647 nbits = sp->lzw_nbits;
648 nextdata = sp->lzw_nextdata;
649 nextbits = sp->lzw_nextbits;
650 nbitsmask = sp->dec_nbitsmask;
651 oldcodep = sp->dec_oldcodep;
652 free_entp = sp->dec_free_entp;
653 maxcodep = sp->dec_maxcodep;
654 code_t *const dec_codetab = sp->dec_codetab;
655 code_t *codep;
656
657 if (occ == 0)
658 {
659 goto after_loop;
660 }
661
662begin:
663{
664 WordType code;
666 codep = dec_codetab + (unsigned long)code;
667 if (code >= CODE_FIRST)
668 goto code_above_or_equal_to_258;
669 if (code < 256)
670 goto code_below_256;
671 if (code == CODE_EOI)
672 goto after_loop;
673 goto code_clear;
674
675code_below_256:
676{
677 if (codep > free_entp)
678 goto error_code;
679 free_entp->next = oldcodep;
680 free_entp->firstchar = oldcodep->firstchar;
681 free_entp->length = (uint16_t)(oldcodep->length + 1);
682 free_entp->value = (uint8_t)code;
683 free_entp->repeated =
684 (bool)(oldcodep->repeated & (oldcodep->value == code));
685 if (++free_entp > maxcodep)
686 {
687 if (++nbits > BITS_MAX) /* should not happen for a conformant encoder */
688 nbits = BITS_MAX;
689 nbitsmask = MAXCODE(nbits);
690 maxcodep = dec_codetab + nbitsmask - 1;
691 if (free_entp >= &dec_codetab[CSIZE])
692 {
693 /* At that point, the next valid states are either EOI or a
694 */
695 /* CODE_CLEAR. If a regular code is read, at the next */
696 /* attempt at registering a new entry, we will error out */
697 /* due to setting free_entp before any valid code */
698 free_entp = dec_codetab - 1;
699 }
700 }
701 oldcodep = codep;
702 *op++ = (uint8_t)code;
703 occ--;
704 if (occ == 0)
705 goto after_loop;
706 goto begin;
707}
708
709code_above_or_equal_to_258:
710{
711 /*
712 * Add the new entry to the code table.
713 */
714
715 if (codep >= free_entp)
716 {
717 if (codep != free_entp)
718 goto error_code;
719 free_entp->value = oldcodep->firstchar;
720 }
721 else
722 {
723 free_entp->value = codep->firstchar;
724 }
725 free_entp->repeated =
726 (bool)(oldcodep->repeated & (oldcodep->value == free_entp->value));
727 free_entp->next = oldcodep;
728
729 free_entp->firstchar = oldcodep->firstchar;
730 free_entp->length = (uint16_t)(oldcodep->length + 1);
731 if (++free_entp > maxcodep)
732 {
733 if (++nbits > BITS_MAX) /* should not happen for a conformant encoder */
734 nbits = BITS_MAX;
735 nbitsmask = MAXCODE(nbits);
736 maxcodep = dec_codetab + nbitsmask - 1;
737 if (free_entp >= &dec_codetab[CSIZE])
738 {
739 /* At that point, the next valid states are either EOI or a
740 */
741 /* CODE_CLEAR. If a regular code is read, at the next */
742 /* attempt at registering a new entry, we will error out */
743 /* due to setting free_entp before any valid code */
744 free_entp = dec_codetab - 1;
745 }
746 }
747 oldcodep = codep;
748
749 /*
750 * Code maps to a string, copy string
751 * value to output (written in reverse).
752 */
753 /* tiny bit faster on x86_64 to store in unsigned short than int */
754 unsigned short len = codep->length;
755
756 if (len < 3) /* equivalent to len == 2 given all other conditions */
757 {
758 if (occ <= 2)
759 {
760 if (occ == 2)
761 {
762 memcpy(op, &(codep->firstchar), 2);
763 op += 2;
764 occ -= 2;
765 goto after_loop;
766 }
767 goto too_short_buffer;
768 }
769
770 memcpy(op, &(codep->firstchar), 2);
771 op += 2;
772 occ -= 2;
773 goto begin; /* we can save the comparison occ > 0 */
774 }
775
776 if (len == 3)
777 {
778 if (occ <= 3)
779 {
780 if (occ == 3)
781 {
782 op[0] = codep->firstchar;
783 op[1] = codep->next->value;
784 op[2] = codep->value;
785 op += 3;
786 occ -= 3;
787 goto after_loop;
788 }
789 goto too_short_buffer;
790 }
791
792 op[0] = codep->firstchar;
793 op[1] = codep->next->value;
794 op[2] = codep->value;
795 op += 3;
796 occ -= 3;
797 goto begin; /* we can save the comparison occ > 0 */
798 }
799
800 if (len > occ)
801 {
802 goto too_short_buffer;
803 }
804
805 if (codep->repeated)
806 {
807 memset(op, codep->value, len);
808 op += len;
809 occ -= len;
810 if (occ == 0)
811 goto after_loop;
812 goto begin;
813 }
814
815 uint8_t *tp = op + len;
816
817 assert(len >= 4);
818
819 *--tp = codep->value;
820 codep = codep->next;
821 *--tp = codep->value;
822 codep = codep->next;
823 *--tp = codep->value;
824 codep = codep->next;
825 *--tp = codep->value;
826 if (tp > op)
827 {
828 do
829 {
830 codep = codep->next;
831 *--tp = codep->value;
832 } while (tp > op);
833 }
834
835 assert(occ >= len);
836 op += len;
837 occ -= len;
838 if (occ == 0)
839 goto after_loop;
840 goto begin;
841}
842
843code_clear:
844{
845 free_entp = dec_codetab + CODE_FIRST;
846 nbits = BITS_MIN;
847 nbitsmask = MAXCODE(BITS_MIN);
848 maxcodep = dec_codetab + (unsigned long)nbitsmask - 1;
849 do
850 {
852 } while (code == CODE_CLEAR); /* consecutive CODE_CLEAR codes */
853 if (code == CODE_EOI)
854 goto after_loop;
855 if (code > CODE_EOI)
856 {
857 goto error_code;
858 }
859 *op++ = (uint8_t)code;
860 occ--;
861 oldcodep = dec_codetab + code;
862 if (occ == 0)
863 goto after_loop;
864 goto begin;
865}
866}
867
868too_short_buffer:
869{
870 /*
871 * String is too long for decode buffer,
872 * locate portion that will fit, copy to
873 * the decode buffer, and setup restart
874 * logic for the next decoding call.
875 */
876 sp->dec_codep = codep;
877 do
878 {
879 codep = codep->next;
880 } while (codep->length > occ);
881
882 sp->dec_restart = occ;
883 uint8_t *tp = op + occ;
884 do
885 {
886 *--tp = codep->value;
887 codep = codep->next;
888 } while (--occ);
889}
890
891after_loop:
892 tif->tif_rawcc -= (tmsize_t)((uint8_t *)bp - tif->tif_rawcp);
893 tif->tif_rawcp = (uint8_t *)bp;
894 sp->old_tif_rawcc = tif->tif_rawcc;
895 sp->dec_bitsleft = dec_bitsleft;
896 sp->lzw_nbits = (unsigned short)nbits;
897 sp->lzw_nextdata = nextdata;
898 sp->lzw_nextbits = nextbits;
899 sp->dec_nbitsmask = nbitsmask;
900 sp->dec_oldcodep = oldcodep;
901 sp->dec_free_entp = free_entp;
902 sp->dec_maxcodep = maxcodep;
903
904 if (occ > 0)
905 {
906 memset(op, 0, (size_t)occ);
907 sp->read_error = 1;
908 TIFFErrorExtR(tif, module,
909 "Not enough data at scanline %" PRIu32 " (short %" PRIu64
910 " bytes)",
911 tif->tif_dir.td_row, (uint64_t)occ);
912 return (0);
913 }
914 return (1);
915
916no_eoi:
917 memset(op, 0, (size_t)occ);
918 sp->read_error = 1;
919 TIFFErrorExtR(tif, module,
920 "LZWDecode: Strip %" PRIu32 " not terminated with EOI code",
921 tif->tif_dir.td_curstrip);
922 return 0;
923error_code:
924 memset(op, 0, (size_t)occ);
925 sp->read_error = 1;
926 TIFFErrorExtR(tif, tif->tif_name, "Using code not yet in table");
927 return 0;
928}
929
930#ifdef LZW_COMPAT
931
932/*
933 * This check shouldn't be necessary because each
934 * strip is suppose to be terminated with CODE_EOI.
935 */
936#define NextCode(_tif, _sp, _bp, _code, _get, dec_bitsleft) \
937 { \
938 if (dec_bitsleft < (uint64_t)nbits) \
939 { \
940 TIFFWarningExtR(_tif, module, \
941 "LZWDecode: Strip %" PRIu32 \
942 " not terminated with EOI code", \
943 _tif->tif_dir.td_curstrip); \
944 _code = CODE_EOI; \
945 } \
946 else \
947 { \
948 _get(_sp, _bp, _code); \
949 dec_bitsleft -= (uint64_t)nbits; \
950 } \
951 }
952
953/*
954 * Decode a "hunk of data" for old images.
955 */
956#define GetNextCodeCompat(sp, bp, code) \
957 { \
958 nextdata |= (unsigned long)*(bp)++ << nextbits; \
959 nextbits += 8; \
960 if (nextbits < nbits) \
961 { \
962 nextdata |= (unsigned long)*(bp)++ << nextbits; \
963 nextbits += 8; \
964 } \
965 code = (hcode_t)(nextdata & (unsigned long)nbitsmask); \
966 nextdata >>= nbits; \
967 nextbits -= nbits; \
968 }
969
996static int LZWDecodeCompat(TIFF *tif, uint8_t *op0, tmsize_t occ0, uint16_t s)
997{
998 static const char module[] = "LZWDecodeCompat";
1000 uint8_t *op = (uint8_t *)op0;
1001 tmsize_t occ = occ0;
1002 uint8_t *tp;
1003 uint8_t *bp;
1004 int code, nbits;
1005 int len;
1006 long nextbits, nbitsmask;
1007 WordType nextdata;
1008 code_t *codep, *free_entp, *maxcodep, *oldcodep;
1009
1010 (void)s;
1011 assert(sp != NULL);
1012
1013 if (sp->read_error)
1014 {
1015 memset(op, 0, (size_t)occ);
1016 TIFFErrorExtR(tif, module,
1017 "LZWDecodeCompat: Scanline %" PRIu32
1018 " cannot be read due to previous error",
1019 tif->tif_dir.td_row);
1020 return 0;
1021 }
1022
1023 /*
1024 * Restart interrupted output operation.
1025 */
1026 if (sp->dec_restart)
1027 {
1028 tmsize_t residue;
1029
1030 codep = sp->dec_codep;
1031 residue = codep->length - sp->dec_restart;
1032 if (residue > occ)
1033 {
1034 /*
1035 * Residue from previous decode is sufficient
1036 * to satisfy decode request. Skip to the
1037 * start of the decoded string, place decoded
1038 * values in the output buffer, and return.
1039 */
1040 sp->dec_restart += occ;
1041 do
1042 {
1043 codep = codep->next;
1044 } while (--residue > occ);
1045 tp = op + occ;
1046 do
1047 {
1048 *--tp = codep->value;
1049 codep = codep->next;
1050 } while (--occ);
1051 return (1);
1052 }
1053 /*
1054 * Residue satisfies only part of the decode request.
1055 */
1056 op += residue;
1057 occ -= residue;
1058 tp = op;
1059 do
1060 {
1061 *--tp = codep->value;
1062 codep = codep->next;
1063 } while (--residue);
1064 sp->dec_restart = 0;
1065 }
1066
1067 bp = (uint8_t *)tif->tif_rawcp;
1068
1069 sp->dec_bitsleft +=
1070 (((uint64_t)tif->tif_rawcc - (uint64_t)sp->old_tif_rawcc) << 3);
1071 uint64_t dec_bitsleft = sp->dec_bitsleft;
1072
1073 nbits = sp->lzw_nbits;
1074 nextdata = sp->lzw_nextdata;
1075 nextbits = sp->lzw_nextbits;
1076 nbitsmask = sp->dec_nbitsmask;
1077 oldcodep = sp->dec_oldcodep;
1078 free_entp = sp->dec_free_entp;
1079 maxcodep = sp->dec_maxcodep;
1080
1081 while (occ > 0)
1082 {
1083 NextCode(tif, sp, bp, code, GetNextCodeCompat, dec_bitsleft);
1084 if (code == CODE_EOI)
1085 break;
1086 if (code == CODE_CLEAR)
1087 {
1088 do
1089 {
1090 free_entp = sp->dec_codetab + CODE_FIRST;
1091 _TIFFmemset(free_entp, 0,
1092 (CSIZE - CODE_FIRST) * sizeof(code_t));
1093 nbits = BITS_MIN;
1094 nbitsmask = MAXCODE(BITS_MIN);
1095 maxcodep = sp->dec_codetab + nbitsmask;
1096 NextCode(tif, sp, bp, code, GetNextCodeCompat, dec_bitsleft);
1097 } while (code == CODE_CLEAR); /* consecutive CODE_CLEAR codes */
1098 if (code == CODE_EOI)
1099 break;
1100 if (code > CODE_CLEAR)
1101 {
1102 memset(op0, 0, (size_t)occ0);
1103 sp->read_error = 1;
1105 tif, tif->tif_name,
1106 "LZWDecode: Corrupted LZW table at scanline %" PRIu32,
1107 tif->tif_dir.td_row);
1108 return (0);
1109 }
1110 *op++ = (uint8_t)code;
1111 occ--;
1112 oldcodep = sp->dec_codetab + code;
1113 continue;
1114 }
1115 codep = sp->dec_codetab + code;
1116
1117 /*
1118 * Add the new entry to the code table.
1119 */
1120 if (free_entp < &sp->dec_codetab[0] ||
1121 free_entp >= &sp->dec_codetab[CSIZE])
1122 {
1123 memset(op0, 0, (size_t)occ0);
1124 sp->read_error = 1;
1125 TIFFErrorExtR(tif, module,
1126 "Corrupted LZW table at scanline %" PRIu32,
1127 tif->tif_dir.td_row);
1128 return (0);
1129 }
1130
1131 free_entp->next = oldcodep;
1132 if (free_entp->next < &sp->dec_codetab[0] ||
1133 free_entp->next >= &sp->dec_codetab[CSIZE])
1134 {
1135 memset(op0, 0, (size_t)occ0);
1136 sp->read_error = 1;
1137 TIFFErrorExtR(tif, module,
1138 "Corrupted LZW table at scanline %" PRIu32,
1139 tif->tif_dir.td_row);
1140 return (0);
1141 }
1142 free_entp->firstchar = free_entp->next->firstchar;
1143 free_entp->length = (uint16_t)(free_entp->next->length + 1);
1144 free_entp->value =
1145 (codep < free_entp) ? codep->firstchar : free_entp->firstchar;
1146 if (++free_entp > maxcodep)
1147 {
1148 if (++nbits > BITS_MAX) /* should not happen */
1149 nbits = BITS_MAX;
1150 nbitsmask = MAXCODE(nbits);
1151 maxcodep = sp->dec_codetab + nbitsmask;
1152 }
1153 oldcodep = codep;
1154 if (code >= 256)
1155 {
1156 /*
1157 * Code maps to a string, copy string
1158 * value to output (written in reverse).
1159 */
1160 if (codep->length == 0)
1161 {
1162 memset(op0, 0, (size_t)occ0);
1163 sp->read_error = 1;
1165 tif, module,
1166 "Wrong length of decoded "
1167 "string: data probably corrupted at scanline %" PRIu32,
1168 tif->tif_dir.td_row);
1169 return (0);
1170 }
1171 if (codep->length > occ)
1172 {
1173 /*
1174 * String is too long for decode buffer,
1175 * locate portion that will fit, copy to
1176 * the decode buffer, and setup restart
1177 * logic for the next decoding call.
1178 */
1179 sp->dec_codep = codep;
1180 do
1181 {
1182 codep = codep->next;
1183 } while (codep->length > occ);
1184 sp->dec_restart = occ;
1185 tp = op + occ;
1186 do
1187 {
1188 *--tp = codep->value;
1189 codep = codep->next;
1190 } while (--occ);
1191 break;
1192 }
1193 len = codep->length;
1194 tp = op + len;
1195 do
1196 {
1197 *--tp = codep->value;
1198 codep = codep->next;
1199 } while (codep && tp > op);
1200 assert(occ >= len);
1201 op += len;
1202 occ -= len;
1203 }
1204 else
1205 {
1206 *op++ = (uint8_t)code;
1207 occ--;
1208 }
1209 }
1210
1211 tif->tif_rawcc -= (tmsize_t)((uint8_t *)bp - tif->tif_rawcp);
1212 tif->tif_rawcp = (uint8_t *)bp;
1213
1214 sp->old_tif_rawcc = tif->tif_rawcc;
1215 sp->dec_bitsleft = dec_bitsleft;
1216
1217 sp->lzw_nbits = (unsigned short)nbits;
1218 sp->lzw_nextdata = nextdata;
1219 sp->lzw_nextbits = nextbits;
1220 sp->dec_nbitsmask = nbitsmask;
1221 sp->dec_oldcodep = oldcodep;
1222 sp->dec_free_entp = free_entp;
1223 sp->dec_maxcodep = maxcodep;
1224
1225 if (occ > 0)
1226 {
1227 memset(op, 0, (size_t)occ);
1228 sp->read_error = 1;
1229 TIFFErrorExtR(tif, module,
1230 "Not enough data at scanline %" PRIu32 " (short %" PRIu64
1231 " bytes)",
1232 tif->tif_dir.td_row, (uint64_t)occ);
1233 return (0);
1234 }
1235 return (1);
1236}
1237#endif /* LZW_COMPAT */
1238
1239#ifndef LZW_READ_ONLY
1240
1241static void cl_hash(LZWCodecState *);
1242
1243/*
1244 * LZW Encoding.
1245 */
1246
1259static int LZWSetupEncode(TIFF *tif)
1260{
1261 static const char module[] = "LZWSetupEncode";
1262 LZWCodecState *sp = LZWEncoderState(tif);
1263
1264 assert(sp != NULL);
1265 sp->enc_hashtab = (hash_t *)_TIFFmallocExt(tif, HSIZE * sizeof(hash_t));
1266 if (sp->enc_hashtab == NULL)
1267 {
1268 TIFFErrorExtR(tif, module, "No space for LZW hash table");
1269 return (0);
1270 }
1271 return (1);
1272}
1273
1274/*
1275 * Reset encoding state at the start of a strip.
1276 */
1297static int LZWPreEncode(TIFF *tif, uint16_t s)
1298{
1299 static const char module[] = "LZWPreEncode";
1300 LZWCodecState *sp = LZWEncoderState(tif);
1301
1302 (void)s;
1303 assert(sp != NULL);
1304
1305 /*
1306 * LZWEncode() may write two codes (up to 4 bytes) after its room check,
1307 * and LZWPostEncode() may write up to 5 bytes. Both assume the raw data
1308 * buffer holds at least 5 bytes.
1309 */
1310 if (tif->tif_rawdatasize < 5)
1311 {
1312 TIFFErrorExtR(tif, module,
1313 "Raw data buffer of %" TIFF_SSIZE_FORMAT
1314 " bytes is too small for LZW encoding, at least 5 bytes"
1315 " are needed",
1316 tif->tif_rawdatasize);
1317 return (0);
1318 }
1319
1320 if (sp->enc_hashtab == NULL)
1321 {
1322 tif->tif_setupencode(tif);
1323 }
1324
1325 sp->lzw_nbits = BITS_MIN;
1326 sp->lzw_maxcode = MAXCODE(BITS_MIN);
1327 sp->lzw_free_ent = CODE_FIRST;
1328 sp->lzw_nextbits = 0;
1329 sp->lzw_nextdata = 0;
1330 sp->enc_checkpoint = CHECK_GAP;
1331 sp->enc_ratio = 0;
1332 sp->enc_incount = 0;
1333 sp->enc_outcount = 0;
1334 /*
1335 * The 4 here insures there is space for 2 max-sized
1336 * codes in LZWEncode and LZWPostDecode.
1337 */
1338 sp->enc_rawlimit = tif->tif_rawdata + tif->tif_rawdatasize - 1 - 4;
1339 cl_hash(sp); /* clear hash table */
1340 sp->enc_oldcode = (hcode_t)-1; /* generates CODE_CLEAR in LZWEncode */
1341 return (1);
1342}
1343
1344#define CALCRATIO(sp, rat) \
1345 { \
1346 if (incount > 0x007fffff) \
1347 { /* NB: shift will overflow */ \
1348 rat = outcount >> 8; \
1349 rat = (rat == 0 ? 0x7fffffff : incount / rat); \
1350 } \
1351 else \
1352 rat = (incount << 8) / outcount; \
1353 }
1354
1355/* Explicit 0xff masking to make icc -check=conversions happy */
1356#define PutNextCode(op, c) \
1357 { \
1358 nextdata = (nextdata << nbits) | c; \
1359 nextbits += nbits; \
1360 *op++ = (unsigned char)((nextdata >> (nextbits - 8)) & 0xff); \
1361 nextbits -= 8; \
1362 if (nextbits >= 8) \
1363 { \
1364 *op++ = (unsigned char)((nextdata >> (nextbits - 8)) & 0xff); \
1365 nextbits -= 8; \
1366 } \
1367 outcount += nbits; \
1368 }
1369
1370/*
1371 * Encode a chunk of pixels.
1372 *
1373 * Uses an open addressing double hashing (no chaining) on the
1374 * prefix code/next character combination. We do a variant of
1375 * Knuth's algorithm D (vol. 3, sec. 6.4) along with G. Knott's
1376 * relatively-prime secondary probe. Here, the modular division
1377 * first probe is gives way to a faster exclusive-or manipulation.
1378 * Also do block compression with an adaptive reset, whereby the
1379 * code table is cleared when the compression ratio decreases,
1380 * but after the table fills. The variable-length output codes
1381 * are re-sized at this point, and a CODE_CLEAR is generated
1382 * for the decoder.
1383 */
1403static int LZWEncode(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
1404{
1405 LZWCodecState *sp = LZWEncoderState(tif);
1406 long fcode;
1407 hash_t *hp;
1408 int h, c;
1409 hcode_t ent;
1410 long disp;
1411 tmsize_t incount, outcount, checkpoint;
1412 WordType nextdata;
1413 long nextbits;
1414 int free_ent, maxcode, nbits;
1415 uint8_t *op;
1416 uint8_t *limit;
1417
1418 (void)s;
1419 if (sp == NULL)
1420 return (0);
1421
1422 assert(sp->enc_hashtab != NULL);
1423
1424 /*
1425 * Load local state.
1426 */
1427 incount = sp->enc_incount;
1428 outcount = sp->enc_outcount;
1429 checkpoint = sp->enc_checkpoint;
1430 nextdata = sp->lzw_nextdata;
1431 nextbits = sp->lzw_nextbits;
1432 free_ent = sp->lzw_free_ent;
1433 maxcode = sp->lzw_maxcode;
1434 nbits = sp->lzw_nbits;
1435 op = tif->tif_rawcp;
1436 limit = sp->enc_rawlimit;
1437 ent = (hcode_t)sp->enc_oldcode;
1438
1439 if (ent == (hcode_t)-1 && cc > 0)
1440 {
1441 /*
1442 * NB: This is safe because it can only happen
1443 * at the start of a strip where we know there
1444 * is space in the data buffer.
1445 */
1447 ent = *bp++;
1448 cc--;
1449 incount++;
1450 }
1451 while (cc > 0)
1452 {
1453 c = *bp++;
1454 cc--;
1455 incount++;
1456 fcode = ((long)c << BITS_MAX) + ent;
1457 h = (c << HSHIFT) ^ ent; /* xor hashing */
1458 hp = &sp->enc_hashtab[h];
1459 if (hp->hash == fcode)
1460 {
1461 ent = hp->code;
1462 continue;
1463 }
1464 if (hp->hash >= 0)
1465 {
1466 /*
1467 * Primary hash failed, check secondary hash.
1468 */
1469 disp = HSIZE - h;
1470 if (h == 0)
1471 disp = 1;
1472 do
1473 {
1474 /*
1475 * Avoid pointer arithmetic because of
1476 * wraparound problems with segments.
1477 */
1478 if ((h -= (int)disp) < 0)
1479 h += HSIZE;
1480 hp = &sp->enc_hashtab[h];
1481 if (hp->hash == fcode)
1482 {
1483 ent = hp->code;
1484 goto hit;
1485 }
1486 } while (hp->hash >= 0);
1487 }
1488 /*
1489 * New entry, emit code and add to table.
1490 */
1491 /*
1492 * Verify there is space in the buffer for the code
1493 * and any potential Clear code that might be emitted
1494 * below. The value of limit is setup so that there
1495 * are at least 4 bytes free--room for 2 codes.
1496 */
1497 if (op > limit)
1498 {
1499 tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata);
1500 if (!TIFFFlushData1(tif))
1501 return 0;
1502 op = tif->tif_rawdata;
1503 }
1504 PutNextCode(op, ent);
1505 ent = (hcode_t)c;
1506 hp->code = (hcode_t)(free_ent++);
1507 hp->hash = fcode;
1508 if (free_ent == CODE_MAX - 1)
1509 {
1510 /* table is full, emit clear code and reset */
1511 cl_hash(sp);
1512 sp->enc_ratio = 0;
1513 incount = 0;
1514 outcount = 0;
1515 free_ent = CODE_FIRST;
1517 nbits = BITS_MIN;
1518 maxcode = MAXCODE(BITS_MIN);
1519 }
1520 else
1521 {
1522 /*
1523 * If the next entry is going to be too big for
1524 * the code size, then increase it, if possible.
1525 */
1526 if (free_ent > maxcode)
1527 {
1528 nbits++;
1529 assert(nbits <= BITS_MAX);
1530 maxcode = (int)MAXCODE(nbits);
1531 }
1532 else if (incount >= checkpoint)
1533 {
1534 tmsize_t rat;
1535 /*
1536 * Check compression ratio and, if things seem
1537 * to be slipping, clear the hash table and
1538 * reset state. The compression ratio is a
1539 * 24+8-bit fractional number.
1540 */
1541 checkpoint = incount + CHECK_GAP;
1542 CALCRATIO(sp, rat);
1543 if (rat <= sp->enc_ratio)
1544 {
1545 cl_hash(sp);
1546 sp->enc_ratio = 0;
1547 incount = 0;
1548 outcount = 0;
1549 free_ent = CODE_FIRST;
1551 nbits = BITS_MIN;
1552 maxcode = MAXCODE(BITS_MIN);
1553 }
1554 else
1555 sp->enc_ratio = rat;
1556 }
1557 }
1558 hit:;
1559 }
1560
1561 /*
1562 * Restore global state.
1563 */
1564 sp->enc_incount = incount;
1565 sp->enc_outcount = outcount;
1566 sp->enc_checkpoint = checkpoint;
1567 sp->enc_oldcode = ent;
1568 sp->lzw_nextdata = nextdata;
1569 sp->lzw_nextbits = nextbits;
1570 sp->lzw_free_ent = (unsigned short)free_ent;
1571 sp->lzw_maxcode = (unsigned short)maxcode;
1572 sp->lzw_nbits = (unsigned short)nbits;
1573 tif->tif_rawcp = op;
1574 return (1);
1575}
1576
1577/*
1578 * Finish off an encoded strip by flushing the last
1579 * string and tacking on an End Of Information code.
1580 */
1595static int LZWPostEncode(TIFF *tif)
1596{
1597 LZWCodecState *sp = LZWEncoderState(tif);
1598 uint8_t *op = tif->tif_rawcp;
1599 long nextbits = sp->lzw_nextbits;
1600 WordType nextdata = sp->lzw_nextdata;
1601 tmsize_t outcount = sp->enc_outcount;
1602 int nbits = sp->lzw_nbits;
1603
1604 if (op > sp->enc_rawlimit)
1605 {
1606 tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata);
1607 if (!TIFFFlushData1(tif))
1608 return 0;
1609 op = tif->tif_rawdata;
1610 }
1611 if (sp->enc_oldcode != (hcode_t)-1)
1612 {
1613 int free_ent = sp->lzw_free_ent;
1614
1616 sp->enc_oldcode = (hcode_t)-1;
1617 free_ent++;
1618
1619 if (free_ent == CODE_MAX - 1)
1620 {
1621 /* table is full, emit clear code and reset */
1622 outcount = 0;
1624 nbits = BITS_MIN;
1625 }
1626 else
1627 {
1628 /*
1629 * If the next entry is going to be too big for
1630 * the code size, then increase it, if possible.
1631 */
1632 if (free_ent > sp->lzw_maxcode)
1633 {
1634 nbits++;
1635 assert(nbits <= BITS_MAX);
1636 }
1637 }
1638 }
1639 PutNextCode(op, CODE_EOI);
1640 /* Explicit 0xff masking to make icc -check=conversions happy */
1641 if (nextbits > 0)
1642 *op++ = (unsigned char)((nextdata << (8 - nextbits)) & 0xff);
1643 tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata);
1644 (void)outcount;
1645 return (1);
1646}
1647
1648/*
1649 * Reset encoding hash table.
1650 */
1662static void cl_hash(LZWCodecState *sp)
1663{
1664 hash_t *hp = &sp->enc_hashtab[HSIZE - 1];
1665 long i = HSIZE - 8;
1666
1667 do
1668 {
1669 i -= 8;
1670 hp[-7].hash = -1;
1671 hp[-6].hash = -1;
1672 hp[-5].hash = -1;
1673 hp[-4].hash = -1;
1674 hp[-3].hash = -1;
1675 hp[-2].hash = -1;
1676 hp[-1].hash = -1;
1677 hp[0].hash = -1;
1678 hp -= 8;
1679 } while (i >= 0);
1680 for (i += 8; i > 0; i--, hp--)
1681 hp->hash = -1;
1682}
1683
1684#endif
1685
1699static void LZWCleanup(TIFF *tif)
1700{
1701 (void)TIFFPredictorCleanup(tif);
1702
1703 assert(tif->tif_data != NULL);
1704
1705 if (LZWDecoderState(tif)->dec_codetab)
1706 _TIFFfreeExt(tif, LZWDecoderState(tif)->dec_codetab);
1707
1708 if (LZWEncoderState(tif)->enc_hashtab)
1709 _TIFFfreeExt(tif, LZWEncoderState(tif)->enc_hashtab);
1710
1711 _TIFFfreeExt(tif, tif->tif_data);
1712 tif->tif_data = NULL;
1713
1715}
1716
1727static uint64_t LZWGetMaxCompressionRatio(TIFF *tif)
1728{
1729 (void)tif;
1730
1731 /* See README_for_libtiff_developpers.md for raw data used to estimate
1732 * the maximum compression rate. */
1733
1734 /* 1024x1024: 562 */
1735 /* 4096x4096: 1243 */
1736 /* 16383x16383: 1353 */
1737 /* 65536x65536: 1362 */
1738
1739 return 1400;
1740}
1741
1742int TIFFInitLZW(TIFF *tif, int scheme)
1743{
1744 static const char module[] = "TIFFInitLZW";
1745 (void)scheme;
1746 assert(scheme == COMPRESSION_LZW);
1747 /*
1748 * Allocate state block so tag methods have storage to record values.
1749 */
1750 tif->tif_data = (uint8_t *)_TIFFmallocExt(tif, sizeof(LZWCodecState));
1751 if (tif->tif_data == NULL)
1752 goto bad;
1753 LZWDecoderState(tif)->dec_codetab = NULL;
1754 LZWDecoderState(tif)->dec_decode = NULL;
1755 LZWEncoderState(tif)->enc_hashtab = NULL;
1756 LZWState(tif)->rw_mode = tif->tif_mode;
1757
1758 /*
1759 * Install codec methods.
1760 */
1764 tif->tif_decoderow = LZWDecode;
1767#ifndef LZW_READ_ONLY
1771 tif->tif_encoderow = LZWEncode;
1774#endif
1776 tif->tif_cleanup = LZWCleanup;
1777 /*
1778 * Setup predictor setup.
1779 */
1780 (void)TIFFPredictorInit(tif);
1781 return (1);
1782bad:
1783 TIFFErrorExtR(tif, module, "No space for LZW state block");
1784 return (0);
1785}
1786
1787/*
1788 * Copyright (c) 1985, 1986 The Regents of the University of California.
1789 * All rights reserved.
1790 *
1791 * This code is derived from software contributed to Berkeley by
1792 * James A. Woods, derived from original work by Spencer Thomas
1793 * and Joseph Orost.
1794 *
1795 * Redistribution and use in source and binary forms are permitted
1796 * provided that the above copyright notice and this paragraph are
1797 * duplicated in all such forms and that any documentation,
1798 * advertising materials, and other materials related to such
1799 * distribution and use acknowledge that the software was developed
1800 * by the University of California, Berkeley. The name of the
1801 * University may not be used to endorse or promote products derived
1802 * from this software without specific prior written permission.
1803 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
1804 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
1805 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
1806 */
1807#endif /* LZW_SUPPORT */
1808
void _TIFFSetDefaultCompressionState(TIFF *tif)
Install fallback codec callbacks and reset raw-access flags.
#define TIFF_SSIZE_FORMAT
Provide the printf conversion fragment for tmsize_t, without a percent sign.
Definition tif_config.h:294
int TIFFFlushData1(TIFF *tif)
Append buffered encoded bytes without invoking postencode recursively.
Definition tif_write.c:1213
#define CODE_EOI
Reserved code 257 that ends the strip or tile.
Definition tif_lzw.c:81
static uint64_t LZWGetMaxCompressionRatio(TIFF *tif)
Report the empirical LZW expansion heuristic.
Definition tif_lzw.c:1727
#define BITS_MIN
Initial and post-clear code width: 9 bits.
Definition tif_lzw.c:77
#define PutNextCode(op, c)
Append the nbits-wide code c MSB-first to the encoder output at op.
Definition tif_lzw.c:1356
#define MAXCODE(n)
Compute the inclusive maximum code for a valid bit width.
Definition tif_lzw.c:72
static int LZWPreEncode(TIFF *tif, uint16_t s)
Reset the LZW encoder dictionary bit cache and counters.
Definition tif_lzw.c:1297
static int LZWPreDecode(TIFF *tif, uint16_t s)
Reset LZW bit and dictionary state for a strile.
Definition tif_lzw.c:389
#define CODE_MAX
Largest 12-bit code: MAXCODE(BITS_MAX), i.e. 4095.
Definition tif_lzw.c:83
#define BITS_MAX
Maximum code width allowed by TIFF LZW: 12 bits.
Definition tif_lzw.c:78
#define CALCRATIO(sp, rat)
Compute the encoder compression ratio incount/outcount as a 24.8 fixed-point value into rat.
Definition tif_lzw.c:1344
#define LZWEncoderState(tif)
Cast tif->tif_data to the full LZWCodecState for encoding.
Definition tif_lzw.c:262
struct code_ent code_t
Link one decoder string to its preceding dictionary string.
#define LZWDecoderState(tif)
Cast tif->tif_data to the full LZWCodecState for decoding.
Definition tif_lzw.c:261
uint16_t hcode_t
Store an encoder dictionary code in sixteen bits.
Definition tif_lzw.c:138
#define CODE_CLEAR
Reserved code 256 that resets the string table.
Definition tif_lzw.c:80
static int LZWDecode(TIFF *tif, uint8_t *op0, tmsize_t occ0, uint16_t s)
Expand standard TIFF LZW codes into caller output.
Definition tif_lzw.c:571
int TIFFInitLZW(TIFF *tif, int scheme)
Allocate LZW codec state and install predictor-aware methods.
Definition tif_lzw.c:1742
#define GetNextCodeLZW()
Extract the next nbits-wide MSB-first code from the decoder bit cache into code, refilling from bp as...
Definition tif_lzw.c:506
static int LZWEncode(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
Compress borrowed bytes into buffered TIFF LZW codes.
Definition tif_lzw.c:1403
static int LZWFixupTags(TIFF *tif)
Accept LZW tag fixup without changes.
Definition tif_lzw.c:282
size_t WordType
Select the native size_t word for buffered LZW bits.
Definition tif_lzw.c:55
#define NextCode(_tif, _sp, _bp, _code, _get, dec_bitsleft)
Fetch the next compatibility-mode code with _get, or yield CODE_EOI with a warning when fewer than nb...
Definition tif_lzw.c:936
static void LZWCleanup(TIFF *tif)
Release LZW tables and codec state and reset methods.
Definition tif_lzw.c:1699
#define CHECK_GAP
Encoder input bytes between compression-ratio checks: 10000.
Definition tif_lzw.c:247
static void cl_hash(LZWCodecState *)
Mark every LZW encoder hash slot unused.
Definition tif_lzw.c:1662
#define CODE_FIRST
First dictionary code assigned to a new string: 258.
Definition tif_lzw.c:82
static int LZWDecodeCompat(TIFF *tif, uint8_t *op0, tmsize_t occ0, uint16_t s)
Expand historical reversed-order LZW codes into caller output.
Definition tif_lzw.c:996
#define HSIZE
Number of entries in the encoder hash table: 9001.
Definition tif_lzw.c:84
static int LZWSetupEncode(TIFF *tif)
Allocate the LZW encoder hash table.
Definition tif_lzw.c:1259
static int LZWPostEncode(TIFF *tif)
Emit the final LZW string end code and padding bits.
Definition tif_lzw.c:1595
#define CSIZE
Number of entries allocated for the decoder string table.
Definition tif_lzw.c:88
#define HSHIFT
Left shift applied to the input byte when hashing encoder strings.
Definition tif_lzw.c:85
#define LZWState(tif)
Cast tif->tif_data to the shared LZWBaseState prefix.
Definition tif_lzw.c:260
int(* decodeFunc)(TIFF *tif, uint8_t *buf, tmsize_t size, uint16_t sample)
Signature shared by the LZW decode entry points (recorded in dec_decode).
Definition tif_lzw.c:200
#define GetNextCodeCompat(sp, bp, code)
Extract the next nbits-wide LSB-first code for old reversed-order LZW data.
Definition tif_lzw.c:956
static int LZWSetupDecode(TIFF *tif)
Allocate and initialise the LZW decode dictionary.
Definition tif_lzw.c:302
void _TIFFfreeExt(TIFF *tif, void *p)
Release a handle-aware allocation and its payload charge.
Definition tif_open.c:301
void * _TIFFmallocExt(TIFF *tif, tmsize_t s)
Allocate uninitialised bytes under a handle's allocation policy.
Definition tif_open.c:195
int TIFFPredictorCleanup(TIFF *tif)
Restore saved Predictor tag print and setup hooks.
int TIFFPredictorInit(TIFF *tif)
Install Predictor tag and setup hooks around a codec.
void TIFFWarningExtR(TIFF *tif, const char *module, const char *fmt,...)
Dispatch a warning diagnostic to the configured handlers.
Definition tif_warning.c:85
void TIFFErrorExtR(TIFF *tif, const char *module, const char *fmt,...)
Dispatch a error diagnostic to the configured handlers.
Definition tif_error.c:112
void _TIFFmemset(void *p, int v, tmsize_t c)
Fill a byte range with one repeated byte.
Definition tif_unix.c:495
#define COMPRESSION_LZW
Lempel-Ziv & Welch.
Definition tiff.h:314
TIFF_SSIZE_T tmsize_t
Represent a signed memory or I/O size in bytes.
Definition tiffio.h:89
Prefix LZW state with Predictor hooks and shared bit-code state.
Definition tif_lzw.c:106
WordType nextdata
Buffered input/output code bits.
Definition tif_lzw.c:117
unsigned short free_ent
Next available dictionary code.
Definition tif_lzw.c:115
unsigned short maxcode
Largest code under the current width convention.
Definition tif_lzw.c:113
unsigned short nbits
Current code width in bits.
Definition tif_lzw.c:111
long nextbits
Number of valid buffered code bits.
Definition tif_lzw.c:119
TIFFPredictorState predict
Predictor prefix; must be the first member.
Definition tif_lzw.c:108
int rw_mode
Open mode saved at codec initialisation.
Definition tif_lzw.c:122
Own LZW dictionaries hash storage and transfer restart state.
Definition tif_lzw.c:212
uint8_t * enc_rawlimit
Borrowed raw-buffer limit leaving room for final codes.
Definition tif_lzw.c:255
code_t * dec_codep
Borrowed current/restart entry within dec_codetab.
Definition tif_lzw.c:231
tmsize_t enc_outcount
Output code bits counted for ratio estimation.
Definition tif_lzw.c:253
tmsize_t old_tif_rawcc
Raw byte count saved after the preceding decoder call.
Definition tif_lzw.c:223
code_t * dec_maxcodep
Current width-dependent dictionary limit cursor.
Definition tif_lzw.c:237
hash_t * enc_hashtab
Owned HSIZE-entry encoding table, released by cleanup.
Definition tif_lzw.c:257
tmsize_t enc_ratio
Cached compression ratio in fixed-point form.
Definition tif_lzw.c:249
long dec_nbitsmask
Right-adjusted mask for current decode width.
Definition tif_lzw.c:217
tmsize_t enc_checkpoint
Input-byte threshold for the next ratio test.
Definition tif_lzw.c:246
int read_error
Latched same-strile failure cleared by predecode.
Definition tif_lzw.c:241
tmsize_t enc_incount
Input bytes counted for ratio estimation.
Definition tif_lzw.c:251
LZWBaseState base
Shared LZW/Predictor prefix, first in the codec allocation.
Definition tif_lzw.c:214
code_t * dec_oldcodep
Borrowed preceding recognised entry.
Definition tif_lzw.c:233
uint64_t dec_bitsleft
Number of cached raw-input bits remaining.
Definition tif_lzw.c:221
tmsize_t dec_restart
Bytes already returned from an interrupted decoded string.
Definition tif_lzw.c:219
int enc_oldcode
Pending previous encoder string code.
Definition tif_lzw.c:244
code_t * dec_codetab
Owned decoder entry allocation, released by cleanup.
Definition tif_lzw.c:239
code_t * dec_free_entp
Next available decoder table entry cursor.
Definition tif_lzw.c:235
decodeFunc dec_decode
Decoder last recorded by predecode; NULL until the first predecode. Used only as a first-strile detec...
Definition tif_lzw.c:229
uint32_t td_row
Current scanline index; UINT32_MAX before traversal starts.
Definition tif_dir.h:240
uint32_t td_curstrip
Current strip index, or NOSTRIP.
Definition tif_dir.h:242
Prefix codec state with Predictor method chains and row geometry.
Definition tif_predict.h:76
Link one decoder string to its preceding dictionary string.
Definition tif_lzw.c:165
struct code_ent * next
Borrowed link within the decoder table to the preceding string entry.
Definition tif_lzw.c:170
unsigned char value
Final byte represented by this entry.
Definition tif_lzw.c:180
bool repeated
Whether the string consists of one repeated byte.
Definition tif_lzw.c:182
unsigned char firstchar
First byte of the decoded string; immediately precedes value for fast paths.
Definition tif_lzw.c:178
unsigned short length
Decoded string length including this entry.
Definition tif_lzw.c:172
Pair an encoder hash key with its dictionary code.
Definition tif_lzw.c:147
long hash
Encoder lookup key; minus one means unused.
Definition tif_lzw.c:149
hcode_t code
Encoder dictionary code for the key.
Definition tif_lzw.c:151
Hold private state for one open TIFF library instance.
Definition tiffiop.h:389
TIFFCodeMethod tif_encodestrip
Codec callback encoding strip data.
Definition tiffiop.h:649
TIFFCodeMethod tif_encodetile
Codec callback encoding tile data.
Definition tiffiop.h:653
TIFFPreMethod tif_preencode
Codec callback preparing a row, strip, or tile encode.
Definition tiffiop.h:639
TIFFBoolMethod tif_fixuptags
Codec callback for directory-dependent tag corrections.
Definition tiffiop.h:626
tmsize_t tif_rawcc
Raw-buffer byte count interpreted according to read/write state.
Definition tiffiop.h:696
TIFFPreMethod tif_predecode
Codec callback preparing a row, strip, or tile decode.
Definition tiffiop.h:630
TIFFCodeMethod tif_decodestrip
Codec callback decoding strip data.
Definition tiffiop.h:647
TIFFGetMaxCompressionRatioMethod tif_getmaxcompressionratio
Codec callback returning its maximum compression ratio.
Definition tiffiop.h:670
char * tif_name
Current filename pointer; may refer to inline or client-supplied storage.
Definition tiffiop.h:394
TIFFCodeMethod tif_decoderow
Codec callback decoding a scanline.
Definition tiffiop.h:643
TIFFBoolMethod tif_setupencode
Codec setup callback run before preencode.
Definition tiffiop.h:632
TIFFDirectory tif_dir
Inline representation of the current image directory.
Definition tiffiop.h:572
TIFFBoolMethod tif_postencode
Codec callback completing buffered encoding.
Definition tiffiop.h:641
TIFFCodeMethod tif_encoderow
Codec callback encoding a scanline.
Definition tiffiop.h:645
TIFFVoidMethod tif_cleanup
Codec callback releasing codec-private state.
Definition tiffiop.h:661
uint8_t * tif_data
Codec-private storage; allocation and cleanup follow the selected codec.
Definition tiffiop.h:675
uint8_t * tif_rawcp
Borrowed current-position pointer into the raw buffer.
Definition tiffiop.h:692
TIFFBoolMethod tif_setupdecode
Codec setup callback run before predecode.
Definition tiffiop.h:628
uint8_t * tif_rawdata
Raw buffer; ownership/mapping follow TIFF_MYBUFFER and TIFF_BUFFERMMAP.
Definition tiffiop.h:681
tmsize_t tif_rawdatasize
Raw-buffer capacity in bytes; kept in step with tif_rawdata, including zero whenever tif_rawdata is N...
Definition tiffiop.h:686
TIFFCodeMethod tif_decodetile
Codec callback decoding tile data.
Definition tiffiop.h:651
int tif_mode
Current access mode using the O_* constants.
Definition tiffiop.h:400
Define the predictor prefix and method-chain contracts.
Declare private library state, callbacks, and implementation helpers.