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