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