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