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