LibTIFF 4.7.2
TIFF library public API and implementation reference
Loading...
Searching...
No Matches
tif_fax3.c
Go to the documentation of this file.
1/*
2 * Copyright (c) 1990-1997 Sam Leffler
3 * Copyright (c) 1991-1997 Silicon Graphics, Inc.
4 *
5 * Permission to use, copy, modify, distribute, and sell this software and
6 * its documentation for any purpose is hereby granted without fee, provided
7 * that (i) the above copyright notices and this permission notice appear in
8 * all copies of the software and related documentation, and (ii) the names of
9 * Sam Leffler and Silicon Graphics may not be used in any advertising or
10 * publicity relating to the software without the specific, prior written
11 * permission of Sam Leffler and Silicon Graphics.
12 *
13 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
14 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
15 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
16 *
17 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
18 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
19 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
20 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
21 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
22 * OF THIS SOFTWARE.
23 */
24
30#include "tiffiop.h"
31#ifdef CCITT_SUPPORT
32/*
33 * TIFF Library.
34 *
35 * CCITT Group 3 (T.4) and Group 4 (T.6) Compression Support.
36 *
37 * This file contains support for decoding and encoding TIFF
38 * compression algorithms 2, 3, 4, and 32771.
39 *
40 * Decoder support is derived, with permission, from the code
41 * in Frank Cringle's viewfax program;
42 * Copyright (C) 1990, 1995 Frank D. Cringle.
43 */
44#include "tif_fax3.h"
45#define G3CODES
46#include "t4.h"
47#include <stdio.h>
48
49#ifndef EOF_REACHED_COUNT_THRESHOLD
50/* Arbitrary threshold to avoid corrupted single-strip files with extremely
51 * large imageheight to cause apparently endless looping, such as in
52 * https://gitlab.com/libtiff/libtiff/-/issues/583
53 */
54#define EOF_REACHED_COUNT_THRESHOLD 8192
55#endif
56
57/*
58 * Compression+decompression state blocks are
59 * derived from this ``base state'' block.
60 */
96#define Fax3State(tif) ((Fax3BaseState *)(tif)->tif_data)
97
102typedef enum
103{
107 G3_2D
116typedef struct
117{
120
125 const unsigned char *bitmap;
127 uint32_t data;
129 int bit;
147 uint32_t *runs;
149 uint32_t nruns;
154 uint32_t *refruns;
159 uint32_t *curruns;
160
164 unsigned char *refline;
168 int k;
170 int maxk;
171
173 int line;
175#define DecoderState(tif) ((Fax3CodecState *)Fax3State(tif))
176#define EncoderState(tif) ((Fax3CodecState *)Fax3State(tif))
177
178#define is2DEncoding(sp) (sp->b.groupoptions & GROUP3OPT_2DENCODING)
179#define isAligned(p, t) ((((size_t)(p)) & (sizeof(t) - 1)) == 0)
180
181/*
182 * Group 3 and Group 4 Decoding.
183 */
184
185/*
186 * These macros glue the TIFF library state to
187 * the state expected by Frank's decoder.
188 */
189#define DECLARE_STATE(tif, sp, mod) \
190 static const char module[] = mod; \
191 Fax3CodecState *sp = DecoderState(tif); \
192 int a0; /* reference element */ \
193 int lastx = (int)sp->b.rowpixels; /* last element in row */ \
194 uint32_t BitAcc; /* bit accumulator */ \
195 int BitsAvail; /* # valid bits in BitAcc */ \
196 int RunLength; /* length of current run */ \
197 unsigned char *cp; /* next byte of input data */ \
198 unsigned char *ep; /* end of input data */ \
199 uint32_t *pa; /* place to stuff next run */ \
200 uint32_t *thisrun; /* current row's run array */ \
201 int EOLcnt; /* # EOL codes recognized */ \
202 const unsigned char *bitmap = sp->bitmap; /* input data bit reverser */ \
203 const TIFFFaxTabEnt *TabEnt
204
205#define DECLARE_STATE_2D(tif, sp, mod) \
206 DECLARE_STATE(tif, sp, mod); \
207 int b1; /* next change on prev line */ \
208 uint32_t \
209 *pb /* next run in reference line */ /* \
210 * Load any state that may be \
211 * changed during decoding. \
212 */
213#define CACHE_STATE(tif, sp) \
214 do \
215 { \
216 BitAcc = sp->data; \
217 BitsAvail = sp->bit; \
218 EOLcnt = sp->EOLcnt; \
219 cp = (unsigned char *)tif->tif_rawcp; \
220 ep = cp + tif->tif_rawcc; \
221 } while (0)
223 * Save state possibly changed during decoding.
224 */
225#define UNCACHE_STATE(tif, sp) \
226 do \
227 { \
228 sp->bit = BitsAvail; \
229 sp->data = BitAcc; \
230 sp->EOLcnt = EOLcnt; \
231 tif->tif_rawcc -= (tmsize_t)((uint8_t *)cp - tif->tif_rawcp); \
232 tif->tif_rawcp = (uint8_t *)cp; \
233 } while (0)
234
235/*
236 * Setup state for decoding a strip.
237 */
255static int Fax3PreDecode(TIFF *tif, uint16_t s)
256{
257 Fax3CodecState *sp = DecoderState(tif);
258
259 (void)s;
260 assert(sp != NULL);
261 sp->bit = 0; /* force initial read */
262 sp->data = 0;
263 sp->EOLcnt = 0; /* force initial scan for EOL */
264 sp->eofReachedCount = 0;
265 sp->eolReachedCount = 0;
267 /*
268 * Decoder assumes lsb-to-msb bit order. Note that we select
269 * this here rather than in Fax3SetupState so that viewers can
270 * hold the image open, fiddle with the FillOrder tag value,
271 * and then re-decode the image. Otherwise they'd need to close
272 * and open the image to get the state reset.
273 */
274 sp->bitmap =
276 sp->curruns = sp->runs;
277 if (sp->refruns)
278 { /* init reference line to white */
279 sp->refruns = sp->runs + sp->nruns;
280 sp->refruns[0] = (uint32_t)sp->b.rowpixels;
281 sp->refruns[1] = 0;
282 }
283 sp->line = 0;
284 return (1);
285}
286
287/*
288 * Routine for handling various errors/conditions.
289 * Note how they are "glued into the decoder" by
290 * overriding the definitions used by the decoder.
291 */
292
308static void Fax3Unexpected(const char *module, TIFF *tif, uint32_t line,
309 uint32_t a0)
310{
312 tif, module,
313 "Bad code word at line %" PRIu32 " of %s %" PRIu32 " (x %" PRIu32 ")",
314 line, isTiled(tif) ? "tile" : "strip",
315 (isTiled(tif) ? tif->tif_dir.td_curtile : tif->tif_dir.td_curstrip),
316 a0);
317}
318#define unexpected(table, a0) \
319 do \
320 { \
321 Fax3Unexpected(module, tif, (uint32_t)sp->line, (uint32_t)(a0)); \
322 ++sp->unexpectedReachedCount; \
323 } while (0)
324
340static void Fax3Extension(const char *module, TIFF *tif, uint32_t line,
341 uint32_t a0)
342{
344 tif, module,
345 "Uncompressed data (not supported) at line %" PRIu32 " of %s %" PRIu32
346 " (x %" PRIu32 ")",
347 line, isTiled(tif) ? "tile" : "strip",
349 a0);
350}
351#define extension(a0) \
352 Fax3Extension(module, tif, (uint32_t)sp->line, (uint32_t)(a0))
353
370static void Fax3BadLength(const char *module, TIFF *tif, uint32_t line,
371 uint32_t a0, uint32_t lastx)
372{
374 tif, module,
375 "%s at line %" PRIu32 " of %s %" PRIu32 " (got %" PRIu32
376 ", expected %" PRIu32 ")",
377 a0 < lastx ? "Premature EOL" : "Line length mismatch", line,
378 isTiled(tif) ? "tile" : "strip",
379 (isTiled(tif) ? tif->tif_dir.td_curtile : tif->tif_dir.td_curstrip), a0,
380 lastx);
381}
382#define badlength(a0, lastx) \
383 do \
384 { \
385 Fax3BadLength(module, tif, (uint32_t)sp->line, (uint32_t)(a0), \
386 (uint32_t)(lastx)); \
387 ++sp->eolReachedCount; \
388 } while (0)
389
405static void Fax3PrematureEOF(const char *module, TIFF *tif, uint32_t line,
406 uint32_t a0)
407{
409 tif, module,
410 "Premature EOF at line %" PRIu32 " of %s %" PRIu32 " (x %" PRIu32 ")",
411 line, isTiled(tif) ? "tile" : "strip",
413 a0);
414}
415#define prematureEOF(a0) \
416 do \
417 { \
418 Fax3PrematureEOF(module, tif, (uint32_t)sp->line, (uint32_t)(a0)); \
419 ++sp->eofReachedCount; \
420 } while (0)
421
437static void Fax3TryG3WithoutEOL(const char *module, TIFF *tif, uint32_t line,
438 uint32_t a0)
439{
441 tif, module,
442 "Try to decode (read) fax Group 3 data without EOL at line %" PRIu32
443 " of %s %" PRIu32 " (x %" PRIu32 "). Please check result",
444 line, isTiled(tif) ? "tile" : "strip",
445 (isTiled(tif) ? tif->tif_dir.td_curtile : tif->tif_dir.td_curstrip),
446 a0);
447}
448#define tryG3WithoutEOL(a0) \
449 do \
450 { \
451 Fax3TryG3WithoutEOL(module, tif, (uint32_t)sp->line, (uint32_t)(a0)); \
452 } while (0)
453
468static int CheckReachedCounters(TIFF *tif, const char *module,
469 Fax3CodecState *sp)
470{
472 {
473 TIFFErrorExtR(tif, module,
474 "End of file (EOF) has already been reached %d times "
475 "within that %s.",
476 sp->eofReachedCount, isTiled(tif) ? "tile" : "strip");
477 return (-1);
478 }
480 {
481 TIFFErrorExtR(tif, module,
482 "Bad line length (EOL) has already been reached %d times "
483 "within that %s",
484 sp->eolReachedCount, isTiled(tif) ? "tile" : "strip");
485 return (-1);
486 }
488 {
489 TIFFErrorExtR(tif, module,
490 "Bad code word (unexpected) has already been reached %d "
491 "times within that %s",
493 isTiled(tif) ? "tile" : "strip");
494 return (-1);
495 }
496 return (0);
497}
498
514static void Fax3ClearUnwritten(int has_buf, uint8_t *buf, tmsize_t occ)
515{
516 if (has_buf)
517 memset(buf, 0, (size_t)occ);
518}
519
550static int Fax3Decode1D(TIFF *tif, uint8_t *buf, tmsize_t occ, uint16_t s)
551{
552 DECLARE_STATE(tif, sp, "Fax3Decode1D");
553 (void)s;
554 /* buf is advanced as rows are decoded, so whether the caller supplied a
555 * buffer at all has to be remembered here. */
556 const int has_buf = (buf != NULL);
557 if (occ % sp->b.rowbytes)
558 {
559 Fax3ClearUnwritten(has_buf, buf, occ);
560 TIFFErrorExtR(tif, module, "Fractional scanlines cannot be read");
561 return (-1);
562 }
563 if (CheckReachedCounters(tif, module, sp))
564 {
565 Fax3ClearUnwritten(has_buf, buf, occ);
566 return (-1);
567 }
568RETRY_WITHOUT_EOL_1D:
569 CACHE_STATE(tif, sp);
570 thisrun = sp->curruns;
571 while (occ > 0)
572 {
573 a0 = 0;
574 RunLength = 0;
575 pa = thisrun;
576#ifdef FAX3_DEBUG
577 printf("\nBitAcc=%08" PRIX32 ", BitsAvail = %d\n", BitAcc, BitsAvail);
578 printf("-------------------- %" PRIu32 "\n", tif->tif_dir.td_row);
579 fflush(stdout);
580#endif
581 SYNC_EOL(EOF1D, RETRY_WITHOUT_EOL_1D);
582 EXPAND1D(EOF1Da);
583 (*sp->fill)(buf, thisrun, pa, (uint32_t)lastx);
584 buf += sp->b.rowbytes;
585 occ -= sp->b.rowbytes;
586 sp->line++;
587 continue;
588 EOF1D: /* premature EOF */
589 CLEANUP_RUNS();
590 EOF1Da: /* premature EOF */
591 Fax3ClearUnwritten(has_buf, buf, occ);
592 (*sp->fill)(buf, thisrun, pa, (uint32_t)lastx);
593 UNCACHE_STATE(tif, sp);
594 return (-1);
595 }
596 UNCACHE_STATE(tif, sp);
597 return (1);
598RUN_OVERFLOW: /* run array overflow, reported by the decoder macros */
599 Fax3ClearUnwritten(has_buf, buf, occ);
600 UNCACHE_STATE(tif, sp);
601 return (-1);
602}
603
604#define SWAP(t, a, b) \
605 { \
606 t x; \
607 x = (a); \
608 (a) = (b); \
609 (b) = x; \
610 }
611/*
612 * Decode the requested amount of G3 2D-encoded data.
613 */
644static int Fax3Decode2D(TIFF *tif, uint8_t *buf, tmsize_t occ, uint16_t s)
645{
646 DECLARE_STATE_2D(tif, sp, "Fax3Decode2D");
647 int is1D; /* current line is 1d/2d-encoded */
648 (void)s;
649 /* buf is advanced as rows are decoded, so whether the caller supplied a
650 * buffer at all has to be remembered here. */
651 const int has_buf = (buf != NULL);
652 if (occ % sp->b.rowbytes)
653 {
654 Fax3ClearUnwritten(has_buf, buf, occ);
655 TIFFErrorExtR(tif, module, "Fractional scanlines cannot be read");
656 return (-1);
657 }
658 if (CheckReachedCounters(tif, module, sp))
659 {
660 Fax3ClearUnwritten(has_buf, buf, occ);
661 return (-1);
662 }
663RETRY_WITHOUT_EOL_2D:
664 CACHE_STATE(tif, sp);
665 while (occ > 0)
666 {
667 a0 = 0;
668 RunLength = 0;
669 pa = thisrun = sp->curruns;
670#ifdef FAX3_DEBUG
671 printf("\nBitAcc=%08" PRIX32 ", BitsAvail = %d EOLcnt = %d", BitAcc,
672 BitsAvail, EOLcnt);
673#endif
674 SYNC_EOL(EOF2D, RETRY_WITHOUT_EOL_2D);
675 NeedBits8(1, EOF2D);
676 is1D = GetBits(1); /* 1D/2D-encoding tag bit */
677 ClrBits(1);
678#ifdef FAX3_DEBUG
679 printf(" %s\n-------------------- %" PRIu32 "\n", is1D ? "1D" : "2D",
680 tif->tif_dir.td_row);
681 fflush(stdout);
682#endif
683 pb = sp->refruns;
684 b1 = (int)*pb++;
685 if (is1D)
686 EXPAND1D(EOF2Da);
687 else
688 EXPAND2D(EOF2Da);
689 (*sp->fill)(buf, thisrun, pa, (uint32_t)lastx);
690 if (pa < thisrun + sp->nruns)
691 {
692 SETVALUE(0); /* imaginary change for reference */
693 }
694 SWAP(uint32_t *, sp->curruns, sp->refruns);
695 buf += sp->b.rowbytes;
696 occ -= sp->b.rowbytes;
697 sp->line++;
698 continue;
699 EOF2D: /* premature EOF */
700 CLEANUP_RUNS();
701 EOF2Da: /* premature EOF */
702 Fax3ClearUnwritten(has_buf, buf, occ);
703 (*sp->fill)(buf, thisrun, pa, (uint32_t)lastx);
704 UNCACHE_STATE(tif, sp);
705 return (-1);
706 }
707 UNCACHE_STATE(tif, sp);
708 return (1);
709RUN_OVERFLOW: /* run array overflow, reported by the decoder macros */
710 Fax3ClearUnwritten(has_buf, buf, occ);
711 UNCACHE_STATE(tif, sp);
712 return (-1);
714#undef SWAP
715
716#define FILL(n, cp) \
717 for (int32_t ifill = 0; ifill < (n); ++ifill) \
718 { \
719 (cp)[ifill] = 0xff; \
720 } \
721 (cp) += (n);
722
723#define ZERO(n, cp) \
724 for (int32_t izero = 0; izero < (n); ++izero) \
725 { \
726 (cp)[izero] = 0; \
727 } \
728 (cp) += (n);
729
730/*
731 * Bit-fill a row according to the white/black
732 * runs generated during G3/G4 decoding.
733 */
734void _TIFFFax3fillruns(unsigned char *buf, uint32_t *runs, uint32_t *erun,
735 uint32_t lastx)
736{
737 static const unsigned char _fillmasks[] = {0x00, 0x80, 0xc0, 0xe0, 0xf0,
738 0xf8, 0xfc, 0xfe, 0xff};
739 unsigned char *cp;
740 uint32_t x, bx, run;
741 int32_t n, nw;
742 int64_t *lp;
743
744 /* Zero the final partial byte before filling it. */
745 if (lastx & 7U)
746 buf[lastx >> 3] = 0;
747
748 if ((erun - runs) & 1)
749 *erun++ = 0;
750 x = 0;
751 for (; runs < erun; runs += 2)
752 {
753 run = runs[0];
754 if (x + run > lastx || run > lastx)
755 run = runs[0] = (uint32_t)(lastx - x);
756 if (run)
757 {
758 cp = buf + (x >> 3);
759 bx = x & 7;
760 if (run > 8 - bx)
761 {
762 if (bx)
763 { /* align to byte boundary */
764 *cp++ &= (unsigned char)(0xff << (8 - bx));
765 run -= 8 - bx;
766 }
767 if ((n = (int32_t)(run >> 3)) != 0)
768 { /* multiple bytes to fill */
769 if (((size_t)n / sizeof(int64_t)) > 1)
770 {
771 /*
772 * Align to int64_tword boundary and fill.
773 */
774 for (; n && !isAligned(cp, int64_t); n--)
775 *cp++ = 0x00;
776 lp = (int64_t *)cp;
777 nw = (int32_t)((size_t)n / sizeof(int64_t));
778 n -= (int32_t)((size_t)nw * sizeof(int64_t));
779 do
780 {
781 *lp++ = 0L;
782 } while (--nw);
783 cp = (unsigned char *)lp;
784 }
785 ZERO(n, cp);
786 run &= 7;
787 }
788 if (run)
789 cp[0] &= (unsigned char)(0xff >> run);
790 }
791 else
792 cp[0] &= (unsigned char)~(_fillmasks[run] >> bx);
793 x += runs[0];
794 }
795 run = runs[1];
796 if (x + run > lastx || run > lastx)
797 run = runs[1] = lastx - x;
798 if (run)
799 {
800 cp = buf + (x >> 3);
801 bx = x & 7;
802 if (run > 8 - bx)
803 {
804 if (bx)
805 { /* align to byte boundary */
806 *cp++ |= (unsigned char)(0xff >> bx);
807 run -= 8 - bx;
808 }
809 if ((n = (int32_t)(run >> 3)) != 0)
810 { /* multiple bytes to fill */
811 if (((size_t)n / sizeof(int64_t)) > 1)
812 {
813 /*
814 * Align to int64_t boundary and fill.
815 */
816 for (; n && !isAligned(cp, int64_t); n--)
817 *cp++ = 0xff;
818 lp = (int64_t *)cp;
819 nw = (int32_t)((size_t)n / sizeof(int64_t));
820 n -= (int32_t)((size_t)nw * sizeof(int64_t));
821 do
822 {
823 *lp++ = -1L;
824 } while (--nw);
825 cp = (unsigned char *)lp;
826 }
827 FILL(n, cp);
828 run &= 7;
829 }
830 /* Explicit 0xff masking to make icc -check=conversions happy */
831 if (run)
832 cp[0] = (unsigned char)((cp[0] | (0xff00 >> run)) & 0xff);
833 }
834 else
835 cp[0] |= (unsigned char)(_fillmasks[run] >> bx);
836 x += runs[1];
837 }
838 }
839 assert(x == lastx);
840}
841#undef ZERO
842#undef FILL
843
854static int Fax3FixupTags(TIFF *tif)
855{
856 (void)tif;
857 return (1);
858}
859
860/*
861 * Setup G3/G4-related compression/decompression state
862 * before data is processed. This routine is called once
863 * per image -- it sets up different state based on whether
864 * or not decoding or encoding is being done and whether
865 * 1D- or 2D-encoded data is involved.
866 */
885static int Fax3SetupState(TIFF *tif)
886{
887 static const char module[] = "Fax3SetupState";
888 TIFFDirectory *td = &tif->tif_dir;
889 Fax3BaseState *sp = Fax3State(tif);
890 int needsRefLine;
892 tmsize_t rowbytes;
893 uint32_t rowpixels;
894 uint32_t totalRuns;
895
896 if (td->td_bitspersample != 1)
897 {
898 TIFFErrorExtR(tif, module,
899 "Bits/sample must be 1 for Group 3/4 encoding/decoding");
900 return (0);
901 }
902 if (td->td_samplesperpixel != 1 &&
903 td->td_planarconfig != PLANARCONFIG_SEPARATE)
904 {
906 tif, module,
907 "Samples/pixel shall be 1 for Group 3/4 encoding/decoding, "
908 "or PlanarConfiguration must be set to Separate.");
909 return 0;
910 }
911 /*
912 * Calculate the scanline/tile widths.
913 */
914 if (isTiled(tif))
915 {
916 rowbytes = TIFFTileRowSize(tif);
917 rowpixels = td->td_tilewidth;
918 }
919 else
920 {
921 rowbytes = TIFFScanlineSize(tif);
922 rowpixels = td->td_imagewidth;
923 }
924 if ((int64_t)rowbytes < ((int64_t)rowpixels + 7) / 8)
925 {
926 TIFFErrorExtR(tif, module,
927 "Inconsistent number of bytes per row : rowbytes=%" PRId64
928 " rowpixels=%" PRIu32,
929 (int64_t)rowbytes, rowpixels);
930 return (0);
931 }
932 sp->rowbytes = rowbytes;
933 sp->rowpixels = rowpixels;
934 /*
935 * Allocate any additional space required for decoding/encoding.
936 */
937 needsRefLine = ((sp->groupoptions & GROUP3OPT_2DENCODING) ||
938 td->td_compression == COMPRESSION_CCITTFAX4);
939
940 /*
941 Assure that allocation computations do not overflow.
942
943 TIFFroundup and _TIFFMultiply32 return zero on integer overflow.
944 TIFFroundup does so silently, so it is reported here; _TIFFMultiply32
945 reports its own overflow, and its operands are non-zero here, so a
946 zero result needs no second message.
947 */
948 if (dsp->runs != NULL)
949 {
950 _TIFFfreeExt(tif, dsp->runs);
951 dsp->runs = (uint32_t *)NULL;
952 }
953 dsp->nruns = TIFFroundup_32(rowpixels + 1, 32);
954 if (dsp->nruns == 0)
955 {
956 TIFFErrorExtR(tif, module,
957 "Row pixels integer overflow (rowpixels %" PRIu32 ")",
958 rowpixels);
959 return (0);
960 }
961 if (needsRefLine)
962 {
963 dsp->nruns = _TIFFMultiply32(tif, dsp->nruns, 2, module);
964 if (dsp->nruns == 0)
965 return (0);
966 }
967 /* totalRuns is the size actually allocated and cleared below. */
968 totalRuns = _TIFFMultiply32(tif, dsp->nruns, 2, module);
969 if (totalRuns == 0)
970 return (0);
971 dsp->runs = (uint32_t *)_TIFFCheckMalloc(tif, totalRuns, sizeof(uint32_t),
972 "for Group 3/4 run arrays");
973 if (dsp->runs == NULL)
974 return (0);
975 memset(dsp->runs, 0, totalRuns * sizeof(uint32_t));
976 dsp->curruns = dsp->runs;
977 if (needsRefLine)
978 dsp->refruns = dsp->runs + dsp->nruns;
979 else
980 dsp->refruns = NULL;
981 if (td->td_compression == COMPRESSION_CCITTFAX3 && is2DEncoding(dsp))
982 { /* NB: default is 1D routine */
986 }
987
988 if (needsRefLine)
989 { /* 2d encoding */
990 Fax3CodecState *esp = EncoderState(tif);
991 /*
992 * 2d encoding requires a scanline
993 * buffer for the ``reference line''; the
994 * scanline against which delta encoding
995 * is referenced. The reference line must
996 * be initialized to be ``white'' (done elsewhere).
997 */
998 if (esp->refline != NULL)
999 {
1000 _TIFFfreeExt(tif, esp->refline);
1001 }
1002 esp->refline = (unsigned char *)_TIFFmallocExt(tif, rowbytes);
1003 if (esp->refline == NULL)
1004 {
1005 TIFFErrorExtR(tif, module, "No space for Group 3/4 reference line");
1006 return (0);
1007 }
1008 }
1009 else /* 1d encoding */
1010 EncoderState(tif)->refline = NULL;
1011
1012 return (1);
1013}
1014
1015/*
1016 * CCITT Group 3 FAX Encoding.
1017 */
1018
1019#define Fax3FlushBits(tif, sp) \
1020 { \
1021 if ((tif)->tif_rawcc >= (tif)->tif_rawdatasize) \
1022 { \
1023 if (!TIFFFlushData1(tif)) \
1024 return 0; \
1025 } \
1026 *(tif)->tif_rawcp++ = (uint8_t)(sp)->data; \
1027 (tif)->tif_rawcc++; \
1028 (sp)->data = 0, (sp)->bit = 8; \
1029 }
1030#define _FlushBits(tif) \
1031 { \
1032 if ((tif)->tif_rawcc >= (tif)->tif_rawdatasize) \
1033 { \
1034 if (!TIFFFlushData1(tif)) \
1035 return 0; \
1036 } \
1037 *(tif)->tif_rawcp++ = (uint8_t)data; \
1038 (tif)->tif_rawcc++; \
1039 data = 0, bit = 8; \
1040 }
1047static const int _msbmask[9] = {0x00, 0x01, 0x03, 0x07, 0x0f,
1048 0x1f, 0x3f, 0x7f, 0xff};
1049#define _PutBits(tif, bits, length) \
1050 { \
1051 while (length > bit) \
1052 { \
1053 data |= (int)((unsigned int)bits >> (length - bit)); \
1054 length -= bit; \
1055 _FlushBits(tif); \
1056 } \
1057 assert(length < 9); \
1058 data |= (int)(((unsigned int)bits & (unsigned int)_msbmask[length]) \
1059 << (unsigned int)(bit - length)); \
1060 bit -= length; \
1061 if (bit == 0) \
1062 _FlushBits(tif); \
1063 }
1064
1065/*
1066 * Write a variable-length bit-value to
1067 * the output stream. Values are
1068 * assumed to be at most 16 bits.
1069 */
1086static int Fax3PutBits(TIFF *tif, unsigned int bits, unsigned int length)
1087{
1088 Fax3CodecState *sp = EncoderState(tif);
1089 unsigned int bit = (unsigned int)sp->bit;
1090 int data = (int)sp->data;
1091
1092 _PutBits(tif, bits, length);
1093
1094 sp->data = (uint32_t)data;
1095 sp->bit = (int)bit;
1096 return 1;
1097}
1098
1100 * Write a code to the output stream.
1101 */
1102#define putcode(tif, te) Fax3PutBits(tif, (te)->code, (te)->length)
1103
1104#ifdef FAX3_DEBUG
1116#define DEBUG_COLOR(w) (tab == TIFFFaxWhiteCodes ? w "W" : w "B")
1128#define DEBUG_PRINT(what, len) \
1129 { \
1130 int t; \
1131 printf("%08" PRIX32 "/%-2d: %s%5d\t", data, bit, DEBUG_COLOR(what), \
1132 len); \
1133 for (t = length - 1; t >= 0; t--) \
1134 putchar(code & (1 << t) ? '1' : '0'); \
1135 putchar('\n'); \
1136 }
1137#endif
1138
1139/*
1140 * Write the sequence of codes that describes
1141 * the specified span of zero's or one's. The
1142 * appropriate table that holds the make-up and
1143 * terminating codes is supplied.
1144 */
1163static int putspan(TIFF *tif, int32_t span, const tableentry *tab)
1164{
1165 Fax3CodecState *sp = EncoderState(tif);
1166 unsigned int bit = (unsigned int)sp->bit;
1167 int data = (int)sp->data;
1168 unsigned int code, length;
1169
1170 while (span >= 2624)
1171 {
1172 const tableentry *te = &tab[63 + (2560 >> 6)];
1173 code = te->code;
1174 length = te->length;
1175#ifdef FAX3_DEBUG
1176 DEBUG_PRINT("MakeUp", te->runlen);
1177#endif
1178 _PutBits(tif, code, length);
1179 span -= te->runlen;
1180 }
1181 if (span >= 64)
1182 {
1183 const tableentry *te = &tab[63 + (span >> 6)];
1184 assert(te->runlen == 64 * (span >> 6));
1185 code = te->code;
1186 length = te->length;
1187#ifdef FAX3_DEBUG
1188 DEBUG_PRINT("MakeUp", te->runlen);
1189#endif
1190 _PutBits(tif, code, length);
1191 span -= te->runlen;
1192 }
1193 code = tab[span].code;
1194 length = tab[span].length;
1195#ifdef FAX3_DEBUG
1196 DEBUG_PRINT(" Term", tab[span].runlen);
1197#endif
1198 _PutBits(tif, code, length);
1199
1200 sp->data = (uint32_t)data;
1201 sp->bit = (int)bit;
1202
1203 return 1;
1204}
1205
1206/*
1207 * Write an EOL code to the output stream. The zero-fill
1208 * logic for byte-aligning encoded scanlines is handled
1209 * here. We also handle writing the tag bit for the next
1210 * scanline when doing 2d encoding.
1211 */
1224static int Fax3PutEOL(TIFF *tif)
1225{
1226 Fax3CodecState *sp = EncoderState(tif);
1227 unsigned int bit = (unsigned int)sp->bit;
1228 int data = (int)sp->data;
1229 unsigned int code, length, tparm;
1230
1231 if (sp->b.groupoptions & GROUP3OPT_FILLBITS)
1232 {
1233 /*
1234 * Force bit alignment so EOL will terminate on
1235 * a byte boundary. That is, force the bit alignment
1236 * to 16-12 = 4 before putting out the EOL code.
1237 */
1238 int align = 8 - 4;
1239 if (align != sp->bit)
1240 {
1241 if (align > sp->bit)
1242 align = sp->bit + (8 - align);
1243 else
1244 align = sp->bit - align;
1245 tparm = (unsigned int)align;
1246 _PutBits(tif, 0, tparm);
1247 }
1248 }
1249 code = EOL;
1250 length = 12;
1251 if (is2DEncoding(sp))
1252 {
1253 code = (code << 1) | (sp->tag == G3_1D);
1254 length++;
1255 }
1256 _PutBits(tif, code, length);
1257
1258 sp->data = (uint32_t)data;
1259 sp->bit = (int)bit;
1260
1261 return 1;
1262}
1263
1264/*
1265 * Reset encoding state at the start of a strip.
1266 */
1281static int Fax3PreEncode(TIFF *tif, uint16_t s)
1282{
1283 Fax3CodecState *sp = EncoderState(tif);
1284
1285 (void)s;
1286 assert(sp != NULL);
1287 sp->bit = 8;
1288 sp->data = 0;
1289 sp->tag = G3_1D;
1290 /*
1291 * This is necessary for Group 4; otherwise it isn't
1292 * needed because the first scanline of each strip ends
1293 * up being copied into the refline.
1294 */
1295 if (sp->refline)
1296 _TIFFmemset(sp->refline, 0x00, sp->b.rowbytes);
1297 if (is2DEncoding(sp))
1298 {
1299 float res = tif->tif_dir.td_yresolution;
1300 /*
1301 * The CCITT spec says that when doing 2d encoding, you
1302 * should only do it on K consecutive scanlines, where K
1303 * depends on the resolution of the image being encoded
1304 * (2 for <= 200 lpi, 4 for > 200 lpi). Since the directory
1305 * code initializes td_yresolution to 0, this code will
1306 * select a K of 2 unless the YResolution tag is set
1307 * appropriately. (Note also that we fudge a little here
1308 * and use 150 lpi to avoid problems with units conversion.)
1309 */
1311 res *= 2.54f; /* convert to inches */
1312 sp->maxk = (res > 150 ? 4 : 2);
1313 sp->k = sp->maxk - 1;
1314 }
1315 else
1316 sp->k = sp->maxk = 0;
1317 sp->line = 0;
1318 return (1);
1319}
1320
1327static const unsigned char zeroruns[256] = {
1328 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, /* 0x00 - 0x0f */
1329 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 0x10 - 0x1f */
1330 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0x20 - 0x2f */
1331 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0x30 - 0x3f */
1332 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40 - 0x4f */
1333 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x50 - 0x5f */
1334 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60 - 0x6f */
1335 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x70 - 0x7f */
1336 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x80 - 0x8f */
1337 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x90 - 0x9f */
1338 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xa0 - 0xaf */
1339 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xb0 - 0xbf */
1340 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xc0 - 0xcf */
1341 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xd0 - 0xdf */
1342 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xe0 - 0xef */
1343 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xf0 - 0xff */
1344};
1351static const unsigned char oneruns[256] = {
1352 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 - 0x0f */
1353 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x10 - 0x1f */
1354 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20 - 0x2f */
1355 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x30 - 0x3f */
1356 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x40 - 0x4f */
1357 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x50 - 0x5f */
1358 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x60 - 0x6f */
1359 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x70 - 0x7f */
1360 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x80 - 0x8f */
1361 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x90 - 0x9f */
1362 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0xa0 - 0xaf */
1363 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0xb0 - 0xbf */
1364 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0xc0 - 0xcf */
1365 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0xd0 - 0xdf */
1366 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 0xe0 - 0xef */
1367 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 7, 8, /* 0xf0 - 0xff */
1368};
1369
1370/*
1371 * Find a span of ones or zeros using the supplied
1372 * table. The ``base'' of the bit string is supplied
1373 * along with the start+end bit indices.
1374 */
1389static inline int32_t find0span(unsigned char *bp, int32_t bs, int32_t be)
1390{
1391 int32_t bits = be - bs;
1392 int32_t n, span;
1393
1394 bp += bs >> 3;
1395 /*
1396 * Check partial byte on lhs.
1397 */
1398 if (bits > 0 && (n = (bs & 7)) != 0)
1399 {
1400 span = zeroruns[(*bp << n) & 0xff];
1401 if (span > 8 - n) /* table value too generous */
1402 span = 8 - n;
1403 if (span > bits) /* constrain span to bit range */
1404 span = bits;
1405 if (n + span < 8) /* doesn't extend to edge of byte */
1406 return (span);
1407 bits -= span;
1408 bp++;
1409 }
1410 else
1411 span = 0;
1412 if (bits >= (int32_t)(2 * 8 * sizeof(int64_t)))
1413 {
1414 int64_t *lp;
1415 /*
1416 * Align to int64_t boundary and check int64_t words.
1417 */
1418 while (!isAligned(bp, int64_t))
1419 {
1420 if (*bp != 0x00)
1421 return (span + zeroruns[*bp]);
1422 span += 8;
1423 bits -= 8;
1424 bp++;
1425 }
1426 lp = (int64_t *)bp;
1427 while ((bits >= (int32_t)(size_t)(8 * sizeof(int64_t))) && (0 == *lp))
1428 {
1429 span += (int32_t)(size_t)(8 * sizeof(int64_t));
1430 bits -= (int32_t)(size_t)(8 * sizeof(int64_t));
1431 lp++;
1432 }
1433 bp = (unsigned char *)lp;
1434 }
1435 /*
1436 * Scan full bytes for all 0's.
1437 */
1438 while (bits >= 8)
1439 {
1440 if (*bp != 0x00) /* end of run */
1441 return (span + zeroruns[*bp]);
1442 span += 8;
1443 bits -= 8;
1444 bp++;
1445 }
1446 /*
1447 * Check partial byte on rhs.
1448 */
1449 if (bits > 0)
1450 {
1451 n = zeroruns[*bp];
1452 span += (n > bits ? bits : n);
1453 }
1454 return (span);
1455}
1456
1471static inline int32_t find1span(unsigned char *bp, int32_t bs, int32_t be)
1472{
1473 int32_t bits = be - bs;
1474 int32_t n, span;
1475
1476 bp += bs >> 3;
1477 /*
1478 * Check partial byte on lhs.
1479 */
1480 if (bits > 0 && (n = (bs & 7)) != 0)
1481 {
1482 span = oneruns[(*bp << n) & 0xff];
1483 if (span > 8 - n) /* table value too generous */
1484 span = 8 - n;
1485 if (span > bits) /* constrain span to bit range */
1486 span = bits;
1487 if (n + span < 8) /* doesn't extend to edge of byte */
1488 return (span);
1489 bits -= span;
1490 bp++;
1491 }
1492 else
1493 span = 0;
1494 if (bits >= (int32_t)(2 * 8 * sizeof(int64_t)))
1495 {
1496 int64_t *lp;
1497 /*
1498 * Align to int64_t boundary and check int64_t words.
1499 */
1500 while (!isAligned(bp, int64_t))
1501 {
1502 if (*bp != 0xff)
1503 return (span + oneruns[*bp]);
1504 span += 8;
1505 bits -= 8;
1506 bp++;
1507 }
1508 lp = (int64_t *)bp;
1509 while ((bits >= (int32_t)(size_t)(8 * sizeof(int64_t))) &&
1510 (~((uint64_t)0) == (uint64_t)*lp))
1511 {
1512 span += (int32_t)(size_t)(8 * sizeof(int64_t));
1513 bits -= (int32_t)(size_t)(8 * sizeof(int64_t));
1514 lp++;
1515 }
1516 bp = (unsigned char *)lp;
1517 }
1518 /*
1519 * Scan full bytes for all 1's.
1520 */
1521 while (bits >= 8)
1522 {
1523 if (*bp != 0xff) /* end of run */
1524 return (span + oneruns[*bp]);
1525 span += 8;
1526 bits -= 8;
1527 bp++;
1528 }
1529 /*
1530 * Check partial byte on rhs.
1531 */
1532 if (bits > 0)
1533 {
1534 n = oneruns[*bp];
1535 span += (n > bits ? bits : n);
1536 }
1537 return (span);
1538}
1539
1540/*
1541 * Return the offset of the next bit in the range
1542 * [bs..be] that is different from the specified
1543 * color. The end, be, is returned if no such bit
1544 * exists.
1545 */
1546#define finddiff(_cp, _bs, _be, _color) \
1547 (_bs + (_color ? find1span(_cp, _bs, _be) : find0span(_cp, _bs, _be)))
1548/*
1549 * Like finddiff, but also check the starting bit
1550 * against the end in case start > end.
1551 */
1552#define finddiff2(_cp, _bs, _be, _color) \
1553 (_bs < _be ? finddiff(_cp, _bs, _be, _color) : _be)
1554
1555/*
1556 * 1d-encode a row of pixels. The encoding is
1557 * a sequence of all-white or all-black spans
1558 * of pixels encoded with Huffman codes.
1559 */
1577static int Fax3Encode1DRow(TIFF *tif, unsigned char *bp, uint32_t bits)
1578{
1579 Fax3CodecState *sp = EncoderState(tif);
1580 int32_t span;
1581 uint32_t bs = 0;
1582
1583 for (;;)
1584 {
1585 span = find0span(bp, (int32_t)bs, (int32_t)bits); /* white span */
1586 if (!putspan(tif, span, TIFFFaxWhiteCodes))
1587 return 0;
1588 bs += (uint32_t)span;
1589 if (bs >= bits)
1590 break;
1591 span = find1span(bp, (int32_t)bs, (int32_t)bits); /* black span */
1592 if (!putspan(tif, span, TIFFFaxBlackCodes))
1593 return 0;
1594 bs += (uint32_t)span;
1595 if (bs >= bits)
1596 break;
1597 }
1599 {
1600 if (sp->bit != 8) /* byte-align */
1601 Fax3FlushBits(tif, sp);
1602 if ((sp->b.mode & FAXMODE_WORDALIGN) &&
1603 !isAligned(tif->tif_rawcp, uint16_t))
1604 Fax3FlushBits(tif, sp);
1605 }
1606 return (1);
1607}
1608
1615static const tableentry horizcode = {3, 0x1, 0}; /* 001 */
1622static const tableentry passcode = {4, 0x1, 0}; /* 0001 */
1629static const tableentry vcodes[7] = {
1630 {7, 0x03, 0}, /* 0000 011 */
1631 {6, 0x03, 0}, /* 0000 11 */
1632 {3, 0x03, 0}, /* 011 */
1633 {1, 0x1, 0}, /* 1 */
1634 {3, 0x2, 0}, /* 010 */
1635 {6, 0x02, 0}, /* 0000 10 */
1636 {7, 0x02, 0} /* 0000 010 */
1637};
1638
1639/*
1640 * 2d-encode a row of pixels. Consult the CCITT
1641 * documentation for the algorithm.
1642 */
1663static int Fax3Encode2DRow(TIFF *tif, unsigned char *bp, unsigned char *rp,
1664 uint32_t bits)
1665{
1666#define PIXEL(buf, ix) ((((buf)[(ix) >> 3]) >> (7 - ((ix) & 7))) & 1)
1667 uint32_t a0 = 0;
1668 uint32_t a1 = (PIXEL(bp, 0) != 0
1669 ? 0
1670 : (uint32_t)finddiff(bp, (int32_t)0, (int32_t)bits, 0));
1671 uint32_t b1 = (PIXEL(rp, 0) != 0
1672 ? 0
1673 : (uint32_t)finddiff(rp, (int32_t)0, (int32_t)bits, 0));
1674 uint32_t a2, b2;
1675
1676 for (;;)
1677 {
1678 b2 = (uint32_t)finddiff2(rp, (int32_t)b1, (int32_t)bits,
1679 (int32_t)PIXEL(rp, b1));
1680 if (b2 >= a1)
1681 {
1682 /* Naive computation triggers
1683 * -fsanitize=undefined,unsigned-integer-overflow */
1684 /* although it is correct unless the difference between both is < 31
1685 * bit */
1686 /* int32_t d = b1 - a1; */
1687 int32_t d = (b1 >= a1 && b1 - a1 <= 3U) ? (int32_t)(b1 - a1)
1688 : (b1 < a1 && a1 - b1 <= 3U) ? -(int32_t)(a1 - b1)
1689 : 0x7FFFFFFF;
1690 if (!(-3 <= d && d <= 3))
1691 { /* horizontal mode */
1692 a2 = (uint32_t)finddiff2(bp, (int32_t)a1, (int32_t)bits,
1693 (int32_t)PIXEL(bp, a1));
1694 if (!putcode(tif, &horizcode))
1695 return 0;
1696 if (a0 + a1 == 0 || PIXEL(bp, a0) == 0)
1697 {
1698 if (!putspan(tif, (int32_t)(a1 - a0), TIFFFaxWhiteCodes))
1699 return 0;
1700 if (!putspan(tif, (int32_t)(a2 - a1), TIFFFaxBlackCodes))
1701 return 0;
1702 }
1703 else
1704 {
1705 if (!putspan(tif, (int32_t)(a1 - a0), TIFFFaxBlackCodes))
1706 return 0;
1707 if (!putspan(tif, (int32_t)(a2 - a1), TIFFFaxWhiteCodes))
1708 return 0;
1709 }
1710 a0 = a2;
1711 }
1712 else
1713 { /* vertical mode */
1714 if (!putcode(tif, &vcodes[d + 3]))
1715 return 0;
1716 a0 = a1;
1717 }
1718 }
1719 else
1720 { /* pass mode */
1721 if (!putcode(tif, &passcode))
1722 return 0;
1723 a0 = b2;
1724 }
1725 if (a0 >= bits)
1726 break;
1727 a1 = (uint32_t)finddiff(bp, (int32_t)a0, (int32_t)bits,
1728 (int32_t)PIXEL(bp, a0));
1729 b1 = (uint32_t)finddiff(rp, (int32_t)a0, (int32_t)bits,
1730 (int32_t)!PIXEL(bp, a0));
1731 b1 = (uint32_t)finddiff(rp, (int32_t)b1, (int32_t)bits,
1732 (int32_t)PIXEL(bp, a0));
1733 }
1734 return (1);
1735#undef PIXEL
1736}
1737
1738/*
1739 * Encode a buffer of pixels.
1740 */
1759static int Fax3Encode(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
1760{
1761 static const char module[] = "Fax3Encode";
1762 Fax3CodecState *sp = EncoderState(tif);
1763 (void)s;
1764 if (cc % sp->b.rowbytes)
1765 {
1766 TIFFErrorExtR(tif, module, "Fractional scanlines cannot be written");
1767 return (0);
1768 }
1769 while (cc > 0)
1770 {
1771 if ((sp->b.mode & FAXMODE_NOEOL) == 0)
1772 {
1773 if (!Fax3PutEOL(tif))
1774 return 0;
1775 }
1776 if (is2DEncoding(sp))
1777 {
1778 if (sp->tag == G3_1D)
1779 {
1780 if (!Fax3Encode1DRow(tif, bp, sp->b.rowpixels))
1781 return (0);
1782 sp->tag = G3_2D;
1783 }
1784 else
1785 {
1786 if (!Fax3Encode2DRow(tif, bp, sp->refline, sp->b.rowpixels))
1787 return (0);
1788 sp->k--;
1789 }
1790 if (sp->k == 0)
1791 {
1792 sp->tag = G3_1D;
1793 sp->k = sp->maxk - 1;
1794 }
1795 else
1796 _TIFFmemcpy(sp->refline, bp, sp->b.rowbytes);
1797 }
1798 else
1799 {
1800 if (!Fax3Encode1DRow(tif, bp, sp->b.rowpixels))
1801 return (0);
1802 }
1803 bp += sp->b.rowbytes;
1804 cc -= sp->b.rowbytes;
1805 }
1806 return (1);
1807}
1808
1821static int Fax3PostEncode(TIFF *tif)
1822{
1823 Fax3CodecState *sp = EncoderState(tif);
1824
1825 if (sp->bit != 8)
1826 Fax3FlushBits(tif, sp);
1827 return (1);
1828}
1829
1843static int _Fax3Close(TIFF *tif)
1844{
1845 if ((Fax3State(tif)->mode & FAXMODE_NORTC) == 0 && tif->tif_rawcp)
1846 {
1847 Fax3CodecState *sp = EncoderState(tif);
1848 unsigned int code = EOL;
1849 unsigned int length = 12;
1850 int i;
1851
1852 if (is2DEncoding(sp))
1853 {
1854 code = (code << 1) | (sp->tag == G3_1D);
1855 length++;
1856 }
1857 for (i = 0; i < 6; i++)
1858 Fax3PutBits(tif, code, length);
1859 Fax3FlushBits(tif, sp);
1860 }
1861 return 1;
1862}
1863
1875static void Fax3Close(TIFF *tif) { _Fax3Close(tif); }
1876
1889static void Fax3Cleanup(TIFF *tif)
1890{
1891 Fax3CodecState *sp = DecoderState(tif);
1892
1893 assert(sp != 0);
1894
1897 tif->tif_tagmethods.printdir = sp->b.printdir;
1898
1899 if (sp->runs)
1900 _TIFFfreeExt(tif, sp->runs);
1901 if (sp->refline)
1902 _TIFFfreeExt(tif, sp->refline);
1903
1904 _TIFFfreeExt(tif, tif->tif_data);
1905 tif->tif_data = NULL;
1906
1910#define FIELD_BADFAXLINES (FIELD_CODEC + 0)
1911#define FIELD_CLEANFAXDATA (FIELD_CODEC + 1)
1912#define FIELD_BADFAXRUN (FIELD_CODEC + 2)
1913
1914#define FIELD_OPTIONS (FIELD_CODEC + 7)
1915
1923static const TIFFField faxFields[] = {
1925 FALSE, "FaxMode", NULL},
1927 FALSE, FALSE, "FaxFillFunc", NULL},
1929 FIELD_BADFAXLINES, TRUE, FALSE, "BadFaxLines", NULL},
1931 FIELD_CLEANFAXDATA, TRUE, FALSE, "CleanFaxData", NULL},
1933 FIELD_BADFAXRUN, TRUE, FALSE, "ConsecutiveBadFaxLines", NULL}};
1941static const TIFFField fax3Fields[] = {
1943 FIELD_OPTIONS, FALSE, FALSE, "Group3Options", NULL},
1944};
1952static const TIFFField fax4Fields[] = {
1954 FIELD_OPTIONS, FALSE, FALSE, "Group4Options", NULL},
1955};
1956
1980static int Fax3VSetField(TIFF *tif, uint32_t tag, va_list ap)
1981{
1982 Fax3BaseState *sp = Fax3State(tif);
1983 const TIFFField *fip;
1984
1985 assert(sp != 0);
1986 assert(sp->vsetparent != 0);
1987
1988 switch (tag)
1989 {
1990 case TIFFTAG_FAXMODE:
1991 sp->mode = (int)va_arg(ap, int);
1992 return 1; /* NB: pseudo tag */
1994 DecoderState(tif)->fill = va_arg(ap, TIFFFaxFillFunc);
1995 return 1; /* NB: pseudo tag */
1997 /* XXX: avoid reading options if compression mismatches. */
1999 sp->groupoptions = (uint32_t)va_arg(ap, uint32_t);
2000 break;
2002 /* XXX: avoid reading options if compression mismatches. */
2004 sp->groupoptions = (uint32_t)va_arg(ap, uint32_t);
2005 break;
2007 sp->badfaxlines = (uint32_t)va_arg(ap, uint32_t);
2008 break;
2010 sp->cleanfaxdata = (uint16_t)va_arg(ap, uint16_vap);
2011 break;
2013 sp->badfaxrun = (uint32_t)va_arg(ap, uint32_t);
2014 break;
2015 default:
2016 return (*sp->vsetparent)(tif, tag, ap);
2017 }
2018
2019 if ((fip = TIFFFieldWithTag(tif, tag)) != NULL)
2020 TIFFSetFieldBit(tif, fip->field_bit);
2021 else
2022 return 0;
2023
2025 return 1;
2026}
2027
2044static int Fax3VGetField(TIFF *tif, uint32_t tag, va_list ap)
2045{
2046 Fax3BaseState *sp = Fax3State(tif);
2047
2048 assert(sp != 0);
2049
2050 switch (tag)
2051 {
2052 case TIFFTAG_FAXMODE:
2053 *va_arg(ap, int *) = sp->mode;
2054 break;
2056 *va_arg(ap, TIFFFaxFillFunc *) = DecoderState(tif)->fill;
2057 break;
2060 *va_arg(ap, uint32_t *) = sp->groupoptions;
2061 break;
2063 *va_arg(ap, uint32_t *) = sp->badfaxlines;
2064 break;
2066 *va_arg(ap, uint16_t *) = sp->cleanfaxdata;
2067 break;
2069 *va_arg(ap, uint32_t *) = sp->badfaxrun;
2070 break;
2071 default:
2072 return (*sp->vgetparent)(tif, tag, ap);
2073 }
2074 return (1);
2075}
2076
2090static void Fax3PrintDir(TIFF *tif, FILE *fd, long flags)
2091{
2092 Fax3BaseState *sp = Fax3State(tif);
2093
2094 assert(sp != 0);
2095
2096 (void)flags;
2097 if (TIFFFieldSet(tif, FIELD_OPTIONS))
2098 {
2099 const char *sep = " ";
2101 {
2102 fprintf(fd, " Group 4 Options:");
2104 fprintf(fd, "%suncompressed data", sep);
2105 }
2106 else
2107 {
2108
2109 fprintf(fd, " Group 3 Options:");
2111 {
2112 fprintf(fd, "%s2-d encoding", sep);
2113 sep = "+";
2114 }
2116 {
2117 fprintf(fd, "%sEOL padding", sep);
2118 sep = "+";
2119 }
2121 fprintf(fd, "%suncompressed data", sep);
2122 }
2123 fprintf(fd, " (%" PRIu32 " = 0x%" PRIx32 ")\n", sp->groupoptions,
2124 sp->groupoptions);
2125 }
2127 {
2128 fprintf(fd, " Fax Data:");
2129 switch (sp->cleanfaxdata)
2130 {
2131 case CLEANFAXDATA_CLEAN:
2132 fprintf(fd, " clean");
2133 break;
2135 fprintf(fd, " receiver regenerated");
2136 break;
2138 fprintf(fd, " uncorrected errors");
2139 break;
2140 default:
2141 break;
2142 }
2143 fprintf(fd, " (%" PRIu16 " = 0x%" PRIx16 ")\n", sp->cleanfaxdata,
2144 sp->cleanfaxdata);
2145 }
2147 fprintf(fd, " Bad Fax Lines: %" PRIu32 "\n", sp->badfaxlines);
2148 if (TIFFFieldSet(tif, FIELD_BADFAXRUN))
2149 fprintf(fd, " Consecutive Bad Fax Lines: %" PRIu32 "\n",
2150 sp->badfaxrun);
2151 if (sp->printdir)
2152 (*sp->printdir)(tif, fd, flags);
2153}
2154
2165static uint64_t Fax3GetMaxCompressionRatio(TIFF *tif)
2166{
2167 (void)tif;
2168
2169 /* See README_for_libtiff_developpers.md for raw data used to estimate
2170 * the maximum compression rate. */
2171
2172 /* 1024x1024: 36 */
2173 /* 4096x4096: 100 */
2174 /* 16383x16383: 163 */
2175 /* 65536x65536: 200 */
2176 /* 200000x200000: 208 */
2177
2178 return 250;
2179}
2180
2197static int InitCCITTFax3(TIFF *tif)
2198{
2199 static const char module[] = "InitCCITTFax3";
2200 Fax3BaseState *sp;
2201
2202 /*
2203 * Merge codec-specific tag information.
2204 */
2206 {
2207 TIFFErrorExtR(tif, "InitCCITTFax3",
2208 "Merging common CCITT Fax codec-specific tags failed");
2209 return 0;
2210 }
2211
2212 /*
2213 * Allocate state block so tag methods have storage to record values.
2214 */
2215 tif->tif_data = (uint8_t *)_TIFFmallocExt(tif, sizeof(Fax3CodecState));
2216
2217 if (tif->tif_data == NULL)
2218 {
2219 TIFFErrorExtR(tif, module, "No space for state block");
2220 return (0);
2221 }
2222 _TIFFmemset(tif->tif_data, 0, sizeof(Fax3CodecState));
2223
2224 sp = Fax3State(tif);
2225 sp->rw_mode = tif->tif_mode;
2226
2227 /*
2228 * Override parent get/set field methods.
2229 */
2230 sp->vgetparent = tif->tif_tagmethods.vgetfield;
2231 tif->tif_tagmethods.vgetfield = Fax3VGetField; /* hook for codec tags */
2232 sp->vsetparent = tif->tif_tagmethods.vsetfield;
2233 tif->tif_tagmethods.vsetfield = Fax3VSetField; /* hook for codec tags */
2234 sp->printdir = tif->tif_tagmethods.printdir;
2235 tif->tif_tagmethods.printdir = Fax3PrintDir; /* hook for codec tags */
2236 sp->groupoptions = 0;
2237
2238 if (sp->rw_mode == O_RDONLY) /* FIXME: improve for in place update */
2239 tif->tif_flags |= TIFF_NOBITREV; /* decoder does bit reversal */
2240 DecoderState(tif)->runs = NULL;
2242 EncoderState(tif)->refline = NULL;
2243
2244 /*
2245 * Install codec methods.
2246 */
2259 tif->tif_close = Fax3Close;
2260 tif->tif_cleanup = Fax3Cleanup;
2262
2263 return (1);
2264}
2265
2266int TIFFInitCCITTFax3(TIFF *tif, int scheme)
2267{
2268 (void)scheme;
2269 if (InitCCITTFax3(tif))
2270 {
2271 /*
2272 * Merge codec-specific tag information.
2273 */
2275 {
2276 TIFFErrorExtR(tif, "TIFFInitCCITTFax3",
2277 "Merging CCITT Fax 3 codec-specific tags failed");
2278 return 0;
2279 }
2280
2281 /*
2282 * The default format is Class/F-style w/o RTC.
2283 */
2285 }
2286 else
2287 return 0;
2288}
2289
2290/*
2291 * CCITT Group 4 (T.6) Facsimile-compatible
2292 * Compression Scheme Support.
2293 */
2294
2295#define SWAP(t, a, b) \
2296 { \
2297 t x; \
2298 x = (a); \
2299 (a) = (b); \
2300 (b) = x; \
2301 }
2302/*
2303 * Decode the requested amount of G4-encoded data.
2304 */
2340static int Fax4Decode(TIFF *tif, uint8_t *buf, tmsize_t occ, uint16_t s)
2341{
2342 DECLARE_STATE_2D(tif, sp, "Fax4Decode");
2343 (void)s;
2344 /* buf is advanced as rows are decoded, so whether the caller supplied a
2345 * buffer at all has to be remembered here. */
2346 const int has_buf = (buf != NULL);
2347 if (occ % sp->b.rowbytes)
2348 {
2349 Fax3ClearUnwritten(has_buf, buf, occ);
2350 TIFFErrorExtR(tif, module, "Fractional scanlines cannot be read");
2351 return (-1);
2352 }
2353 if (CheckReachedCounters(tif, module, sp))
2354 {
2355 Fax3ClearUnwritten(has_buf, buf, occ);
2356 return (-1);
2357 }
2358 CACHE_STATE(tif, sp);
2359 int start = sp->line;
2360 while (occ > 0)
2361 {
2362 a0 = 0;
2363 RunLength = 0;
2364 pa = thisrun = sp->curruns;
2365 pb = sp->refruns;
2366 b1 = (int)*pb++;
2367#ifdef FAX3_DEBUG
2368 printf("\nBitAcc=%08" PRIX32 ", BitsAvail = %d\n", BitAcc, BitsAvail);
2369 printf("-------------------- %d\n", tif->tif_dir.td_row);
2370 fflush(stdout);
2371#endif
2372 EXPAND2D(EOFG4);
2373 if (EOLcnt)
2374 goto EOFG4;
2375 if (((lastx + 7) >> 3) > (int)occ) /* check for buffer overrun */
2376 {
2377 Fax3ClearUnwritten(has_buf, buf, occ);
2378 TIFFErrorExtR(tif, module,
2379 "Buffer overrun detected : %" TIFF_SSIZE_FORMAT
2380 " bytes available, %d bits needed",
2381 occ, lastx);
2382 return -1;
2383 }
2384 (*sp->fill)(buf, thisrun, pa, (uint32_t)lastx);
2385 SETVALUE(0); /* imaginary change for reference */
2386 SWAP(uint32_t *, sp->curruns, sp->refruns);
2387 buf += sp->b.rowbytes;
2388 occ -= sp->b.rowbytes;
2389 sp->line++;
2390 continue;
2391 EOFG4:
2392 NeedBits16(13, BADG4);
2393 BADG4:
2394#ifdef FAX3_DEBUG
2395 if (GetBits(13) != 0x1001)
2396 fputs("Bad EOFB\n", stderr);
2397#endif
2398 ClrBits(13);
2399 if (((lastx + 7) >> 3) > (int)occ) /* check for buffer overrun */
2400 {
2401 Fax3ClearUnwritten(has_buf, buf, occ);
2402 TIFFErrorExtR(tif, module,
2403 "Buffer overrun detected : %" TIFF_SSIZE_FORMAT
2404 " bytes available, %d bits needed",
2405 occ, lastx);
2406 return -1;
2407 }
2408 /* This path may return 1, so the caller is not told that the
2409 * remaining rows were never decoded. */
2410 Fax3ClearUnwritten(has_buf, buf, occ);
2411 (*sp->fill)(buf, thisrun, pa, (uint32_t)lastx);
2412 UNCACHE_STATE(tif, sp);
2413 return (sp->line != start
2414 ? 1
2415 : -1); /* don't error on badly-terminated strips */
2416 }
2417 UNCACHE_STATE(tif, sp);
2418 return (1);
2419RUN_OVERFLOW: /* run array overflow, reported by the decoder macros */
2420 Fax3ClearUnwritten(has_buf, buf, occ);
2421 UNCACHE_STATE(tif, sp);
2422 return (-1);
2423}
2424#undef SWAP
2425
2426/*
2427 * Encode the requested amount of data.
2428 */
2447static int Fax4Encode(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
2448{
2449 static const char module[] = "Fax4Encode";
2450 Fax3CodecState *sp = EncoderState(tif);
2451 (void)s;
2452 if (cc % sp->b.rowbytes)
2453 {
2454 TIFFErrorExtR(tif, module, "Fractional scanlines cannot be written");
2455 return (0);
2456 }
2457 while (cc > 0)
2458 {
2459 if (!Fax3Encode2DRow(tif, bp, sp->refline, sp->b.rowpixels))
2460 return (0);
2461 _TIFFmemcpy(sp->refline, bp, sp->b.rowbytes);
2462 bp += sp->b.rowbytes;
2463 cc -= sp->b.rowbytes;
2464 }
2465 return (1);
2466}
2467
2482static int Fax4PostEncode(TIFF *tif)
2483{
2484 Fax3CodecState *sp = EncoderState(tif);
2485
2486 /* terminate strip w/ EOFB */
2487 Fax3PutBits(tif, EOL, 12);
2488 Fax3PutBits(tif, EOL, 12);
2489 if (sp->bit != 8)
2490 Fax3FlushBits(tif, sp);
2491 return (1);
2492}
2493
2505static uint64_t Fax4GetMaxCompressionRatio(TIFF *tif)
2506{
2507 /* FAX4 can compress up to almost one byte per line, so the compression
2508 * ratio can be up to the tile/strip width.
2509 * See README_for_libtiff_developpers.md for raw data
2510 */
2511 return isTiled(tif) ? tif->tif_dir.td_tilewidth
2513}
2514
2515int TIFFInitCCITTFax4(TIFF *tif, int scheme)
2516{
2517 (void)scheme;
2518 if (InitCCITTFax3(tif))
2519 { /* reuse G3 support */
2520 /*
2521 * Merge codec-specific tag information.
2522 */
2524 {
2525 TIFFErrorExtR(tif, "TIFFInitCCITTFax4",
2526 "Merging CCITT Fax 4 codec-specific tags failed");
2527 return 0;
2528 }
2529
2538 /*
2539 * Suppress RTC at the end of each strip.
2540 */
2542 }
2543 else
2544 return (0);
2545}
2546
2547/*
2548 * CCITT Group 3 1-D Modified Huffman RLE Compression Support.
2549 * (Compression algorithms 2 and 32771)
2550 */
2551
2552/*
2553 * Decode the requested amount of RLE-encoded data.
2554 */
2586static int Fax3DecodeRLE(TIFF *tif, uint8_t *buf, tmsize_t occ, uint16_t s)
2587{
2588 DECLARE_STATE(tif, sp, "Fax3DecodeRLE");
2589 int mode = sp->b.mode;
2590 (void)s;
2591 /* buf is advanced as rows are decoded, so whether the caller supplied a
2592 * buffer at all has to be remembered here. */
2593 const int has_buf = (buf != NULL);
2594 if (occ % sp->b.rowbytes)
2595 {
2596 Fax3ClearUnwritten(has_buf, buf, occ);
2597 TIFFErrorExtR(tif, module, "Fractional scanlines cannot be read");
2598 return (-1);
2599 }
2600 if (CheckReachedCounters(tif, module, sp))
2601 {
2602 Fax3ClearUnwritten(has_buf, buf, occ);
2603 return (-1);
2604 }
2605 CACHE_STATE(tif, sp);
2606 thisrun = sp->curruns;
2607 while (occ > 0)
2608 {
2609 a0 = 0;
2610 RunLength = 0;
2611 pa = thisrun;
2612#ifdef FAX3_DEBUG
2613 printf("\nBitAcc=%08" PRIX32 ", BitsAvail = %d\n", BitAcc, BitsAvail);
2614 printf("-------------------- %" PRIu32 "\n", tif->tif_dir.td_row);
2615 fflush(stdout);
2616#endif
2617 EXPAND1D(EOFRLE);
2618 (*sp->fill)(buf, thisrun, pa, (uint32_t)lastx);
2619 /*
2620 * Cleanup at the end of the row.
2621 */
2622 if (mode & FAXMODE_BYTEALIGN)
2623 {
2624 int n = BitsAvail - (BitsAvail & ~7);
2625 ClrBits(n);
2626 }
2627 else if (mode & FAXMODE_WORDALIGN)
2628 {
2629 int n = BitsAvail - (BitsAvail & ~15);
2630 ClrBits(n);
2631 if (BitsAvail == 0 && !isAligned(cp, uint16_t))
2632 cp++;
2633 }
2634 buf += sp->b.rowbytes;
2635 occ -= sp->b.rowbytes;
2636 sp->line++;
2637 continue;
2638 EOFRLE: /* premature EOF */
2639 Fax3ClearUnwritten(has_buf, buf, occ);
2640 (*sp->fill)(buf, thisrun, pa, (uint32_t)lastx);
2641 UNCACHE_STATE(tif, sp);
2642 return (-1);
2643 }
2644 UNCACHE_STATE(tif, sp);
2645 return (1);
2646RUN_OVERFLOW: /* run array overflow, reported by the decoder macros */
2647 Fax3ClearUnwritten(has_buf, buf, occ);
2648 UNCACHE_STATE(tif, sp);
2649 return (-1);
2650}
2651
2662static uint64_t Fax3RLEGetMaxCompressionRatio(TIFF *tif)
2663{
2664 (void)tif;
2665 /* See README_for_libtiff_developpers.md for raw data used to estimate
2666 * the maximum compression rate. */
2667
2668 /* 1024x1024: 43 */
2669 /* 4096x4096: 128 */
2670 /* 16383x16383: 171 */
2671 /* 65536x65536: 205 */
2672 /* 200000x200000: 211 */
2673
2674 return 250;
2675}
2676
2677int TIFFInitCCITTRLE(TIFF *tif, int scheme)
2678{
2679 (void)scheme;
2680 if (InitCCITTFax3(tif))
2681 { /* reuse G3 support */
2686 /*
2687 * Suppress RTC+EOLs when encoding and byte-align data.
2688 */
2689 return TIFFSetField(tif, TIFFTAG_FAXMODE,
2691 }
2692 else
2693 return (0);
2694}
2695
2696int TIFFInitCCITTRLEW(TIFF *tif, int scheme)
2697{
2698 (void)scheme;
2699 if (InitCCITTFax3(tif))
2700 { /* reuse G3 support */
2705 /*
2706 * Suppress RTC+EOLs when encoding and word-align data.
2707 */
2708 return TIFFSetField(tif, TIFFTAG_FAXMODE,
2710 }
2711 else
2712 return (0);
2713}
2714#endif /* CCITT_SUPPORT */
2715
uint32_t _TIFFMultiply32(TIFF *tif, uint32_t first, uint32_t second, const char *where)
Multiply two unsigned values with an overflow check.
Definition tif_aux.c:40
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
void(* TIFFFaxFillFunc)(unsigned char *buf, uint32_t *runs, uint32_t *erun, uint32_t lastx)
Render decoded fax runs through an installed callback.
Definition tif_fax3.h:78
#define FIELD_BADFAXRUN
Reserve the consecutive-bad-lines codec field bit.
Definition tif_fax3.c:1909
static int putspan(TIFF *tif, int32_t span, const tableentry *tab)
Emit makeup and terminating Huffman codes for one fax run.
Definition tif_fax3.c:1160
static void Fax3Close(TIFF *tif)
Invoke fax return-to-control completion without a status channel.
Definition tif_fax3.c:1872
static int Fax3PreEncode(TIFF *tif, uint16_t s)
Reset fax encoding bits reference line and dimensional schedule.
Definition tif_fax3.c:1278
static int Fax3PreDecode(TIFF *tif, uint16_t s)
Reset fax bit state run pointers and recovery counters.
Definition tif_fax3.c:252
static int Fax3DecodeRLE(TIFF *tif, uint8_t *buf, tmsize_t occ, uint16_t s)
Decode complete aligned modified-Huffman fax rows.
Definition tif_fax3.c:2583
int TIFFInitCCITTRLE(TIFF *tif, int scheme)
Install CCITTRLE fax callbacks and default mode.
Definition tif_fax3.c:2674
static int Fax4Encode(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
Encode complete Group4 rows relative to the preceding row.
Definition tif_fax3.c:2444
static const TIFFField fax3Fields[]
Define Group3 options metadata.
Definition tif_fax3.c:1938
static uint64_t Fax3RLEGetMaxCompressionRatio(TIFF *tif)
Report the fax expansion allocation heuristic.
Definition tif_fax3.c:2659
#define EncoderState(tif)
Borrow the complete fax encoder state.
Definition tif_fax3.c:176
static int Fax4Decode(TIFF *tif, uint8_t *buf, tmsize_t occ, uint16_t s)
Decode complete Group4 two-dimensional fax rows.
Definition tif_fax3.c:2337
#define DECLARE_STATE_2D(tif, sp, mod)
Declare local two-dimensional decode and reference state.
Definition tif_fax3.c:205
static int Fax3VGetField(TIFF *tif, uint32_t tag, va_list ap)
Retrieve fax mode callback or persistent fax values.
Definition tif_fax3.c:2041
#define SWAP(t, a, b)
Exchange current and reference run-array pointers.
Definition tif_fax3.c:601
static int Fax3PutBits(TIFF *tif, unsigned int bits, unsigned int length)
Append up to sixteen significant fax code bits.
Definition tif_fax3.c:1083
int TIFFInitCCITTRLEW(TIFF *tif, int scheme)
Install CCITTRLEW fax callbacks and default mode.
Definition tif_fax3.c:2693
static void Fax3TryG3WithoutEOL(const char *module, TIFF *tif, uint32_t line, uint32_t a0)
Warn that Group3 recovery will retry without EOL.
Definition tif_fax3.c:434
static int Fax3Decode1D(TIFF *tif, uint8_t *buf, tmsize_t occ, uint16_t s)
Decode complete Group3 one-dimensional fax rows.
Definition tif_fax3.c:547
#define CACHE_STATE(tif, sp)
Load codec and raw cursor state into decode locals.
Definition tif_fax3.c:210
static void Fax3PrintDir(TIFF *tif, FILE *fd, long flags)
Print present fax values then chain the saved directory printer.
Definition tif_fax3.c:2087
#define ClrBits(n)
Consume low bits from the local accumulator.
Definition tif_fax3.h:283
#define EXPAND2D(eoflab)
Expand a two-dimensional row relative to reference runs.
Definition tif_fax3.h:573
#define EOL
Represent the twelve-bit EOL code value.
Definition t4.h:52
static void Fax3BadLength(const char *module, TIFF *tif, uint32_t line, uint32_t a0, uint32_t lastx)
Warn about a fax row-length mismatch.
Definition tif_fax3.c:367
#define is2DEncoding(sp)
Test Group3 two-dimensional mode.
Definition tif_fax3.c:178
#define DecoderState(tif)
Borrow the complete fax decoder state.
Definition tif_fax3.c:175
const tableentry TIFFFaxWhiteCodes[]
Describe white CCITT terminating and makeup run codes.
#define FIELD_OPTIONS
Reserve the Group3/4 options codec field bit.
Definition tif_fax3.c:1911
#define finddiff(_cp, _bs, _be, _color)
Find the next pixel differing from the selected colour.
Definition tif_fax3.c:1543
static int Fax3VSetField(TIFF *tif, uint32_t tag, va_list ap)
Assign fax pseudo-tags or persistent fax metadata.
Definition tif_fax3.c:1977
static const unsigned char zeroruns[256]
Count leading zero bits in each byte.
Definition tif_fax3.c:1324
static int Fax3SetupState(TIFF *tif)
Validate bilevel geometry and allocate fax run/reference storage.
Definition tif_fax3.c:882
static const int _msbmask[9]
Mask the requested low bit count for encoder code packing.
Definition tif_fax3.c:1044
static void Fax3PrematureEOF(const char *module, TIFF *tif, uint32_t line, uint32_t a0)
Warn about premature fax input exhaustion.
Definition tif_fax3.c:402
#define FILL(n, cp)
Set complete black output bytes and advance the pointer.
Definition tif_fax3.c:713
static const TIFFField fax4Fields[]
Define Group4 options metadata.
Definition tif_fax3.c:1949
#define putcode(tif, te)
Emit one Huffman table entry.
Definition tif_fax3.c:1099
#define ZERO(n, cp)
Clear complete white output bytes and advance the pointer.
Definition tif_fax3.c:720
static void Fax3Extension(const char *module, TIFF *tif, uint32_t line, uint32_t a0)
Diagnose unsupported fax uncompressed extension data.
Definition tif_fax3.c:337
static int Fax3FixupTags(TIFF *tif)
Accept fax tag fixup without changes.
Definition tif_fax3.c:851
#define EOF_REACHED_COUNT_THRESHOLD
Limit repeated fax recovery conditions per strile.
Definition tif_fax3.c:54
#define Fax3FlushBits(tif, sp)
Append a partial code byte and flush raw output when full.
Definition tif_fax3.c:1016
static void Fax3ClearUnwritten(int has_buf, uint8_t *buf, tmsize_t occ)
Zero the part of the caller buffer the decoder will not write.
Definition tif_fax3.c:511
#define isAligned(p, t)
Test a pointer against a type-sized alignment.
Definition tif_fax3.c:179
static const TIFFField faxFields[]
Define common fax metadata and pseudo-tags.
Definition tif_fax3.c:1920
static const tableentry passcode
Encode the Group4 pass mode prefix.
Definition tif_fax3.c:1619
static int32_t find1span(unsigned char *bp, int32_t bs, int32_t be)
Measure the leading one bit run in a bounded packed row.
Definition tif_fax3.c:1468
#define SYNC_EOL(eoflab, retrywithouteol)
Synchronise EOL or retry configured no-EOL recovery.
Definition tif_fax3.h:403
Ttag
Select the next Group3 encoded row dimensionality.
Definition tif_fax3.c:103
static int Fax3Encode1DRow(TIFF *tif, unsigned char *bp, uint32_t bits)
Encode alternating white and black runs for one bilevel row.
Definition tif_fax3.c:1574
static uint64_t Fax4GetMaxCompressionRatio(TIFF *tif)
Report the fax expansion allocation heuristic.
Definition tif_fax3.c:2502
#define _PutBits(tif, bits, length)
Append local code bits across partial-byte boundaries.
Definition tif_fax3.c:1046
static int _Fax3Close(TIFF *tif)
Append an optional six-EOL fax return-to-control sequence.
Definition tif_fax3.c:1840
#define FIELD_BADFAXLINES
Reserve the BadFaxLines codec field bit.
Definition tif_fax3.c:1907
#define DECLARE_STATE(tif, sp, mod)
Declare cached local one-dimensional decode state.
Definition tif_fax3.c:189
static int Fax3Encode(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
Encode complete Group3 or aligned RLE rows.
Definition tif_fax3.c:1756
#define CLEANUP_RUNS()
Repair the current row run total to the requested width.
Definition tif_fax3.h:443
#define EXPAND1D(eoflab)
Expand a one-dimensional Huffman row into runs.
Definition tif_fax3.h:481
void _TIFFFax3fillruns(unsigned char *buf, uint32_t *runs, uint32_t *erun, uint32_t lastx)
Render alternating white/black fax runs into an MSB-first row.
Definition tif_fax3.c:731
static void Fax3Cleanup(TIFF *tif)
Restore fax tag/print methods and release run/reference state.
Definition tif_fax3.c:1886
static const tableentry vcodes[7]
Encode Group4 vertical offsets minus three through three.
Definition tif_fax3.c:1626
#define NeedBits16(n, eoflab)
Load up to sixteen bits or branch to EOF.
Definition tif_fax3.h:251
static void Fax3Unexpected(const char *module, TIFF *tif, uint32_t line, uint32_t a0)
Diagnose an invalid fax code word.
Definition tif_fax3.c:305
static int Fax3PutEOL(TIFF *tif)
Append Group3 EOL padding and optional dimensional tag.
Definition tif_fax3.c:1221
static uint64_t Fax3GetMaxCompressionRatio(TIFF *tif)
Report the fax expansion allocation heuristic.
Definition tif_fax3.c:2162
#define SETVALUE(x)
Append a checked decoded run and reset its local length.
Definition tif_fax3.h:376
static int Fax3PostEncode(TIFF *tif)
Pad and buffer the final partial fax code byte.
Definition tif_fax3.c:1818
static const tableentry horizcode
Encode the Group4 horizontal mode prefix.
Definition tif_fax3.c:1612
#define UNCACHE_STATE(tif, sp)
Commit local bit state and consumed raw bytes.
Definition tif_fax3.c:222
static int Fax3Encode2DRow(TIFF *tif, unsigned char *bp, unsigned char *rp, uint32_t bits)
Encode one bilevel row relative to its reference row.
Definition tif_fax3.c:1660
static int InitCCITTFax3(TIFF *tif)
Allocate shared fax state and install tag and transfer methods.
Definition tif_fax3.c:2194
static int CheckReachedCounters(TIFF *tif, const char *module, Fax3CodecState *sp)
Stop fax recovery after repeated EOF EOL or bad-code conditions.
Definition tif_fax3.c:465
#define GetBits(n)
Inspect low bits of the local accumulator.
Definition tif_fax3.h:282
#define PIXEL(buf, ix)
Read one MSB-first packed pixel bit.
#define Fax3State(tif)
Borrow the shared fax state prefix.
Definition tif_fax3.c:96
#define NeedBits8(n, eoflab)
Load bits or branch to the caller EOF label.
Definition tif_fax3.h:231
const tableentry TIFFFaxBlackCodes[]
Describe black CCITT terminating and makeup run codes.
#define FIELD_CLEANFAXDATA
Reserve the CleanFaxData codec field bit.
Definition tif_fax3.c:1908
static const unsigned char oneruns[256]
Count leading one bits in each byte.
Definition tif_fax3.c:1348
int TIFFInitCCITTFax4(TIFF *tif, int scheme)
Install CCITTFax4 fax callbacks and default mode.
Definition tif_fax3.c:2512
static int Fax3Decode2D(TIFF *tif, uint8_t *buf, tmsize_t occ, uint16_t s)
Decode complete Group3 mixed-dimensional fax rows.
Definition tif_fax3.c:641
static int32_t find0span(unsigned char *bp, int32_t bs, int32_t be)
Measure the leading zero bit run in a bounded packed row.
Definition tif_fax3.c:1386
static int Fax4PostEncode(TIFF *tif)
Append Group4 EOFB and align the final byte.
Definition tif_fax3.c:2479
#define finddiff2(_cp, _bs, _be, _color)
Find a change while bounding an already exhausted start.
Definition tif_fax3.c:1549
int TIFFInitCCITTFax3(TIFF *tif, int scheme)
Install CCITTFax3 fax callbacks and default mode.
Definition tif_fax3.c:2263
@ G3_2D
Encode the next row relative to its predecessor.
Definition tif_fax3.c:107
@ G3_1D
Encode the next row independently.
Definition tif_fax3.c:105
int _TIFFMergeFields(TIFF *tif, const TIFFField info[], uint32_t n)
Merge borrowed field definitions into the lookup table.
#define TIFFFieldSet(tif, field)
Test a directory presence bit.
Definition tif_dir.h:662
#define FIELD_PSEUDO
Share bit zero with FIELD_IGNORE for pseudo-tags.
Definition tif_dir.h:620
#define TIFFSetFieldBit(tif, field)
Set a directory presence bit.
Definition tif_dir.h:675
@ TIFF_SETGET_INT
Promoted int scalar representation.
Definition tif_dir.h:762
@ TIFF_SETGET_UINT16
Unsigned 16-bit scalar storage.
Definition tif_dir.h:744
@ TIFF_SETGET_OTHER
Tag-specific calling convention outside the regular encodings.
Definition tif_dir.h:838
@ TIFF_SETGET_UINT32
Unsigned 32-bit scalar storage.
Definition tif_dir.h:748
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
void * _TIFFCheckMalloc(TIFF *tif, tmsize_t nmemb, tmsize_t elem_size, const char *what)
Allocate a checked array with an allocation-failure diagnostic.
Definition tif_aux.c:274
#define isTiled(tif)
Test whether a handle uses tiled storage.
Definition tiffiop.h:833
#define TIFFroundup_32(x, y)
Round a 32-bit value up to a multiple using the guarded quotient.
Definition tiffiop.h:1102
#define TRUE
Represent the legacy internal true value.
Definition tiffiop.h:131
#define FALSE
Represent the legacy internal false value.
Definition tiffiop.h:136
#define TIFF_DIRTYDIRECT
Mark a current directory that needs writing.
Definition tiffiop.h:421
#define TIFF_NOBITREV
Suppress automatic bit reversal.
Definition tiffiop.h:446
#define TIFFArrayCount(a)
Compute the element count of an actual array.
Definition tiffiop.h:1239
const unsigned char * TIFFGetBitRevTable(int reversed)
Select the immutable byte reversal or identity lookup table.
Definition tif_swab.c:325
#define TIFF_ANY
Match any data type when searching for a field descriptor.
Definition tiffio.h:1289
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
const TIFFField * TIFFFieldWithTag(TIFF *tif, uint32_t tag)
Find a registered field by tag number.
tmsize_t TIFFScanlineSize(TIFF *tif)
Compute the current scanline I/O byte estimate.
Definition tif_strip.c:383
tmsize_t TIFFTileRowSize(TIFF *tif)
Compute the packed byte count of one tile row.
Definition tif_tile.c:276
void _TIFFmemset(void *p, int v, tmsize_t c)
Fill a byte range with one repeated byte.
Definition tif_unix.c:495
void _TIFFmemcpy(void *d, const void *s, tmsize_t c)
Copy a non-overlapping byte range.
Definition tif_unix.c:497
#define FAXMODE_NORTC
No RTC at end of data.
Definition tiff.h:1534
#define TIFFTAG_FAXFILLFUNC
Pseudo-tag: G3/G4 fill function.
Definition tiff.h:1560
#define FAXMODE_BYTEALIGN
Byte align row.
Definition tiff.h:1538
#define FAXMODE_NOEOL
No EOL code at end of row.
Definition tiff.h:1536
#define TIFFTAG_FAXMODE
Pseudo-tag: Group 3/4 format control.
Definition tiff.h:1530
#define FAXMODE_CLASSF
TIFF Class F.
Definition tiff.h:1542
#define FAXMODE_WORDALIGN
Word align row.
Definition tiff.h:1540
int(* TIFFVGetMethod)(TIFF *tif, uint32_t tag, va_list ap)
Implement a handle's variadic tag getter.
Definition tiffio.h:1540
int TIFFSetField(TIFF *tif, uint32_t tag,...)
Set a tag value in the current in-memory directory.
Definition tif_dir.c:1627
void(* TIFFPrintMethod)(TIFF *tif, FILE *fd, long flags)
Append extension-specific directory information to a stream.
Definition tiffio.h:1561
int(* TIFFVSetMethod)(TIFF *tif, uint32_t tag, va_list ap)
Implement a handle's variadic tag setter.
Definition tiffio.h:1521
#define PLANARCONFIG_SEPARATE
Separate planes of data.
Definition tiff.h:474
#define COMPRESSION_CCITTFAX3
CCITT Group 3 fax encoding.
Definition tiff.h:306
#define RESUNIT_CENTIMETER
Resolution measured in pixels per centimetre.
Definition tiff.h:522
#define GROUP3OPT_2DENCODING
2-dimensional coding.
Definition tiff.h:504
#define TIFFTAG_GROUP3OPTIONS
TIFF tag: 32 flag bits.
Definition tiff.h:500
#define TIFFTAG_GROUP4OPTIONS
TIFF tag: 32 flag bits.
Definition tiff.h:510
#define CLEANFAXDATA_REGENERATED
Receiver regenerated lines.
Definition tiff.h:578
#define TIFFTAG_CONSECUTIVEBADFAXLINES
TIFF tag: Max consecutive bad lines.
Definition tiff.h:582
#define GROUP3OPT_UNCOMPRESSED
Data not compressed.
Definition tiff.h:506
#define FILLORDER_LSB2MSB
Least significant -> most.
Definition tiff.h:426
#define CLEANFAXDATA_CLEAN
No errors detected.
Definition tiff.h:576
#define CLEANFAXDATA_UNCLEAN
Uncorrected errors exist.
Definition tiff.h:580
#define GROUP3OPT_FILLBITS
Fill to byte boundary.
Definition tiff.h:508
#define TIFFTAG_CLEANFAXDATA
TIFF tag: Regenerated line info.
Definition tiff.h:574
#define TIFFTAG_BADFAXLINES
TIFF tag: Lines w/ wrong pixel count.
Definition tiff.h:572
#define COMPRESSION_CCITTFAX4
CCITT Group 4 fax encoding.
Definition tiff.h:310
#define GROUP4OPT_UNCOMPRESSED
Data not compressed.
Definition tiff.h:514
int uint16_vap
Represent a uint16_t value after default variadic argument promotion.
Definition tiff.h:159
TIFF_SSIZE_T tmsize_t
Represent a signed memory or I/O size in bytes.
Definition tiffio.h:89
@ TIFF_SHORT
Unsigned 16-bit integer.
Definition tiff.h:237
@ TIFF_LONG
Unsigned 32-bit integer.
Definition tiff.h:239
Prefix fax state with geometry options and saved method chains.
Definition tif_fax3.c:70
uint16_t cleanfaxdata
Cached CleanFaxData tag value.
Definition tif_fax3.c:81
uint32_t badfaxrun
Cached consecutive bad fax line count.
Definition tif_fax3.c:83
int mode
FAXMODE control bits.
Definition tif_fax3.c:74
TIFFPrintMethod printdir
Borrowed optional parent printer restored during cleanup.
Definition tif_fax3.c:94
uint32_t rowpixels
Pixels per scanline/tile row, within signed decoder limits.
Definition tif_fax3.c:78
uint32_t badfaxlines
Cached total bad fax line count.
Definition tif_fax3.c:85
TIFFVSetMethod vsetparent
Borrowed parent tag setter restored during cleanup.
Definition tif_fax3.c:92
TIFFVGetMethod vgetparent
Borrowed parent tag getter restored during cleanup.
Definition tif_fax3.c:90
int rw_mode
Open mode saved during codec initialisation.
Definition tif_fax3.c:72
uint32_t groupoptions
Cached Group3/4 options for the selected scheme.
Definition tif_fax3.c:87
tmsize_t rowbytes
Positive decoded scanline/tile-row byte extent after setup.
Definition tif_fax3.c:76
Own fax run/reference buffers and bit-stream progress.
Definition tif_fax3.c:117
uint32_t data
Cached decoder bit accumulator or encoder partial byte.
Definition tif_fax3.c:127
int line
Current line count within the strile.
Definition tif_fax3.c:173
int bit
Valid input bits or remaining output bit positions.
Definition tif_fax3.c:129
Fax3BaseState b
Shared base prefix, first in codec state.
Definition tif_fax3.c:119
int unexpectedReachedCount
Repeated invalid-code recovery count in the current strile.
Definition tif_fax3.c:137
int maxk
Resolution-derived maximum dimensional schedule interval.
Definition tif_fax3.c:170
TIFFFaxFillFunc fill
Borrowed synchronous run renderer; application code/context must remain live.
Definition tif_fax3.c:142
int eofReachedCount
Repeated EOF recovery count in the current strile.
Definition tif_fax3.c:133
Ttag tag
Next Group3 row dimensionality.
Definition tif_fax3.c:162
int EOLcnt
Recognised end-of-line count/state.
Definition tif_fax3.c:131
int k
Remaining two-dimensional rows before another one-dimensional row.
Definition tif_fax3.c:168
unsigned char * refline
Owned Ext packed reference row used by 2D encoding.
Definition tif_fax3.c:164
uint32_t * runs
Owned Ext allocation holding current and optional reference run arrays.
Definition tif_fax3.c:147
const unsigned char * bitmap
Borrowed immutable byte reversal table selected for current FillOrder.
Definition tif_fax3.c:125
uint32_t * refruns
Borrowed reference partition within runs, or NULL for one-dimensional state.
Definition tif_fax3.c:154
uint32_t * curruns
Borrowed current partition within runs; swapped with reference in 2D decoding.
Definition tif_fax3.c:159
int eolReachedCount
Repeated bad-length recovery count in the current strile.
Definition tif_fax3.c:135
uint32_t nruns
Capacity of each run-array partition in uint32_t entries.
Definition tif_fax3.c:149
Store the current directory values and image traversal state.
Definition tif_dir.h:143
uint16_t td_fillorder
FILLORDER_* bit order within file bytes.
Definition tif_dir.h:178
uint32_t td_imagewidth
Image width in pixels.
Definition tif_dir.h:154
uint16_t td_compression
COMPRESSION_* codec identifier.
Definition tif_dir.h:172
uint32_t td_tilewidth
Tile width in pixels.
Definition tif_dir.h:160
float td_yresolution
Vertical pixels per resolution unit.
Definition tif_dir.h:196
uint32_t td_row
Current scanline index; UINT32_MAX before traversal starts.
Definition tif_dir.h:240
uint16_t td_resolutionunit
RESUNIT_* unit for resolution and position values.
Definition tif_dir.h:198
uint32_t td_curtile
Current tile index, or NOTILE.
Definition tif_dir.h:256
uint32_t td_curstrip
Current strip index, or NOSTRIP.
Definition tif_dir.h:242
TIFFVGetMethod vgetfield
Variadic tag-query implementation for the handle.
Definition tiffio.h:1577
TIFFVSetMethod vsetfield
Variadic tag-setting implementation for the handle.
Definition tiffio.h:1575
TIFFPrintMethod printdir
Optional codec/extension directory-print callback.
Definition tiffio.h:1579
Describe a field's file type and internal argument contract.
Definition tif_dir.h:993
unsigned short field_bit
FIELD_* presence index; FIELD_CUSTOM shares storage through the custom list.
Definition tif_dir.h:1023
Describe one CCITT Huffman run-length code.
Definition t4.h:43
unsigned short code
Right-adjusted code bits.
Definition t4.h:47
unsigned short length
Code width in bits.
Definition t4.h:45
short runlen
Run length in pixels or negative G3CODE sentinel.
Definition t4.h:49
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
TIFFTagMethods tif_tagmethods
Inline table of directory field and print callbacks.
Definition tiffiop.h:742
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
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
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_close
Codec close callback; distinct from the client I/O close callback.
Definition tiffiop.h:657
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
uint32_t tif_flags
Bitmask combining the TIFF_* handle-state flags declared below.
Definition tiffiop.h:404
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 CCITT Huffman code entries tables and run sentinels.
Define fax run callbacks generated transitions and decoder state macros.
Declare private library state, callbacks, and implementation helpers.