PageRenderTime 132ms CodeModel.GetById 17ms app.highlight 102ms RepoModel.GetById 1ms app.codeStats 0ms

/src/FreeImage/Source/LibTIFF/tif_fax3.c

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