1 /* $Id$ */
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
LogL16Decode(TIFF * tif,uint8 * op,tmsize_t occ,uint16 s)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
LogLuvDecode24(TIFF * tif,uint8 * op,tmsize_t occ,uint16 s)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
LogLuvDecode32(TIFF * tif,uint8 * op,tmsize_t occ,uint16 s)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
LogLuvDecodeStrip(TIFF * tif,uint8 * bp,tmsize_t cc,uint16 s)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;
406 		cc -= rowlen;
407 	}
408 	return (cc == 0);
409 }
410 
411 /*
412  * Decode a tile of pixels.  We break it into rows to
413  * maintain synchrony with the encode algorithm, which
414  * is row by row.
415  */
416 static int
LogLuvDecodeTile(TIFF * tif,uint8 * bp,tmsize_t cc,uint16 s)417 LogLuvDecodeTile(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
418 {
419 	tmsize_t rowlen = TIFFTileRowSize(tif);
420 
421         if (rowlen == 0)
422                 return 0;
423 
424 	assert(cc%rowlen == 0);
425 	while (cc && (*tif->tif_decoderow)(tif, bp, rowlen, s)) {
426 		bp += rowlen;
427 		cc -= rowlen;
428 	}
429 	return (cc == 0);
430 }
431 
432 /*
433  * Encode a row of 16-bit pixels.
434  */
435 static int
LogL16Encode(TIFF * tif,uint8 * bp,tmsize_t cc,uint16 s)436 LogL16Encode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
437 {
438 	static const char module[] = "LogL16Encode";
439 	LogLuvState* sp = EncoderState(tif);
440 	int shft;
441 	tmsize_t i;
442 	tmsize_t j;
443 	tmsize_t npixels;
444 	uint8* op;
445 	int16* tp;
446 	int16 b;
447 	tmsize_t occ;
448 	int rc=0, mask;
449 	tmsize_t beg;
450 
451 	assert(s == 0);
452 	assert(sp != NULL);
453 	npixels = cc / sp->pixel_size;
454 
455 	if (sp->user_datafmt == SGILOGDATAFMT_16BIT)
456 		tp = (int16*) bp;
457 	else {
458 		tp = (int16*) sp->tbuf;
459 		if(sp->tbuflen < npixels) {
460 			TIFFErrorExt(tif->tif_clientdata, module,
461 						 "Translation buffer too short");
462 			return (0);
463 		}
464 		(*sp->tfunc)(sp, bp, npixels);
465 	}
466 	/* compress each byte string */
467 	op = tif->tif_rawcp;
468 	occ = tif->tif_rawdatasize - tif->tif_rawcc;
469 	for (shft = 2*8; (shft -= 8) >= 0; )
470 		for (i = 0; i < npixels; i += rc) {
471 			if (occ < 4) {
472 				tif->tif_rawcp = op;
473 				tif->tif_rawcc = tif->tif_rawdatasize - occ;
474 				if (!TIFFFlushData1(tif))
475 					return (-1);
476 				op = tif->tif_rawcp;
477 				occ = tif->tif_rawdatasize - tif->tif_rawcc;
478 			}
479 			mask = 0xff << shft;		/* find next run */
480 			for (beg = i; beg < npixels; beg += rc) {
481 				b = (int16) (tp[beg] & mask);
482 				rc = 1;
483 				while (rc < 127+2 && beg+rc < npixels &&
484 				    (tp[beg+rc] & mask) == b)
485 					rc++;
486 				if (rc >= MINRUN)
487 					break;		/* long enough */
488 			}
489 			if (beg-i > 1 && beg-i < MINRUN) {
490 				b = (int16) (tp[i] & mask);/*check short run */
491 				j = i+1;
492 				while ((tp[j++] & mask) == b)
493 					if (j == beg) {
494 						*op++ = (uint8)(128-2+j-i);
495 						*op++ = (uint8)(b >> shft);
496 						occ -= 2;
497 						i = beg;
498 						break;
499 					}
500 			}
501 			while (i < beg) {		/* write out non-run */
502 				if ((j = beg-i) > 127) j = 127;
503 				if (occ < j+3) {
504 					tif->tif_rawcp = op;
505 					tif->tif_rawcc = tif->tif_rawdatasize - occ;
506 					if (!TIFFFlushData1(tif))
507 						return (-1);
508 					op = tif->tif_rawcp;
509 					occ = tif->tif_rawdatasize - tif->tif_rawcc;
510 				}
511 				*op++ = (uint8) j; occ--;
512 				while (j--) {
513 					*op++ = (uint8) (tp[i++] >> shft & 0xff);
514 					occ--;
515 				}
516 			}
517 			if (rc >= MINRUN) {		/* write out run */
518 				*op++ = (uint8) (128-2+rc);
519 				*op++ = (uint8) (tp[beg] >> shft & 0xff);
520 				occ -= 2;
521 			} else
522 				rc = 0;
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
LogLuvEncode24(TIFF * tif,uint8 * bp,tmsize_t cc,uint16 s)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 (-1);
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
LogLuvEncode32(TIFF * tif,uint8 * bp,tmsize_t cc,uint16 s)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 = 4*8; (shft -= 8) >= 0; )
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 (-1);
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 (-1);
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 	tif->tif_rawcp = op;
676 	tif->tif_rawcc = tif->tif_rawdatasize - occ;
677 
678 	return (1);
679 }
680 
681 /*
682  * Encode a strip of pixels.  We break it into rows to
683  * avoid encoding runs across row boundaries.
684  */
685 static int
LogLuvEncodeStrip(TIFF * tif,uint8 * bp,tmsize_t cc,uint16 s)686 LogLuvEncodeStrip(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
687 {
688 	tmsize_t rowlen = TIFFScanlineSize(tif);
689 
690         if (rowlen == 0)
691                 return 0;
692 
693 	assert(cc%rowlen == 0);
694 	while (cc && (*tif->tif_encoderow)(tif, bp, rowlen, s) == 1) {
695 		bp += rowlen;
696 		cc -= rowlen;
697 	}
698 	return (cc == 0);
699 }
700 
701 /*
702  * Encode a tile of pixels.  We break it into rows to
703  * avoid encoding runs across row boundaries.
704  */
705 static int
LogLuvEncodeTile(TIFF * tif,uint8 * bp,tmsize_t cc,uint16 s)706 LogLuvEncodeTile(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
707 {
708 	tmsize_t rowlen = TIFFTileRowSize(tif);
709 
710         if (rowlen == 0)
711                 return 0;
712 
713 	assert(cc%rowlen == 0);
714 	while (cc && (*tif->tif_encoderow)(tif, bp, rowlen, s) == 1) {
715 		bp += rowlen;
716 		cc -= rowlen;
717 	}
718 	return (cc == 0);
719 }
720 
721 /*
722  * Encode/Decode functions for converting to and from user formats.
723  */
724 
725 #include "uvcode.h"
726 
727 #ifndef UVSCALE
728 #define U_NEU		0.210526316
729 #define V_NEU		0.473684211
730 #define UVSCALE		410.
731 #endif
732 
733 #ifndef	M_LN2
734 #define M_LN2		0.69314718055994530942
735 #endif
736 #ifndef M_PI
737 #define M_PI		3.14159265358979323846
738 #endif
739 #undef log2 /* Conflict with C'99 function */
740 #define log2(x)		((1./M_LN2)*log(x))
741 #undef exp2  /* Conflict with C'99 function */
742 #define exp2(x)		exp(M_LN2*(x))
743 
744 #define itrunc(x,m)	((m)==SGILOGENCODE_NODITHER ? \
745 				(int)(x) : \
746 				(int)((x) + rand()*(1./RAND_MAX) - .5))
747 
748 #if !LOGLUV_PUBLIC
749 static
750 #endif
751 double
LogL16toY(int p16)752 LogL16toY(int p16)		/* compute luminance from 16-bit LogL */
753 {
754 	int	Le = p16 & 0x7fff;
755 	double	Y;
756 
757 	if (!Le)
758 		return (0.);
759 	Y = exp(M_LN2/256.*(Le+.5) - M_LN2*64.);
760 	return (!(p16 & 0x8000) ? Y : -Y);
761 }
762 
763 #if !LOGLUV_PUBLIC
764 static
765 #endif
766 int
LogL16fromY(double Y,int em)767 LogL16fromY(double Y, int em)	/* get 16-bit LogL from Y */
768 {
769 	if (Y >= 1.8371976e19)
770 		return (0x7fff);
771 	if (Y <= -1.8371976e19)
772 		return (0xffff);
773 	if (Y > 5.4136769e-20)
774 		return itrunc(256.*(log2(Y) + 64.), em);
775 	if (Y < -5.4136769e-20)
776 		return (~0x7fff | itrunc(256.*(log2(-Y) + 64.), em));
777 	return (0);
778 }
779 
780 static void
L16toY(LogLuvState * sp,uint8 * op,tmsize_t n)781 L16toY(LogLuvState* sp, uint8* op, tmsize_t n)
782 {
783 	int16* l16 = (int16*) sp->tbuf;
784 	float* yp = (float*) op;
785 
786 	while (n-- > 0)
787 		*yp++ = (float)LogL16toY(*l16++);
788 }
789 
790 static void
L16toGry(LogLuvState * sp,uint8 * op,tmsize_t n)791 L16toGry(LogLuvState* sp, uint8* op, tmsize_t n)
792 {
793 	int16* l16 = (int16*) sp->tbuf;
794 	uint8* gp = (uint8*) op;
795 
796 	while (n-- > 0) {
797 		double Y = LogL16toY(*l16++);
798 		*gp++ = (uint8) ((Y <= 0.) ? 0 : (Y >= 1.) ? 255 : (int)(256.*sqrt(Y)));
799 	}
800 }
801 
802 static void
L16fromY(LogLuvState * sp,uint8 * op,tmsize_t n)803 L16fromY(LogLuvState* sp, uint8* op, tmsize_t n)
804 {
805 	int16* l16 = (int16*) sp->tbuf;
806 	float* yp = (float*) op;
807 
808 	while (n-- > 0)
809 		*l16++ = (int16) (LogL16fromY(*yp++, sp->encode_meth));
810 }
811 
812 #if !LOGLUV_PUBLIC
813 static
814 #endif
815 void
XYZtoRGB24(float xyz[3],uint8 rgb[3])816 XYZtoRGB24(float xyz[3], uint8 rgb[3])
817 {
818 	double	r, g, b;
819 					/* assume CCIR-709 primaries */
820 	r =  2.690*xyz[0] + -1.276*xyz[1] + -0.414*xyz[2];
821 	g = -1.022*xyz[0] +  1.978*xyz[1] +  0.044*xyz[2];
822 	b =  0.061*xyz[0] + -0.224*xyz[1] +  1.163*xyz[2];
823 					/* assume 2.0 gamma for speed */
824 	/* could use integer sqrt approx., but this is probably faster */
825 	rgb[0] = (uint8)((r<=0.) ? 0 : (r >= 1.) ? 255 : (int)(256.*sqrt(r)));
826 	rgb[1] = (uint8)((g<=0.) ? 0 : (g >= 1.) ? 255 : (int)(256.*sqrt(g)));
827 	rgb[2] = (uint8)((b<=0.) ? 0 : (b >= 1.) ? 255 : (int)(256.*sqrt(b)));
828 }
829 
830 #if !LOGLUV_PUBLIC
831 static
832 #endif
833 double
LogL10toY(int p10)834 LogL10toY(int p10)		/* compute luminance from 10-bit LogL */
835 {
836 	if (p10 == 0)
837 		return (0.);
838 	return (exp(M_LN2/64.*(p10+.5) - M_LN2*12.));
839 }
840 
841 #if !LOGLUV_PUBLIC
842 static
843 #endif
844 int
LogL10fromY(double Y,int em)845 LogL10fromY(double Y, int em)	/* get 10-bit LogL from Y */
846 {
847 	if (Y >= 15.742)
848 		return (0x3ff);
849 	else if (Y <= .00024283)
850 		return (0);
851 	else
852 		return itrunc(64.*(log2(Y) + 12.), em);
853 }
854 
855 #define NANGLES		100
856 #define uv2ang(u, v)	( (NANGLES*.499999999/M_PI) \
857 				* atan2((v)-V_NEU,(u)-U_NEU) + .5*NANGLES )
858 
859 static int
oog_encode(double u,double v)860 oog_encode(double u, double v)		/* encode out-of-gamut chroma */
861 {
862 	static int	oog_table[NANGLES];
863 	static int	initialized = 0;
864 	register int	i;
865 
866 	if (!initialized) {		/* set up perimeter table */
867 		double	eps[NANGLES], ua, va, ang, epsa;
868 		int	ui, vi, ustep;
869 		for (i = NANGLES; i--; )
870 			eps[i] = 2.;
871 		for (vi = UV_NVS; vi--; ) {
872 			va = UV_VSTART + (vi+.5)*UV_SQSIZ;
873 			ustep = uv_row[vi].nus-1;
874 			if (vi == UV_NVS-1 || vi == 0 || ustep <= 0)
875 				ustep = 1;
876 			for (ui = uv_row[vi].nus-1; ui >= 0; ui -= ustep) {
877 				ua = uv_row[vi].ustart + (ui+.5)*UV_SQSIZ;
878 				ang = uv2ang(ua, va);
879 				i = (int) ang;
880 				epsa = fabs(ang - (i+.5));
881 				if (epsa < eps[i]) {
882 					oog_table[i] = uv_row[vi].ncum + ui;
883 					eps[i] = epsa;
884 				}
885 			}
886 		}
887 		for (i = NANGLES; i--; )	/* fill any holes */
888 			if (eps[i] > 1.5) {
889 				int	i1, i2;
890 				for (i1 = 1; i1 < NANGLES/2; i1++)
891 					if (eps[(i+i1)%NANGLES] < 1.5)
892 						break;
893 				for (i2 = 1; i2 < NANGLES/2; i2++)
894 					if (eps[(i+NANGLES-i2)%NANGLES] < 1.5)
895 						break;
896 				if (i1 < i2)
897 					oog_table[i] =
898 						oog_table[(i+i1)%NANGLES];
899 				else
900 					oog_table[i] =
901 						oog_table[(i+NANGLES-i2)%NANGLES];
902 			}
903 		initialized = 1;
904 	}
905 	i = (int) uv2ang(u, v);		/* look up hue angle */
906 	return (oog_table[i]);
907 }
908 
909 #undef uv2ang
910 #undef NANGLES
911 
912 #if !LOGLUV_PUBLIC
913 static
914 #endif
915 int
uv_encode(double u,double v,int em)916 uv_encode(double u, double v, int em)	/* encode (u',v') coordinates */
917 {
918 	register int	vi, ui;
919 
920 	if (v < UV_VSTART)
921 		return oog_encode(u, v);
922 	vi = itrunc((v - UV_VSTART)*(1./UV_SQSIZ), em);
923 	if (vi >= UV_NVS)
924 		return oog_encode(u, v);
925 	if (u < uv_row[vi].ustart)
926 		return oog_encode(u, v);
927 	ui = itrunc((u - uv_row[vi].ustart)*(1./UV_SQSIZ), em);
928 	if (ui >= uv_row[vi].nus)
929 		return oog_encode(u, v);
930 
931 	return (uv_row[vi].ncum + ui);
932 }
933 
934 #if !LOGLUV_PUBLIC
935 static
936 #endif
937 int
uv_decode(double * up,double * vp,int c)938 uv_decode(double *up, double *vp, int c)	/* decode (u',v') index */
939 {
940 	int	upper, lower;
941 	register int	ui, vi;
942 
943 	if (c < 0 || c >= UV_NDIVS)
944 		return (-1);
945 	lower = 0;				/* binary search */
946 	upper = UV_NVS;
947 	while (upper - lower > 1) {
948 		vi = (lower + upper) >> 1;
949 		ui = c - uv_row[vi].ncum;
950 		if (ui > 0)
951 			lower = vi;
952 		else if (ui < 0)
953 			upper = vi;
954 		else {
955 			lower = vi;
956 			break;
957 		}
958 	}
959 	vi = lower;
960 	ui = c - uv_row[vi].ncum;
961 	*up = uv_row[vi].ustart + (ui+.5)*UV_SQSIZ;
962 	*vp = UV_VSTART + (vi+.5)*UV_SQSIZ;
963 	return (0);
964 }
965 
966 #if !LOGLUV_PUBLIC
967 static
968 #endif
969 void
LogLuv24toXYZ(uint32 p,float XYZ[3])970 LogLuv24toXYZ(uint32 p, float XYZ[3])
971 {
972 	int	Ce;
973 	double	L, u, v, s, x, y;
974 					/* decode luminance */
975 	L = LogL10toY(p>>14 & 0x3ff);
976 	if (L <= 0.) {
977 		XYZ[0] = XYZ[1] = XYZ[2] = 0.;
978 		return;
979 	}
980 					/* decode color */
981 	Ce = p & 0x3fff;
982 	if (uv_decode(&u, &v, Ce) < 0) {
983 		u = U_NEU; v = V_NEU;
984 	}
985 	s = 1./(6.*u - 16.*v + 12.);
986 	x = 9.*u * s;
987 	y = 4.*v * s;
988 					/* convert to XYZ */
989 	XYZ[0] = (float)(x/y * L);
990 	XYZ[1] = (float)L;
991 	XYZ[2] = (float)((1.-x-y)/y * L);
992 }
993 
994 #if !LOGLUV_PUBLIC
995 static
996 #endif
997 uint32
LogLuv24fromXYZ(float XYZ[3],int em)998 LogLuv24fromXYZ(float XYZ[3], int em)
999 {
1000 	int	Le, Ce;
1001 	double	u, v, s;
1002 					/* encode luminance */
1003 	Le = LogL10fromY(XYZ[1], em);
1004 					/* encode color */
1005 	s = XYZ[0] + 15.*XYZ[1] + 3.*XYZ[2];
1006 	if (!Le || s <= 0.) {
1007 		u = U_NEU;
1008 		v = V_NEU;
1009 	} else {
1010 		u = 4.*XYZ[0] / s;
1011 		v = 9.*XYZ[1] / s;
1012 	}
1013 	Ce = uv_encode(u, v, em);
1014 	if (Ce < 0)			/* never happens */
1015 		Ce = uv_encode(U_NEU, V_NEU, SGILOGENCODE_NODITHER);
1016 					/* combine encodings */
1017 	return (Le << 14 | Ce);
1018 }
1019 
1020 static void
Luv24toXYZ(LogLuvState * sp,uint8 * op,tmsize_t n)1021 Luv24toXYZ(LogLuvState* sp, uint8* op, tmsize_t n)
1022 {
1023 	uint32* luv = (uint32*) sp->tbuf;
1024 	float* xyz = (float*) op;
1025 
1026 	while (n-- > 0) {
1027 		LogLuv24toXYZ(*luv, xyz);
1028 		xyz += 3;
1029 		luv++;
1030 	}
1031 }
1032 
1033 static void
Luv24toLuv48(LogLuvState * sp,uint8 * op,tmsize_t n)1034 Luv24toLuv48(LogLuvState* sp, uint8* op, tmsize_t n)
1035 {
1036 	uint32* luv = (uint32*) sp->tbuf;
1037 	int16* luv3 = (int16*) op;
1038 
1039 	while (n-- > 0) {
1040 		double u, v;
1041 
1042 		*luv3++ = (int16)((*luv >> 12 & 0xffd) + 13314);
1043 		if (uv_decode(&u, &v, *luv&0x3fff) < 0) {
1044 			u = U_NEU;
1045 			v = V_NEU;
1046 		}
1047 		*luv3++ = (int16)(u * (1L<<15));
1048 		*luv3++ = (int16)(v * (1L<<15));
1049 		luv++;
1050 	}
1051 }
1052 
1053 static void
Luv24toRGB(LogLuvState * sp,uint8 * op,tmsize_t n)1054 Luv24toRGB(LogLuvState* sp, uint8* op, tmsize_t n)
1055 {
1056 	uint32* luv = (uint32*) sp->tbuf;
1057 	uint8* rgb = (uint8*) op;
1058 
1059 	while (n-- > 0) {
1060 		float xyz[3];
1061 
1062 		LogLuv24toXYZ(*luv++, xyz);
1063 		XYZtoRGB24(xyz, rgb);
1064 		rgb += 3;
1065 	}
1066 }
1067 
1068 static void
Luv24fromXYZ(LogLuvState * sp,uint8 * op,tmsize_t n)1069 Luv24fromXYZ(LogLuvState* sp, uint8* op, tmsize_t n)
1070 {
1071 	uint32* luv = (uint32*) sp->tbuf;
1072 	float* xyz = (float*) op;
1073 
1074 	while (n-- > 0) {
1075 		*luv++ = LogLuv24fromXYZ(xyz, sp->encode_meth);
1076 		xyz += 3;
1077 	}
1078 }
1079 
1080 static void
Luv24fromLuv48(LogLuvState * sp,uint8 * op,tmsize_t n)1081 Luv24fromLuv48(LogLuvState* sp, uint8* op, tmsize_t n)
1082 {
1083 	uint32* luv = (uint32*) sp->tbuf;
1084 	int16* luv3 = (int16*) op;
1085 
1086 	while (n-- > 0) {
1087 		int Le, Ce;
1088 
1089 		if (luv3[0] <= 0)
1090 			Le = 0;
1091 		else if (luv3[0] >= (1<<12)+3314)
1092 			Le = (1<<10) - 1;
1093 		else if (sp->encode_meth == SGILOGENCODE_NODITHER)
1094 			Le = (luv3[0]-3314) >> 2;
1095 		else
1096 			Le = itrunc(.25*(luv3[0]-3314.), sp->encode_meth);
1097 
1098 		Ce = uv_encode((luv3[1]+.5)/(1<<15), (luv3[2]+.5)/(1<<15),
1099 					sp->encode_meth);
1100 		if (Ce < 0)	/* never happens */
1101 			Ce = uv_encode(U_NEU, V_NEU, SGILOGENCODE_NODITHER);
1102 		*luv++ = (uint32)Le << 14 | Ce;
1103 		luv3 += 3;
1104 	}
1105 }
1106 
1107 #if !LOGLUV_PUBLIC
1108 static
1109 #endif
1110 void
LogLuv32toXYZ(uint32 p,float XYZ[3])1111 LogLuv32toXYZ(uint32 p, float XYZ[3])
1112 {
1113 	double	L, u, v, s, x, y;
1114 					/* decode luminance */
1115 	L = LogL16toY((int)p >> 16);
1116 	if (L <= 0.) {
1117 		XYZ[0] = XYZ[1] = XYZ[2] = 0.;
1118 		return;
1119 	}
1120 					/* decode color */
1121 	u = 1./UVSCALE * ((p>>8 & 0xff) + .5);
1122 	v = 1./UVSCALE * ((p & 0xff) + .5);
1123 	s = 1./(6.*u - 16.*v + 12.);
1124 	x = 9.*u * s;
1125 	y = 4.*v * s;
1126 					/* convert to XYZ */
1127 	XYZ[0] = (float)(x/y * L);
1128 	XYZ[1] = (float)L;
1129 	XYZ[2] = (float)((1.-x-y)/y * L);
1130 }
1131 
1132 #if !LOGLUV_PUBLIC
1133 static
1134 #endif
1135 uint32
LogLuv32fromXYZ(float XYZ[3],int em)1136 LogLuv32fromXYZ(float XYZ[3], int em)
1137 {
1138 	unsigned int	Le, ue, ve;
1139 	double	u, v, s;
1140 					/* encode luminance */
1141 	Le = (unsigned int)LogL16fromY(XYZ[1], em);
1142 					/* encode color */
1143 	s = XYZ[0] + 15.*XYZ[1] + 3.*XYZ[2];
1144 	if (!Le || s <= 0.) {
1145 		u = U_NEU;
1146 		v = V_NEU;
1147 	} else {
1148 		u = 4.*XYZ[0] / s;
1149 		v = 9.*XYZ[1] / s;
1150 	}
1151 	if (u <= 0.) ue = 0;
1152 	else ue = itrunc(UVSCALE*u, em);
1153 	if (ue > 255) ue = 255;
1154 	if (v <= 0.) ve = 0;
1155 	else ve = itrunc(UVSCALE*v, em);
1156 	if (ve > 255) ve = 255;
1157 					/* combine encodings */
1158 	return (Le << 16 | ue << 8 | ve);
1159 }
1160 
1161 static void
Luv32toXYZ(LogLuvState * sp,uint8 * op,tmsize_t n)1162 Luv32toXYZ(LogLuvState* sp, uint8* op, tmsize_t n)
1163 {
1164 	uint32* luv = (uint32*) sp->tbuf;
1165 	float* xyz = (float*) op;
1166 
1167 	while (n-- > 0) {
1168 		LogLuv32toXYZ(*luv++, xyz);
1169 		xyz += 3;
1170 	}
1171 }
1172 
1173 static void
Luv32toLuv48(LogLuvState * sp,uint8 * op,tmsize_t n)1174 Luv32toLuv48(LogLuvState* sp, uint8* op, tmsize_t n)
1175 {
1176 	uint32* luv = (uint32*) sp->tbuf;
1177 	int16* luv3 = (int16*) op;
1178 
1179 	while (n-- > 0) {
1180 		double u, v;
1181 
1182 		*luv3++ = (int16)(*luv >> 16);
1183 		u = 1./UVSCALE * ((*luv>>8 & 0xff) + .5);
1184 		v = 1./UVSCALE * ((*luv & 0xff) + .5);
1185 		*luv3++ = (int16)(u * (1L<<15));
1186 		*luv3++ = (int16)(v * (1L<<15));
1187 		luv++;
1188 	}
1189 }
1190 
1191 static void
Luv32toRGB(LogLuvState * sp,uint8 * op,tmsize_t n)1192 Luv32toRGB(LogLuvState* sp, uint8* op, tmsize_t n)
1193 {
1194 	uint32* luv = (uint32*) sp->tbuf;
1195 	uint8* rgb = (uint8*) op;
1196 
1197 	while (n-- > 0) {
1198 		float xyz[3];
1199 
1200 		LogLuv32toXYZ(*luv++, xyz);
1201 		XYZtoRGB24(xyz, rgb);
1202 		rgb += 3;
1203 	}
1204 }
1205 
1206 static void
Luv32fromXYZ(LogLuvState * sp,uint8 * op,tmsize_t n)1207 Luv32fromXYZ(LogLuvState* sp, uint8* op, tmsize_t n)
1208 {
1209 	uint32* luv = (uint32*) sp->tbuf;
1210 	float* xyz = (float*) op;
1211 
1212 	while (n-- > 0) {
1213 		*luv++ = LogLuv32fromXYZ(xyz, sp->encode_meth);
1214 		xyz += 3;
1215 	}
1216 }
1217 
1218 static void
Luv32fromLuv48(LogLuvState * sp,uint8 * op,tmsize_t n)1219 Luv32fromLuv48(LogLuvState* sp, uint8* op, tmsize_t n)
1220 {
1221 	uint32* luv = (uint32*) sp->tbuf;
1222 	int16* luv3 = (int16*) op;
1223 
1224 	if (sp->encode_meth == SGILOGENCODE_NODITHER) {
1225 		while (n-- > 0) {
1226 			*luv++ = (uint32)luv3[0] << 16 |
1227 				(luv3[1]*(uint32)(UVSCALE+.5) >> 7 & 0xff00) |
1228 				(luv3[2]*(uint32)(UVSCALE+.5) >> 15 & 0xff);
1229 			luv3 += 3;
1230 		}
1231 		return;
1232 	}
1233 	while (n-- > 0) {
1234 		*luv++ = (uint32)luv3[0] << 16 |
1235 	(itrunc(luv3[1]*(UVSCALE/(1<<15)), sp->encode_meth) << 8 & 0xff00) |
1236 		(itrunc(luv3[2]*(UVSCALE/(1<<15)), sp->encode_meth) & 0xff);
1237 		luv3 += 3;
1238 	}
1239 }
1240 
1241 static void
_logLuvNop(LogLuvState * sp,uint8 * op,tmsize_t n)1242 _logLuvNop(LogLuvState* sp, uint8* op, tmsize_t n)
1243 {
1244 	(void) sp; (void) op; (void) n;
1245 }
1246 
1247 static int
LogL16GuessDataFmt(TIFFDirectory * td)1248 LogL16GuessDataFmt(TIFFDirectory *td)
1249 {
1250 #define	PACK(s,b,f)	(((b)<<6)|((s)<<3)|(f))
1251 	switch (PACK(td->td_samplesperpixel, td->td_bitspersample, td->td_sampleformat)) {
1252 	case PACK(1, 32, SAMPLEFORMAT_IEEEFP):
1253 		return (SGILOGDATAFMT_FLOAT);
1254 	case PACK(1, 16, SAMPLEFORMAT_VOID):
1255 	case PACK(1, 16, SAMPLEFORMAT_INT):
1256 	case PACK(1, 16, SAMPLEFORMAT_UINT):
1257 		return (SGILOGDATAFMT_16BIT);
1258 	case PACK(1,  8, SAMPLEFORMAT_VOID):
1259 	case PACK(1,  8, SAMPLEFORMAT_UINT):
1260 		return (SGILOGDATAFMT_8BIT);
1261 	}
1262 #undef PACK
1263 	return (SGILOGDATAFMT_UNKNOWN);
1264 }
1265 
1266 static tmsize_t
multiply_ms(tmsize_t m1,tmsize_t m2)1267 multiply_ms(tmsize_t m1, tmsize_t m2)
1268 {
1269 	tmsize_t bytes = m1 * m2;
1270 
1271 	if (m1 && bytes / m1 != m2)
1272 		bytes = 0;
1273 
1274 	return bytes;
1275 }
1276 
1277 static int
LogL16InitState(TIFF * tif)1278 LogL16InitState(TIFF* tif)
1279 {
1280 	static const char module[] = "LogL16InitState";
1281 	TIFFDirectory *td = &tif->tif_dir;
1282 	LogLuvState* sp = DecoderState(tif);
1283 
1284 	assert(sp != NULL);
1285 	assert(td->td_photometric == PHOTOMETRIC_LOGL);
1286 
1287 	if( td->td_samplesperpixel != 1 )
1288 	{
1289 		TIFFErrorExt(tif->tif_clientdata, module,
1290 		             "Sorry, can not handle LogL image with %s=%d",
1291 			     "Samples/pixel", td->td_samplesperpixel);
1292 		return 0;
1293 	}
1294 
1295 	/* for some reason, we can't do this in TIFFInitLogL16 */
1296 	if (sp->user_datafmt == SGILOGDATAFMT_UNKNOWN)
1297 		sp->user_datafmt = LogL16GuessDataFmt(td);
1298 	switch (sp->user_datafmt) {
1299 	case SGILOGDATAFMT_FLOAT:
1300 		sp->pixel_size = sizeof (float);
1301 		break;
1302 	case SGILOGDATAFMT_16BIT:
1303 		sp->pixel_size = sizeof (int16);
1304 		break;
1305 	case SGILOGDATAFMT_8BIT:
1306 		sp->pixel_size = sizeof (uint8);
1307 		break;
1308 	default:
1309 		TIFFErrorExt(tif->tif_clientdata, module,
1310 		    "No support for converting user data format to LogL");
1311 		return (0);
1312 	}
1313         if( isTiled(tif) )
1314             sp->tbuflen = multiply_ms(td->td_tilewidth, td->td_tilelength);
1315         else
1316             sp->tbuflen = multiply_ms(td->td_imagewidth, td->td_rowsperstrip);
1317 	if (multiply_ms(sp->tbuflen, sizeof (int16)) == 0 ||
1318 	    (sp->tbuf = (uint8*) _TIFFmalloc(sp->tbuflen * sizeof (int16))) == NULL) {
1319 		TIFFErrorExt(tif->tif_clientdata, module, "No space for SGILog translation buffer");
1320 		return (0);
1321 	}
1322 	return (1);
1323 }
1324 
1325 static int
LogLuvGuessDataFmt(TIFFDirectory * td)1326 LogLuvGuessDataFmt(TIFFDirectory *td)
1327 {
1328 	int guess;
1329 
1330 	/*
1331 	 * If the user didn't tell us their datafmt,
1332 	 * take our best guess from the bitspersample.
1333 	 */
1334 #define	PACK(a,b)	(((a)<<3)|(b))
1335 	switch (PACK(td->td_bitspersample, td->td_sampleformat)) {
1336 	case PACK(32, SAMPLEFORMAT_IEEEFP):
1337 		guess = SGILOGDATAFMT_FLOAT;
1338 		break;
1339 	case PACK(32, SAMPLEFORMAT_VOID):
1340 	case PACK(32, SAMPLEFORMAT_UINT):
1341 	case PACK(32, SAMPLEFORMAT_INT):
1342 		guess = SGILOGDATAFMT_RAW;
1343 		break;
1344 	case PACK(16, SAMPLEFORMAT_VOID):
1345 	case PACK(16, SAMPLEFORMAT_INT):
1346 	case PACK(16, SAMPLEFORMAT_UINT):
1347 		guess = SGILOGDATAFMT_16BIT;
1348 		break;
1349 	case PACK( 8, SAMPLEFORMAT_VOID):
1350 	case PACK( 8, SAMPLEFORMAT_UINT):
1351 		guess = SGILOGDATAFMT_8BIT;
1352 		break;
1353 	default:
1354 		guess = SGILOGDATAFMT_UNKNOWN;
1355 		break;
1356 #undef PACK
1357 	}
1358 	/*
1359 	 * Double-check samples per pixel.
1360 	 */
1361 	switch (td->td_samplesperpixel) {
1362 	case 1:
1363 		if (guess != SGILOGDATAFMT_RAW)
1364 			guess = SGILOGDATAFMT_UNKNOWN;
1365 		break;
1366 	case 3:
1367 		if (guess == SGILOGDATAFMT_RAW)
1368 			guess = SGILOGDATAFMT_UNKNOWN;
1369 		break;
1370 	default:
1371 		guess = SGILOGDATAFMT_UNKNOWN;
1372 		break;
1373 	}
1374 	return (guess);
1375 }
1376 
1377 static int
LogLuvInitState(TIFF * tif)1378 LogLuvInitState(TIFF* tif)
1379 {
1380 	static const char module[] = "LogLuvInitState";
1381 	TIFFDirectory* td = &tif->tif_dir;
1382 	LogLuvState* sp = DecoderState(tif);
1383 
1384 	assert(sp != NULL);
1385 	assert(td->td_photometric == PHOTOMETRIC_LOGLUV);
1386 
1387 	/* for some reason, we can't do this in TIFFInitLogLuv */
1388 	if (td->td_planarconfig != PLANARCONFIG_CONTIG) {
1389 		TIFFErrorExt(tif->tif_clientdata, module,
1390 		    "SGILog compression cannot handle non-contiguous data");
1391 		return (0);
1392 	}
1393 	if (sp->user_datafmt == SGILOGDATAFMT_UNKNOWN)
1394 		sp->user_datafmt = LogLuvGuessDataFmt(td);
1395 	switch (sp->user_datafmt) {
1396 	case SGILOGDATAFMT_FLOAT:
1397 		sp->pixel_size = 3*sizeof (float);
1398 		break;
1399 	case SGILOGDATAFMT_16BIT:
1400 		sp->pixel_size = 3*sizeof (int16);
1401 		break;
1402 	case SGILOGDATAFMT_RAW:
1403 		sp->pixel_size = sizeof (uint32);
1404 		break;
1405 	case SGILOGDATAFMT_8BIT:
1406 		sp->pixel_size = 3*sizeof (uint8);
1407 		break;
1408 	default:
1409 		TIFFErrorExt(tif->tif_clientdata, module,
1410 		    "No support for converting user data format to LogLuv");
1411 		return (0);
1412 	}
1413         if( isTiled(tif) )
1414             sp->tbuflen = multiply_ms(td->td_tilewidth, td->td_tilelength);
1415         else
1416             sp->tbuflen = multiply_ms(td->td_imagewidth, td->td_rowsperstrip);
1417 	if (multiply_ms(sp->tbuflen, sizeof (uint32)) == 0 ||
1418 	    (sp->tbuf = (uint8*) _TIFFmalloc(sp->tbuflen * sizeof (uint32))) == NULL) {
1419 		TIFFErrorExt(tif->tif_clientdata, module, "No space for SGILog translation buffer");
1420 		return (0);
1421 	}
1422 	return (1);
1423 }
1424 
1425 static int
LogLuvFixupTags(TIFF * tif)1426 LogLuvFixupTags(TIFF* tif)
1427 {
1428 	(void) tif;
1429 	return (1);
1430 }
1431 
1432 static int
LogLuvSetupDecode(TIFF * tif)1433 LogLuvSetupDecode(TIFF* tif)
1434 {
1435 	static const char module[] = "LogLuvSetupDecode";
1436 	LogLuvState* sp = DecoderState(tif);
1437 	TIFFDirectory* td = &tif->tif_dir;
1438 
1439 	tif->tif_postdecode = _TIFFNoPostDecode;
1440 	switch (td->td_photometric) {
1441 	case PHOTOMETRIC_LOGLUV:
1442 		if (!LogLuvInitState(tif))
1443 			break;
1444 		if (td->td_compression == COMPRESSION_SGILOG24) {
1445 			tif->tif_decoderow = LogLuvDecode24;
1446 			switch (sp->user_datafmt) {
1447 			case SGILOGDATAFMT_FLOAT:
1448 				sp->tfunc = Luv24toXYZ;
1449 				break;
1450 			case SGILOGDATAFMT_16BIT:
1451 				sp->tfunc = Luv24toLuv48;
1452 				break;
1453 			case SGILOGDATAFMT_8BIT:
1454 				sp->tfunc = Luv24toRGB;
1455 				break;
1456 			}
1457 		} else {
1458 			tif->tif_decoderow = LogLuvDecode32;
1459 			switch (sp->user_datafmt) {
1460 			case SGILOGDATAFMT_FLOAT:
1461 				sp->tfunc = Luv32toXYZ;
1462 				break;
1463 			case SGILOGDATAFMT_16BIT:
1464 				sp->tfunc = Luv32toLuv48;
1465 				break;
1466 			case SGILOGDATAFMT_8BIT:
1467 				sp->tfunc = Luv32toRGB;
1468 				break;
1469 			}
1470 		}
1471 		return (1);
1472 	case PHOTOMETRIC_LOGL:
1473 		if (!LogL16InitState(tif))
1474 			break;
1475 		tif->tif_decoderow = LogL16Decode;
1476 		switch (sp->user_datafmt) {
1477 		case SGILOGDATAFMT_FLOAT:
1478 			sp->tfunc = L16toY;
1479 			break;
1480 		case SGILOGDATAFMT_8BIT:
1481 			sp->tfunc = L16toGry;
1482 			break;
1483 		}
1484 		return (1);
1485 	default:
1486 		TIFFErrorExt(tif->tif_clientdata, module,
1487 		    "Inappropriate photometric interpretation %d for SGILog compression; %s",
1488 		    td->td_photometric, "must be either LogLUV or LogL");
1489 		break;
1490 	}
1491 	return (0);
1492 }
1493 
1494 static int
LogLuvSetupEncode(TIFF * tif)1495 LogLuvSetupEncode(TIFF* tif)
1496 {
1497 	static const char module[] = "LogLuvSetupEncode";
1498 	LogLuvState* sp = EncoderState(tif);
1499 	TIFFDirectory* td = &tif->tif_dir;
1500 
1501 	switch (td->td_photometric) {
1502 	case PHOTOMETRIC_LOGLUV:
1503 		if (!LogLuvInitState(tif))
1504 			break;
1505 		if (td->td_compression == COMPRESSION_SGILOG24) {
1506 			tif->tif_encoderow = LogLuvEncode24;
1507 			switch (sp->user_datafmt) {
1508 			case SGILOGDATAFMT_FLOAT:
1509 				sp->tfunc = Luv24fromXYZ;
1510 				break;
1511 			case SGILOGDATAFMT_16BIT:
1512 				sp->tfunc = Luv24fromLuv48;
1513 				break;
1514 			case SGILOGDATAFMT_RAW:
1515 				break;
1516 			default:
1517 				goto notsupported;
1518 			}
1519 		} else {
1520 			tif->tif_encoderow = LogLuvEncode32;
1521 			switch (sp->user_datafmt) {
1522 			case SGILOGDATAFMT_FLOAT:
1523 				sp->tfunc = Luv32fromXYZ;
1524 				break;
1525 			case SGILOGDATAFMT_16BIT:
1526 				sp->tfunc = Luv32fromLuv48;
1527 				break;
1528 			case SGILOGDATAFMT_RAW:
1529 				break;
1530 			default:
1531 				goto notsupported;
1532 			}
1533 		}
1534 		break;
1535 	case PHOTOMETRIC_LOGL:
1536 		if (!LogL16InitState(tif))
1537 			break;
1538 		tif->tif_encoderow = LogL16Encode;
1539 		switch (sp->user_datafmt) {
1540 		case SGILOGDATAFMT_FLOAT:
1541 			sp->tfunc = L16fromY;
1542 			break;
1543 		case SGILOGDATAFMT_16BIT:
1544 			break;
1545 		default:
1546 			goto notsupported;
1547 		}
1548 		break;
1549 	default:
1550 		TIFFErrorExt(tif->tif_clientdata, module,
1551 		    "Inappropriate photometric interpretation %d for SGILog compression; %s",
1552 		    td->td_photometric, "must be either LogLUV or LogL");
1553 		break;
1554 	}
1555 	return (1);
1556 notsupported:
1557 	TIFFErrorExt(tif->tif_clientdata, module,
1558 	    "SGILog compression supported only for %s, or raw data",
1559 	    td->td_photometric == PHOTOMETRIC_LOGL ? "Y, L" : "XYZ, Luv");
1560 	return (0);
1561 }
1562 
1563 static void
LogLuvClose(TIFF * tif)1564 LogLuvClose(TIFF* tif)
1565 {
1566 	TIFFDirectory *td = &tif->tif_dir;
1567 
1568 	/*
1569 	 * For consistency, we always want to write out the same
1570 	 * bitspersample and sampleformat for our TIFF file,
1571 	 * regardless of the data format being used by the application.
1572 	 * Since this routine is called after tags have been set but
1573 	 * before they have been recorded in the file, we reset them here.
1574 	 */
1575 	td->td_samplesperpixel =
1576 	    (td->td_photometric == PHOTOMETRIC_LOGL) ? 1 : 3;
1577 	td->td_bitspersample = 16;
1578 	td->td_sampleformat = SAMPLEFORMAT_INT;
1579 }
1580 
1581 static void
LogLuvCleanup(TIFF * tif)1582 LogLuvCleanup(TIFF* tif)
1583 {
1584 	LogLuvState* sp = (LogLuvState *)tif->tif_data;
1585 
1586 	assert(sp != 0);
1587 
1588 	tif->tif_tagmethods.vgetfield = sp->vgetparent;
1589 	tif->tif_tagmethods.vsetfield = sp->vsetparent;
1590 
1591 	if (sp->tbuf)
1592 		_TIFFfree(sp->tbuf);
1593 	_TIFFfree(sp);
1594 	tif->tif_data = NULL;
1595 
1596 	_TIFFSetDefaultCompressionState(tif);
1597 }
1598 
1599 static int
LogLuvVSetField(TIFF * tif,uint32 tag,va_list ap)1600 LogLuvVSetField(TIFF* tif, uint32 tag, va_list ap)
1601 {
1602 	static const char module[] = "LogLuvVSetField";
1603 	LogLuvState* sp = DecoderState(tif);
1604 	int bps, fmt;
1605 
1606 	switch (tag) {
1607 	case TIFFTAG_SGILOGDATAFMT:
1608 		sp->user_datafmt = (int) va_arg(ap, int);
1609 		/*
1610 		 * Tweak the TIFF header so that the rest of libtiff knows what
1611 		 * size of data will be passed between app and library, and
1612 		 * assume that the app knows what it is doing and is not
1613 		 * confused by these header manipulations...
1614 		 */
1615 		switch (sp->user_datafmt) {
1616 		case SGILOGDATAFMT_FLOAT:
1617 			bps = 32;
1618 			fmt = SAMPLEFORMAT_IEEEFP;
1619 			break;
1620 		case SGILOGDATAFMT_16BIT:
1621 			bps = 16;
1622 			fmt = SAMPLEFORMAT_INT;
1623 			break;
1624 		case SGILOGDATAFMT_RAW:
1625 			bps = 32;
1626 			fmt = SAMPLEFORMAT_UINT;
1627 			TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1);
1628 			break;
1629 		case SGILOGDATAFMT_8BIT:
1630 			bps = 8;
1631 			fmt = SAMPLEFORMAT_UINT;
1632 			break;
1633 		default:
1634 			TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
1635 			    "Unknown data format %d for LogLuv compression",
1636 			    sp->user_datafmt);
1637 			return (0);
1638 		}
1639 		TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps);
1640 		TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, fmt);
1641 		/*
1642 		 * Must recalculate sizes should bits/sample change.
1643 		 */
1644 		tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tmsize_t) -1;
1645 		tif->tif_scanlinesize = TIFFScanlineSize(tif);
1646 		return (1);
1647 	case TIFFTAG_SGILOGENCODE:
1648 		sp->encode_meth = (int) va_arg(ap, int);
1649 		if (sp->encode_meth != SGILOGENCODE_NODITHER &&
1650 		    sp->encode_meth != SGILOGENCODE_RANDITHER) {
1651 			TIFFErrorExt(tif->tif_clientdata, module,
1652 			    "Unknown encoding %d for LogLuv compression",
1653 			    sp->encode_meth);
1654 			return (0);
1655 		}
1656 		return (1);
1657 	default:
1658 		return (*sp->vsetparent)(tif, tag, ap);
1659 	}
1660 }
1661 
1662 static int
LogLuvVGetField(TIFF * tif,uint32 tag,va_list ap)1663 LogLuvVGetField(TIFF* tif, uint32 tag, va_list ap)
1664 {
1665 	LogLuvState *sp = (LogLuvState *)tif->tif_data;
1666 
1667 	switch (tag) {
1668 	case TIFFTAG_SGILOGDATAFMT:
1669 		*va_arg(ap, int*) = sp->user_datafmt;
1670 		return (1);
1671 	default:
1672 		return (*sp->vgetparent)(tif, tag, ap);
1673 	}
1674 }
1675 
1676 static const TIFFField LogLuvFields[] = {
1677     { TIFFTAG_SGILOGDATAFMT, 0, 0, TIFF_SHORT, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, TRUE, FALSE, "SGILogDataFmt", NULL},
1678     { TIFFTAG_SGILOGENCODE, 0, 0, TIFF_SHORT, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, TRUE, FALSE, "SGILogEncode", NULL}
1679 };
1680 
1681 int
TIFFInitSGILog(TIFF * tif,int scheme)1682 TIFFInitSGILog(TIFF* tif, int scheme)
1683 {
1684 	static const char module[] = "TIFFInitSGILog";
1685 	LogLuvState* sp;
1686 
1687 	assert(scheme == COMPRESSION_SGILOG24 || scheme == COMPRESSION_SGILOG);
1688 
1689 	/*
1690 	 * Merge codec-specific tag information.
1691 	 */
1692 	if (!_TIFFMergeFields(tif, LogLuvFields,
1693 			      TIFFArrayCount(LogLuvFields))) {
1694 		TIFFErrorExt(tif->tif_clientdata, module,
1695 		    "Merging SGILog codec-specific tags failed");
1696 		return 0;
1697 	}
1698 
1699 	/*
1700 	 * Allocate state block so tag methods have storage to record values.
1701 	 */
1702 	tif->tif_data = (uint8*) _TIFFmalloc(sizeof (LogLuvState));
1703 	if (tif->tif_data == NULL)
1704 		goto bad;
1705 	sp = (LogLuvState*) tif->tif_data;
1706 	_TIFFmemset((void*)sp, 0, sizeof (*sp));
1707 	sp->user_datafmt = SGILOGDATAFMT_UNKNOWN;
1708 	sp->encode_meth = (scheme == COMPRESSION_SGILOG24) ?
1709 	    SGILOGENCODE_RANDITHER : SGILOGENCODE_NODITHER;
1710 	sp->tfunc = _logLuvNop;
1711 
1712 	/*
1713 	 * Install codec methods.
1714 	 * NB: tif_decoderow & tif_encoderow are filled
1715 	 *     in at setup time.
1716 	 */
1717 	tif->tif_fixuptags = LogLuvFixupTags;
1718 	tif->tif_setupdecode = LogLuvSetupDecode;
1719 	tif->tif_decodestrip = LogLuvDecodeStrip;
1720 	tif->tif_decodetile = LogLuvDecodeTile;
1721 	tif->tif_setupencode = LogLuvSetupEncode;
1722 	tif->tif_encodestrip = LogLuvEncodeStrip;
1723 	tif->tif_encodetile = LogLuvEncodeTile;
1724 	tif->tif_close = LogLuvClose;
1725 	tif->tif_cleanup = LogLuvCleanup;
1726 
1727 	/*
1728 	 * Override parent get/set field methods.
1729 	 */
1730 	sp->vgetparent = tif->tif_tagmethods.vgetfield;
1731 	tif->tif_tagmethods.vgetfield = LogLuvVGetField;   /* hook for codec tags */
1732 	sp->vsetparent = tif->tif_tagmethods.vsetfield;
1733 	tif->tif_tagmethods.vsetfield = LogLuvVSetField;   /* hook for codec tags */
1734 
1735 	return (1);
1736 bad:
1737 	TIFFErrorExt(tif->tif_clientdata, module,
1738 		     "%s: No space for LogLuv state block", tif->tif_name);
1739 	return (0);
1740 }
1741 #endif /* LOGLUV_SUPPORT */
1742 
1743 /* vim: set ts=8 sts=8 sw=8 noet: */
1744 /*
1745  * Local Variables:
1746  * mode: c
1747  * c-basic-offset: 8
1748  * fill-column: 78
1749  * End:
1750  */
1751