]> git.saurik.com Git - wxWidgets.git/blame - src/tiff/tif_fax3.c
fixed typo : _ instead of wxT
[wxWidgets.git] / src / tiff / tif_fax3.c
CommitLineData
b47c832e
RR
1/* $Header$ */
2
3/*
4 * Copyright (c) 1990-1997 Sam Leffler
5 * Copyright (c) 1991-1997 Silicon Graphics, Inc.
6 *
94fbea12 7 * Permission to use, copy, modify, distribute, and sell this software and
b47c832e
RR
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.
94fbea12
DW
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 *
b47c832e
RR
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,
94fbea12
DW
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
b47c832e
RR
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 */
57typedef 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
74typedef 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
87typedef struct {
615a9936
DW
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 */
b47c832e
RR
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 */
153static int
154Fax3PreDecode(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
94fbea12 185static void LINKAGEMODE
b47c832e
RR
186Fax3Unexpected(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
94fbea12 193static void LINKAGEMODE
b47c832e
RR
194Fax3Extension(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
94fbea12 202static void LINKAGEMODE
b47c832e
RR
203Fax3BadLength(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
94fbea12 212static void LINKAGEMODE
b47c832e
RR
213Fax3PrematureEOF(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 */
94fbea12 225static int LINKAGEMODE
b47c832e
RR
226Fax3Decode1D(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 */
94fbea12 265static int LINKAGEMODE
b47c832e
RR
266Fax3Decode2D(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 */
360void
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 */
465static int
466Fax3SetupState(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(nruns*sizeof (uint16));
503 if (dsp->runs == NULL) {
504 TIFFError("Fax3SetupState",
505 "%s: No space for Group 3/4 run arrays",
506 tif->tif_name);
507 return (0);
508 }
509 dsp->curruns = dsp->runs;
510 if (needsRefLine)
511 dsp->refruns = dsp->runs + (nruns>>1);
512 else
513 dsp->refruns = NULL;
514 if (is2DEncoding(dsp)) { /* NB: default is 1D routine */
515 tif->tif_decoderow = Fax3Decode2D;
516 tif->tif_decodestrip = Fax3Decode2D;
517 tif->tif_decodetile = Fax3Decode2D;
518 }
519 } else if (needsRefLine) { /* 2d encoding */
520 Fax3EncodeState* esp = EncoderState(tif);
521 /*
522 * 2d encoding requires a scanline
523 * buffer for the ``reference line''; the
524 * scanline against which delta encoding
525 * is referenced. The reference line must
526 * be initialized to be ``white'' (done elsewhere).
527 */
528 esp->refline = (u_char*) _TIFFmalloc(rowbytes);
529 if (esp->refline == NULL) {
530 TIFFError("Fax3SetupState",
531 "%s: No space for Group 3/4 reference line",
532 tif->tif_name);
533 return (0);
534 }
535 } else /* 1d encoding */
536 EncoderState(tif)->refline = NULL;
537 return (1);
538}
539
540/*
541 * CCITT Group 3 FAX Encoding.
542 */
543
544#define Fax3FlushBits(tif, sp) { \
545 if ((tif)->tif_rawcc >= (tif)->tif_rawdatasize) \
546 (void) TIFFFlushData1(tif); \
547 *(tif)->tif_rawcp++ = (sp)->data; \
548 (tif)->tif_rawcc++; \
549 (sp)->data = 0, (sp)->bit = 8; \
550}
551#define _FlushBits(tif) { \
552 if ((tif)->tif_rawcc >= (tif)->tif_rawdatasize) \
553 (void) TIFFFlushData1(tif); \
554 *(tif)->tif_rawcp++ = data; \
555 (tif)->tif_rawcc++; \
556 data = 0, bit = 8; \
557}
558static const int _msbmask[9] =
559 { 0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff };
560#define _PutBits(tif, bits, length) { \
561 while (length > bit) { \
562 data |= bits >> (length - bit); \
563 length -= bit; \
564 _FlushBits(tif); \
565 } \
566 data |= (bits & _msbmask[length]) << (bit - length); \
567 bit -= length; \
568 if (bit == 0) \
569 _FlushBits(tif); \
570}
571
572/*
573 * Write a variable-length bit-value to
574 * the output stream. Values are
575 * assumed to be at most 16 bits.
576 */
94fbea12 577static void LINKAGEMODE
b47c832e
RR
578Fax3PutBits(TIFF* tif, u_int bits, u_int length)
579{
580 Fax3EncodeState* sp = EncoderState(tif);
581 int bit = sp->bit;
582 int data = sp->data;
583
584 _PutBits(tif, bits, length);
585
586 sp->data = data;
587 sp->bit = bit;
588}
589
590/*
591 * Write a code to the output stream.
592 */
593#define putcode(tif, te) Fax3PutBits(tif, (te)->code, (te)->length)
594
595#ifdef FAX3_DEBUG
596#define DEBUG_COLOR(w) (tab == TIFFFaxWhiteCodes ? w "W" : w "B")
597#define DEBUG_PRINT(what,len) { \
598 int t; \
599 printf("%08X/%-2d: %s%5d\t", data, bit, DEBUG_COLOR(what), len); \
600 for (t = length-1; t >= 0; t--) \
601 putchar(code & (1<<t) ? '1' : '0'); \
602 putchar('\n'); \
603}
604#endif
605
606/*
607 * Write the sequence of codes that describes
608 * the specified span of zero's or one's. The
609 * appropriate table that holds the make-up and
610 * terminating codes is supplied.
611 */
94fbea12 612static void LINKAGEMODE
b47c832e
RR
613putspan(TIFF* tif, int32 span, const tableentry* tab)
614{
615 Fax3EncodeState* sp = EncoderState(tif);
616 int bit = sp->bit;
617 int data = sp->data;
618 u_int code, length;
619
620 while (span >= 2624) {
621 const tableentry* te = &tab[63 + (2560>>6)];
622 code = te->code, length = te->length;
623#ifdef FAX3_DEBUG
624 DEBUG_PRINT("MakeUp", te->runlen);
625#endif
626 _PutBits(tif, code, length);
627 span -= te->runlen;
628 }
629 if (span >= 64) {
630 const tableentry* te = &tab[63 + (span>>6)];
631 assert(te->runlen == 64*(span>>6));
632 code = te->code, length = te->length;
633#ifdef FAX3_DEBUG
634 DEBUG_PRINT("MakeUp", te->runlen);
635#endif
636 _PutBits(tif, code, length);
637 span -= te->runlen;
638 }
639 code = tab[span].code, length = tab[span].length;
640#ifdef FAX3_DEBUG
641 DEBUG_PRINT(" Term", tab[span].runlen);
642#endif
643 _PutBits(tif, code, length);
644
645 sp->data = data;
646 sp->bit = bit;
647}
648
649/*
650 * Write an EOL code to the output stream. The zero-fill
651 * logic for byte-aligning encoded scanlines is handled
652 * here. We also handle writing the tag bit for the next
653 * scanline when doing 2d encoding.
654 */
94fbea12 655static void LINKAGEMODE
b47c832e
RR
656Fax3PutEOL(TIFF* tif)
657{
658 Fax3EncodeState* sp = EncoderState(tif);
659 int bit = sp->bit;
660 int data = sp->data;
661 u_int code, length;
662
663 if (sp->b.groupoptions & GROUP3OPT_FILLBITS) {
664 /*
665 * Force bit alignment so EOL will terminate on
666 * a byte boundary. That is, force the bit alignment
667 * to 16-12 = 4 before putting out the EOL code.
668 */
669 int align = 8 - 4;
670 if (align != sp->bit) {
671 if (align > sp->bit)
672 align = sp->bit + (8 - align);
673 else
674 align = sp->bit - align;
675 code = 0;
676 _PutBits(tif, 0, align);
677 }
678 }
679 code = EOL, length = 12;
680 if (is2DEncoding(sp))
615a9936
DW
681#if defined(__VISAGECPP30__)
682/* VA 3.0 is just plain wierd. */
683 code = (code<<1) | (sp->tag == Fax3EncodeState::G3_1D), length++;
684#else
b47c832e 685 code = (code<<1) | (sp->tag == G3_1D), length++;
615a9936 686#endif
b47c832e
RR
687 _PutBits(tif, code, length);
688
689 sp->data = data;
690 sp->bit = bit;
691}
692
693/*
694 * Reset encoding state at the start of a strip.
695 */
696static int
697Fax3PreEncode(TIFF* tif, tsample_t s)
698{
699 Fax3EncodeState* sp = EncoderState(tif);
700
701 (void) s;
702 assert(sp != NULL);
703 sp->bit = 8;
704 sp->data = 0;
615a9936
DW
705#if defined(__VISAGECPP30__)
706/* VA 3.0 is just plain wierd. */
707 sp->tag = Fax3EncodeState::G3_1D;
708#else
b47c832e 709 sp->tag = G3_1D;
615a9936 710#endif
b47c832e
RR
711 /*
712 * This is necessary for Group 4; otherwise it isn't
713 * needed because the first scanline of each strip ends
714 * up being copied into the refline.
715 */
716 if (sp->refline)
717 _TIFFmemset(sp->refline, 0x00, sp->b.rowbytes);
718 if (is2DEncoding(sp)) {
719 float res = tif->tif_dir.td_yresolution;
720 /*
721 * The CCITT spec says that when doing 2d encoding, you
722 * should only do it on K consecutive scanlines, where K
723 * depends on the resolution of the image being encoded
724 * (2 for <= 200 lpi, 4 for > 200 lpi). Since the directory
725 * code initializes td_yresolution to 0, this code will
726 * select a K of 2 unless the YResolution tag is set
727 * appropriately. (Note also that we fudge a little here
728 * and use 150 lpi to avoid problems with units conversion.)
729 */
730 if (tif->tif_dir.td_resolutionunit == RESUNIT_CENTIMETER)
731 res *= 2.54f; /* convert to inches */
732 sp->maxk = (res > 150 ? 4 : 2);
733 sp->k = sp->maxk-1;
734 } else
735 sp->k = sp->maxk = 0;
736 return (1);
737}
738
739static const u_char zeroruns[256] = {
740 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, /* 0x00 - 0x0f */
741 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 0x10 - 0x1f */
742 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0x20 - 0x2f */
743 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0x30 - 0x3f */
744 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40 - 0x4f */
745 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x50 - 0x5f */
746 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60 - 0x6f */
747 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x70 - 0x7f */
748 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x80 - 0x8f */
749 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x90 - 0x9f */
750 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xa0 - 0xaf */
751 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xb0 - 0xbf */
752 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xc0 - 0xcf */
753 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xd0 - 0xdf */
754 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xe0 - 0xef */
755 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xf0 - 0xff */
756};
757static const u_char oneruns[256] = {
758 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 - 0x0f */
759 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x10 - 0x1f */
760 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20 - 0x2f */
761 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x30 - 0x3f */
762 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x40 - 0x4f */
763 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x50 - 0x5f */
764 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x60 - 0x6f */
765 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x70 - 0x7f */
766 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x80 - 0x8f */
767 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x90 - 0x9f */
768 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0xa0 - 0xaf */
769 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0xb0 - 0xbf */
770 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0xc0 - 0xcf */
771 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0xd0 - 0xdf */
772 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 0xe0 - 0xef */
773 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 7, 8, /* 0xf0 - 0xff */
774};
775
776/*
777 * On certain systems it pays to inline
778 * the routines that find pixel spans.
779 */
780#ifdef VAXC
781static int32 find0span(u_char*, int32, int32);
782static int32 find1span(u_char*, int32, int32);
783#pragma inline(find0span,find1span)
784#endif
785
786/*
787 * Find a span of ones or zeros using the supplied
788 * table. The ``base'' of the bit string is supplied
789 * along with the start+end bit indices.
790 */
94fbea12 791INLINE static int32 LINKAGEMODE
b47c832e
RR
792find0span(u_char* bp, int32 bs, int32 be)
793{
794 int32 bits = be - bs;
795 int32 n, span;
796
797 bp += bs>>3;
798 /*
799 * Check partial byte on lhs.
800 */
801 if (bits > 0 && (n = (bs & 7))) {
802 span = zeroruns[(*bp << n) & 0xff];
803 if (span > 8-n) /* table value too generous */
804 span = 8-n;
805 if (span > bits) /* constrain span to bit range */
806 span = bits;
807 if (n+span < 8) /* doesn't extend to edge of byte */
808 return (span);
809 bits -= span;
810 bp++;
811 } else
812 span = 0;
813 if (bits >= 2*8*sizeof (long)) {
814 long* lp;
815 /*
816 * Align to longword boundary and check longwords.
817 */
818 while (!isAligned(bp, long)) {
819 if (*bp != 0x00)
820 return (span + zeroruns[*bp]);
821 span += 8, bits -= 8;
822 bp++;
823 }
824 lp = (long*) bp;
825 while (bits >= 8*sizeof (long) && *lp == 0) {
826 span += 8*sizeof (long), bits -= 8*sizeof (long);
827 lp++;
828 }
829 bp = (u_char*) lp;
830 }
831 /*
832 * Scan full bytes for all 0's.
833 */
834 while (bits >= 8) {
835 if (*bp != 0x00) /* end of run */
836 return (span + zeroruns[*bp]);
837 span += 8, bits -= 8;
838 bp++;
839 }
840 /*
841 * Check partial byte on rhs.
842 */
843 if (bits > 0) {
844 n = zeroruns[*bp];
845 span += (n > bits ? bits : n);
846 }
847 return (span);
848}
849
94fbea12 850INLINE static int32 LINKAGEMODE
b47c832e
RR
851find1span(u_char* bp, int32 bs, int32 be)
852{
853 int32 bits = be - bs;
854 int32 n, span;
855
856 bp += bs>>3;
857 /*
858 * Check partial byte on lhs.
859 */
860 if (bits > 0 && (n = (bs & 7))) {
861 span = oneruns[(*bp << n) & 0xff];
862 if (span > 8-n) /* table value too generous */
863 span = 8-n;
864 if (span > bits) /* constrain span to bit range */
865 span = bits;
866 if (n+span < 8) /* doesn't extend to edge of byte */
867 return (span);
868 bits -= span;
869 bp++;
870 } else
871 span = 0;
872 if (bits >= 2*8*sizeof (long)) {
873 long* lp;
874 /*
875 * Align to longword boundary and check longwords.
876 */
877 while (!isAligned(bp, long)) {
878 if (*bp != 0xff)
879 return (span + oneruns[*bp]);
880 span += 8, bits -= 8;
881 bp++;
882 }
883 lp = (long*) bp;
884 while (bits >= 8*sizeof (long) && *lp == ~0) {
885 span += 8*sizeof (long), bits -= 8*sizeof (long);
886 lp++;
887 }
888 bp = (u_char*) lp;
889 }
890 /*
891 * Scan full bytes for all 1's.
892 */
893 while (bits >= 8) {
894 if (*bp != 0xff) /* end of run */
895 return (span + oneruns[*bp]);
896 span += 8, bits -= 8;
897 bp++;
898 }
899 /*
900 * Check partial byte on rhs.
901 */
902 if (bits > 0) {
903 n = oneruns[*bp];
904 span += (n > bits ? bits : n);
905 }
906 return (span);
907}
908
909/*
910 * Return the offset of the next bit in the range
911 * [bs..be] that is different from the specified
912 * color. The end, be, is returned if no such bit
913 * exists.
914 */
915#define finddiff(_cp, _bs, _be, _color) \
916 (_bs + (_color ? find1span(_cp,_bs,_be) : find0span(_cp,_bs,_be)))
917/*
918 * Like finddiff, but also check the starting bit
919 * against the end in case start > end.
920 */
921#define finddiff2(_cp, _bs, _be, _color) \
922 (_bs < _be ? finddiff(_cp,_bs,_be,_color) : _be)
923
924/*
925 * 1d-encode a row of pixels. The encoding is
926 * a sequence of all-white or all-black spans
927 * of pixels encoded with Huffman codes.
928 */
94fbea12 929static int LINKAGEMODE
b47c832e
RR
930Fax3Encode1DRow(TIFF* tif, u_char* bp, uint32 bits)
931{
932 Fax3EncodeState* sp = EncoderState(tif);
933 int32 bs = 0, span;
934
935 for (;;) {
936 span = find0span(bp, bs, bits); /* white span */
937 putspan(tif, span, TIFFFaxWhiteCodes);
938 bs += span;
939 if (bs >= bits)
940 break;
941 span = find1span(bp, bs, bits); /* black span */
942 putspan(tif, span, TIFFFaxBlackCodes);
943 bs += span;
944 if (bs >= bits)
945 break;
946 }
947 if (sp->b.mode & (FAXMODE_BYTEALIGN|FAXMODE_WORDALIGN)) {
948 if (sp->bit != 8) /* byte-align */
949 Fax3FlushBits(tif, sp);
950 if ((sp->b.mode&FAXMODE_WORDALIGN) &&
951 !isAligned(tif->tif_rawcp, uint16))
952 Fax3FlushBits(tif, sp);
953 }
954 return (1);
955}
956
957static const tableentry horizcode =
958 { 3, 0x1 }; /* 001 */
959static const tableentry passcode =
960 { 4, 0x1 }; /* 0001 */
961static const tableentry vcodes[7] = {
962 { 7, 0x03 }, /* 0000 011 */
963 { 6, 0x03 }, /* 0000 11 */
964 { 3, 0x03 }, /* 011 */
965 { 1, 0x1 }, /* 1 */
966 { 3, 0x2 }, /* 010 */
967 { 6, 0x02 }, /* 0000 10 */
968 { 7, 0x02 } /* 0000 010 */
969};
970
971/*
972 * 2d-encode a row of pixels. Consult the CCITT
973 * documentation for the algorithm.
974 */
94fbea12 975static int LINKAGEMODE
b47c832e
RR
976Fax3Encode2DRow(TIFF* tif, u_char* bp, u_char* rp, uint32 bits)
977{
978#define PIXEL(buf,ix) ((((buf)[(ix)>>3]) >> (7-((ix)&7))) & 1)
979 int32 a0 = 0;
980 int32 a1 = (PIXEL(bp, 0) != 0 ? 0 : finddiff(bp, 0, bits, 0));
981 int32 b1 = (PIXEL(rp, 0) != 0 ? 0 : finddiff(rp, 0, bits, 0));
982 int32 a2, b2;
983
984 for (;;) {
985 b2 = finddiff2(rp, b1, bits, PIXEL(rp,b1));
986 if (b2 >= a1) {
987 int32 d = b1 - a1;
988 if (!(-3 <= d && d <= 3)) { /* horizontal mode */
989 a2 = finddiff2(bp, a1, bits, PIXEL(bp,a1));
990 putcode(tif, &horizcode);
991 if (a0+a1 == 0 || PIXEL(bp, a0) == 0) {
992 putspan(tif, a1-a0, TIFFFaxWhiteCodes);
993 putspan(tif, a2-a1, TIFFFaxBlackCodes);
994 } else {
995 putspan(tif, a1-a0, TIFFFaxBlackCodes);
996 putspan(tif, a2-a1, TIFFFaxWhiteCodes);
997 }
998 a0 = a2;
999 } else { /* vertical mode */
1000 putcode(tif, &vcodes[d+3]);
1001 a0 = a1;
1002 }
1003 } else { /* pass mode */
1004 putcode(tif, &passcode);
1005 a0 = b2;
1006 }
1007 if (a0 >= bits)
1008 break;
1009 a1 = finddiff(bp, a0, bits, PIXEL(bp,a0));
1010 b1 = finddiff(rp, a0, bits, !PIXEL(bp,a0));
1011 b1 = finddiff(rp, b1, bits, PIXEL(bp,a0));
1012 }
1013 return (1);
1014#undef PIXEL
1015}
1016
1017/*
1018 * Encode a buffer of pixels.
1019 */
94fbea12 1020static int LINKAGEMODE
b47c832e
RR
1021Fax3Encode(TIFF* tif, tidata_t bp, tsize_t cc, tsample_t s)
1022{
1023 Fax3EncodeState* sp = EncoderState(tif);
1024
1025 (void) s;
1026 while ((long)cc > 0) {
1027 if ((sp->b.mode & FAXMODE_NOEOL) == 0)
1028 Fax3PutEOL(tif);
1029 if (is2DEncoding(sp)) {
615a9936
DW
1030#if defined(__VISAGECPP30__)
1031/* VA 3.0 is just plain wierd. */
1032 if (sp->tag == Fax3EncodeState::G3_1D) {
1033#else
b47c832e 1034 if (sp->tag == G3_1D) {
615a9936 1035#endif
b47c832e
RR
1036 if (!Fax3Encode1DRow(tif, bp, sp->b.rowpixels))
1037 return (0);
615a9936
DW
1038#if defined(__VISAGECPP30__)
1039/* VA 3.0 is just plain wierd. */
1040 sp->tag = Fax3EncodeState::G3_2D;
1041#else
b47c832e 1042 sp->tag = G3_2D;
615a9936 1043#endif
b47c832e
RR
1044 } else {
1045 if (!Fax3Encode2DRow(tif, bp, sp->refline, sp->b.rowpixels))
1046 return (0);
1047 sp->k--;
1048 }
1049 if (sp->k == 0) {
615a9936
DW
1050#if defined(__VISAGECPP30__)
1051/* VA 3.0 is just plain wierd. */
1052 sp->tag = Fax3EncodeState::G3_1D;
1053#else
b47c832e 1054 sp->tag = G3_1D;
615a9936 1055#endif
b47c832e
RR
1056 sp->k = sp->maxk-1;
1057 } else
1058 _TIFFmemcpy(sp->refline, bp, sp->b.rowbytes);
1059 } else {
1060 if (!Fax3Encode1DRow(tif, bp, sp->b.rowpixels))
1061 return (0);
1062 }
1063 bp += sp->b.rowbytes;
1064 cc -= sp->b.rowbytes;
1065 if (cc != 0)
1066 tif->tif_row++;
1067 }
1068 return (1);
1069}
1070
1071static int
1072Fax3PostEncode(TIFF* tif)
1073{
1074 Fax3EncodeState* sp = EncoderState(tif);
1075
1076 if (sp->bit != 8)
1077 Fax3FlushBits(tif, sp);
1078 return (1);
1079}
1080
1081static void
1082Fax3Close(TIFF* tif)
1083{
1084 if ((Fax3State(tif)->mode & FAXMODE_NORTC) == 0) {
1085 Fax3EncodeState* sp = EncoderState(tif);
1086 u_int code = EOL;
1087 u_int length = 12;
1088 int i;
1089
1090 if (is2DEncoding(sp))
615a9936
DW
1091#if defined(__VISAGECPP30__)
1092/* VA 3.0 is just plain wierd. */
1093 code = (code<<1) | (sp->tag == Fax3EncodeState::G3_1D), length++;
1094#else
b47c832e 1095 code = (code<<1) | (sp->tag == G3_1D), length++;
615a9936 1096#endif
b47c832e
RR
1097 for (i = 0; i < 6; i++)
1098 Fax3PutBits(tif, code, length);
1099 Fax3FlushBits(tif, sp);
1100 }
1101}
1102
1103static void
1104Fax3Cleanup(TIFF* tif)
1105{
1106 if (tif->tif_data) {
1107 if (tif->tif_mode == O_RDONLY) {
1108 Fax3DecodeState* sp = DecoderState(tif);
1109 if (sp->runs)
1110 _TIFFfree(sp->runs);
1111 } else {
1112 Fax3EncodeState* sp = EncoderState(tif);
1113 if (sp->refline)
1114 _TIFFfree(sp->refline);
1115 }
1116 if (Fax3State(tif)->subaddress)
1117 _TIFFfree(Fax3State(tif)->subaddress);
1118 _TIFFfree(tif->tif_data);
1119 tif->tif_data = NULL;
1120 }
1121}
1122
1123#define FIELD_BADFAXLINES (FIELD_CODEC+0)
1124#define FIELD_CLEANFAXDATA (FIELD_CODEC+1)
1125#define FIELD_BADFAXRUN (FIELD_CODEC+2)
1126#define FIELD_RECVPARAMS (FIELD_CODEC+3)
1127#define FIELD_SUBADDRESS (FIELD_CODEC+4)
1128#define FIELD_RECVTIME (FIELD_CODEC+5)
1129
1130#define FIELD_OPTIONS (FIELD_CODEC+6)
1131
1132static const TIFFFieldInfo faxFieldInfo[] = {
1133 { TIFFTAG_FAXMODE, 0, 0, TIFF_ANY, FIELD_PSEUDO,
1134 FALSE, FALSE, "FaxMode" },
1135 { TIFFTAG_FAXFILLFUNC, 0, 0, TIFF_ANY, FIELD_PSEUDO,
1136 FALSE, FALSE, "FaxFillFunc" },
1137 { TIFFTAG_BADFAXLINES, 1, 1, TIFF_LONG, FIELD_BADFAXLINES,
1138 TRUE, FALSE, "BadFaxLines" },
1139 { TIFFTAG_BADFAXLINES, 1, 1, TIFF_SHORT, FIELD_BADFAXLINES,
1140 TRUE, FALSE, "BadFaxLines" },
1141 { TIFFTAG_CLEANFAXDATA, 1, 1, TIFF_SHORT, FIELD_CLEANFAXDATA,
1142 TRUE, FALSE, "CleanFaxData" },
1143 { TIFFTAG_CONSECUTIVEBADFAXLINES,1,1, TIFF_LONG, FIELD_BADFAXRUN,
1144 TRUE, FALSE, "ConsecutiveBadFaxLines" },
1145 { TIFFTAG_CONSECUTIVEBADFAXLINES,1,1, TIFF_SHORT, FIELD_BADFAXRUN,
1146 TRUE, FALSE, "ConsecutiveBadFaxLines" },
1147 { TIFFTAG_FAXRECVPARAMS, 1, 1, TIFF_LONG, FIELD_RECVPARAMS,
1148 TRUE, FALSE, "FaxRecvParams" },
1149 { TIFFTAG_FAXSUBADDRESS, -1,-1, TIFF_ASCII, FIELD_SUBADDRESS,
1150 TRUE, FALSE, "FaxSubAddress" },
1151 { TIFFTAG_FAXRECVTIME, 1, 1, TIFF_LONG, FIELD_RECVTIME,
1152 TRUE, FALSE, "FaxRecvTime" },
1153};
1154static const TIFFFieldInfo fax3FieldInfo[] = {
1155 { TIFFTAG_GROUP3OPTIONS, 1, 1, TIFF_LONG, FIELD_OPTIONS,
1156 FALSE, FALSE, "Group3Options" },
1157};
1158static const TIFFFieldInfo fax4FieldInfo[] = {
1159 { TIFFTAG_GROUP4OPTIONS, 1, 1, TIFF_LONG, FIELD_OPTIONS,
1160 FALSE, FALSE, "Group4Options" },
1161};
1162#define N(a) (sizeof (a) / sizeof (a[0]))
1163
1164static int
1165Fax3VSetField(TIFF* tif, ttag_t tag, va_list ap)
1166{
1167 Fax3BaseState* sp = Fax3State(tif);
1168
1169 switch (tag) {
1170 case TIFFTAG_FAXMODE:
1171 sp->mode = va_arg(ap, int);
1172 return (1); /* NB: pseudo tag */
1173 case TIFFTAG_FAXFILLFUNC:
1174 if (tif->tif_mode == O_RDONLY)
1175 DecoderState(tif)->fill = va_arg(ap, TIFFFaxFillFunc);
1176 return (1); /* NB: pseudo tag */
1177 case TIFFTAG_GROUP3OPTIONS:
1178 case TIFFTAG_GROUP4OPTIONS:
1179 sp->groupoptions = va_arg(ap, uint32);
1180 break;
1181 case TIFFTAG_BADFAXLINES:
1182 sp->badfaxlines = va_arg(ap, uint32);
1183 break;
1184 case TIFFTAG_CLEANFAXDATA:
1185 sp->cleanfaxdata = (uint16) va_arg(ap, int);
1186 break;
1187 case TIFFTAG_CONSECUTIVEBADFAXLINES:
1188 sp->badfaxrun = va_arg(ap, uint32);
1189 break;
1190 case TIFFTAG_FAXRECVPARAMS:
1191 sp->recvparams = va_arg(ap, uint32);
1192 break;
1193 case TIFFTAG_FAXSUBADDRESS:
1194 _TIFFsetString(&sp->subaddress, va_arg(ap, char*));
1195 break;
1196 case TIFFTAG_FAXRECVTIME:
1197 sp->recvtime = va_arg(ap, uint32);
1198 break;
1199 default:
1200 return (*sp->vsetparent)(tif, tag, ap);
1201 }
1202 TIFFSetFieldBit(tif, _TIFFFieldWithTag(tif, tag)->field_bit);
1203 tif->tif_flags |= TIFF_DIRTYDIRECT;
1204 return (1);
1205}
1206
1207static int
1208Fax3VGetField(TIFF* tif, ttag_t tag, va_list ap)
1209{
1210 Fax3BaseState* sp = Fax3State(tif);
1211
1212 switch (tag) {
1213 case TIFFTAG_FAXMODE:
1214 *va_arg(ap, int*) = sp->mode;
1215 break;
1216 case TIFFTAG_FAXFILLFUNC:
1217 if (tif->tif_mode == O_RDONLY)
1218 *va_arg(ap, TIFFFaxFillFunc*) = DecoderState(tif)->fill;
1219 break;
1220 case TIFFTAG_GROUP3OPTIONS:
1221 case TIFFTAG_GROUP4OPTIONS:
1222 *va_arg(ap, uint32*) = sp->groupoptions;
1223 break;
1224 case TIFFTAG_BADFAXLINES:
1225 *va_arg(ap, uint32*) = sp->badfaxlines;
1226 break;
1227 case TIFFTAG_CLEANFAXDATA:
1228 *va_arg(ap, uint16*) = sp->cleanfaxdata;
1229 break;
1230 case TIFFTAG_CONSECUTIVEBADFAXLINES:
1231 *va_arg(ap, uint32*) = sp->badfaxrun;
1232 break;
1233 case TIFFTAG_FAXRECVPARAMS:
1234 *va_arg(ap, uint32*) = sp->recvparams;
1235 break;
1236 case TIFFTAG_FAXSUBADDRESS:
1237 *va_arg(ap, char**) = sp->subaddress;
1238 break;
1239 case TIFFTAG_FAXRECVTIME:
1240 *va_arg(ap, uint32*) = sp->recvtime;
1241 break;
1242 default:
1243 return (*sp->vgetparent)(tif, tag, ap);
1244 }
1245 return (1);
1246}
1247
94fbea12 1248static void LINKAGEMODE
b47c832e
RR
1249Fax3PrintDir(TIFF* tif, FILE* fd, long flags)
1250{
1251 Fax3BaseState* sp = Fax3State(tif);
1252
1253 (void) flags;
1254 if (TIFFFieldSet(tif,FIELD_OPTIONS)) {
1255 const char* sep = " ";
1256 if (tif->tif_dir.td_compression == COMPRESSION_CCITTFAX4) {
1257 fprintf(fd, " Group 4 Options:");
1258 if (sp->groupoptions & GROUP4OPT_UNCOMPRESSED)
1259 fprintf(fd, "%suncompressed data", sep);
1260 } else {
1261
1262 fprintf(fd, " Group 3 Options:");
1263 if (sp->groupoptions & GROUP3OPT_2DENCODING)
1264 fprintf(fd, "%s2-d encoding", sep), sep = "+";
1265 if (sp->groupoptions & GROUP3OPT_FILLBITS)
1266 fprintf(fd, "%sEOL padding", sep), sep = "+";
1267 if (sp->groupoptions & GROUP3OPT_UNCOMPRESSED)
1268 fprintf(fd, "%suncompressed data", sep);
1269 }
1270 fprintf(fd, " (%lu = 0x%lx)\n",
1271 (u_long) sp->groupoptions, (u_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", (u_long) sp->badfaxlines);
1291 if (TIFFFieldSet(tif,FIELD_BADFAXRUN))
1292 fprintf(fd, " Consecutive Bad Fax Lines: %lu\n",
1293 (u_long) sp->badfaxrun);
1294 if (TIFFFieldSet(tif,FIELD_RECVPARAMS))
1295 fprintf(fd, " Fax Receive Parameters: %08lx\n",
1296 (u_long) sp->recvparams);
1297 if (TIFFFieldSet(tif,FIELD_SUBADDRESS))
1298 fprintf(fd, " Fax SubAddress: %s\n", sp->subaddress);
1299 if (TIFFFieldSet(tif,FIELD_RECVTIME))
1300 fprintf(fd, " Fax Receive Time: %lu secs\n",
1301 (u_long) sp->recvtime);
1302}
1303
94fbea12 1304static int LINKAGEMODE
b47c832e
RR
1305InitCCITTFax3(TIFF* tif)
1306{
1307 Fax3BaseState* sp;
1308
1309 /*
1310 * Allocate state block so tag methods have storage to record values.
1311 */
1312 if (tif->tif_mode == O_RDONLY)
615a9936
DW
1313#if defined(__VISAGECPP__)
1314 tif->tif_data = (tidata_t)_TIFFmalloc(sizeof (Fax3DecodeState));
1315 else
1316 tif->tif_data = (tidata_t)_TIFFmalloc(sizeof (Fax3EncodeState));
1317#else
b47c832e
RR
1318 tif->tif_data = _TIFFmalloc(sizeof (Fax3DecodeState));
1319 else
1320 tif->tif_data = _TIFFmalloc(sizeof (Fax3EncodeState));
615a9936 1321#endif
b47c832e
RR
1322 if (tif->tif_data == NULL) {
1323 TIFFError("TIFFInitCCITTFax3",
1324 "%s: No space for state block", tif->tif_name);
1325 return (0);
1326 }
1327 sp = Fax3State(tif);
1328
1329 /*
1330 * Merge codec-specific tag information and
1331 * override parent get/set field methods.
1332 */
1333 _TIFFMergeFieldInfo(tif, faxFieldInfo, N(faxFieldInfo));
1334 sp->vgetparent = tif->tif_vgetfield;
1335 tif->tif_vgetfield = Fax3VGetField; /* hook for codec tags */
1336 sp->vsetparent = tif->tif_vsetfield;
1337 tif->tif_vsetfield = Fax3VSetField; /* hook for codec tags */
1338 tif->tif_printdir = Fax3PrintDir; /* hook for codec tags */
1339 sp->groupoptions = 0;
1340 sp->recvparams = 0;
1341 sp->subaddress = NULL;
1342
1343 if (tif->tif_mode == O_RDONLY) {
1344 tif->tif_flags |= TIFF_NOBITREV;/* decoder does bit reversal */
1345 DecoderState(tif)->runs = NULL;
1346 TIFFSetField(tif, TIFFTAG_FAXFILLFUNC, _TIFFFax3fillruns);
1347 } else
1348 EncoderState(tif)->refline = NULL;
1349
1350 /*
1351 * Install codec methods.
1352 */
1353 tif->tif_setupdecode = Fax3SetupState;
1354 tif->tif_predecode = Fax3PreDecode;
1355 tif->tif_decoderow = Fax3Decode1D;
1356 tif->tif_decodestrip = Fax3Decode1D;
1357 tif->tif_decodetile = Fax3Decode1D;
1358 tif->tif_setupencode = Fax3SetupState;
1359 tif->tif_preencode = Fax3PreEncode;
1360 tif->tif_postencode = Fax3PostEncode;
1361 tif->tif_encoderow = Fax3Encode;
1362 tif->tif_encodestrip = Fax3Encode;
1363 tif->tif_encodetile = Fax3Encode;
1364 tif->tif_close = Fax3Close;
1365 tif->tif_cleanup = Fax3Cleanup;
1366
1367 return (1);
1368}
1369
1370int
1371TIFFInitCCITTFax3(TIFF* tif, int scheme)
1372{
1373 if (InitCCITTFax3(tif)) {
1374 _TIFFMergeFieldInfo(tif, fax3FieldInfo, N(fax3FieldInfo));
1375
1376 /*
1377 * The default format is Class/F-style w/o RTC.
1378 */
1379 return TIFFSetField(tif, TIFFTAG_FAXMODE, FAXMODE_CLASSF);
1380 } else
1381 return (0);
1382}
1383
1384/*
1385 * CCITT Group 4 (T.6) Facsimile-compatible
1386 * Compression Scheme Support.
1387 */
1388
1389#define SWAP(t,a,b) { t x; x = (a); (a) = (b); (b) = x; }
1390/*
1391 * Decode the requested amount of G4-encoded data.
1392 */
94fbea12 1393static int LINKAGEMODE
b47c832e
RR
1394Fax4Decode(TIFF* tif, tidata_t buf, tsize_t occ, tsample_t s)
1395{
1396 DECLARE_STATE_2D(tif, sp, "Fax4Decode");
1397
1398 (void) s;
1399 CACHE_STATE(tif, sp);
1400 while ((long)occ > 0) {
1401 a0 = 0;
1402 RunLength = 0;
1403 pa = thisrun = sp->curruns;
1404 pb = sp->refruns;
1405 b1 = *pb++;
1406#ifdef FAX3_DEBUG
1407 printf("\nBitAcc=%08X, BitsAvail = %d\n", BitAcc, BitsAvail);
1408 printf("-------------------- %d\n", tif->tif_row);
1409 fflush(stdout);
1410#endif
1411 EXPAND2D(EOFG4);
1412 (*sp->fill)(buf, thisrun, pa, lastx);
1413 SETVAL(0); /* imaginary change for reference */
1414 SWAP(uint32*, sp->curruns, sp->refruns);
1415 buf += sp->b.rowbytes;
1416 occ -= sp->b.rowbytes;
1417 if (occ != 0)
1418 tif->tif_row++;
1419 continue;
1420 EOFG4:
1421 (*sp->fill)(buf, thisrun, pa, lastx);
1422 UNCACHE_STATE(tif, sp);
1423 return (-1);
1424 }
1425 UNCACHE_STATE(tif, sp);
1426 return (1);
1427}
1428#undef SWAP
1429
1430/*
1431 * Encode the requested amount of data.
1432 */
94fbea12 1433static int LINKAGEMODE
b47c832e
RR
1434Fax4Encode(TIFF* tif, tidata_t bp, tsize_t cc, tsample_t s)
1435{
1436 Fax3EncodeState *sp = EncoderState(tif);
1437
1438 (void) s;
1439 while ((long)cc > 0) {
1440 if (!Fax3Encode2DRow(tif, bp, sp->refline, sp->b.rowpixels))
1441 return (0);
1442 _TIFFmemcpy(sp->refline, bp, sp->b.rowbytes);
1443 bp += sp->b.rowbytes;
1444 cc -= sp->b.rowbytes;
1445 if (cc != 0)
1446 tif->tif_row++;
1447 }
1448 return (1);
1449}
1450
1451static int
1452Fax4PostEncode(TIFF* tif)
1453{
1454 Fax3EncodeState *sp = EncoderState(tif);
1455
1456 /* terminate strip w/ EOFB */
1457 Fax3PutBits(tif, EOL, 12);
1458 Fax3PutBits(tif, EOL, 12);
1459 if (sp->bit != 8)
1460 Fax3FlushBits(tif, sp);
1461 return (1);
1462}
1463
1464int
1465TIFFInitCCITTFax4(TIFF* tif, int scheme)
1466{
1467 if (InitCCITTFax3(tif)) { /* reuse G3 support */
1468 _TIFFMergeFieldInfo(tif, fax4FieldInfo, N(fax4FieldInfo));
1469
1470 tif->tif_decoderow = Fax4Decode;
1471 tif->tif_decodestrip = Fax4Decode;
1472 tif->tif_decodetile = Fax4Decode;
1473 tif->tif_encoderow = Fax4Encode;
1474 tif->tif_encodestrip = Fax4Encode;
1475 tif->tif_encodetile = Fax4Encode;
1476 tif->tif_postencode = Fax4PostEncode;
1477 /*
1478 * Suppress RTC at the end of each strip.
1479 */
1480 return TIFFSetField(tif, TIFFTAG_FAXMODE, FAXMODE_NORTC);
1481 } else
1482 return (0);
1483}
1484
1485/*
1486 * CCITT Group 3 1-D Modified Huffman RLE Compression Support.
1487 * (Compression algorithms 2 and 32771)
1488 */
1489
1490/*
1491 * Decode the requested amount of RLE-encoded data.
1492 */
94fbea12 1493static int LINKAGEMODE
b47c832e
RR
1494Fax3DecodeRLE(TIFF* tif, tidata_t buf, tsize_t occ, tsample_t s)
1495{
1496 DECLARE_STATE(tif, sp, "Fax3DecodeRLE");
1497 int mode = sp->b.mode;
1498
1499 (void) s;
1500 CACHE_STATE(tif, sp);
1501 thisrun = sp->curruns;
1502 while ((long)occ > 0) {
1503 a0 = 0;
1504 RunLength = 0;
1505 pa = thisrun;
1506#ifdef FAX3_DEBUG
1507 printf("\nBitAcc=%08X, BitsAvail = %d\n", BitAcc, BitsAvail);
1508 printf("-------------------- %d\n", tif->tif_row);
1509 fflush(stdout);
1510#endif
1511 EXPAND1D(EOFRLE);
1512 (*sp->fill)(buf, thisrun, pa, lastx);
1513 /*
1514 * Cleanup at the end of the row.
1515 */
1516 if (mode & FAXMODE_BYTEALIGN) {
1517 int n = BitsAvail - (BitsAvail &~ 7);
1518 ClrBits(n);
1519 } else if (mode & FAXMODE_WORDALIGN) {
1520 int n = BitsAvail - (BitsAvail &~ 15);
1521 ClrBits(n);
1522 if (BitsAvail == 0 && !isAligned(cp, uint16))
1523 cp++;
1524 }
1525 buf += sp->b.rowbytes;
1526 occ -= sp->b.rowbytes;
1527 if (occ != 0)
1528 tif->tif_row++;
1529 continue;
1530 EOFRLE: /* premature EOF */
1531 (*sp->fill)(buf, thisrun, pa, lastx);
1532 UNCACHE_STATE(tif, sp);
1533 return (-1);
1534 }
1535 UNCACHE_STATE(tif, sp);
1536 return (1);
1537}
1538
1539int
1540TIFFInitCCITTRLE(TIFF* tif, int scheme)
1541{
1542 if (InitCCITTFax3(tif)) { /* reuse G3 support */
1543 tif->tif_decoderow = Fax3DecodeRLE;
1544 tif->tif_decodestrip = Fax3DecodeRLE;
1545 tif->tif_decodetile = Fax3DecodeRLE;
1546 /*
1547 * Suppress RTC+EOLs when encoding and byte-align data.
1548 */
1549 return TIFFSetField(tif, TIFFTAG_FAXMODE,
1550 FAXMODE_NORTC|FAXMODE_NOEOL|FAXMODE_BYTEALIGN);
1551 } else
1552 return (0);
1553}
1554
1555int
1556TIFFInitCCITTRLEW(TIFF* tif, int scheme)
1557{
1558 if (InitCCITTFax3(tif)) { /* reuse G3 support */
1559 tif->tif_decoderow = Fax3DecodeRLE;
1560 tif->tif_decodestrip = Fax3DecodeRLE;
1561 tif->tif_decodetile = Fax3DecodeRLE;
1562 /*
1563 * Suppress RTC+EOLs when encoding and word-align data.
1564 */
1565 return TIFFSetField(tif, TIFFTAG_FAXMODE,
1566 FAXMODE_NORTC|FAXMODE_NOEOL|FAXMODE_WORDALIGN);
1567 } else
1568 return (0);
1569}
1570#endif /* CCITT_SUPPORT */