Debian Codegraph @

texk/xdvipsk/thirdparty/libtiff/libtiff-src/tif_fax3.c

raw
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
25 #include "tiffiop.h"
26 #ifdef CCITT_SUPPORT
27 /*
28 * TIFF Library.
29 *
30 * CCITT Group 3 (T.4) and Group 4 (T.6) Compression Support.
31 *
32 * This file contains support for decoding and encoding TIFF
33 * compression algorithms 2, 3, 4, and 32771.
34 *
35 * Decoder support is derived, with permission, from the code
36 * in Frank Cringle's viewfax program;
37 * Copyright (C) 1990, 1995 Frank D. Cringle.
38 */
39 #include "tif_fax3.h"
40 #define G3CODES
41 #include "t4.h"
42 #include <stdio.h>
43
44 #ifndef EOF_REACHED_COUNT_THRESHOLD
45 /* Arbitrary threshold to avoid corrupted single-strip files with extremely
46 * large imageheight to cause apparently endless looping, such as in
47 * https://gitlab.com/libtiff/libtiff/-/issues/583
48 */
49 #define EOF_REACHED_COUNT_THRESHOLD 8192
50 #endif
51
52 /*
53 * Compression+decompression state blocks are
54 * derived from this ``base state'' block.
55 */
56 typedef struct
57 {
58 int rw_mode; /* O_RDONLY for decode, else encode */
59 int mode; /* operating mode */
60 tmsize_t rowbytes; /* bytes in a decoded scanline */
61 uint32_t rowpixels; /* pixels in a scanline */
62
63 uint16_t cleanfaxdata; /* CleanFaxData tag */
64 uint32_t badfaxrun; /* BadFaxRun tag */
65 uint32_t badfaxlines; /* BadFaxLines tag */
66 uint32_t groupoptions; /* Group 3/4 options tag */
67
68 TIFFVGetMethod vgetparent; /* super-class method */
69 TIFFVSetMethod vsetparent; /* super-class method */
70 TIFFPrintMethod printdir; /* super-class method */
71 } Fax3BaseState;
72 #define Fax3State(tif) ((Fax3BaseState *)(tif)->tif_data)
73
74 typedef enum
75 {
76 G3_1D,
77 G3_2D
78 } Ttag;
79 typedef struct
80 {
81 Fax3BaseState b;
82
83 /* Decoder state info */
84 const unsigned char *bitmap; /* bit reversal table */
85 uint32_t data; /* current i/o byte/word */
86 int bit; /* current i/o bit in byte */
87 int EOLcnt; /* count of EOL codes recognized */
88 int eofReachedCount; /* number of times decode has been called with
89 EOF already reached */
90 TIFFFaxFillFunc fill; /* fill routine */
91 uint32_t *runs; /* b&w runs for current/previous row */
92 uint32_t nruns; /* size of the refruns / curruns arrays */
93 uint32_t *refruns; /* runs for reference line */
94 uint32_t *curruns; /* runs for current line */
95
96 /* Encoder state info */
97 Ttag tag; /* encoding state */
98 unsigned char *refline; /* reference line for 2d decoding */
99 int k; /* #rows left that can be 2d encoded */
100 int maxk; /* max #rows that can be 2d encoded */
101
102 int line;
103 } Fax3CodecState;
104 #define DecoderState(tif) ((Fax3CodecState *)Fax3State(tif))
105 #define EncoderState(tif) ((Fax3CodecState *)Fax3State(tif))
106
107 #define is2DEncoding(sp) (sp->b.groupoptions & GROUP3OPT_2DENCODING)
108 #define isAligned(p, t) ((((size_t)(p)) & (sizeof(t) - 1)) == 0)
109
110 /*
111 * Group 3 and Group 4 Decoding.
112 */
113
114 /*
115 * These macros glue the TIFF library state to
116 * the state expected by Frank's decoder.
117 */
118 #define DECLARE_STATE(tif, sp, mod) \
119 static const char module[] = mod; \
120 Fax3CodecState *sp = DecoderState(tif); \
121 int a0; /* reference element */ \
122 int lastx = sp->b.rowpixels; /* last element in row */ \
123 uint32_t BitAcc; /* bit accumulator */ \
124 int BitsAvail; /* # valid bits in BitAcc */ \
125 int RunLength; /* length of current run */ \
126 unsigned char *cp; /* next byte of input data */ \
127 unsigned char *ep; /* end of input data */ \
128 uint32_t *pa; /* place to stuff next run */ \
129 uint32_t *thisrun; /* current row's run array */ \
130 int EOLcnt; /* # EOL codes recognized */ \
131 const unsigned char *bitmap = sp->bitmap; /* input data bit reverser */ \
132 const TIFFFaxTabEnt *TabEnt
133
134 #define DECLARE_STATE_2D(tif, sp, mod) \
135 DECLARE_STATE(tif, sp, mod); \
136 int b1; /* next change on prev line */ \
137 uint32_t \
138 *pb /* next run in reference line */ /* \
139 * Load any state that may be \
140 * changed during decoding. \
141 */
142 #define CACHE_STATE(tif, sp) \
143 do \
144 { \
145 BitAcc = sp->data; \
146 BitsAvail = sp->bit; \
147 EOLcnt = sp->EOLcnt; \
148 cp = (unsigned char *)tif->tif_rawcp; \
149 ep = cp + tif->tif_rawcc; \
150 } while (0)
151 /*
152 * Save state possibly changed during decoding.
153 */
154 #define UNCACHE_STATE(tif, sp) \
155 do \
156 { \
157 sp->bit = BitsAvail; \
158 sp->data = BitAcc; \
159 sp->EOLcnt = EOLcnt; \
160 tif->tif_rawcc -= (tmsize_t)((uint8_t *)cp - tif->tif_rawcp); \
161 tif->tif_rawcp = (uint8_t *)cp; \
162 } while (0)
163
164 /*
165 * Setup state for decoding a strip.
166 */
167 static int Fax3PreDecode(TIFF *tif, uint16_t s)
168 {
169 Fax3CodecState *sp = DecoderState(tif);
170
171 (void)s;
172 assert(sp != NULL);
173 sp->bit = 0; /* force initial read */
174 sp->data = 0;
175 sp->EOLcnt = 0; /* force initial scan for EOL */
176 sp->eofReachedCount = 0;
177 /*
178 * Decoder assumes lsb-to-msb bit order. Note that we select
179 * this here rather than in Fax3SetupState so that viewers can
180 * hold the image open, fiddle with the FillOrder tag value,
181 * and then re-decode the image. Otherwise they'd need to close
182 * and open the image to get the state reset.
183 */
184 sp->bitmap =
185 TIFFGetBitRevTable(tif->tif_dir.td_fillorder != FILLORDER_LSB2MSB);
186 sp->curruns = sp->runs;
187 if (sp->refruns)
188 { /* init reference line to white */
189 sp->refruns = sp->runs + sp->nruns;
190 sp->refruns[0] = (uint32_t)sp->b.rowpixels;
191 sp->refruns[1] = 0;
192 }
193 sp->line = 0;
194 return (1);
195 }
196
197 /*
198 * Routine for handling various errors/conditions.
199 * Note how they are "glued into the decoder" by
200 * overriding the definitions used by the decoder.
201 */
202
203 static void Fax3Unexpected(const char *module, TIFF *tif, uint32_t line,
204 uint32_t a0)
205 {
206 TIFFErrorExtR(tif, module,
207 "Bad code word at line %" PRIu32 " of %s %" PRIu32
208 " (x %" PRIu32 ")",
209 line, isTiled(tif) ? "tile" : "strip",
210 (isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip), a0);
211 }
212 #define unexpected(table, a0) Fax3Unexpected(module, tif, sp->line, a0)
213
214 static void Fax3Extension(const char *module, TIFF *tif, uint32_t line,
215 uint32_t a0)
216 {
217 TIFFErrorExtR(tif, module,
218 "Uncompressed data (not supported) at line %" PRIu32
219 " of %s %" PRIu32 " (x %" PRIu32 ")",
220 line, isTiled(tif) ? "tile" : "strip",
221 (isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip), a0);
222 }
223 #define extension(a0) Fax3Extension(module, tif, sp->line, a0)
224
225 static void Fax3BadLength(const char *module, TIFF *tif, uint32_t line,
226 uint32_t a0, uint32_t lastx)
227 {
228 TIFFWarningExtR(tif, module,
229 "%s at line %" PRIu32 " of %s %" PRIu32 " (got %" PRIu32
230 ", expected %" PRIu32 ")",
231 a0 < lastx ? "Premature EOL" : "Line length mismatch", line,
232 isTiled(tif) ? "tile" : "strip",
233 (isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip), a0,
234 lastx);
235 }
236 #define badlength(a0, lastx) Fax3BadLength(module, tif, sp->line, a0, lastx)
237
238 static void Fax3PrematureEOF(const char *module, TIFF *tif, uint32_t line,
239 uint32_t a0)
240 {
241 TIFFWarningExtR(tif, module,
242 "Premature EOF at line %" PRIu32 " of %s %" PRIu32
243 " (x %" PRIu32 ")",
244 line, isTiled(tif) ? "tile" : "strip",
245 (isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip), a0);
246 }
247 #define prematureEOF(a0) \
248 do \
249 { \
250 Fax3PrematureEOF(module, tif, sp->line, a0); \
251 ++sp->eofReachedCount; \
252 } while (0)
253
254 #define Nop
255
256 /**
257 * Decode the requested amount of G3 1D-encoded data.
258 * @param buf destination buffer
259 * @param occ available bytes in destination buffer
260 * @param s number of planes (ignored)
261 * @returns 1 for success, -1 in case of error
262 */
263 static int Fax3Decode1D(TIFF *tif, uint8_t *buf, tmsize_t occ, uint16_t s)
264 {
265 DECLARE_STATE(tif, sp, "Fax3Decode1D");
266 (void)s;
267 if (occ % sp->b.rowbytes)
268 {
269 TIFFErrorExtR(tif, module, "Fractional scanlines cannot be read");
270 return (-1);
271 }
272 if (sp->eofReachedCount >= EOF_REACHED_COUNT_THRESHOLD)
273 {
274 TIFFErrorExtR(
275 tif, module,
276 "End of file has already been reached %d times within that strip",
277 sp->eofReachedCount);
278 return (-1);
279 }
280 CACHE_STATE(tif, sp);
281 thisrun = sp->curruns;
282 while (occ > 0)
283 {
284 a0 = 0;
285 RunLength = 0;
286 pa = thisrun;
287 #ifdef FAX3_DEBUG
288 printf("\nBitAcc=%08" PRIX32 ", BitsAvail = %d\n", BitAcc, BitsAvail);
289 printf("-------------------- %" PRIu32 "\n", tif->tif_row);
290 fflush(stdout);
291 #endif
292 SYNC_EOL(EOF1D);
293 EXPAND1D(EOF1Da);
294 (*sp->fill)(buf, thisrun, pa, lastx);
295 buf += sp->b.rowbytes;
296 occ -= sp->b.rowbytes;
297 sp->line++;
298 continue;
299 EOF1D: /* premature EOF */
300 CLEANUP_RUNS();
301 EOF1Da: /* premature EOF */
302 (*sp->fill)(buf, thisrun, pa, lastx);
303 UNCACHE_STATE(tif, sp);
304 return (-1);
305 }
306 UNCACHE_STATE(tif, sp);
307 return (1);
308 }
309
310 #define SWAP(t, a, b) \
311 { \
312 t x; \
313 x = (a); \
314 (a) = (b); \
315 (b) = x; \
316 }
317 /*
318 * Decode the requested amount of G3 2D-encoded data.
319 */
320 static int Fax3Decode2D(TIFF *tif, uint8_t *buf, tmsize_t occ, uint16_t s)
321 {
322 DECLARE_STATE_2D(tif, sp, "Fax3Decode2D");
323 int is1D; /* current line is 1d/2d-encoded */
324 (void)s;
325 if (occ % sp->b.rowbytes)
326 {
327 TIFFErrorExtR(tif, module, "Fractional scanlines cannot be read");
328 return (-1);
329 }
330 if (sp->eofReachedCount >= EOF_REACHED_COUNT_THRESHOLD)
331 {
332 TIFFErrorExtR(
333 tif, module,
334 "End of file has already been reached %d times within that strip",
335 sp->eofReachedCount);
336 return (-1);
337 }
338 CACHE_STATE(tif, sp);
339 while (occ > 0)
340 {
341 a0 = 0;
342 RunLength = 0;
343 pa = thisrun = sp->curruns;
344 #ifdef FAX3_DEBUG
345 printf("\nBitAcc=%08" PRIX32 ", BitsAvail = %d EOLcnt = %d", BitAcc,
346 BitsAvail, EOLcnt);
347 #endif
348 SYNC_EOL(EOF2D);
349 NeedBits8(1, EOF2D);
350 is1D = GetBits(1); /* 1D/2D-encoding tag bit */
351 ClrBits(1);
352 #ifdef FAX3_DEBUG
353 printf(" %s\n-------------------- %" PRIu32 "\n", is1D ? "1D" : "2D",
354 tif->tif_row);
355 fflush(stdout);
356 #endif
357 pb = sp->refruns;
358 b1 = *pb++;
359 if (is1D)
360 EXPAND1D(EOF2Da);
361 else
362 EXPAND2D(EOF2Da);
363 (*sp->fill)(buf, thisrun, pa, lastx);
364 if (pa < thisrun + sp->nruns)
365 {
366 SETVALUE(0); /* imaginary change for reference */
367 }
368 SWAP(uint32_t *, sp->curruns, sp->refruns);
369 buf += sp->b.rowbytes;
370 occ -= sp->b.rowbytes;
371 sp->line++;
372 continue;
373 EOF2D: /* premature EOF */
374 CLEANUP_RUNS();
375 EOF2Da: /* premature EOF */
376 (*sp->fill)(buf, thisrun, pa, lastx);
377 UNCACHE_STATE(tif, sp);
378 return (-1);
379 }
380 UNCACHE_STATE(tif, sp);
381 return (1);
382 }
383 #undef SWAP
384
385 #define FILL(n, cp) \
386 for (int32_t ifill = 0; ifill < (n); ++ifill) \
387 { \
388 (cp)[ifill] = 0xff; \
389 } \
390 (cp) += (n);
391
392 #define ZERO(n, cp) \
393 for (int32_t izero = 0; izero < (n); ++izero) \
394 { \
395 (cp)[izero] = 0; \
396 } \
397 (cp) += (n);
398
399 /*
400 * Bit-fill a row according to the white/black
401 * runs generated during G3/G4 decoding.
402 */
403 void _TIFFFax3fillruns(unsigned char *buf, uint32_t *runs, uint32_t *erun,
404 uint32_t lastx)
405 {
406 static const unsigned char _fillmasks[] = {0x00, 0x80, 0xc0, 0xe0, 0xf0,
407 0xf8, 0xfc, 0xfe, 0xff};
408 unsigned char *cp;
409 uint32_t x, bx, run;
410 int32_t n, nw;
411 int64_t *lp;
412
413 if ((erun - runs) & 1)
414 *erun++ = 0;
415 x = 0;
416 for (; runs < erun; runs += 2)
417 {
418 run = runs[0];
419 if (x + run > lastx || run > lastx)
420 run = runs[0] = (uint32_t)(lastx - x);
421 if (run)
422 {
423 cp = buf + (x >> 3);
424 bx = x & 7;
425 if (run > 8 - bx)
426 {
427 if (bx)
428 { /* align to byte boundary */
429 *cp++ &= 0xff << (8 - bx);
430 run -= 8 - bx;
431 }
432 if ((n = run >> 3) != 0)
433 { /* multiple bytes to fill */
434 if ((n / sizeof(int64_t)) > 1)
435 {
436 /*
437 * Align to int64_tword boundary and fill.
438 */
439 for (; n && !isAligned(cp, int64_t); n--)
440 *cp++ = 0x00;
441 lp = (int64_t *)cp;
442 nw = (int32_t)(n / sizeof(int64_t));
443 n -= nw * sizeof(int64_t);
444 do
445 {
446 *lp++ = 0L;
447 } while (--nw);
448 cp = (unsigned char *)lp;
449 }
450 ZERO(n, cp);
451 run &= 7;
452 }
453 if (run)
454 cp[0] &= 0xff >> run;
455 }
456 else
457 cp[0] &= ~(_fillmasks[run] >> bx);
458 x += runs[0];
459 }
460 run = runs[1];
461 if (x + run > lastx || run > lastx)
462 run = runs[1] = lastx - x;
463 if (run)
464 {
465 cp = buf + (x >> 3);
466 bx = x & 7;
467 if (run > 8 - bx)
468 {
469 if (bx)
470 { /* align to byte boundary */
471 *cp++ |= 0xff >> bx;
472 run -= 8 - bx;
473 }
474 if ((n = run >> 3) != 0)
475 { /* multiple bytes to fill */
476 if ((n / sizeof(int64_t)) > 1)
477 {
478 /*
479 * Align to int64_t boundary and fill.
480 */
481 for (; n && !isAligned(cp, int64_t); n--)
482 *cp++ = 0xff;
483 lp = (int64_t *)cp;
484 nw = (int32_t)(n / sizeof(int64_t));
485 n -= nw * sizeof(int64_t);
486 do
487 {
488 *lp++ = -1L;
489 } while (--nw);
490 cp = (unsigned char *)lp;
491 }
492 FILL(n, cp);
493 run &= 7;
494 }
495 /* Explicit 0xff masking to make icc -check=conversions happy */
496 if (run)
497 cp[0] = (unsigned char)((cp[0] | (0xff00 >> run)) & 0xff);
498 }
499 else
500 cp[0] |= _fillmasks[run] >> bx;
501 x += runs[1];
502 }
503 }
504 assert(x == lastx);
505 }
506 #undef ZERO
507 #undef FILL
508
509 static int Fax3FixupTags(TIFF *tif)
510 {
511 (void)tif;
512 return (1);
513 }
514
515 /*
516 * Setup G3/G4-related compression/decompression state
517 * before data is processed. This routine is called once
518 * per image -- it sets up different state based on whether
519 * or not decoding or encoding is being done and whether
520 * 1D- or 2D-encoded data is involved.
521 */
522 static int Fax3SetupState(TIFF *tif)
523 {
524 static const char module[] = "Fax3SetupState";
525 TIFFDirectory *td = &tif->tif_dir;
526 Fax3BaseState *sp = Fax3State(tif);
527 int needsRefLine;
528 Fax3CodecState *dsp = (Fax3CodecState *)Fax3State(tif);
529 tmsize_t rowbytes;
530 uint32_t rowpixels;
531
532 if (td->td_bitspersample != 1)
533 {
534 TIFFErrorExtR(tif, module,
535 "Bits/sample must be 1 for Group 3/4 encoding/decoding");
536 return (0);
537 }
538 /*
539 * Calculate the scanline/tile widths.
540 */
541 if (isTiled(tif))
542 {
543 rowbytes = TIFFTileRowSize(tif);
544 rowpixels = td->td_tilewidth;
545 }
546 else
547 {
548 rowbytes = TIFFScanlineSize(tif);
549 rowpixels = td->td_imagewidth;
550 }
551 if ((int64_t)rowbytes < ((int64_t)rowpixels + 7) / 8)
552 {
553 TIFFErrorExtR(tif, module,
554 "Inconsistent number of bytes per row : rowbytes=%" PRId64
555 " rowpixels=%" PRIu32,
556 (int64_t)rowbytes, rowpixels);
557 return (0);
558 }
559 sp->rowbytes = rowbytes;
560 sp->rowpixels = rowpixels;
561 /*
562 * Allocate any additional space required for decoding/encoding.
563 */
564 needsRefLine = ((sp->groupoptions & GROUP3OPT_2DENCODING) ||
565 td->td_compression == COMPRESSION_CCITTFAX4);
566
567 /*
568 Assure that allocation computations do not overflow.
569
570 TIFFroundup and TIFFSafeMultiply return zero on integer overflow
571 */
572 if (dsp->runs != NULL)
573 {
574 _TIFFfreeExt(tif, dsp->runs);
575 dsp->runs = (uint32_t *)NULL;
576 }
577 dsp->nruns = TIFFroundup_32(rowpixels + 1, 32);
578 if (needsRefLine)
579 {
580 dsp->nruns = TIFFSafeMultiply(uint32_t, dsp->nruns, 2);
581 }
582 if ((dsp->nruns == 0) || (TIFFSafeMultiply(uint32_t, dsp->nruns, 2) == 0))
583 {
584 TIFFErrorExtR(tif, tif->tif_name,
585 "Row pixels integer overflow (rowpixels %" PRIu32 ")",
586 rowpixels);
587 return (0);
588 }
589 dsp->runs = (uint32_t *)_TIFFCheckMalloc(
590 tif, TIFFSafeMultiply(uint32_t, dsp->nruns, 2), sizeof(uint32_t),
591 "for Group 3/4 run arrays");
592 if (dsp->runs == NULL)
593 return (0);
594 memset(dsp->runs, 0,
595 TIFFSafeMultiply(uint32_t, dsp->nruns, 2) * sizeof(uint32_t));
596 dsp->curruns = dsp->runs;
597 if (needsRefLine)
598 dsp->refruns = dsp->runs + dsp->nruns;
599 else
600 dsp->refruns = NULL;
601 if (td->td_compression == COMPRESSION_CCITTFAX3 && is2DEncoding(dsp))
602 { /* NB: default is 1D routine */
603 tif->tif_decoderow = Fax3Decode2D;
604 tif->tif_decodestrip = Fax3Decode2D;
605 tif->tif_decodetile = Fax3Decode2D;
606 }
607
608 if (needsRefLine)
609 { /* 2d encoding */
610 Fax3CodecState *esp = EncoderState(tif);
611 /*
612 * 2d encoding requires a scanline
613 * buffer for the ``reference line''; the
614 * scanline against which delta encoding
615 * is referenced. The reference line must
616 * be initialized to be ``white'' (done elsewhere).
617 */
618 if (esp->refline != NULL)
619 {
620 _TIFFfreeExt(tif, esp->refline);
621 }
622 esp->refline = (unsigned char *)_TIFFmallocExt(tif, rowbytes);
623 if (esp->refline == NULL)
624 {
625 TIFFErrorExtR(tif, module, "No space for Group 3/4 reference line");
626 return (0);
627 }
628 }
629 else /* 1d encoding */
630 EncoderState(tif)->refline = NULL;
631
632 return (1);
633 }
634
635 /*
636 * CCITT Group 3 FAX Encoding.
637 */
638
639 #define Fax3FlushBits(tif, sp) \
640 { \
641 if ((tif)->tif_rawcc >= (tif)->tif_rawdatasize) \
642 { \
643 if (!TIFFFlushData1(tif)) \
644 return 0; \
645 } \
646 *(tif)->tif_rawcp++ = (uint8_t)(sp)->data; \
647 (tif)->tif_rawcc++; \
648 (sp)->data = 0, (sp)->bit = 8; \
649 }
650 #define _FlushBits(tif) \
651 { \
652 if ((tif)->tif_rawcc >= (tif)->tif_rawdatasize) \
653 { \
654 if (!TIFFFlushData1(tif)) \
655 return 0; \
656 } \
657 *(tif)->tif_rawcp++ = (uint8_t)data; \
658 (tif)->tif_rawcc++; \
659 data = 0, bit = 8; \
660 }
661 static const int _msbmask[9] = {0x00, 0x01, 0x03, 0x07, 0x0f,
662 0x1f, 0x3f, 0x7f, 0xff};
663 #define _PutBits(tif, bits, length) \
664 { \
665 while (length > bit) \
666 { \
667 data |= bits >> (length - bit); \
668 length -= bit; \
669 _FlushBits(tif); \
670 } \
671 assert(length < 9); \
672 data |= (bits & _msbmask[length]) << (bit - length); \
673 bit -= length; \
674 if (bit == 0) \
675 _FlushBits(tif); \
676 }
677
678 /*
679 * Write a variable-length bit-value to
680 * the output stream. Values are
681 * assumed to be at most 16 bits.
682 */
683 static int Fax3PutBits(TIFF *tif, unsigned int bits, unsigned int length)
684 {
685 Fax3CodecState *sp = EncoderState(tif);
686 unsigned int bit = sp->bit;
687 int data = sp->data;
688
689 _PutBits(tif, bits, length);
690
691 sp->data = data;
692 sp->bit = bit;
693 return 1;
694 }
695
696 /*
697 * Write a code to the output stream.
698 */
699 #define putcode(tif, te) Fax3PutBits(tif, (te)->code, (te)->length)
700
701 #ifdef FAX3_DEBUG
702 #define DEBUG_COLOR(w) (tab == TIFFFaxWhiteCodes ? w "W" : w "B")
703 #define DEBUG_PRINT(what, len) \
704 { \
705 int t; \
706 printf("%08" PRIX32 "/%-2d: %s%5d\t", data, bit, DEBUG_COLOR(what), \
707 len); \
708 for (t = length - 1; t >= 0; t--) \
709 putchar(code & (1 << t) ? '1' : '0'); \
710 putchar('\n'); \
711 }
712 #endif
713
714 /*
715 * Write the sequence of codes that describes
716 * the specified span of zero's or one's. The
717 * appropriate table that holds the make-up and
718 * terminating codes is supplied.
719 */
720 static int putspan(TIFF *tif, int32_t span, const tableentry *tab)
721 {
722 Fax3CodecState *sp = EncoderState(tif);
723 unsigned int bit = sp->bit;
724 int data = sp->data;
725 unsigned int code, length;
726
727 while (span >= 2624)
728 {
729 const tableentry *te = &tab[63 + (2560 >> 6)];
730 code = te->code;
731 length = te->length;
732 #ifdef FAX3_DEBUG
733 DEBUG_PRINT("MakeUp", te->runlen);
734 #endif
735 _PutBits(tif, code, length);
736 span -= te->runlen;
737 }
738 if (span >= 64)
739 {
740 const tableentry *te = &tab[63 + (span >> 6)];
741 assert(te->runlen == 64 * (span >> 6));
742 code = te->code;
743 length = te->length;
744 #ifdef FAX3_DEBUG
745 DEBUG_PRINT("MakeUp", te->runlen);
746 #endif
747 _PutBits(tif, code, length);
748 span -= te->runlen;
749 }
750 code = tab[span].code;
751 length = tab[span].length;
752 #ifdef FAX3_DEBUG
753 DEBUG_PRINT(" Term", tab[span].runlen);
754 #endif
755 _PutBits(tif, code, length);
756
757 sp->data = data;
758 sp->bit = bit;
759
760 return 1;
761 }
762
763 /*
764 * Write an EOL code to the output stream. The zero-fill
765 * logic for byte-aligning encoded scanlines is handled
766 * here. We also handle writing the tag bit for the next
767 * scanline when doing 2d encoding.
768 */
769 static int Fax3PutEOL(TIFF *tif)
770 {
771 Fax3CodecState *sp = EncoderState(tif);
772 unsigned int bit = sp->bit;
773 int data = sp->data;
774 unsigned int code, length, tparm;
775
776 if (sp->b.groupoptions & GROUP3OPT_FILLBITS)
777 {
778 /*
779 * Force bit alignment so EOL will terminate on
780 * a byte boundary. That is, force the bit alignment
781 * to 16-12 = 4 before putting out the EOL code.
782 */
783 int align = 8 - 4;
784 if (align != sp->bit)
785 {
786 if (align > sp->bit)
787 align = sp->bit + (8 - align);
788 else
789 align = sp->bit - align;
790 tparm = align;
791 _PutBits(tif, 0, tparm);
792 }
793 }
794 code = EOL;
795 length = 12;
796 if (is2DEncoding(sp))
797 {
798 code = (code << 1) | (sp->tag == G3_1D);
799 length++;
800 }
801 _PutBits(tif, code, length);
802
803 sp->data = data;
804 sp->bit = bit;
805
806 return 1;
807 }
808
809 /*
810 * Reset encoding state at the start of a strip.
811 */
812 static int Fax3PreEncode(TIFF *tif, uint16_t s)
813 {
814 Fax3CodecState *sp = EncoderState(tif);
815
816 (void)s;
817 assert(sp != NULL);
818 sp->bit = 8;
819 sp->data = 0;
820 sp->tag = G3_1D;
821 /*
822 * This is necessary for Group 4; otherwise it isn't
823 * needed because the first scanline of each strip ends
824 * up being copied into the refline.
825 */
826 if (sp->refline)
827 _TIFFmemset(sp->refline, 0x00, sp->b.rowbytes);
828 if (is2DEncoding(sp))
829 {
830 float res = tif->tif_dir.td_yresolution;
831 /*
832 * The CCITT spec says that when doing 2d encoding, you
833 * should only do it on K consecutive scanlines, where K
834 * depends on the resolution of the image being encoded
835 * (2 for <= 200 lpi, 4 for > 200 lpi). Since the directory
836 * code initializes td_yresolution to 0, this code will
837 * select a K of 2 unless the YResolution tag is set
838 * appropriately. (Note also that we fudge a little here
839 * and use 150 lpi to avoid problems with units conversion.)
840 */
841 if (tif->tif_dir.td_resolutionunit == RESUNIT_CENTIMETER)
842 res *= 2.54f; /* convert to inches */
843 sp->maxk = (res > 150 ? 4 : 2);
844 sp->k = sp->maxk - 1;
845 }
846 else
847 sp->k = sp->maxk = 0;
848 sp->line = 0;
849 return (1);
850 }
851
852 static const unsigned char zeroruns[256] = {
853 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, /* 0x00 - 0x0f */
854 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 0x10 - 0x1f */
855 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0x20 - 0x2f */
856 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0x30 - 0x3f */
857 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40 - 0x4f */
858 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x50 - 0x5f */
859 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60 - 0x6f */
860 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x70 - 0x7f */
861 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x80 - 0x8f */
862 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x90 - 0x9f */
863 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xa0 - 0xaf */
864 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xb0 - 0xbf */
865 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xc0 - 0xcf */
866 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xd0 - 0xdf */
867 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xe0 - 0xef */
868 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xf0 - 0xff */
869 };
870 static const unsigned char oneruns[256] = {
871 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 - 0x0f */
872 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x10 - 0x1f */
873 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20 - 0x2f */
874 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x30 - 0x3f */
875 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x40 - 0x4f */
876 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x50 - 0x5f */
877 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x60 - 0x6f */
878 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x70 - 0x7f */
879 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x80 - 0x8f */
880 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x90 - 0x9f */
881 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0xa0 - 0xaf */
882 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0xb0 - 0xbf */
883 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0xc0 - 0xcf */
884 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0xd0 - 0xdf */
885 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 0xe0 - 0xef */
886 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 7, 8, /* 0xf0 - 0xff */
887 };
888
889 /*
890 * Find a span of ones or zeros using the supplied
891 * table. The ``base'' of the bit string is supplied
892 * along with the start+end bit indices.
893 */
894 static inline int32_t find0span(unsigned char *bp, int32_t bs, int32_t be)
895 {
896 int32_t bits = be - bs;
897 int32_t n, span;
898
899 bp += bs >> 3;
900 /*
901 * Check partial byte on lhs.
902 */
903 if (bits > 0 && (n = (bs & 7)) != 0)
904 {
905 span = zeroruns[(*bp << n) & 0xff];
906 if (span > 8 - n) /* table value too generous */
907 span = 8 - n;
908 if (span > bits) /* constrain span to bit range */
909 span = bits;
910 if (n + span < 8) /* doesn't extend to edge of byte */
911 return (span);
912 bits -= span;
913 bp++;
914 }
915 else
916 span = 0;
917 if (bits >= (int32_t)(2 * 8 * sizeof(int64_t)))
918 {
919 int64_t *lp;
920 /*
921 * Align to int64_t boundary and check int64_t words.
922 */
923 while (!isAligned(bp, int64_t))
924 {
925 if (*bp != 0x00)
926 return (span + zeroruns[*bp]);
927 span += 8;
928 bits -= 8;
929 bp++;
930 }
931 lp = (int64_t *)bp;
932 while ((bits >= (int32_t)(8 * sizeof(int64_t))) && (0 == *lp))
933 {
934 span += 8 * sizeof(int64_t);
935 bits -= 8 * sizeof(int64_t);
936 lp++;
937 }
938 bp = (unsigned char *)lp;
939 }
940 /*
941 * Scan full bytes for all 0's.
942 */
943 while (bits >= 8)
944 {
945 if (*bp != 0x00) /* end of run */
946 return (span + zeroruns[*bp]);
947 span += 8;
948 bits -= 8;
949 bp++;
950 }
951 /*
952 * Check partial byte on rhs.
953 */
954 if (bits > 0)
955 {
956 n = zeroruns[*bp];
957 span += (n > bits ? bits : n);
958 }
959 return (span);
960 }
961
962 static inline int32_t find1span(unsigned char *bp, int32_t bs, int32_t be)
963 {
964 int32_t bits = be - bs;
965 int32_t n, span;
966
967 bp += bs >> 3;
968 /*
969 * Check partial byte on lhs.
970 */
971 if (bits > 0 && (n = (bs & 7)) != 0)
972 {
973 span = oneruns[(*bp << n) & 0xff];
974 if (span > 8 - n) /* table value too generous */
975 span = 8 - n;
976 if (span > bits) /* constrain span to bit range */
977 span = bits;
978 if (n + span < 8) /* doesn't extend to edge of byte */
979 return (span);
980 bits -= span;
981 bp++;
982 }
983 else
984 span = 0;
985 if (bits >= (int32_t)(2 * 8 * sizeof(int64_t)))
986 {
987 int64_t *lp;
988 /*
989 * Align to int64_t boundary and check int64_t words.
990 */
991 while (!isAligned(bp, int64_t))
992 {
993 if (*bp != 0xff)
994 return (span + oneruns[*bp]);
995 span += 8;
996 bits -= 8;
997 bp++;
998 }
999 lp = (int64_t *)bp;
1000 while ((bits >= (int32_t)(8 * sizeof(int64_t))) &&
1001 (~((uint64_t)0) == (uint64_t)*lp))
1002 {
1003 span += 8 * sizeof(int64_t);
1004 bits -= 8 * sizeof(int64_t);
1005 lp++;
1006 }
1007 bp = (unsigned char *)lp;
1008 }
1009 /*
1010 * Scan full bytes for all 1's.
1011 */
1012 while (bits >= 8)
1013 {
1014 if (*bp != 0xff) /* end of run */
1015 return (span + oneruns[*bp]);
1016 span += 8;
1017 bits -= 8;
1018 bp++;
1019 }
1020 /*
1021 * Check partial byte on rhs.
1022 */
1023 if (bits > 0)
1024 {
1025 n = oneruns[*bp];
1026 span += (n > bits ? bits : n);
1027 }
1028 return (span);
1029 }
1030
1031 /*
1032 * Return the offset of the next bit in the range
1033 * [bs..be] that is different from the specified
1034 * color. The end, be, is returned if no such bit
1035 * exists.
1036 */
1037 #define finddiff(_cp, _bs, _be, _color) \
1038 (_bs + (_color ? find1span(_cp, _bs, _be) : find0span(_cp, _bs, _be)))
1039 /*
1040 * Like finddiff, but also check the starting bit
1041 * against the end in case start > end.
1042 */
1043 #define finddiff2(_cp, _bs, _be, _color) \
1044 (_bs < _be ? finddiff(_cp, _bs, _be, _color) : _be)
1045
1046 /*
1047 * 1d-encode a row of pixels. The encoding is
1048 * a sequence of all-white or all-black spans
1049 * of pixels encoded with Huffman codes.
1050 */
1051 static int Fax3Encode1DRow(TIFF *tif, unsigned char *bp, uint32_t bits)
1052 {
1053 Fax3CodecState *sp = EncoderState(tif);
1054 int32_t span;
1055 uint32_t bs = 0;
1056
1057 for (;;)
1058 {
1059 span = find0span(bp, bs, bits); /* white span */
1060 if (!putspan(tif, span, TIFFFaxWhiteCodes))
1061 return 0;
1062 bs += span;
1063 if (bs >= bits)
1064 break;
1065 span = find1span(bp, bs, bits); /* black span */
1066 if (!putspan(tif, span, TIFFFaxBlackCodes))
1067 return 0;
1068 bs += span;
1069 if (bs >= bits)
1070 break;
1071 }
1072 if (sp->b.mode & (FAXMODE_BYTEALIGN | FAXMODE_WORDALIGN))
1073 {
1074 if (sp->bit != 8) /* byte-align */
1075 Fax3FlushBits(tif, sp);
1076 if ((sp->b.mode & FAXMODE_WORDALIGN) &&
1077 !isAligned(tif->tif_rawcp, uint16_t))
1078 Fax3FlushBits(tif, sp);
1079 }
1080 return (1);
1081 }
1082
1083 static const tableentry horizcode = {3, 0x1, 0}; /* 001 */
1084 static const tableentry passcode = {4, 0x1, 0}; /* 0001 */
1085 static const tableentry vcodes[7] = {
1086 {7, 0x03, 0}, /* 0000 011 */
1087 {6, 0x03, 0}, /* 0000 11 */
1088 {3, 0x03, 0}, /* 011 */
1089 {1, 0x1, 0}, /* 1 */
1090 {3, 0x2, 0}, /* 010 */
1091 {6, 0x02, 0}, /* 0000 10 */
1092 {7, 0x02, 0} /* 0000 010 */
1093 };
1094
1095 /*
1096 * 2d-encode a row of pixels. Consult the CCITT
1097 * documentation for the algorithm.
1098 */
1099 static int Fax3Encode2DRow(TIFF *tif, unsigned char *bp, unsigned char *rp,
1100 uint32_t bits)
1101 {
1102 #define PIXEL(buf, ix) ((((buf)[(ix) >> 3]) >> (7 - ((ix)&7))) & 1)
1103 uint32_t a0 = 0;
1104 uint32_t a1 = (PIXEL(bp, 0) != 0 ? 0 : finddiff(bp, 0, bits, 0));
1105 uint32_t b1 = (PIXEL(rp, 0) != 0 ? 0 : finddiff(rp, 0, bits, 0));
1106 uint32_t a2, b2;
1107
1108 for (;;)
1109 {
1110 b2 = finddiff2(rp, b1, bits, PIXEL(rp, b1));
1111 if (b2 >= a1)
1112 {
1113 /* Naive computation triggers
1114 * -fsanitize=undefined,unsigned-integer-overflow */
1115 /* although it is correct unless the difference between both is < 31
1116 * bit */
1117 /* int32_t d = b1 - a1; */
1118 int32_t d = (b1 >= a1 && b1 - a1 <= 3U) ? (int32_t)(b1 - a1)
1119 : (b1 < a1 && a1 - b1 <= 3U) ? -(int32_t)(a1 - b1)
1120 : 0x7FFFFFFF;
1121 if (!(-3 <= d && d <= 3))
1122 { /* horizontal mode */
1123 a2 = finddiff2(bp, a1, bits, PIXEL(bp, a1));
1124 if (!putcode(tif, &horizcode))
1125 return 0;
1126 if (a0 + a1 == 0 || PIXEL(bp, a0) == 0)
1127 {
1128 if (!putspan(tif, a1 - a0, TIFFFaxWhiteCodes))
1129 return 0;
1130 if (!putspan(tif, a2 - a1, TIFFFaxBlackCodes))
1131 return 0;
1132 }
1133 else
1134 {
1135 if (!putspan(tif, a1 - a0, TIFFFaxBlackCodes))
1136 return 0;
1137 if (!putspan(tif, a2 - a1, TIFFFaxWhiteCodes))
1138 return 0;
1139 }
1140 a0 = a2;
1141 }
1142 else
1143 { /* vertical mode */
1144 if (!putcode(tif, &vcodes[d + 3]))
1145 return 0;
1146 a0 = a1;
1147 }
1148 }
1149 else
1150 { /* pass mode */
1151 if (!putcode(tif, &passcode))
1152 return 0;
1153 a0 = b2;
1154 }
1155 if (a0 >= bits)
1156 break;
1157 a1 = finddiff(bp, a0, bits, PIXEL(bp, a0));
1158 b1 = finddiff(rp, a0, bits, !PIXEL(bp, a0));
1159 b1 = finddiff(rp, b1, bits, PIXEL(bp, a0));
1160 }
1161 return (1);
1162 #undef PIXEL
1163 }
1164
1165 /*
1166 * Encode a buffer of pixels.
1167 */
1168 static int Fax3Encode(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
1169 {
1170 static const char module[] = "Fax3Encode";
1171 Fax3CodecState *sp = EncoderState(tif);
1172 (void)s;
1173 if (cc % sp->b.rowbytes)
1174 {
1175 TIFFErrorExtR(tif, module, "Fractional scanlines cannot be written");
1176 return (0);
1177 }
1178 while (cc > 0)
1179 {
1180 if ((sp->b.mode & FAXMODE_NOEOL) == 0)
1181 {
1182 if (!Fax3PutEOL(tif))
1183 return 0;
1184 }
1185 if (is2DEncoding(sp))
1186 {
1187 if (sp->tag == G3_1D)
1188 {
1189 if (!Fax3Encode1DRow(tif, bp, sp->b.rowpixels))
1190 return (0);
1191 sp->tag = G3_2D;
1192 }
1193 else
1194 {
1195 if (!Fax3Encode2DRow(tif, bp, sp->refline, sp->b.rowpixels))
1196 return (0);
1197 sp->k--;
1198 }
1199 if (sp->k == 0)
1200 {
1201 sp->tag = G3_1D;
1202 sp->k = sp->maxk - 1;
1203 }
1204 else
1205 _TIFFmemcpy(sp->refline, bp, sp->b.rowbytes);
1206 }
1207 else
1208 {
1209 if (!Fax3Encode1DRow(tif, bp, sp->b.rowpixels))
1210 return (0);
1211 }
1212 bp += sp->b.rowbytes;
1213 cc -= sp->b.rowbytes;
1214 }
1215 return (1);
1216 }
1217
1218 static int Fax3PostEncode(TIFF *tif)
1219 {
1220 Fax3CodecState *sp = EncoderState(tif);
1221
1222 if (sp->bit != 8)
1223 Fax3FlushBits(tif, sp);
1224 return (1);
1225 }
1226
1227 static int _Fax3Close(TIFF *tif)
1228 {
1229 if ((Fax3State(tif)->mode & FAXMODE_NORTC) == 0 && tif->tif_rawcp)
1230 {
1231 Fax3CodecState *sp = EncoderState(tif);
1232 unsigned int code = EOL;
1233 unsigned int length = 12;
1234 int i;
1235
1236 if (is2DEncoding(sp))
1237 {
1238 code = (code << 1) | (sp->tag == G3_1D);
1239 length++;
1240 }
1241 for (i = 0; i < 6; i++)
1242 Fax3PutBits(tif, code, length);
1243 Fax3FlushBits(tif, sp);
1244 }
1245 return 1;
1246 }
1247
1248 static void Fax3Close(TIFF *tif) { _Fax3Close(tif); }
1249
1250 static void Fax3Cleanup(TIFF *tif)
1251 {
1252 Fax3CodecState *sp = DecoderState(tif);
1253
1254 assert(sp != 0);
1255
1256 tif->tif_tagmethods.vgetfield = sp->b.vgetparent;
1257 tif->tif_tagmethods.vsetfield = sp->b.vsetparent;
1258 tif->tif_tagmethods.printdir = sp->b.printdir;
1259
1260 if (sp->runs)
1261 _TIFFfreeExt(tif, sp->runs);
1262 if (sp->refline)
1263 _TIFFfreeExt(tif, sp->refline);
1264
1265 _TIFFfreeExt(tif, tif->tif_data);
1266 tif->tif_data = NULL;
1267
1268 _TIFFSetDefaultCompressionState(tif);
1269 }
1270
1271 #define FIELD_BADFAXLINES (FIELD_CODEC + 0)
1272 #define FIELD_CLEANFAXDATA (FIELD_CODEC + 1)
1273 #define FIELD_BADFAXRUN (FIELD_CODEC + 2)
1274
1275 #define FIELD_OPTIONS (FIELD_CODEC + 7)
1276
1277 static const TIFFField faxFields[] = {
1278 {TIFFTAG_FAXMODE, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED,
1279 FIELD_PSEUDO, FALSE, FALSE, "FaxMode", NULL},
1280 {TIFFTAG_FAXFILLFUNC, 0, 0, TIFF_ANY, 0, TIFF_SETGET_OTHER,
1281 TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "FaxFillFunc", NULL},
1282 {TIFFTAG_BADFAXLINES, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32,
1283 TIFF_SETGET_UINT32, FIELD_BADFAXLINES, TRUE, FALSE, "BadFaxLines", NULL},
1284 {TIFFTAG_CLEANFAXDATA, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16,
1285 TIFF_SETGET_UINT16, FIELD_CLEANFAXDATA, TRUE, FALSE, "CleanFaxData", NULL},
1286 {TIFFTAG_CONSECUTIVEBADFAXLINES, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32,
1287 TIFF_SETGET_UINT32, FIELD_BADFAXRUN, TRUE, FALSE, "ConsecutiveBadFaxLines",
1288 NULL}};
1289 static const TIFFField fax3Fields[] = {
1290 {TIFFTAG_GROUP3OPTIONS, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32,
1291 TIFF_SETGET_UINT32, FIELD_OPTIONS, FALSE, FALSE, "Group3Options", NULL},
1292 };
1293 static const TIFFField fax4Fields[] = {
1294 {TIFFTAG_GROUP4OPTIONS, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32,
1295 TIFF_SETGET_UINT32, FIELD_OPTIONS, FALSE, FALSE, "Group4Options", NULL},
1296 };
1297
1298 static int Fax3VSetField(TIFF *tif, uint32_t tag, va_list ap)
1299 {
1300 Fax3BaseState *sp = Fax3State(tif);
1301 const TIFFField *fip;
1302
1303 assert(sp != 0);
1304 assert(sp->vsetparent != 0);
1305
1306 switch (tag)
1307 {
1308 case TIFFTAG_FAXMODE:
1309 sp->mode = (int)va_arg(ap, int);
1310 return 1; /* NB: pseudo tag */
1311 case TIFFTAG_FAXFILLFUNC:
1312 DecoderState(tif)->fill = va_arg(ap, TIFFFaxFillFunc);
1313 return 1; /* NB: pseudo tag */
1314 case TIFFTAG_GROUP3OPTIONS:
1315 /* XXX: avoid reading options if compression mismatches. */
1316 if (tif->tif_dir.td_compression == COMPRESSION_CCITTFAX3)
1317 sp->groupoptions = (uint32_t)va_arg(ap, uint32_t);
1318 break;
1319 case TIFFTAG_GROUP4OPTIONS:
1320 /* XXX: avoid reading options if compression mismatches. */
1321 if (tif->tif_dir.td_compression == COMPRESSION_CCITTFAX4)
1322 sp->groupoptions = (uint32_t)va_arg(ap, uint32_t);
1323 break;
1324 case TIFFTAG_BADFAXLINES:
1325 sp->badfaxlines = (uint32_t)va_arg(ap, uint32_t);
1326 break;
1327 case TIFFTAG_CLEANFAXDATA:
1328 sp->cleanfaxdata = (uint16_t)va_arg(ap, uint16_vap);
1329 break;
1330 case TIFFTAG_CONSECUTIVEBADFAXLINES:
1331 sp->badfaxrun = (uint32_t)va_arg(ap, uint32_t);
1332 break;
1333 default:
1334 return (*sp->vsetparent)(tif, tag, ap);
1335 }
1336
1337 if ((fip = TIFFFieldWithTag(tif, tag)) != NULL)
1338 TIFFSetFieldBit(tif, fip->field_bit);
1339 else
1340 return 0;
1341
1342 tif->tif_flags |= TIFF_DIRTYDIRECT;
1343 return 1;
1344 }
1345
1346 static int Fax3VGetField(TIFF *tif, uint32_t tag, va_list ap)
1347 {
1348 Fax3BaseState *sp = Fax3State(tif);
1349
1350 assert(sp != 0);
1351
1352 switch (tag)
1353 {
1354 case TIFFTAG_FAXMODE:
1355 *va_arg(ap, int *) = sp->mode;
1356 break;
1357 case TIFFTAG_FAXFILLFUNC:
1358 *va_arg(ap, TIFFFaxFillFunc *) = DecoderState(tif)->fill;
1359 break;
1360 case TIFFTAG_GROUP3OPTIONS:
1361 case TIFFTAG_GROUP4OPTIONS:
1362 *va_arg(ap, uint32_t *) = sp->groupoptions;
1363 break;
1364 case TIFFTAG_BADFAXLINES:
1365 *va_arg(ap, uint32_t *) = sp->badfaxlines;
1366 break;
1367 case TIFFTAG_CLEANFAXDATA:
1368 *va_arg(ap, uint16_t *) = sp->cleanfaxdata;
1369 break;
1370 case TIFFTAG_CONSECUTIVEBADFAXLINES:
1371 *va_arg(ap, uint32_t *) = sp->badfaxrun;
1372 break;
1373 default:
1374 return (*sp->vgetparent)(tif, tag, ap);
1375 }
1376 return (1);
1377 }
1378
1379 static void Fax3PrintDir(TIFF *tif, FILE *fd, long flags)
1380 {
1381 Fax3BaseState *sp = Fax3State(tif);
1382
1383 assert(sp != 0);
1384
1385 (void)flags;
1386 if (TIFFFieldSet(tif, FIELD_OPTIONS))
1387 {
1388 const char *sep = " ";
1389 if (tif->tif_dir.td_compression == COMPRESSION_CCITTFAX4)
1390 {
1391 fprintf(fd, " Group 4 Options:");
1392 if (sp->groupoptions & GROUP4OPT_UNCOMPRESSED)
1393 fprintf(fd, "%suncompressed data", sep);
1394 }
1395 else
1396 {
1397
1398 fprintf(fd, " Group 3 Options:");
1399 if (sp->groupoptions & GROUP3OPT_2DENCODING)
1400 {
1401 fprintf(fd, "%s2-d encoding", sep);
1402 sep = "+";
1403 }
1404 if (sp->groupoptions & GROUP3OPT_FILLBITS)
1405 {
1406 fprintf(fd, "%sEOL padding", sep);
1407 sep = "+";
1408 }
1409 if (sp->groupoptions & GROUP3OPT_UNCOMPRESSED)
1410 fprintf(fd, "%suncompressed data", sep);
1411 }
1412 fprintf(fd, " (%" PRIu32 " = 0x%" PRIx32 ")\n", sp->groupoptions,
1413 sp->groupoptions);
1414 }
1415 if (TIFFFieldSet(tif, FIELD_CLEANFAXDATA))
1416 {
1417 fprintf(fd, " Fax Data:");
1418 switch (sp->cleanfaxdata)
1419 {
1420 case CLEANFAXDATA_CLEAN:
1421 fprintf(fd, " clean");
1422 break;
1423 case CLEANFAXDATA_REGENERATED:
1424 fprintf(fd, " receiver regenerated");
1425 break;
1426 case CLEANFAXDATA_UNCLEAN:
1427 fprintf(fd, " uncorrected errors");
1428 break;
1429 }
1430 fprintf(fd, " (%" PRIu16 " = 0x%" PRIx16 ")\n", sp->cleanfaxdata,
1431 sp->cleanfaxdata);
1432 }
1433 if (TIFFFieldSet(tif, FIELD_BADFAXLINES))
1434 fprintf(fd, " Bad Fax Lines: %" PRIu32 "\n", sp->badfaxlines);
1435 if (TIFFFieldSet(tif, FIELD_BADFAXRUN))
1436 fprintf(fd, " Consecutive Bad Fax Lines: %" PRIu32 "\n",
1437 sp->badfaxrun);
1438 if (sp->printdir)
1439 (*sp->printdir)(tif, fd, flags);
1440 }
1441
1442 static int InitCCITTFax3(TIFF *tif)
1443 {
1444 static const char module[] = "InitCCITTFax3";
1445 Fax3BaseState *sp;
1446
1447 /*
1448 * Merge codec-specific tag information.
1449 */
1450 if (!_TIFFMergeFields(tif, faxFields, TIFFArrayCount(faxFields)))
1451 {
1452 TIFFErrorExtR(tif, "InitCCITTFax3",
1453 "Merging common CCITT Fax codec-specific tags failed");
1454 return 0;
1455 }
1456
1457 /*
1458 * Allocate state block so tag methods have storage to record values.
1459 */
1460 tif->tif_data = (uint8_t *)_TIFFmallocExt(tif, sizeof(Fax3CodecState));
1461
1462 if (tif->tif_data == NULL)
1463 {
1464 TIFFErrorExtR(tif, module, "No space for state block");
1465 return (0);
1466 }
1467 _TIFFmemset(tif->tif_data, 0, sizeof(Fax3CodecState));
1468
1469 sp = Fax3State(tif);
1470 sp->rw_mode = tif->tif_mode;
1471
1472 /*
1473 * Override parent get/set field methods.
1474 */
1475 sp->vgetparent = tif->tif_tagmethods.vgetfield;
1476 tif->tif_tagmethods.vgetfield = Fax3VGetField; /* hook for codec tags */
1477 sp->vsetparent = tif->tif_tagmethods.vsetfield;
1478 tif->tif_tagmethods.vsetfield = Fax3VSetField; /* hook for codec tags */
1479 sp->printdir = tif->tif_tagmethods.printdir;
1480 tif->tif_tagmethods.printdir = Fax3PrintDir; /* hook for codec tags */
1481 sp->groupoptions = 0;
1482
1483 if (sp->rw_mode == O_RDONLY) /* FIXME: improve for in place update */
1484 tif->tif_flags |= TIFF_NOBITREV; /* decoder does bit reversal */
1485 DecoderState(tif)->runs = NULL;
1486 TIFFSetField(tif, TIFFTAG_FAXFILLFUNC, _TIFFFax3fillruns);
1487 EncoderState(tif)->refline = NULL;
1488
1489 /*
1490 * Install codec methods.
1491 */
1492 tif->tif_fixuptags = Fax3FixupTags;
1493 tif->tif_setupdecode = Fax3SetupState;
1494 tif->tif_predecode = Fax3PreDecode;
1495 tif->tif_decoderow = Fax3Decode1D;
1496 tif->tif_decodestrip = Fax3Decode1D;
1497 tif->tif_decodetile = Fax3Decode1D;
1498 tif->tif_setupencode = Fax3SetupState;
1499 tif->tif_preencode = Fax3PreEncode;
1500 tif->tif_postencode = Fax3PostEncode;
1501 tif->tif_encoderow = Fax3Encode;
1502 tif->tif_encodestrip = Fax3Encode;
1503 tif->tif_encodetile = Fax3Encode;
1504 tif->tif_close = Fax3Close;
1505 tif->tif_cleanup = Fax3Cleanup;
1506
1507 return (1);
1508 }
1509
1510 int TIFFInitCCITTFax3(TIFF *tif, int scheme)
1511 {
1512 (void)scheme;
1513 if (InitCCITTFax3(tif))
1514 {
1515 /*
1516 * Merge codec-specific tag information.
1517 */
1518 if (!_TIFFMergeFields(tif, fax3Fields, TIFFArrayCount(fax3Fields)))
1519 {
1520 TIFFErrorExtR(tif, "TIFFInitCCITTFax3",
1521 "Merging CCITT Fax 3 codec-specific tags failed");
1522 return 0;
1523 }
1524
1525 /*
1526 * The default format is Class/F-style w/o RTC.
1527 */
1528 return TIFFSetField(tif, TIFFTAG_FAXMODE, FAXMODE_CLASSF);
1529 }
1530 else
1531 return 01;
1532 }
1533
1534 /*
1535 * CCITT Group 4 (T.6) Facsimile-compatible
1536 * Compression Scheme Support.
1537 */
1538
1539 #define SWAP(t, a, b) \
1540 { \
1541 t x; \
1542 x = (a); \
1543 (a) = (b); \
1544 (b) = x; \
1545 }
1546 /*
1547 * Decode the requested amount of G4-encoded data.
1548 */
1549 static int Fax4Decode(TIFF *tif, uint8_t *buf, tmsize_t occ, uint16_t s)
1550 {
1551 DECLARE_STATE_2D(tif, sp, "Fax4Decode");
1552 (void)s;
1553 if (occ % sp->b.rowbytes)
1554 {
1555 TIFFErrorExtR(tif, module, "Fractional scanlines cannot be read");
1556 return (-1);
1557 }
1558 if (sp->eofReachedCount >= EOF_REACHED_COUNT_THRESHOLD)
1559 {
1560 TIFFErrorExtR(
1561 tif, module,
1562 "End of file has already been reached %d times within that strip",
1563 sp->eofReachedCount);
1564 return (-1);
1565 }
1566 CACHE_STATE(tif, sp);
1567 int start = sp->line;
1568 while (occ > 0)
1569 {
1570 a0 = 0;
1571 RunLength = 0;
1572 pa = thisrun = sp->curruns;
1573 pb = sp->refruns;
1574 b1 = *pb++;
1575 #ifdef FAX3_DEBUG
1576 printf("\nBitAcc=%08" PRIX32 ", BitsAvail = %d\n", BitAcc, BitsAvail);
1577 printf("-------------------- %d\n", tif->tif_row);
1578 fflush(stdout);
1579 #endif
1580 EXPAND2D(EOFG4);
1581 if (EOLcnt)
1582 goto EOFG4;
1583 if (((lastx + 7) >> 3) > (int)occ) /* check for buffer overrun */
1584 {
1585 TIFFErrorExtR(tif, module,
1586 "Buffer overrun detected : %" TIFF_SSIZE_FORMAT
1587 " bytes available, %d bits needed",
1588 occ, lastx);
1589 return -1;
1590 }
1591 (*sp->fill)(buf, thisrun, pa, lastx);
1592 SETVALUE(0); /* imaginary change for reference */
1593 SWAP(uint32_t *, sp->curruns, sp->refruns);
1594 buf += sp->b.rowbytes;
1595 occ -= sp->b.rowbytes;
1596 sp->line++;
1597 continue;
1598 EOFG4:
1599 NeedBits16(13, BADG4);
1600 BADG4:
1601 #ifdef FAX3_DEBUG
1602 if (GetBits(13) != 0x1001)
1603 fputs("Bad EOFB\n", stderr);
1604 #endif
1605 ClrBits(13);
1606 if (((lastx + 7) >> 3) > (int)occ) /* check for buffer overrun */
1607 {
1608 TIFFErrorExtR(tif, module,
1609 "Buffer overrun detected : %" TIFF_SSIZE_FORMAT
1610 " bytes available, %d bits needed",
1611 occ, lastx);
1612 return -1;
1613 }
1614 (*sp->fill)(buf, thisrun, pa, lastx);
1615 UNCACHE_STATE(tif, sp);
1616 return (sp->line != start
1617 ? 1
1618 : -1); /* don't error on badly-terminated strips */
1619 }
1620 UNCACHE_STATE(tif, sp);
1621 return (1);
1622 }
1623 #undef SWAP
1624
1625 /*
1626 * Encode the requested amount of data.
1627 */
1628 static int Fax4Encode(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
1629 {
1630 static const char module[] = "Fax4Encode";
1631 Fax3CodecState *sp = EncoderState(tif);
1632 (void)s;
1633 if (cc % sp->b.rowbytes)
1634 {
1635 TIFFErrorExtR(tif, module, "Fractional scanlines cannot be written");
1636 return (0);
1637 }
1638 while (cc > 0)
1639 {
1640 if (!Fax3Encode2DRow(tif, bp, sp->refline, sp->b.rowpixels))
1641 return (0);
1642 _TIFFmemcpy(sp->refline, bp, sp->b.rowbytes);
1643 bp += sp->b.rowbytes;
1644 cc -= sp->b.rowbytes;
1645 }
1646 return (1);
1647 }
1648
1649 static int Fax4PostEncode(TIFF *tif)
1650 {
1651 Fax3CodecState *sp = EncoderState(tif);
1652
1653 /* terminate strip w/ EOFB */
1654 Fax3PutBits(tif, EOL, 12);
1655 Fax3PutBits(tif, EOL, 12);
1656 if (sp->bit != 8)
1657 Fax3FlushBits(tif, sp);
1658 return (1);
1659 }
1660
1661 int TIFFInitCCITTFax4(TIFF *tif, int scheme)
1662 {
1663 (void)scheme;
1664 if (InitCCITTFax3(tif))
1665 { /* reuse G3 support */
1666 /*
1667 * Merge codec-specific tag information.
1668 */
1669 if (!_TIFFMergeFields(tif, fax4Fields, TIFFArrayCount(fax4Fields)))
1670 {
1671 TIFFErrorExtR(tif, "TIFFInitCCITTFax4",
1672 "Merging CCITT Fax 4 codec-specific tags failed");
1673 return 0;
1674 }
1675
1676 tif->tif_decoderow = Fax4Decode;
1677 tif->tif_decodestrip = Fax4Decode;
1678 tif->tif_decodetile = Fax4Decode;
1679 tif->tif_encoderow = Fax4Encode;
1680 tif->tif_encodestrip = Fax4Encode;
1681 tif->tif_encodetile = Fax4Encode;
1682 tif->tif_postencode = Fax4PostEncode;
1683 /*
1684 * Suppress RTC at the end of each strip.
1685 */
1686 return TIFFSetField(tif, TIFFTAG_FAXMODE, FAXMODE_NORTC);
1687 }
1688 else
1689 return (0);
1690 }
1691
1692 /*
1693 * CCITT Group 3 1-D Modified Huffman RLE Compression Support.
1694 * (Compression algorithms 2 and 32771)
1695 */
1696
1697 /*
1698 * Decode the requested amount of RLE-encoded data.
1699 */
1700 static int Fax3DecodeRLE(TIFF *tif, uint8_t *buf, tmsize_t occ, uint16_t s)
1701 {
1702 DECLARE_STATE(tif, sp, "Fax3DecodeRLE");
1703 int mode = sp->b.mode;
1704 (void)s;
1705 if (occ % sp->b.rowbytes)
1706 {
1707 TIFFErrorExtR(tif, module, "Fractional scanlines cannot be read");
1708 return (-1);
1709 }
1710 CACHE_STATE(tif, sp);
1711 thisrun = sp->curruns;
1712 while (occ > 0)
1713 {
1714 a0 = 0;
1715 RunLength = 0;
1716 pa = thisrun;
1717 #ifdef FAX3_DEBUG
1718 printf("\nBitAcc=%08" PRIX32 ", BitsAvail = %d\n", BitAcc, BitsAvail);
1719 printf("-------------------- %" PRIu32 "\n", tif->tif_row);
1720 fflush(stdout);
1721 #endif
1722 EXPAND1D(EOFRLE);
1723 (*sp->fill)(buf, thisrun, pa, lastx);
1724 /*
1725 * Cleanup at the end of the row.
1726 */
1727 if (mode & FAXMODE_BYTEALIGN)
1728 {
1729 int n = BitsAvail - (BitsAvail & ~7);
1730 ClrBits(n);
1731 }
1732 else if (mode & FAXMODE_WORDALIGN)
1733 {
1734 int n = BitsAvail - (BitsAvail & ~15);
1735 ClrBits(n);
1736 if (BitsAvail == 0 && !isAligned(cp, uint16_t))
1737 cp++;
1738 }
1739 buf += sp->b.rowbytes;
1740 occ -= sp->b.rowbytes;
1741 sp->line++;
1742 continue;
1743 EOFRLE: /* premature EOF */
1744 (*sp->fill)(buf, thisrun, pa, lastx);
1745 UNCACHE_STATE(tif, sp);
1746 return (-1);
1747 }
1748 UNCACHE_STATE(tif, sp);
1749 return (1);
1750 }
1751
1752 int TIFFInitCCITTRLE(TIFF *tif, int scheme)
1753 {
1754 (void)scheme;
1755 if (InitCCITTFax3(tif))
1756 { /* reuse G3 support */
1757 tif->tif_decoderow = Fax3DecodeRLE;
1758 tif->tif_decodestrip = Fax3DecodeRLE;
1759 tif->tif_decodetile = Fax3DecodeRLE;
1760 /*
1761 * Suppress RTC+EOLs when encoding and byte-align data.
1762 */
1763 return TIFFSetField(tif, TIFFTAG_FAXMODE,
1764 FAXMODE_NORTC | FAXMODE_NOEOL | FAXMODE_BYTEALIGN);
1765 }
1766 else
1767 return (0);
1768 }
1769
1770 int TIFFInitCCITTRLEW(TIFF *tif, int scheme)
1771 {
1772 (void)scheme;
1773 if (InitCCITTFax3(tif))
1774 { /* reuse G3 support */
1775 tif->tif_decoderow = Fax3DecodeRLE;
1776 tif->tif_decodestrip = Fax3DecodeRLE;
1777 tif->tif_decodetile = Fax3DecodeRLE;
1778 /*
1779 * Suppress RTC+EOLs when encoding and word-align data.
1780 */
1781 return TIFFSetField(tif, TIFFTAG_FAXMODE,
1782 FAXMODE_NORTC | FAXMODE_NOEOL | FAXMODE_WORDALIGN);
1783 }
1784 else
1785 return (0);
1786 }
1787 #endif /* CCITT_SUPPORT */