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