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