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