Home | History | Annotate | Download | only in libtiff
      1 /* $Id: tif_luv.c,v 1.40 2015-06-21 01:09:09 bfriesen Exp $ */
      2 
      3 /*
      4  * Copyright (c) 1997 Greg Ward Larson
      5  * Copyright (c) 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, Greg Larson and Silicon Graphics may not be used in any
     12  * advertising or publicity relating to the software without the specific,
     13  * prior written permission of Sam Leffler, Greg Larson 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, GREG LARSON OR SILICON GRAPHICS BE LIABLE
     20  * FOR 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 LOGLUV_SUPPORT
     29 
     30 /*
     31  * TIFF Library.
     32  * LogLuv compression support for high dynamic range images.
     33  *
     34  * Contributed by Greg Larson.
     35  *
     36  * LogLuv image support uses the TIFF library to store 16 or 10-bit
     37  * log luminance values with 8 bits each of u and v or a 14-bit index.
     38  *
     39  * The codec can take as input and produce as output 32-bit IEEE float values
     40  * as well as 16-bit integer values.  A 16-bit luminance is interpreted
     41  * as a sign bit followed by a 15-bit integer that is converted
     42  * to and from a linear magnitude using the transformation:
     43  *
     44  *	L = 2^( (Le+.5)/256 - 64 )		# real from 15-bit
     45  *
     46  *	Le = floor( 256*(log2(L) + 64) )	# 15-bit from real
     47  *
     48  * The actual conversion to world luminance units in candelas per sq. meter
     49  * requires an additional multiplier, which is stored in the TIFFTAG_STONITS.
     50  * This value is usually set such that a reasonable exposure comes from
     51  * clamping decoded luminances above 1 to 1 in the displayed image.
     52  *
     53  * The 16-bit values for u and v may be converted to real values by dividing
     54  * each by 32768.  (This allows for negative values, which aren't useful as
     55  * far as we know, but are left in case of future improvements in human
     56  * color vision.)
     57  *
     58  * Conversion from (u,v), which is actually the CIE (u',v') system for
     59  * you color scientists, is accomplished by the following transformation:
     60  *
     61  *	u = 4*x / (-2*x + 12*y + 3)
     62  *	v = 9*y / (-2*x + 12*y + 3)
     63  *
     64  *	x = 9*u / (6*u - 16*v + 12)
     65  *	y = 4*v / (6*u - 16*v + 12)
     66  *
     67  * This process is greatly simplified by passing 32-bit IEEE floats
     68  * for each of three CIE XYZ coordinates.  The codec then takes care
     69  * of conversion to and from LogLuv, though the application is still
     70  * responsible for interpreting the TIFFTAG_STONITS calibration factor.
     71  *
     72  * By definition, a CIE XYZ vector of [1 1 1] corresponds to a neutral white
     73  * point of (x,y)=(1/3,1/3).  However, most color systems assume some other
     74  * white point, such as D65, and an absolute color conversion to XYZ then
     75  * to another color space with a different white point may introduce an
     76  * unwanted color cast to the image.  It is often desirable, therefore, to
     77  * perform a white point conversion that maps the input white to [1 1 1]
     78  * in XYZ, then record the original white point using the TIFFTAG_WHITEPOINT
     79  * tag value.  A decoder that demands absolute color calibration may use
     80  * this white point tag to get back the original colors, but usually it
     81  * will be ignored and the new white point will be used instead that
     82  * matches the output color space.
     83  *
     84  * Pixel information is compressed into one of two basic encodings, depending
     85  * on the setting of the compression tag, which is one of COMPRESSION_SGILOG
     86  * or COMPRESSION_SGILOG24.  For COMPRESSION_SGILOG, greyscale data is
     87  * stored as:
     88  *
     89  *	 1       15
     90  *	|-+---------------|
     91  *
     92  * COMPRESSION_SGILOG color data is stored as:
     93  *
     94  *	 1       15           8        8
     95  *	|-+---------------|--------+--------|
     96  *	 S       Le           ue       ve
     97  *
     98  * For the 24-bit COMPRESSION_SGILOG24 color format, the data is stored as:
     99  *
    100  *	     10           14
    101  *	|----------|--------------|
    102  *	     Le'          Ce
    103  *
    104  * There is no sign bit in the 24-bit case, and the (u,v) chromaticity is
    105  * encoded as an index for optimal color resolution.  The 10 log bits are
    106  * defined by the following conversions:
    107  *
    108  *	L = 2^((Le'+.5)/64 - 12)		# real from 10-bit
    109  *
    110  *	Le' = floor( 64*(log2(L) + 12) )	# 10-bit from real
    111  *
    112  * The 10 bits of the smaller format may be converted into the 15 bits of
    113  * the larger format by multiplying by 4 and adding 13314.  Obviously,
    114  * a smaller range of magnitudes is covered (about 5 orders of magnitude
    115  * instead of 38), and the lack of a sign bit means that negative luminances
    116  * are not allowed.  (Well, they aren't allowed in the real world, either,
    117  * but they are useful for certain types of image processing.)
    118  *
    119  * The desired user format is controlled by the setting the internal
    120  * pseudo tag TIFFTAG_SGILOGDATAFMT to one of:
    121  *  SGILOGDATAFMT_FLOAT       = IEEE 32-bit float XYZ values
    122  *  SGILOGDATAFMT_16BIT	      = 16-bit integer encodings of logL, u and v
    123  * Raw data i/o is also possible using:
    124  *  SGILOGDATAFMT_RAW         = 32-bit unsigned integer with encoded pixel
    125  * In addition, the following decoding is provided for ease of display:
    126  *  SGILOGDATAFMT_8BIT        = 8-bit default RGB gamma-corrected values
    127  *
    128  * For grayscale images, we provide the following data formats:
    129  *  SGILOGDATAFMT_FLOAT       = IEEE 32-bit float Y values
    130  *  SGILOGDATAFMT_16BIT       = 16-bit integer w/ encoded luminance
    131  *  SGILOGDATAFMT_8BIT        = 8-bit gray monitor values
    132  *
    133  * Note that the COMPRESSION_SGILOG applies a simple run-length encoding
    134  * scheme by separating the logL, u and v bytes for each row and applying
    135  * a PackBits type of compression.  Since the 24-bit encoding is not
    136  * adaptive, the 32-bit color format takes less space in many cases.
    137  *
    138  * Further control is provided over the conversion from higher-resolution
    139  * formats to final encoded values through the pseudo tag
    140  * TIFFTAG_SGILOGENCODE:
    141  *  SGILOGENCODE_NODITHER     = do not dither encoded values
    142  *  SGILOGENCODE_RANDITHER    = apply random dithering during encoding
    143  *
    144  * The default value of this tag is SGILOGENCODE_NODITHER for
    145  * COMPRESSION_SGILOG to maximize run-length encoding and
    146  * SGILOGENCODE_RANDITHER for COMPRESSION_SGILOG24 to turn
    147  * quantization errors into noise.
    148  */
    149 
    150 #include <stdio.h>
    151 #include <stdlib.h>
    152 #include <math.h>
    153 
    154 /*
    155  * State block for each open TIFF
    156  * file using LogLuv compression/decompression.
    157  */
    158 typedef struct logLuvState LogLuvState;
    159 
    160 struct logLuvState {
    161 	int                     user_datafmt;   /* user data format */
    162 	int                     encode_meth;    /* encoding method */
    163 	int                     pixel_size;     /* bytes per pixel */
    164 
    165 	uint8*                  tbuf;           /* translation buffer */
    166 	tmsize_t                tbuflen;        /* buffer length */
    167 	void (*tfunc)(LogLuvState*, uint8*, tmsize_t);
    168 
    169 	TIFFVSetMethod          vgetparent;     /* super-class method */
    170 	TIFFVSetMethod          vsetparent;     /* super-class method */
    171 };
    172 
    173 #define DecoderState(tif)	((LogLuvState*) (tif)->tif_data)
    174 #define EncoderState(tif)	((LogLuvState*) (tif)->tif_data)
    175 
    176 #define SGILOGDATAFMT_UNKNOWN -1
    177 
    178 #define MINRUN 4 /* minimum run length */
    179 
    180 /*
    181  * Decode a string of 16-bit gray pixels.
    182  */
    183 static int
    184 LogL16Decode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)
    185 {
    186 	static const char module[] = "LogL16Decode";
    187 	LogLuvState* sp = DecoderState(tif);
    188 	int shft;
    189 	tmsize_t i;
    190 	tmsize_t npixels;
    191 	unsigned char* bp;
    192 	int16* tp;
    193 	int16 b;
    194 	tmsize_t cc;
    195 	int rc;
    196 
    197 	assert(s == 0);
    198 	assert(sp != NULL);
    199 
    200 	npixels = occ / sp->pixel_size;
    201 
    202 	if (sp->user_datafmt == SGILOGDATAFMT_16BIT)
    203 		tp = (int16*) op;
    204 	else {
    205 		if(sp->tbuflen < npixels) {
    206 			TIFFErrorExt(tif->tif_clientdata, module,
    207 						 "Translation buffer too short");
    208 			return (0);
    209 		}
    210 		tp = (int16*) sp->tbuf;
    211 	}
    212 	_TIFFmemset((void*) tp, 0, npixels*sizeof (tp[0]));
    213 
    214 	bp = (unsigned char*) tif->tif_rawcp;
    215 	cc = tif->tif_rawcc;
    216 	/* get each byte string */
    217 	for (shft = 2*8; (shft -= 8) >= 0; ) {
    218 		for (i = 0; i < npixels && cc > 0; ) {
    219 			if (*bp >= 128) {		/* run */
    220 				if( cc < 2 )
    221 					break;
    222 				rc = *bp++ + (2-128);
    223 				b = (int16)(*bp++ << shft);
    224 				cc -= 2;
    225 				while (rc-- && i < npixels)
    226 					tp[i++] |= b;
    227 			} else {			/* non-run */
    228 				rc = *bp++;		/* nul is noop */
    229 				while (--cc && rc-- && i < npixels)
    230 					tp[i++] |= (int16)*bp++ << shft;
    231 			}
    232 		}
    233 		if (i != npixels) {
    234 #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
    235 			TIFFErrorExt(tif->tif_clientdata, module,
    236 			    "Not enough data at row %lu (short %I64d pixels)",
    237 				     (unsigned long) tif->tif_row,
    238 				     (unsigned __int64) (npixels - i));
    239 #else
    240 			TIFFErrorExt(tif->tif_clientdata, module,
    241 			    "Not enough data at row %lu (short %llu pixels)",
    242 				     (unsigned long) tif->tif_row,
    243 				     (unsigned long long) (npixels - i));
    244 #endif
    245 			tif->tif_rawcp = (uint8*) bp;
    246 			tif->tif_rawcc = cc;
    247 			return (0);
    248 		}
    249 	}
    250 	(*sp->tfunc)(sp, op, npixels);
    251 	tif->tif_rawcp = (uint8*) bp;
    252 	tif->tif_rawcc = cc;
    253 	return (1);
    254 }
    255 
    256 /*
    257  * Decode a string of 24-bit pixels.
    258  */
    259 static int
    260 LogLuvDecode24(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)
    261 {
    262 	static const char module[] = "LogLuvDecode24";
    263 	LogLuvState* sp = DecoderState(tif);
    264 	tmsize_t cc;
    265 	tmsize_t i;
    266 	tmsize_t npixels;
    267 	unsigned char* bp;
    268 	uint32* tp;
    269 
    270 	assert(s == 0);
    271 	assert(sp != NULL);
    272 
    273 	npixels = occ / sp->pixel_size;
    274 
    275 	if (sp->user_datafmt == SGILOGDATAFMT_RAW)
    276 		tp = (uint32 *)op;
    277 	else {
    278 		if(sp->tbuflen < npixels) {
    279 			TIFFErrorExt(tif->tif_clientdata, module,
    280 						 "Translation buffer too short");
    281 			return (0);
    282 		}
    283 		tp = (uint32 *) sp->tbuf;
    284 	}
    285 	/* copy to array of uint32 */
    286 	bp = (unsigned char*) tif->tif_rawcp;
    287 	cc = tif->tif_rawcc;
    288 	for (i = 0; i < npixels && cc >= 3; i++) {
    289 		tp[i] = bp[0] << 16 | bp[1] << 8 | bp[2];
    290 		bp += 3;
    291 		cc -= 3;
    292 	}
    293 	tif->tif_rawcp = (uint8*) bp;
    294 	tif->tif_rawcc = cc;
    295 	if (i != npixels) {
    296 #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
    297 		TIFFErrorExt(tif->tif_clientdata, module,
    298 			"Not enough data at row %lu (short %I64d pixels)",
    299 			     (unsigned long) tif->tif_row,
    300 			     (unsigned __int64) (npixels - i));
    301 #else
    302 		TIFFErrorExt(tif->tif_clientdata, module,
    303 			"Not enough data at row %lu (short %llu pixels)",
    304 			     (unsigned long) tif->tif_row,
    305 			     (unsigned long long) (npixels - i));
    306 #endif
    307 		return (0);
    308 	}
    309 	(*sp->tfunc)(sp, op, npixels);
    310 	return (1);
    311 }
    312 
    313 /*
    314  * Decode a string of 32-bit pixels.
    315  */
    316 static int
    317 LogLuvDecode32(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)
    318 {
    319 	static const char module[] = "LogLuvDecode32";
    320 	LogLuvState* sp;
    321 	int shft;
    322 	tmsize_t i;
    323 	tmsize_t npixels;
    324 	unsigned char* bp;
    325 	uint32* tp;
    326 	uint32 b;
    327 	tmsize_t cc;
    328 	int rc;
    329 
    330 	assert(s == 0);
    331 	sp = DecoderState(tif);
    332 	assert(sp != NULL);
    333 
    334 	npixels = occ / sp->pixel_size;
    335 
    336 	if (sp->user_datafmt == SGILOGDATAFMT_RAW)
    337 		tp = (uint32*) op;
    338 	else {
    339 		if(sp->tbuflen < npixels) {
    340 			TIFFErrorExt(tif->tif_clientdata, module,
    341 						 "Translation buffer too short");
    342 			return (0);
    343 		}
    344 		tp = (uint32*) sp->tbuf;
    345 	}
    346 	_TIFFmemset((void*) tp, 0, npixels*sizeof (tp[0]));
    347 
    348 	bp = (unsigned char*) tif->tif_rawcp;
    349 	cc = tif->tif_rawcc;
    350 	/* get each byte string */
    351 	for (shft = 4*8; (shft -= 8) >= 0; ) {
    352 		for (i = 0; i < npixels && cc > 0; ) {
    353 			if (*bp >= 128) {		/* run */
    354 				if( cc < 2 )
    355 					break;
    356 				rc = *bp++ + (2-128);
    357 				b = (uint32)*bp++ << shft;
    358 				cc -= 2;
    359 				while (rc-- && i < npixels)
    360 					tp[i++] |= b;
    361 			} else {			/* non-run */
    362 				rc = *bp++;		/* nul is noop */
    363 				while (--cc && rc-- && i < npixels)
    364 					tp[i++] |= (uint32)*bp++ << shft;
    365 			}
    366 		}
    367 		if (i != npixels) {
    368 #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
    369 			TIFFErrorExt(tif->tif_clientdata, module,
    370 			"Not enough data at row %lu (short %I64d pixels)",
    371 				     (unsigned long) tif->tif_row,
    372 				     (unsigned __int64) (npixels - i));
    373 #else
    374 			TIFFErrorExt(tif->tif_clientdata, module,
    375 			"Not enough data at row %lu (short %llu pixels)",
    376 				     (unsigned long) tif->tif_row,
    377 				     (unsigned long long) (npixels - i));
    378 #endif
    379 			tif->tif_rawcp = (uint8*) bp;
    380 			tif->tif_rawcc = cc;
    381 			return (0);
    382 		}
    383 	}
    384 	(*sp->tfunc)(sp, op, npixels);
    385 	tif->tif_rawcp = (uint8*) bp;
    386 	tif->tif_rawcc = cc;
    387 	return (1);
    388 }
    389 
    390 /*
    391  * Decode a strip of pixels.  We break it into rows to
    392  * maintain synchrony with the encode algorithm, which
    393  * is row by row.
    394  */
    395 static int
    396 LogLuvDecodeStrip(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
    397 {
    398 	tmsize_t rowlen = TIFFScanlineSize(tif);
    399 
    400         if (rowlen == 0)
    401                 return 0;
    402 
    403 	assert(cc%rowlen == 0);
    404 	while (cc && (*tif->tif_decoderow)(tif, bp, rowlen, s))
    405 		bp += rowlen, cc -= rowlen;
    406 	return (cc == 0);
    407 }
    408 
    409 /*
    410  * Decode a tile of pixels.  We break it into rows to
    411  * maintain synchrony with the encode algorithm, which
    412  * is row by row.
    413  */
    414 static int
    415 LogLuvDecodeTile(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
    416 {
    417 	tmsize_t rowlen = TIFFTileRowSize(tif);
    418 
    419         if (rowlen == 0)
    420                 return 0;
    421 
    422 	assert(cc%rowlen == 0);
    423 	while (cc && (*tif->tif_decoderow)(tif, bp, rowlen, s))
    424 		bp += rowlen, cc -= rowlen;
    425 	return (cc == 0);
    426 }
    427 
    428 /*
    429  * Encode a row of 16-bit pixels.
    430  */
    431 static int
    432 LogL16Encode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
    433 {
    434 	static const char module[] = "LogL16Encode";
    435 	LogLuvState* sp = EncoderState(tif);
    436 	int shft;
    437 	tmsize_t i;
    438 	tmsize_t j;
    439 	tmsize_t npixels;
    440 	uint8* op;
    441 	int16* tp;
    442 	int16 b;
    443 	tmsize_t occ;
    444 	int rc=0, mask;
    445 	tmsize_t beg;
    446 
    447 	assert(s == 0);
    448 	assert(sp != NULL);
    449 	npixels = cc / sp->pixel_size;
    450 
    451 	if (sp->user_datafmt == SGILOGDATAFMT_16BIT)
    452 		tp = (int16*) bp;
    453 	else {
    454 		tp = (int16*) sp->tbuf;
    455 		if(sp->tbuflen < npixels) {
    456 			TIFFErrorExt(tif->tif_clientdata, module,
    457 						 "Translation buffer too short");
    458 			return (0);
    459 		}
    460 		(*sp->tfunc)(sp, bp, npixels);
    461 	}
    462 	/* compress each byte string */
    463 	op = tif->tif_rawcp;
    464 	occ = tif->tif_rawdatasize - tif->tif_rawcc;
    465 	for (shft = 2*8; (shft -= 8) >= 0; )
    466 		for (i = 0; i < npixels; i += rc) {
    467 			if (occ < 4) {
    468 				tif->tif_rawcp = op;
    469 				tif->tif_rawcc = tif->tif_rawdatasize - occ;
    470 				if (!TIFFFlushData1(tif))
    471 					return (-1);
    472 				op = tif->tif_rawcp;
    473 				occ = tif->tif_rawdatasize - tif->tif_rawcc;
    474 			}
    475 			mask = 0xff << shft;		/* find next run */
    476 			for (beg = i; beg < npixels; beg += rc) {
    477 				b = (int16) (tp[beg] & mask);
    478 				rc = 1;
    479 				while (rc < 127+2 && beg+rc < npixels &&
    480 				    (tp[beg+rc] & mask) == b)
    481 					rc++;
    482 				if (rc >= MINRUN)
    483 					break;		/* long enough */
    484 			}
    485 			if (beg-i > 1 && beg-i < MINRUN) {
    486 				b = (int16) (tp[i] & mask);/*check short run */
    487 				j = i+1;
    488 				while ((tp[j++] & mask) == b)
    489 					if (j == beg) {
    490 						*op++ = (uint8)(128-2+j-i);
    491 						*op++ = (uint8)(b >> shft);
    492 						occ -= 2;
    493 						i = beg;
    494 						break;
    495 					}
    496 			}
    497 			while (i < beg) {		/* write out non-run */
    498 				if ((j = beg-i) > 127) j = 127;
    499 				if (occ < j+3) {
    500 					tif->tif_rawcp = op;
    501 					tif->tif_rawcc = tif->tif_rawdatasize - occ;
    502 					if (!TIFFFlushData1(tif))
    503 						return (-1);
    504 					op = tif->tif_rawcp;
    505 					occ = tif->tif_rawdatasize - tif->tif_rawcc;
    506 				}
    507 				*op++ = (uint8) j; occ--;
    508 				while (j--) {
    509 					*op++ = (uint8) (tp[i++] >> shft & 0xff);
    510 					occ--;
    511 				}
    512 			}
    513 			if (rc >= MINRUN) {		/* write out run */
    514 				*op++ = (uint8) (128-2+rc);
    515 				*op++ = (uint8) (tp[beg] >> shft & 0xff);
    516 				occ -= 2;
    517 			} else
    518 				rc = 0;
    519 		}
    520 	tif->tif_rawcp = op;
    521 	tif->tif_rawcc = tif->tif_rawdatasize - occ;
    522 
    523 	return (1);
    524 }
    525 
    526 /*
    527  * Encode a row of 24-bit pixels.
    528  */
    529 static int
    530 LogLuvEncode24(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
    531 {
    532 	static const char module[] = "LogLuvEncode24";
    533 	LogLuvState* sp = EncoderState(tif);
    534 	tmsize_t i;
    535 	tmsize_t npixels;
    536 	tmsize_t occ;
    537 	uint8* op;
    538 	uint32* tp;
    539 
    540 	assert(s == 0);
    541 	assert(sp != NULL);
    542 	npixels = cc / sp->pixel_size;
    543 
    544 	if (sp->user_datafmt == SGILOGDATAFMT_RAW)
    545 		tp = (uint32*) bp;
    546 	else {
    547 		tp = (uint32*) sp->tbuf;
    548 		if(sp->tbuflen < npixels) {
    549 			TIFFErrorExt(tif->tif_clientdata, module,
    550 						 "Translation buffer too short");
    551 			return (0);
    552 		}
    553 		(*sp->tfunc)(sp, bp, npixels);
    554 	}
    555 	/* write out encoded pixels */
    556 	op = tif->tif_rawcp;
    557 	occ = tif->tif_rawdatasize - tif->tif_rawcc;
    558 	for (i = npixels; i--; ) {
    559 		if (occ < 3) {
    560 			tif->tif_rawcp = op;
    561 			tif->tif_rawcc = tif->tif_rawdatasize - occ;
    562 			if (!TIFFFlushData1(tif))
    563 				return (-1);
    564 			op = tif->tif_rawcp;
    565 			occ = tif->tif_rawdatasize - tif->tif_rawcc;
    566 		}
    567 		*op++ = (uint8)(*tp >> 16);
    568 		*op++ = (uint8)(*tp >> 8 & 0xff);
    569 		*op++ = (uint8)(*tp++ & 0xff);
    570 		occ -= 3;
    571 	}
    572 	tif->tif_rawcp = op;
    573 	tif->tif_rawcc = tif->tif_rawdatasize - occ;
    574 
    575 	return (1);
    576 }
    577 
    578 /*
    579  * Encode a row of 32-bit pixels.
    580  */
    581 static int
    582 LogLuvEncode32(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
    583 {
    584 	static const char module[] = "LogLuvEncode32";
    585 	LogLuvState* sp = EncoderState(tif);
    586 	int shft;
    587 	tmsize_t i;
    588 	tmsize_t j;
    589 	tmsize_t npixels;
    590 	uint8* op;
    591 	uint32* tp;
    592 	uint32 b;
    593 	tmsize_t occ;
    594 	int rc=0, mask;
    595 	tmsize_t beg;
    596 
    597 	assert(s == 0);
    598 	assert(sp != NULL);
    599 
    600 	npixels = cc / sp->pixel_size;
    601 
    602 	if (sp->user_datafmt == SGILOGDATAFMT_RAW)
    603 		tp = (uint32*) bp;
    604 	else {
    605 		tp = (uint32*) sp->tbuf;
    606 		if(sp->tbuflen < npixels) {
    607 			TIFFErrorExt(tif->tif_clientdata, module,
    608 						 "Translation buffer too short");
    609 			return (0);
    610 		}
    611 		(*sp->tfunc)(sp, bp, npixels);
    612 	}
    613 	/* compress each byte string */
    614 	op = tif->tif_rawcp;
    615 	occ = tif->tif_rawdatasize - tif->tif_rawcc;
    616 	for (shft = 4*8; (shft -= 8) >= 0; )
    617 		for (i = 0; i < npixels; i += rc) {
    618 			if (occ < 4) {
    619 				tif->tif_rawcp = op;
    620 				tif->tif_rawcc = tif->tif_rawdatasize - occ;
    621 				if (!TIFFFlushData1(tif))
    622 					return (-1);
    623 				op = tif->tif_rawcp;
    624 				occ = tif->tif_rawdatasize - tif->tif_rawcc;
    625 			}
    626 			mask = 0xff << shft;		/* find next run */
    627 			for (beg = i; beg < npixels; beg += rc) {
    628 				b = tp[beg] & mask;
    629 				rc = 1;
    630 				while (rc < 127+2 && beg+rc < npixels &&
    631 						(tp[beg+rc] & mask) == b)
    632 					rc++;
    633 				if (rc >= MINRUN)
    634 					break;		/* long enough */
    635 			}
    636 			if (beg-i > 1 && beg-i < MINRUN) {
    637 				b = tp[i] & mask;	/* check short run */
    638 				j = i+1;
    639 				while ((tp[j++] & mask) == b)
    640 					if (j == beg) {
    641 						*op++ = (uint8)(128-2+j-i);
    642 						*op++ = (uint8)(b >> shft);
    643 						occ -= 2;
    644 						i = beg;
    645 						break;
    646 					}
    647 			}
    648 			while (i < beg) {		/* write out non-run */
    649 				if ((j = beg-i) > 127) j = 127;
    650 				if (occ < j+3) {
    651 					tif->tif_rawcp = op;
    652 					tif->tif_rawcc = tif->tif_rawdatasize - occ;
    653 					if (!TIFFFlushData1(tif))
    654 						return (-1);
    655 					op = tif->tif_rawcp;
    656 					occ = tif->tif_rawdatasize - tif->tif_rawcc;
    657 				}
    658 				*op++ = (uint8) j; occ--;
    659 				while (j--) {
    660 					*op++ = (uint8)(tp[i++] >> shft & 0xff);
    661 					occ--;
    662 				}
    663 			}
    664 			if (rc >= MINRUN) {		/* write out run */
    665 				*op++ = (uint8) (128-2+rc);
    666 				*op++ = (uint8)(tp[beg] >> shft & 0xff);
    667 				occ -= 2;
    668 			} else
    669 				rc = 0;
    670 		}
    671 	tif->tif_rawcp = op;
    672 	tif->tif_rawcc = tif->tif_rawdatasize - occ;
    673 
    674 	return (1);
    675 }
    676 
    677 /*
    678  * Encode a strip of pixels.  We break it into rows to
    679  * avoid encoding runs across row boundaries.
    680  */
    681 static int
    682 LogLuvEncodeStrip(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
    683 {
    684 	tmsize_t rowlen = TIFFScanlineSize(tif);
    685 
    686         if (rowlen == 0)
    687                 return 0;
    688 
    689 	assert(cc%rowlen == 0);
    690 	while (cc && (*tif->tif_encoderow)(tif, bp, rowlen, s) == 1)
    691 		bp += rowlen, cc -= rowlen;
    692 	return (cc == 0);
    693 }
    694 
    695 /*
    696  * Encode a tile of pixels.  We break it into rows to
    697  * avoid encoding runs across row boundaries.
    698  */
    699 static int
    700 LogLuvEncodeTile(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
    701 {
    702 	tmsize_t rowlen = TIFFTileRowSize(tif);
    703 
    704         if (rowlen == 0)
    705                 return 0;
    706 
    707 	assert(cc%rowlen == 0);
    708 	while (cc && (*tif->tif_encoderow)(tif, bp, rowlen, s) == 1)
    709 		bp += rowlen, cc -= rowlen;
    710 	return (cc == 0);
    711 }
    712 
    713 /*
    714  * Encode/Decode functions for converting to and from user formats.
    715  */
    716 
    717 #include "uvcode.h"
    718 
    719 #ifndef UVSCALE
    720 #define U_NEU		0.210526316
    721 #define V_NEU		0.473684211
    722 #define UVSCALE		410.
    723 #endif
    724 
    725 #ifndef	M_LN2
    726 #define M_LN2		0.69314718055994530942
    727 #endif
    728 #ifndef M_PI
    729 #define M_PI		3.14159265358979323846
    730 #endif
    731 #undef log2 /* Conflict with C'99 function */
    732 #define log2(x)		((1./M_LN2)*log(x))
    733 #undef exp2  /* Conflict with C'99 function */
    734 #define exp2(x)		exp(M_LN2*(x))
    735 
    736 #define itrunc(x,m)	((m)==SGILOGENCODE_NODITHER ? \
    737 				(int)(x) : \
    738 				(int)((x) + rand()*(1./RAND_MAX) - .5))
    739 
    740 #if !LOGLUV_PUBLIC
    741 static
    742 #endif
    743 double
    744 LogL16toY(int p16)		/* compute luminance from 16-bit LogL */
    745 {
    746 	int	Le = p16 & 0x7fff;
    747 	double	Y;
    748 
    749 	if (!Le)
    750 		return (0.);
    751 	Y = exp(M_LN2/256.*(Le+.5) - M_LN2*64.);
    752 	return (!(p16 & 0x8000) ? Y : -Y);
    753 }
    754 
    755 #if !LOGLUV_PUBLIC
    756 static
    757 #endif
    758 int
    759 LogL16fromY(double Y, int em)	/* get 16-bit LogL from Y */
    760 {
    761 	if (Y >= 1.8371976e19)
    762 		return (0x7fff);
    763 	if (Y <= -1.8371976e19)
    764 		return (0xffff);
    765 	if (Y > 5.4136769e-20)
    766 		return itrunc(256.*(log2(Y) + 64.), em);
    767 	if (Y < -5.4136769e-20)
    768 		return (~0x7fff | itrunc(256.*(log2(-Y) + 64.), em));
    769 	return (0);
    770 }
    771 
    772 static void
    773 L16toY(LogLuvState* sp, uint8* op, tmsize_t n)
    774 {
    775 	int16* l16 = (int16*) sp->tbuf;
    776 	float* yp = (float*) op;
    777 
    778 	while (n-- > 0)
    779 		*yp++ = (float)LogL16toY(*l16++);
    780 }
    781 
    782 static void
    783 L16toGry(LogLuvState* sp, uint8* op, tmsize_t n)
    784 {
    785 	int16* l16 = (int16*) sp->tbuf;
    786 	uint8* gp = (uint8*) op;
    787 
    788 	while (n-- > 0) {
    789 		double Y = LogL16toY(*l16++);
    790 		*gp++ = (uint8) ((Y <= 0.) ? 0 : (Y >= 1.) ? 255 : (int)(256.*sqrt(Y)));
    791 	}
    792 }
    793 
    794 static void
    795 L16fromY(LogLuvState* sp, uint8* op, tmsize_t n)
    796 {
    797 	int16* l16 = (int16*) sp->tbuf;
    798 	float* yp = (float*) op;
    799 
    800 	while (n-- > 0)
    801 		*l16++ = (int16) (LogL16fromY(*yp++, sp->encode_meth));
    802 }
    803 
    804 #if !LOGLUV_PUBLIC
    805 static
    806 #endif
    807 void
    808 XYZtoRGB24(float xyz[3], uint8 rgb[3])
    809 {
    810 	double	r, g, b;
    811 					/* assume CCIR-709 primaries */
    812 	r =  2.690*xyz[0] + -1.276*xyz[1] + -0.414*xyz[2];
    813 	g = -1.022*xyz[0] +  1.978*xyz[1] +  0.044*xyz[2];
    814 	b =  0.061*xyz[0] + -0.224*xyz[1] +  1.163*xyz[2];
    815 					/* assume 2.0 gamma for speed */
    816 	/* could use integer sqrt approx., but this is probably faster */
    817 	rgb[0] = (uint8)((r<=0.) ? 0 : (r >= 1.) ? 255 : (int)(256.*sqrt(r)));
    818 	rgb[1] = (uint8)((g<=0.) ? 0 : (g >= 1.) ? 255 : (int)(256.*sqrt(g)));
    819 	rgb[2] = (uint8)((b<=0.) ? 0 : (b >= 1.) ? 255 : (int)(256.*sqrt(b)));
    820 }
    821 
    822 #if !LOGLUV_PUBLIC
    823 static
    824 #endif
    825 double
    826 LogL10toY(int p10)		/* compute luminance from 10-bit LogL */
    827 {
    828 	if (p10 == 0)
    829 		return (0.);
    830 	return (exp(M_LN2/64.*(p10+.5) - M_LN2*12.));
    831 }
    832 
    833 #if !LOGLUV_PUBLIC
    834 static
    835 #endif
    836 int
    837 LogL10fromY(double Y, int em)	/* get 10-bit LogL from Y */
    838 {
    839 	if (Y >= 15.742)
    840 		return (0x3ff);
    841 	else if (Y <= .00024283)
    842 		return (0);
    843 	else
    844 		return itrunc(64.*(log2(Y) + 12.), em);
    845 }
    846 
    847 #define NANGLES		100
    848 #define uv2ang(u, v)	( (NANGLES*.499999999/M_PI) \
    849 				* atan2((v)-V_NEU,(u)-U_NEU) + .5*NANGLES )
    850 
    851 static int
    852 oog_encode(double u, double v)		/* encode out-of-gamut chroma */
    853 {
    854 	static int	oog_table[NANGLES];
    855 	static int	initialized = 0;
    856 	register int	i;
    857 
    858 	if (!initialized) {		/* set up perimeter table */
    859 		double	eps[NANGLES], ua, va, ang, epsa;
    860 		int	ui, vi, ustep;
    861 		for (i = NANGLES; i--; )
    862 			eps[i] = 2.;
    863 		for (vi = UV_NVS; vi--; ) {
    864 			va = UV_VSTART + (vi+.5)*UV_SQSIZ;
    865 			ustep = uv_row[vi].nus-1;
    866 			if (vi == UV_NVS-1 || vi == 0 || ustep <= 0)
    867 				ustep = 1;
    868 			for (ui = uv_row[vi].nus-1; ui >= 0; ui -= ustep) {
    869 				ua = uv_row[vi].ustart + (ui+.5)*UV_SQSIZ;
    870 				ang = uv2ang(ua, va);
    871 				i = (int) ang;
    872 				epsa = fabs(ang - (i+.5));
    873 				if (epsa < eps[i]) {
    874 					oog_table[i] = uv_row[vi].ncum + ui;
    875 					eps[i] = epsa;
    876 				}
    877 			}
    878 		}
    879 		for (i = NANGLES; i--; )	/* fill any holes */
    880 			if (eps[i] > 1.5) {
    881 				int	i1, i2;
    882 				for (i1 = 1; i1 < NANGLES/2; i1++)
    883 					if (eps[(i+i1)%NANGLES] < 1.5)
    884 						break;
    885 				for (i2 = 1; i2 < NANGLES/2; i2++)
    886 					if (eps[(i+NANGLES-i2)%NANGLES] < 1.5)
    887 						break;
    888 				if (i1 < i2)
    889 					oog_table[i] =
    890 						oog_table[(i+i1)%NANGLES];
    891 				else
    892 					oog_table[i] =
    893 						oog_table[(i+NANGLES-i2)%NANGLES];
    894 			}
    895 		initialized = 1;
    896 	}
    897 	i = (int) uv2ang(u, v);		/* look up hue angle */
    898 	return (oog_table[i]);
    899 }
    900 
    901 #undef uv2ang
    902 #undef NANGLES
    903 
    904 #if !LOGLUV_PUBLIC
    905 static
    906 #endif
    907 int
    908 uv_encode(double u, double v, int em)	/* encode (u',v') coordinates */
    909 {
    910 	register int	vi, ui;
    911 
    912 	if (v < UV_VSTART)
    913 		return oog_encode(u, v);
    914 	vi = itrunc((v - UV_VSTART)*(1./UV_SQSIZ), em);
    915 	if (vi >= UV_NVS)
    916 		return oog_encode(u, v);
    917 	if (u < uv_row[vi].ustart)
    918 		return oog_encode(u, v);
    919 	ui = itrunc((u - uv_row[vi].ustart)*(1./UV_SQSIZ), em);
    920 	if (ui >= uv_row[vi].nus)
    921 		return oog_encode(u, v);
    922 
    923 	return (uv_row[vi].ncum + ui);
    924 }
    925 
    926 #if !LOGLUV_PUBLIC
    927 static
    928 #endif
    929 int
    930 uv_decode(double *up, double *vp, int c)	/* decode (u',v') index */
    931 {
    932 	int	upper, lower;
    933 	register int	ui, vi;
    934 
    935 	if (c < 0 || c >= UV_NDIVS)
    936 		return (-1);
    937 	lower = 0;				/* binary search */
    938 	upper = UV_NVS;
    939 	while (upper - lower > 1) {
    940 		vi = (lower + upper) >> 1;
    941 		ui = c - uv_row[vi].ncum;
    942 		if (ui > 0)
    943 			lower = vi;
    944 		else if (ui < 0)
    945 			upper = vi;
    946 		else {
    947 			lower = vi;
    948 			break;
    949 		}
    950 	}
    951 	vi = lower;
    952 	ui = c - uv_row[vi].ncum;
    953 	*up = uv_row[vi].ustart + (ui+.5)*UV_SQSIZ;
    954 	*vp = UV_VSTART + (vi+.5)*UV_SQSIZ;
    955 	return (0);
    956 }
    957 
    958 #if !LOGLUV_PUBLIC
    959 static
    960 #endif
    961 void
    962 LogLuv24toXYZ(uint32 p, float XYZ[3])
    963 {
    964 	int	Ce;
    965 	double	L, u, v, s, x, y;
    966 					/* decode luminance */
    967 	L = LogL10toY(p>>14 & 0x3ff);
    968 	if (L <= 0.) {
    969 		XYZ[0] = XYZ[1] = XYZ[2] = 0.;
    970 		return;
    971 	}
    972 					/* decode color */
    973 	Ce = p & 0x3fff;
    974 	if (uv_decode(&u, &v, Ce) < 0) {
    975 		u = U_NEU; v = V_NEU;
    976 	}
    977 	s = 1./(6.*u - 16.*v + 12.);
    978 	x = 9.*u * s;
    979 	y = 4.*v * s;
    980 					/* convert to XYZ */
    981 	XYZ[0] = (float)(x/y * L);
    982 	XYZ[1] = (float)L;
    983 	XYZ[2] = (float)((1.-x-y)/y * L);
    984 }
    985 
    986 #if !LOGLUV_PUBLIC
    987 static
    988 #endif
    989 uint32
    990 LogLuv24fromXYZ(float XYZ[3], int em)
    991 {
    992 	int	Le, Ce;
    993 	double	u, v, s;
    994 					/* encode luminance */
    995 	Le = LogL10fromY(XYZ[1], em);
    996 					/* encode color */
    997 	s = XYZ[0] + 15.*XYZ[1] + 3.*XYZ[2];
    998 	if (!Le || s <= 0.) {
    999 		u = U_NEU;
   1000 		v = V_NEU;
   1001 	} else {
   1002 		u = 4.*XYZ[0] / s;
   1003 		v = 9.*XYZ[1] / s;
   1004 	}
   1005 	Ce = uv_encode(u, v, em);
   1006 	if (Ce < 0)			/* never happens */
   1007 		Ce = uv_encode(U_NEU, V_NEU, SGILOGENCODE_NODITHER);
   1008 					/* combine encodings */
   1009 	return (Le << 14 | Ce);
   1010 }
   1011 
   1012 static void
   1013 Luv24toXYZ(LogLuvState* sp, uint8* op, tmsize_t n)
   1014 {
   1015 	uint32* luv = (uint32*) sp->tbuf;
   1016 	float* xyz = (float*) op;
   1017 
   1018 	while (n-- > 0) {
   1019 		LogLuv24toXYZ(*luv, xyz);
   1020 		xyz += 3;
   1021 		luv++;
   1022 	}
   1023 }
   1024 
   1025 static void
   1026 Luv24toLuv48(LogLuvState* sp, uint8* op, tmsize_t n)
   1027 {
   1028 	uint32* luv = (uint32*) sp->tbuf;
   1029 	int16* luv3 = (int16*) op;
   1030 
   1031 	while (n-- > 0) {
   1032 		double u, v;
   1033 
   1034 		*luv3++ = (int16)((*luv >> 12 & 0xffd) + 13314);
   1035 		if (uv_decode(&u, &v, *luv&0x3fff) < 0) {
   1036 			u = U_NEU;
   1037 			v = V_NEU;
   1038 		}
   1039 		*luv3++ = (int16)(u * (1L<<15));
   1040 		*luv3++ = (int16)(v * (1L<<15));
   1041 		luv++;
   1042 	}
   1043 }
   1044 
   1045 static void
   1046 Luv24toRGB(LogLuvState* sp, uint8* op, tmsize_t n)
   1047 {
   1048 	uint32* luv = (uint32*) sp->tbuf;
   1049 	uint8* rgb = (uint8*) op;
   1050 
   1051 	while (n-- > 0) {
   1052 		float xyz[3];
   1053 
   1054 		LogLuv24toXYZ(*luv++, xyz);
   1055 		XYZtoRGB24(xyz, rgb);
   1056 		rgb += 3;
   1057 	}
   1058 }
   1059 
   1060 static void
   1061 Luv24fromXYZ(LogLuvState* sp, uint8* op, tmsize_t n)
   1062 {
   1063 	uint32* luv = (uint32*) sp->tbuf;
   1064 	float* xyz = (float*) op;
   1065 
   1066 	while (n-- > 0) {
   1067 		*luv++ = LogLuv24fromXYZ(xyz, sp->encode_meth);
   1068 		xyz += 3;
   1069 	}
   1070 }
   1071 
   1072 static void
   1073 Luv24fromLuv48(LogLuvState* sp, uint8* op, tmsize_t n)
   1074 {
   1075 	uint32* luv = (uint32*) sp->tbuf;
   1076 	int16* luv3 = (int16*) op;
   1077 
   1078 	while (n-- > 0) {
   1079 		int Le, Ce;
   1080 
   1081 		if (luv3[0] <= 0)
   1082 			Le = 0;
   1083 		else if (luv3[0] >= (1<<12)+3314)
   1084 			Le = (1<<10) - 1;
   1085 		else if (sp->encode_meth == SGILOGENCODE_NODITHER)
   1086 			Le = (luv3[0]-3314) >> 2;
   1087 		else
   1088 			Le = itrunc(.25*(luv3[0]-3314.), sp->encode_meth);
   1089 
   1090 		Ce = uv_encode((luv3[1]+.5)/(1<<15), (luv3[2]+.5)/(1<<15),
   1091 					sp->encode_meth);
   1092 		if (Ce < 0)	/* never happens */
   1093 			Ce = uv_encode(U_NEU, V_NEU, SGILOGENCODE_NODITHER);
   1094 		*luv++ = (uint32)Le << 14 | Ce;
   1095 		luv3 += 3;
   1096 	}
   1097 }
   1098 
   1099 #if !LOGLUV_PUBLIC
   1100 static
   1101 #endif
   1102 void
   1103 LogLuv32toXYZ(uint32 p, float XYZ[3])
   1104 {
   1105 	double	L, u, v, s, x, y;
   1106 					/* decode luminance */
   1107 	L = LogL16toY((int)p >> 16);
   1108 	if (L <= 0.) {
   1109 		XYZ[0] = XYZ[1] = XYZ[2] = 0.;
   1110 		return;
   1111 	}
   1112 					/* decode color */
   1113 	u = 1./UVSCALE * ((p>>8 & 0xff) + .5);
   1114 	v = 1./UVSCALE * ((p & 0xff) + .5);
   1115 	s = 1./(6.*u - 16.*v + 12.);
   1116 	x = 9.*u * s;
   1117 	y = 4.*v * s;
   1118 					/* convert to XYZ */
   1119 	XYZ[0] = (float)(x/y * L);
   1120 	XYZ[1] = (float)L;
   1121 	XYZ[2] = (float)((1.-x-y)/y * L);
   1122 }
   1123 
   1124 #if !LOGLUV_PUBLIC
   1125 static
   1126 #endif
   1127 uint32
   1128 LogLuv32fromXYZ(float XYZ[3], int em)
   1129 {
   1130 	unsigned int	Le, ue, ve;
   1131 	double	u, v, s;
   1132 					/* encode luminance */
   1133 	Le = (unsigned int)LogL16fromY(XYZ[1], em);
   1134 					/* encode color */
   1135 	s = XYZ[0] + 15.*XYZ[1] + 3.*XYZ[2];
   1136 	if (!Le || s <= 0.) {
   1137 		u = U_NEU;
   1138 		v = V_NEU;
   1139 	} else {
   1140 		u = 4.*XYZ[0] / s;
   1141 		v = 9.*XYZ[1] / s;
   1142 	}
   1143 	if (u <= 0.) ue = 0;
   1144 	else ue = itrunc(UVSCALE*u, em);
   1145 	if (ue > 255) ue = 255;
   1146 	if (v <= 0.) ve = 0;
   1147 	else ve = itrunc(UVSCALE*v, em);
   1148 	if (ve > 255) ve = 255;
   1149 					/* combine encodings */
   1150 	return (Le << 16 | ue << 8 | ve);
   1151 }
   1152 
   1153 static void
   1154 Luv32toXYZ(LogLuvState* sp, uint8* op, tmsize_t n)
   1155 {
   1156 	uint32* luv = (uint32*) sp->tbuf;
   1157 	float* xyz = (float*) op;
   1158 
   1159 	while (n-- > 0) {
   1160 		LogLuv32toXYZ(*luv++, xyz);
   1161 		xyz += 3;
   1162 	}
   1163 }
   1164 
   1165 static void
   1166 Luv32toLuv48(LogLuvState* sp, uint8* op, tmsize_t n)
   1167 {
   1168 	uint32* luv = (uint32*) sp->tbuf;
   1169 	int16* luv3 = (int16*) op;
   1170 
   1171 	while (n-- > 0) {
   1172 		double u, v;
   1173 
   1174 		*luv3++ = (int16)(*luv >> 16);
   1175 		u = 1./UVSCALE * ((*luv>>8 & 0xff) + .5);
   1176 		v = 1./UVSCALE * ((*luv & 0xff) + .5);
   1177 		*luv3++ = (int16)(u * (1L<<15));
   1178 		*luv3++ = (int16)(v * (1L<<15));
   1179 		luv++;
   1180 	}
   1181 }
   1182 
   1183 static void
   1184 Luv32toRGB(LogLuvState* sp, uint8* op, tmsize_t n)
   1185 {
   1186 	uint32* luv = (uint32*) sp->tbuf;
   1187 	uint8* rgb = (uint8*) op;
   1188 
   1189 	while (n-- > 0) {
   1190 		float xyz[3];
   1191 
   1192 		LogLuv32toXYZ(*luv++, xyz);
   1193 		XYZtoRGB24(xyz, rgb);
   1194 		rgb += 3;
   1195 	}
   1196 }
   1197 
   1198 static void
   1199 Luv32fromXYZ(LogLuvState* sp, uint8* op, tmsize_t n)
   1200 {
   1201 	uint32* luv = (uint32*) sp->tbuf;
   1202 	float* xyz = (float*) op;
   1203 
   1204 	while (n-- > 0) {
   1205 		*luv++ = LogLuv32fromXYZ(xyz, sp->encode_meth);
   1206 		xyz += 3;
   1207 	}
   1208 }
   1209 
   1210 static void
   1211 Luv32fromLuv48(LogLuvState* sp, uint8* op, tmsize_t n)
   1212 {
   1213 	uint32* luv = (uint32*) sp->tbuf;
   1214 	int16* luv3 = (int16*) op;
   1215 
   1216 	if (sp->encode_meth == SGILOGENCODE_NODITHER) {
   1217 		while (n-- > 0) {
   1218 			*luv++ = (uint32)luv3[0] << 16 |
   1219 				(luv3[1]*(uint32)(UVSCALE+.5) >> 7 & 0xff00) |
   1220 				(luv3[2]*(uint32)(UVSCALE+.5) >> 15 & 0xff);
   1221 			luv3 += 3;
   1222 		}
   1223 		return;
   1224 	}
   1225 	while (n-- > 0) {
   1226 		*luv++ = (uint32)luv3[0] << 16 |
   1227 	(itrunc(luv3[1]*(UVSCALE/(1<<15)), sp->encode_meth) << 8 & 0xff00) |
   1228 		(itrunc(luv3[2]*(UVSCALE/(1<<15)), sp->encode_meth) & 0xff);
   1229 		luv3 += 3;
   1230 	}
   1231 }
   1232 
   1233 static void
   1234 _logLuvNop(LogLuvState* sp, uint8* op, tmsize_t n)
   1235 {
   1236 	(void) sp; (void) op; (void) n;
   1237 }
   1238 
   1239 static int
   1240 LogL16GuessDataFmt(TIFFDirectory *td)
   1241 {
   1242 #define	PACK(s,b,f)	(((b)<<6)|((s)<<3)|(f))
   1243 	switch (PACK(td->td_samplesperpixel, td->td_bitspersample, td->td_sampleformat)) {
   1244 	case PACK(1, 32, SAMPLEFORMAT_IEEEFP):
   1245 		return (SGILOGDATAFMT_FLOAT);
   1246 	case PACK(1, 16, SAMPLEFORMAT_VOID):
   1247 	case PACK(1, 16, SAMPLEFORMAT_INT):
   1248 	case PACK(1, 16, SAMPLEFORMAT_UINT):
   1249 		return (SGILOGDATAFMT_16BIT);
   1250 	case PACK(1,  8, SAMPLEFORMAT_VOID):
   1251 	case PACK(1,  8, SAMPLEFORMAT_UINT):
   1252 		return (SGILOGDATAFMT_8BIT);
   1253 	}
   1254 #undef PACK
   1255 	return (SGILOGDATAFMT_UNKNOWN);
   1256 }
   1257 
   1258 static tmsize_t
   1259 multiply_ms(tmsize_t m1, tmsize_t m2)
   1260 {
   1261 	tmsize_t bytes = m1 * m2;
   1262 
   1263 	if (m1 && bytes / m1 != m2)
   1264 		bytes = 0;
   1265 
   1266 	return bytes;
   1267 }
   1268 
   1269 static int
   1270 LogL16InitState(TIFF* tif)
   1271 {
   1272 	static const char module[] = "LogL16InitState";
   1273 	TIFFDirectory *td = &tif->tif_dir;
   1274 	LogLuvState* sp = DecoderState(tif);
   1275 
   1276 	assert(sp != NULL);
   1277 	assert(td->td_photometric == PHOTOMETRIC_LOGL);
   1278 
   1279 	/* for some reason, we can't do this in TIFFInitLogL16 */
   1280 	if (sp->user_datafmt == SGILOGDATAFMT_UNKNOWN)
   1281 		sp->user_datafmt = LogL16GuessDataFmt(td);
   1282 	switch (sp->user_datafmt) {
   1283 	case SGILOGDATAFMT_FLOAT:
   1284 		sp->pixel_size = sizeof (float);
   1285 		break;
   1286 	case SGILOGDATAFMT_16BIT:
   1287 		sp->pixel_size = sizeof (int16);
   1288 		break;
   1289 	case SGILOGDATAFMT_8BIT:
   1290 		sp->pixel_size = sizeof (uint8);
   1291 		break;
   1292 	default:
   1293 		TIFFErrorExt(tif->tif_clientdata, module,
   1294 		    "No support for converting user data format to LogL");
   1295 		return (0);
   1296 	}
   1297         if( isTiled(tif) )
   1298             sp->tbuflen = multiply_ms(td->td_tilewidth, td->td_tilelength);
   1299         else
   1300             sp->tbuflen = multiply_ms(td->td_imagewidth, td->td_rowsperstrip);
   1301 	if (multiply_ms(sp->tbuflen, sizeof (int16)) == 0 ||
   1302 	    (sp->tbuf = (uint8*) _TIFFmalloc(sp->tbuflen * sizeof (int16))) == NULL) {
   1303 		TIFFErrorExt(tif->tif_clientdata, module, "No space for SGILog translation buffer");
   1304 		return (0);
   1305 	}
   1306 	return (1);
   1307 }
   1308 
   1309 static int
   1310 LogLuvGuessDataFmt(TIFFDirectory *td)
   1311 {
   1312 	int guess;
   1313 
   1314 	/*
   1315 	 * If the user didn't tell us their datafmt,
   1316 	 * take our best guess from the bitspersample.
   1317 	 */
   1318 #define	PACK(a,b)	(((a)<<3)|(b))
   1319 	switch (PACK(td->td_bitspersample, td->td_sampleformat)) {
   1320 	case PACK(32, SAMPLEFORMAT_IEEEFP):
   1321 		guess = SGILOGDATAFMT_FLOAT;
   1322 		break;
   1323 	case PACK(32, SAMPLEFORMAT_VOID):
   1324 	case PACK(32, SAMPLEFORMAT_UINT):
   1325 	case PACK(32, SAMPLEFORMAT_INT):
   1326 		guess = SGILOGDATAFMT_RAW;
   1327 		break;
   1328 	case PACK(16, SAMPLEFORMAT_VOID):
   1329 	case PACK(16, SAMPLEFORMAT_INT):
   1330 	case PACK(16, SAMPLEFORMAT_UINT):
   1331 		guess = SGILOGDATAFMT_16BIT;
   1332 		break;
   1333 	case PACK( 8, SAMPLEFORMAT_VOID):
   1334 	case PACK( 8, SAMPLEFORMAT_UINT):
   1335 		guess = SGILOGDATAFMT_8BIT;
   1336 		break;
   1337 	default:
   1338 		guess = SGILOGDATAFMT_UNKNOWN;
   1339 		break;
   1340 #undef PACK
   1341 	}
   1342 	/*
   1343 	 * Double-check samples per pixel.
   1344 	 */
   1345 	switch (td->td_samplesperpixel) {
   1346 	case 1:
   1347 		if (guess != SGILOGDATAFMT_RAW)
   1348 			guess = SGILOGDATAFMT_UNKNOWN;
   1349 		break;
   1350 	case 3:
   1351 		if (guess == SGILOGDATAFMT_RAW)
   1352 			guess = SGILOGDATAFMT_UNKNOWN;
   1353 		break;
   1354 	default:
   1355 		guess = SGILOGDATAFMT_UNKNOWN;
   1356 		break;
   1357 	}
   1358 	return (guess);
   1359 }
   1360 
   1361 static int
   1362 LogLuvInitState(TIFF* tif)
   1363 {
   1364 	static const char module[] = "LogLuvInitState";
   1365 	TIFFDirectory* td = &tif->tif_dir;
   1366 	LogLuvState* sp = DecoderState(tif);
   1367 
   1368 	assert(sp != NULL);
   1369 	assert(td->td_photometric == PHOTOMETRIC_LOGLUV);
   1370 
   1371 	/* for some reason, we can't do this in TIFFInitLogLuv */
   1372 	if (td->td_planarconfig != PLANARCONFIG_CONTIG) {
   1373 		TIFFErrorExt(tif->tif_clientdata, module,
   1374 		    "SGILog compression cannot handle non-contiguous data");
   1375 		return (0);
   1376 	}
   1377 	if (sp->user_datafmt == SGILOGDATAFMT_UNKNOWN)
   1378 		sp->user_datafmt = LogLuvGuessDataFmt(td);
   1379 	switch (sp->user_datafmt) {
   1380 	case SGILOGDATAFMT_FLOAT:
   1381 		sp->pixel_size = 3*sizeof (float);
   1382 		break;
   1383 	case SGILOGDATAFMT_16BIT:
   1384 		sp->pixel_size = 3*sizeof (int16);
   1385 		break;
   1386 	case SGILOGDATAFMT_RAW:
   1387 		sp->pixel_size = sizeof (uint32);
   1388 		break;
   1389 	case SGILOGDATAFMT_8BIT:
   1390 		sp->pixel_size = 3*sizeof (uint8);
   1391 		break;
   1392 	default:
   1393 		TIFFErrorExt(tif->tif_clientdata, module,
   1394 		    "No support for converting user data format to LogLuv");
   1395 		return (0);
   1396 	}
   1397         if( isTiled(tif) )
   1398             sp->tbuflen = multiply_ms(td->td_tilewidth, td->td_tilelength);
   1399         else
   1400             sp->tbuflen = multiply_ms(td->td_imagewidth, td->td_rowsperstrip);
   1401 	if (multiply_ms(sp->tbuflen, sizeof (uint32)) == 0 ||
   1402 	    (sp->tbuf = (uint8*) _TIFFmalloc(sp->tbuflen * sizeof (uint32))) == NULL) {
   1403 		TIFFErrorExt(tif->tif_clientdata, module, "No space for SGILog translation buffer");
   1404 		return (0);
   1405 	}
   1406 	return (1);
   1407 }
   1408 
   1409 static int
   1410 LogLuvFixupTags(TIFF* tif)
   1411 {
   1412 	(void) tif;
   1413 	return (1);
   1414 }
   1415 
   1416 static int
   1417 LogLuvSetupDecode(TIFF* tif)
   1418 {
   1419 	static const char module[] = "LogLuvSetupDecode";
   1420 	LogLuvState* sp = DecoderState(tif);
   1421 	TIFFDirectory* td = &tif->tif_dir;
   1422 
   1423 	tif->tif_postdecode = _TIFFNoPostDecode;
   1424 	switch (td->td_photometric) {
   1425 	case PHOTOMETRIC_LOGLUV:
   1426 		if (!LogLuvInitState(tif))
   1427 			break;
   1428 		if (td->td_compression == COMPRESSION_SGILOG24) {
   1429 			tif->tif_decoderow = LogLuvDecode24;
   1430 			switch (sp->user_datafmt) {
   1431 			case SGILOGDATAFMT_FLOAT:
   1432 				sp->tfunc = Luv24toXYZ;
   1433 				break;
   1434 			case SGILOGDATAFMT_16BIT:
   1435 				sp->tfunc = Luv24toLuv48;
   1436 				break;
   1437 			case SGILOGDATAFMT_8BIT:
   1438 				sp->tfunc = Luv24toRGB;
   1439 				break;
   1440 			}
   1441 		} else {
   1442 			tif->tif_decoderow = LogLuvDecode32;
   1443 			switch (sp->user_datafmt) {
   1444 			case SGILOGDATAFMT_FLOAT:
   1445 				sp->tfunc = Luv32toXYZ;
   1446 				break;
   1447 			case SGILOGDATAFMT_16BIT:
   1448 				sp->tfunc = Luv32toLuv48;
   1449 				break;
   1450 			case SGILOGDATAFMT_8BIT:
   1451 				sp->tfunc = Luv32toRGB;
   1452 				break;
   1453 			}
   1454 		}
   1455 		return (1);
   1456 	case PHOTOMETRIC_LOGL:
   1457 		if (!LogL16InitState(tif))
   1458 			break;
   1459 		tif->tif_decoderow = LogL16Decode;
   1460 		switch (sp->user_datafmt) {
   1461 		case SGILOGDATAFMT_FLOAT:
   1462 			sp->tfunc = L16toY;
   1463 			break;
   1464 		case SGILOGDATAFMT_8BIT:
   1465 			sp->tfunc = L16toGry;
   1466 			break;
   1467 		}
   1468 		return (1);
   1469 	default:
   1470 		TIFFErrorExt(tif->tif_clientdata, module,
   1471 		    "Inappropriate photometric interpretation %d for SGILog compression; %s",
   1472 		    td->td_photometric, "must be either LogLUV or LogL");
   1473 		break;
   1474 	}
   1475 	return (0);
   1476 }
   1477 
   1478 static int
   1479 LogLuvSetupEncode(TIFF* tif)
   1480 {
   1481 	static const char module[] = "LogLuvSetupEncode";
   1482 	LogLuvState* sp = EncoderState(tif);
   1483 	TIFFDirectory* td = &tif->tif_dir;
   1484 
   1485 	switch (td->td_photometric) {
   1486 	case PHOTOMETRIC_LOGLUV:
   1487 		if (!LogLuvInitState(tif))
   1488 			break;
   1489 		if (td->td_compression == COMPRESSION_SGILOG24) {
   1490 			tif->tif_encoderow = LogLuvEncode24;
   1491 			switch (sp->user_datafmt) {
   1492 			case SGILOGDATAFMT_FLOAT:
   1493 				sp->tfunc = Luv24fromXYZ;
   1494 				break;
   1495 			case SGILOGDATAFMT_16BIT:
   1496 				sp->tfunc = Luv24fromLuv48;
   1497 				break;
   1498 			case SGILOGDATAFMT_RAW:
   1499 				break;
   1500 			default:
   1501 				goto notsupported;
   1502 			}
   1503 		} else {
   1504 			tif->tif_encoderow = LogLuvEncode32;
   1505 			switch (sp->user_datafmt) {
   1506 			case SGILOGDATAFMT_FLOAT:
   1507 				sp->tfunc = Luv32fromXYZ;
   1508 				break;
   1509 			case SGILOGDATAFMT_16BIT:
   1510 				sp->tfunc = Luv32fromLuv48;
   1511 				break;
   1512 			case SGILOGDATAFMT_RAW:
   1513 				break;
   1514 			default:
   1515 				goto notsupported;
   1516 			}
   1517 		}
   1518 		break;
   1519 	case PHOTOMETRIC_LOGL:
   1520 		if (!LogL16InitState(tif))
   1521 			break;
   1522 		tif->tif_encoderow = LogL16Encode;
   1523 		switch (sp->user_datafmt) {
   1524 		case SGILOGDATAFMT_FLOAT:
   1525 			sp->tfunc = L16fromY;
   1526 			break;
   1527 		case SGILOGDATAFMT_16BIT:
   1528 			break;
   1529 		default:
   1530 			goto notsupported;
   1531 		}
   1532 		break;
   1533 	default:
   1534 		TIFFErrorExt(tif->tif_clientdata, module,
   1535 		    "Inappropriate photometric interpretation %d for SGILog compression; %s",
   1536 		    td->td_photometric, "must be either LogLUV or LogL");
   1537 		break;
   1538 	}
   1539 	return (1);
   1540 notsupported:
   1541 	TIFFErrorExt(tif->tif_clientdata, module,
   1542 	    "SGILog compression supported only for %s, or raw data",
   1543 	    td->td_photometric == PHOTOMETRIC_LOGL ? "Y, L" : "XYZ, Luv");
   1544 	return (0);
   1545 }
   1546 
   1547 static void
   1548 LogLuvClose(TIFF* tif)
   1549 {
   1550 	TIFFDirectory *td = &tif->tif_dir;
   1551 
   1552 	/*
   1553 	 * For consistency, we always want to write out the same
   1554 	 * bitspersample and sampleformat for our TIFF file,
   1555 	 * regardless of the data format being used by the application.
   1556 	 * Since this routine is called after tags have been set but
   1557 	 * before they have been recorded in the file, we reset them here.
   1558 	 */
   1559 	td->td_samplesperpixel =
   1560 	    (td->td_photometric == PHOTOMETRIC_LOGL) ? 1 : 3;
   1561 	td->td_bitspersample = 16;
   1562 	td->td_sampleformat = SAMPLEFORMAT_INT;
   1563 }
   1564 
   1565 static void
   1566 LogLuvCleanup(TIFF* tif)
   1567 {
   1568 	LogLuvState* sp = (LogLuvState *)tif->tif_data;
   1569 
   1570 	assert(sp != 0);
   1571 
   1572 	tif->tif_tagmethods.vgetfield = sp->vgetparent;
   1573 	tif->tif_tagmethods.vsetfield = sp->vsetparent;
   1574 
   1575 	if (sp->tbuf)
   1576 		_TIFFfree(sp->tbuf);
   1577 	_TIFFfree(sp);
   1578 	tif->tif_data = NULL;
   1579 
   1580 	_TIFFSetDefaultCompressionState(tif);
   1581 }
   1582 
   1583 static int
   1584 LogLuvVSetField(TIFF* tif, uint32 tag, va_list ap)
   1585 {
   1586 	static const char module[] = "LogLuvVSetField";
   1587 	LogLuvState* sp = DecoderState(tif);
   1588 	int bps, fmt;
   1589 
   1590 	switch (tag) {
   1591 	case TIFFTAG_SGILOGDATAFMT:
   1592 		sp->user_datafmt = (int) va_arg(ap, int);
   1593 		/*
   1594 		 * Tweak the TIFF header so that the rest of libtiff knows what
   1595 		 * size of data will be passed between app and library, and
   1596 		 * assume that the app knows what it is doing and is not
   1597 		 * confused by these header manipulations...
   1598 		 */
   1599 		switch (sp->user_datafmt) {
   1600 		case SGILOGDATAFMT_FLOAT:
   1601 			bps = 32, fmt = SAMPLEFORMAT_IEEEFP;
   1602 			break;
   1603 		case SGILOGDATAFMT_16BIT:
   1604 			bps = 16, fmt = SAMPLEFORMAT_INT;
   1605 			break;
   1606 		case SGILOGDATAFMT_RAW:
   1607 			bps = 32, fmt = SAMPLEFORMAT_UINT;
   1608 			TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1);
   1609 			break;
   1610 		case SGILOGDATAFMT_8BIT:
   1611 			bps = 8, fmt = SAMPLEFORMAT_UINT;
   1612 			break;
   1613 		default:
   1614 			TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
   1615 			    "Unknown data format %d for LogLuv compression",
   1616 			    sp->user_datafmt);
   1617 			return (0);
   1618 		}
   1619 		TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps);
   1620 		TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, fmt);
   1621 		/*
   1622 		 * Must recalculate sizes should bits/sample change.
   1623 		 */
   1624 		tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tmsize_t) -1;
   1625 		tif->tif_scanlinesize = TIFFScanlineSize(tif);
   1626 		return (1);
   1627 	case TIFFTAG_SGILOGENCODE:
   1628 		sp->encode_meth = (int) va_arg(ap, int);
   1629 		if (sp->encode_meth != SGILOGENCODE_NODITHER &&
   1630 		    sp->encode_meth != SGILOGENCODE_RANDITHER) {
   1631 			TIFFErrorExt(tif->tif_clientdata, module,
   1632 			    "Unknown encoding %d for LogLuv compression",
   1633 			    sp->encode_meth);
   1634 			return (0);
   1635 		}
   1636 		return (1);
   1637 	default:
   1638 		return (*sp->vsetparent)(tif, tag, ap);
   1639 	}
   1640 }
   1641 
   1642 static int
   1643 LogLuvVGetField(TIFF* tif, uint32 tag, va_list ap)
   1644 {
   1645 	LogLuvState *sp = (LogLuvState *)tif->tif_data;
   1646 
   1647 	switch (tag) {
   1648 	case TIFFTAG_SGILOGDATAFMT:
   1649 		*va_arg(ap, int*) = sp->user_datafmt;
   1650 		return (1);
   1651 	default:
   1652 		return (*sp->vgetparent)(tif, tag, ap);
   1653 	}
   1654 }
   1655 
   1656 static const TIFFField LogLuvFields[] = {
   1657     { TIFFTAG_SGILOGDATAFMT, 0, 0, TIFF_SHORT, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, TRUE, FALSE, "SGILogDataFmt", NULL},
   1658     { TIFFTAG_SGILOGENCODE, 0, 0, TIFF_SHORT, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, TRUE, FALSE, "SGILogEncode", NULL}
   1659 };
   1660 
   1661 int
   1662 TIFFInitSGILog(TIFF* tif, int scheme)
   1663 {
   1664 	static const char module[] = "TIFFInitSGILog";
   1665 	LogLuvState* sp;
   1666 
   1667 	assert(scheme == COMPRESSION_SGILOG24 || scheme == COMPRESSION_SGILOG);
   1668 
   1669 	/*
   1670 	 * Merge codec-specific tag information.
   1671 	 */
   1672 	if (!_TIFFMergeFields(tif, LogLuvFields,
   1673 			      TIFFArrayCount(LogLuvFields))) {
   1674 		TIFFErrorExt(tif->tif_clientdata, module,
   1675 		    "Merging SGILog codec-specific tags failed");
   1676 		return 0;
   1677 	}
   1678 
   1679 	/*
   1680 	 * Allocate state block so tag methods have storage to record values.
   1681 	 */
   1682 	tif->tif_data = (uint8*) _TIFFmalloc(sizeof (LogLuvState));
   1683 	if (tif->tif_data == NULL)
   1684 		goto bad;
   1685 	sp = (LogLuvState*) tif->tif_data;
   1686 	_TIFFmemset((void*)sp, 0, sizeof (*sp));
   1687 	sp->user_datafmt = SGILOGDATAFMT_UNKNOWN;
   1688 	sp->encode_meth = (scheme == COMPRESSION_SGILOG24) ?
   1689 	    SGILOGENCODE_RANDITHER : SGILOGENCODE_NODITHER;
   1690 	sp->tfunc = _logLuvNop;
   1691 
   1692 	/*
   1693 	 * Install codec methods.
   1694 	 * NB: tif_decoderow & tif_encoderow are filled
   1695 	 *     in at setup time.
   1696 	 */
   1697 	tif->tif_fixuptags = LogLuvFixupTags;
   1698 	tif->tif_setupdecode = LogLuvSetupDecode;
   1699 	tif->tif_decodestrip = LogLuvDecodeStrip;
   1700 	tif->tif_decodetile = LogLuvDecodeTile;
   1701 	tif->tif_setupencode = LogLuvSetupEncode;
   1702 	tif->tif_encodestrip = LogLuvEncodeStrip;
   1703 	tif->tif_encodetile = LogLuvEncodeTile;
   1704 	tif->tif_close = LogLuvClose;
   1705 	tif->tif_cleanup = LogLuvCleanup;
   1706 
   1707 	/*
   1708 	 * Override parent get/set field methods.
   1709 	 */
   1710 	sp->vgetparent = tif->tif_tagmethods.vgetfield;
   1711 	tif->tif_tagmethods.vgetfield = LogLuvVGetField;   /* hook for codec tags */
   1712 	sp->vsetparent = tif->tif_tagmethods.vsetfield;
   1713 	tif->tif_tagmethods.vsetfield = LogLuvVSetField;   /* hook for codec tags */
   1714 
   1715 	return (1);
   1716 bad:
   1717 	TIFFErrorExt(tif->tif_clientdata, module,
   1718 		     "%s: No space for LogLuv state block", tif->tif_name);
   1719 	return (0);
   1720 }
   1721 #endif /* LOGLUV_SUPPORT */
   1722 
   1723 /* vim: set ts=8 sts=8 sw=8 noet: */
   1724 /*
   1725  * Local Variables:
   1726  * mode: c
   1727  * c-basic-offset: 8
   1728  * fill-column: 78
   1729  * End:
   1730  */
   1731