1 /* PDFlib GmbH cvsid:
2  * $Id: tif_luv.c,v 1.10 2005/12/21 14:12:52 rjs Exp $ */
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 	tidata_t*		tbuf;		/* translation buffer */
166 	int			tbuflen;	/* buffer length */
167 	void (*tfunc)(LogLuvState*, tidata_t, int);
168 
169 	TIFFVSetMethod		vgetparent;	/* super-class method */
170 	TIFFVSetMethod		vsetparent;	/* super-class method */
171 };
172 
173 #define	DecoderState(tif)	((LogLuvState*) (tif)->tif_data)
174 #ifdef PDFLIB_TIFFWRITE_SUPPORT
175 #define	EncoderState(tif)	((LogLuvState*) (tif)->tif_data)
176 #endif /* PDFLIB_TIFFWRITE_SUPPORT */
177 
178 #define N(a)   (sizeof(a)/sizeof(a[0]))
179 #define SGILOGDATAFMT_UNKNOWN	-1
180 
181 #define MINRUN		4	/* minimum run length */
182 
183 /*
184  * Decode a string of 16-bit gray pixels.
185  */
186 static int
LogL16Decode(TIFF * tif,tidata_t op,tsize_t occ,tsample_t s)187 LogL16Decode(TIFF* tif, tidata_t op, tsize_t occ, tsample_t s)
188 {
189 	LogLuvState* sp = DecoderState(tif);
190 	int shft, i, npixels;
191 	unsigned char* bp;
192 	int16* tp;
193 	int16 b;
194 	int cc, 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 		assert(sp->tbuflen >= npixels);
205 		tp = (int16*) sp->tbuf;
206 	}
207 	_TIFFmemset((tdata_t) tp, 0, npixels*sizeof (tp[0]));
208 
209 	bp = (unsigned char*) tif->tif_rawcp;
210 	cc = tif->tif_rawcc;
211 					/* get each byte string */
212 	for (shft = 2*8; (shft -= 8) >= 0; ) {
213 		for (i = 0; i < npixels && cc > 0; )
214 			if (*bp >= 128) {		/* run */
215 				rc = *bp++ + (2-128);
216 				b = (int16)(*bp++ << shft);
217 				cc -= 2;
218 				while (rc-- && i < npixels)
219 					tp[i++] |= b;
220 			} else {			/* non-run */
221 				rc = *bp++;		/* nul is noop */
222 				while (--cc && rc-- && i < npixels)
223 					tp[i++] |= (int16)*bp++ << shft;
224 			}
225 		if (i != npixels) {
226 			_TIFFError(tif, tif->tif_name,
227 		"LogL16Decode: Not enough data at row %d (short %d pixels)",
228 			    tif->tif_row, npixels - i);
229 			tif->tif_rawcp = (tidata_t) bp;
230 			tif->tif_rawcc = cc;
231 			return (0);
232 		}
233 	}
234 	(*sp->tfunc)(sp, op, npixels);
235 	tif->tif_rawcp = (tidata_t) bp;
236 	tif->tif_rawcc = cc;
237 	return (1);
238 }
239 
240 /*
241  * Decode a string of 24-bit pixels.
242  */
243 static int
LogLuvDecode24(TIFF * tif,tidata_t op,tsize_t occ,tsample_t s)244 LogLuvDecode24(TIFF* tif, tidata_t op, tsize_t occ, tsample_t s)
245 {
246 	LogLuvState* sp = DecoderState(tif);
247 	int cc, i, npixels;
248 	unsigned char * bp;
249 	uint32* tp;
250 
251 	assert(s == 0);
252 	assert(sp != NULL);
253 
254 	npixels = occ / sp->pixel_size;
255 
256 	if (sp->user_datafmt == SGILOGDATAFMT_RAW)
257 		tp = (uint32 *)op;
258 	else {
259 		assert(sp->tbuflen >= npixels);
260 		tp = (uint32 *) sp->tbuf;
261 	}
262 					/* copy to array of uint32 */
263 	bp = (unsigned char*) tif->tif_rawcp;
264 	cc = tif->tif_rawcc;
265 	for (i = 0; i < npixels && cc > 0; i++) {
266 		tp[i] = bp[0] << 16 | bp[1] << 8 | bp[2];
267 		bp += 3;
268 		cc -= 3;
269 	}
270 	tif->tif_rawcp = (tidata_t) bp;
271 	tif->tif_rawcc = cc;
272 	if (i != npixels) {
273 		_TIFFError(tif, tif->tif_name,
274 	    "LogLuvDecode24: Not enough data at row %d (short %d pixels)",
275 		    tif->tif_row, npixels - i);
276 		return (0);
277 	}
278 	(*sp->tfunc)(sp, op, npixels);
279 	return (1);
280 }
281 
282 /*
283  * Decode a string of 32-bit pixels.
284  */
285 static int
LogLuvDecode32(TIFF * tif,tidata_t op,tsize_t occ,tsample_t s)286 LogLuvDecode32(TIFF* tif, tidata_t op, tsize_t occ, tsample_t s)
287 {
288 	LogLuvState* sp;
289 	int shft, i, npixels;
290 	unsigned char* bp;
291 	uint32* tp;
292 	uint32 b;
293 	int cc, rc;
294 
295 	assert(s == 0);
296 	sp = DecoderState(tif);
297 	assert(sp != NULL);
298 
299 	npixels = occ / sp->pixel_size;
300 
301 	if (sp->user_datafmt == SGILOGDATAFMT_RAW)
302 		tp = (uint32*) op;
303 	else {
304 		assert(sp->tbuflen >= npixels);
305 		tp = (uint32*) sp->tbuf;
306 	}
307 	_TIFFmemset((tdata_t) tp, 0, npixels*sizeof (tp[0]));
308 
309 	bp = (unsigned char*) tif->tif_rawcp;
310 	cc = tif->tif_rawcc;
311 					/* get each byte string */
312 	for (shft = 4*8; (shft -= 8) >= 0; ) {
313 		for (i = 0; i < npixels && cc > 0; )
314 			if (*bp >= 128) {		/* run */
315 				rc = *bp++ + (2-128);
316 				b = (uint32)*bp++ << shft;
317 				cc -= 2;
318 				while (rc-- && i < npixels)
319 					tp[i++] |= b;
320 			} else {			/* non-run */
321 				rc = *bp++;		/* nul is noop */
322 				while (--cc && rc-- && i < npixels)
323 					tp[i++] |= (uint32)*bp++ << shft;
324 			}
325 		if (i != npixels) {
326 			_TIFFError(tif, tif->tif_name,
327 		"LogLuvDecode32: Not enough data at row %d (short %d pixels)",
328 			    tif->tif_row, npixels - i);
329 			tif->tif_rawcp = (tidata_t) bp;
330 			tif->tif_rawcc = cc;
331 			return (0);
332 		}
333 	}
334 	(*sp->tfunc)(sp, op, npixels);
335 	tif->tif_rawcp = (tidata_t) bp;
336 	tif->tif_rawcc = cc;
337 	return (1);
338 }
339 
340 /*
341  * Decode a strip of pixels.  We break it into rows to
342  * maintain synchrony with the encode algorithm, which
343  * is row by row.
344  */
345 static int
LogLuvDecodeStrip(TIFF * tif,tidata_t bp,tsize_t cc,tsample_t s)346 LogLuvDecodeStrip(TIFF* tif, tidata_t bp, tsize_t cc, tsample_t s)
347 {
348 	tsize_t rowlen = TIFFScanlineSize(tif);
349 
350 	assert(cc%rowlen == 0);
351 	while (cc && (*tif->tif_decoderow)(tif, bp, rowlen, s))
352 		bp += rowlen, cc -= rowlen;
353 	return (cc == 0);
354 }
355 
356 /*
357  * Decode a tile of pixels.  We break it into rows to
358  * maintain synchrony with the encode algorithm, which
359  * is row by row.
360  */
361 static int
LogLuvDecodeTile(TIFF * tif,tidata_t bp,tsize_t cc,tsample_t s)362 LogLuvDecodeTile(TIFF* tif, tidata_t bp, tsize_t cc, tsample_t s)
363 {
364 	tsize_t rowlen = TIFFTileRowSize(tif);
365 
366 	assert(cc%rowlen == 0);
367 	while (cc && (*tif->tif_decoderow)(tif, bp, rowlen, s))
368 		bp += rowlen, cc -= rowlen;
369 	return (cc == 0);
370 }
371 
372 /*
373  * Encode a row of 16-bit pixels.
374  */
375 #ifdef PDFLIB_TIFFWRITE_SUPPORT
376 static int
LogL16Encode(TIFF * tif,tidata_t bp,tsize_t cc,tsample_t s)377 LogL16Encode(TIFF* tif, tidata_t bp, tsize_t cc, tsample_t s)
378 {
379 	LogLuvState* sp = EncoderState(tif);
380 	int shft, i, j, npixels;
381 	tidata_t op;
382 	int16* tp;
383 	int16 b;
384 	int occ, rc=0, mask, beg;
385 
386 	assert(s == 0);
387 	assert(sp != NULL);
388 	npixels = cc / sp->pixel_size;
389 
390 	if (sp->user_datafmt == SGILOGDATAFMT_16BIT)
391 		tp = (int16*) bp;
392 	else {
393 		tp = (int16*) sp->tbuf;
394 		assert(sp->tbuflen >= npixels);
395 		(*sp->tfunc)(sp, bp, npixels);
396 	}
397 					/* compress each byte string */
398 	op = tif->tif_rawcp;
399 	occ = tif->tif_rawdatasize - tif->tif_rawcc;
400 	for (shft = 2*8; (shft -= 8) >= 0; )
401 		for (i = 0; i < npixels; i += rc) {
402 			if (occ < 4) {
403 				tif->tif_rawcp = op;
404 				tif->tif_rawcc = tif->tif_rawdatasize - occ;
405 				if (!TIFFFlushData1(tif))
406 					return (-1);
407 				op = tif->tif_rawcp;
408 				occ = tif->tif_rawdatasize - tif->tif_rawcc;
409 			}
410 			mask = 0xff << shft;		/* find next run */
411 			for (beg = i; beg < npixels; beg += rc) {
412 				b = (int16) (tp[beg] & mask);
413 				rc = 1;
414 				while (rc < 127+2 && beg+rc < npixels &&
415 						(tp[beg+rc] & mask) == b)
416 					rc++;
417 				if (rc >= MINRUN)
418 					break;		/* long enough */
419 			}
420 			if (beg-i > 1 && beg-i < MINRUN) {
421 				b = (int16) (tp[i] & mask);/*check short run */
422 				j = i+1;
423 				while ((tp[j++] & mask) == b)
424                                     if (j == beg) {
425                                         *op++ = (tidataval_t)(128-2+j-i);
426                                         *op++ = (tidataval_t) (b >> shft);
427                                         occ -= 2;
428                                         i = beg;
429                                         break;
430                                     }
431 			}
432 			while (i < beg) {		/* write out non-run */
433 				if ((j = beg-i) > 127) j = 127;
434 				if (occ < j+3) {
435                                     tif->tif_rawcp = op;
436                                     tif->tif_rawcc = tif->tif_rawdatasize - occ;
437                                     if (!TIFFFlushData1(tif))
438                                         return (-1);
439                                     op = tif->tif_rawcp;
440                                     occ = tif->tif_rawdatasize - tif->tif_rawcc;
441 				}
442 				*op++ = (tidataval_t) j; occ--;
443 				while (j--) {
444 				    *op++ = (tidataval_t) (tp[i++]>>shft&0xff);
445 				    occ--;
446 				}
447 			}
448 			if (rc >= MINRUN) {		/* write out run */
449 				*op++ = (tidataval_t) (128-2+rc);
450 				*op++ = (tidataval_t) (tp[beg] >> shft & 0xff);
451 				occ -= 2;
452 			} else
453 				rc = 0;
454 		}
455 	tif->tif_rawcp = op;
456 	tif->tif_rawcc = tif->tif_rawdatasize - occ;
457 
458 	return (0);
459 }
460 #endif /* PDFLIB_TIFFWRITE_SUPPORT */
461 
462 /*
463  * Encode a row of 24-bit pixels.
464  */
465 #ifdef PDFLIB_TIFFWRITE_SUPPORT
466 static int
LogLuvEncode24(TIFF * tif,tidata_t bp,tsize_t cc,tsample_t s)467 LogLuvEncode24(TIFF* tif, tidata_t bp, tsize_t cc, tsample_t s)
468 {
469 	LogLuvState* sp = EncoderState(tif);
470 	int i, npixels, occ;
471 	tidata_t op;
472 	uint32* tp;
473 
474 	assert(s == 0);
475 	assert(sp != NULL);
476 	npixels = cc / sp->pixel_size;
477 
478 	if (sp->user_datafmt == SGILOGDATAFMT_RAW)
479 		tp = (uint32*) bp;
480 	else {
481 		tp = (uint32*) sp->tbuf;
482 		assert(sp->tbuflen >= npixels);
483 		(*sp->tfunc)(sp, bp, npixels);
484 	}
485 					/* write out encoded pixels */
486 	op = tif->tif_rawcp;
487 	occ = tif->tif_rawdatasize - tif->tif_rawcc;
488 	for (i = npixels; i--; ) {
489 		if (occ < 3) {
490 			tif->tif_rawcp = op;
491 			tif->tif_rawcc = tif->tif_rawdatasize - occ;
492 			if (!TIFFFlushData1(tif))
493 				return (-1);
494 			op = tif->tif_rawcp;
495 			occ = tif->tif_rawdatasize - tif->tif_rawcc;
496 		}
497 		*op++ = (tidataval_t)(*tp >> 16);
498 		*op++ = (tidataval_t)(*tp >> 8 & 0xff);
499 		*op++ = (tidataval_t)(*tp++ & 0xff);
500 		occ -= 3;
501 	}
502 	tif->tif_rawcp = op;
503 	tif->tif_rawcc = tif->tif_rawdatasize - occ;
504 
505 	return (0);
506 }
507 #endif /* PDFLIB_TIFFWRITE_SUPPORT */
508 
509 /*
510  * Encode a row of 32-bit pixels.
511  */
512 #ifdef PDFLIB_TIFFWRITE_SUPPORT
513 static int
LogLuvEncode32(TIFF * tif,tidata_t bp,tsize_t cc,tsample_t s)514 LogLuvEncode32(TIFF* tif, tidata_t bp, tsize_t cc, tsample_t s)
515 {
516 	LogLuvState* sp = EncoderState(tif);
517 	int shft, i, j, npixels;
518 	tidata_t op;
519 	uint32* tp;
520 	uint32 b;
521 	int occ, rc=0, mask, beg;
522 
523 	assert(s == 0);
524 	assert(sp != NULL);
525 
526 	npixels = cc / sp->pixel_size;
527 
528 	if (sp->user_datafmt == SGILOGDATAFMT_RAW)
529 		tp = (uint32*) bp;
530 	else {
531 		tp = (uint32*) sp->tbuf;
532 		assert(sp->tbuflen >= npixels);
533 		(*sp->tfunc)(sp, bp, npixels);
534 	}
535 					/* compress each byte string */
536 	op = tif->tif_rawcp;
537 	occ = tif->tif_rawdatasize - tif->tif_rawcc;
538 	for (shft = 4*8; (shft -= 8) >= 0; )
539 		for (i = 0; i < npixels; i += rc) {
540 			if (occ < 4) {
541 				tif->tif_rawcp = op;
542 				tif->tif_rawcc = tif->tif_rawdatasize - occ;
543 				if (!TIFFFlushData1(tif))
544 					return (-1);
545 				op = tif->tif_rawcp;
546 				occ = tif->tif_rawdatasize - tif->tif_rawcc;
547 			}
548 			mask = 0xff << shft;		/* find next run */
549 			for (beg = i; beg < npixels; beg += rc) {
550 				b = tp[beg] & mask;
551 				rc = 1;
552 				while (rc < 127+2 && beg+rc < npixels &&
553 						(tp[beg+rc] & mask) == b)
554 					rc++;
555 				if (rc >= MINRUN)
556 					break;		/* long enough */
557 			}
558 			if (beg-i > 1 && beg-i < MINRUN) {
559 				b = tp[i] & mask;	/* check short run */
560 				j = i+1;
561 				while ((tp[j++] & mask) == b)
562 					if (j == beg) {
563 						*op++ =(tidataval_t)(128-2+j-i);
564 						*op++ =(tidataval_t)(b >> shft);
565 						occ -= 2;
566 						i = beg;
567 						break;
568 					}
569 			}
570 			while (i < beg) {		/* write out non-run */
571 				if ((j = beg-i) > 127) j = 127;
572 				if (occ < j+3) {
573 					tif->tif_rawcp = op;
574 					tif->tif_rawcc = tif->tif_rawdatasize
575 					    - occ;
576 					if (!TIFFFlushData1(tif))
577 						return (-1);
578 					op = tif->tif_rawcp;
579 					occ = tif->tif_rawdatasize
580 					    - tif->tif_rawcc;
581 				}
582 				*op++ = (tidataval_t) j; occ--;
583 				while (j--) {
584 					*op++ = (tidataval_t)(tp[i++] >> shft
585 					    & 0xff);
586 					occ--;
587 				}
588 			}
589 			if (rc >= MINRUN) {		/* write out run */
590 				*op++ = (tidataval_t) (128-2+rc);
591 				*op++ = (tidataval_t)(tp[beg] >> shft & 0xff);
592 				occ -= 2;
593 			} else
594 				rc = 0;
595 		}
596 	tif->tif_rawcp = op;
597 	tif->tif_rawcc = tif->tif_rawdatasize - occ;
598 
599 	return (0);
600 }
601 #endif /* PDFLIB_TIFFWRITE_SUPPORT */
602 
603 /*
604  * Encode a strip of pixels.  We break it into rows to
605  * avoid encoding runs across row boundaries.
606  */
607 #ifdef PDFLIB_TIFFWRITE_SUPPORT
608 static int
LogLuvEncodeStrip(TIFF * tif,tidata_t bp,tsize_t cc,tsample_t s)609 LogLuvEncodeStrip(TIFF* tif, tidata_t bp, tsize_t cc, tsample_t s)
610 {
611 	tsize_t rowlen = TIFFScanlineSize(tif);
612 
613 	assert(cc%rowlen == 0);
614 	while (cc && (*tif->tif_encoderow)(tif, bp, rowlen, s) == 0)
615 		bp += rowlen, cc -= rowlen;
616 	return (cc == 0);
617 }
618 #endif /* PDFLIB_TIFFWRITE_SUPPORT */
619 
620 /*
621  * Encode a tile of pixels.  We break it into rows to
622  * avoid encoding runs across row boundaries.
623  */
624 #ifdef PDFLIB_TIFFWRITE_SUPPORT
625 static int
LogLuvEncodeTile(TIFF * tif,tidata_t bp,tsize_t cc,tsample_t s)626 LogLuvEncodeTile(TIFF* tif, tidata_t bp, tsize_t cc, tsample_t s)
627 {
628 	tsize_t rowlen = TIFFTileRowSize(tif);
629 
630 	assert(cc%rowlen == 0);
631 	while (cc && (*tif->tif_encoderow)(tif, bp, rowlen, s) == 0)
632 		bp += rowlen, cc -= rowlen;
633 	return (cc == 0);
634 }
635 #endif /* PDFLIB_TIFFWRITE_SUPPORT */
636 
637 /*
638  * Encode/Decode functions for converting to and from user formats.
639  */
640 
641 #include "uvcode.h"
642 
643 #ifndef UVSCALE
644 #define U_NEU		0.210526316
645 #define V_NEU		0.473684211
646 #define UVSCALE		410.
647 #endif
648 
649 #ifndef	M_LN2
650 #define M_LN2		0.69314718055994530942
651 #endif
652 #ifndef M_PI
653 #define M_PI		3.14159265358979323846
654 #endif
655 #define log2(x)		((1./M_LN2)*log(x))
656 #define exp2(x)		exp(M_LN2*(x))
657 
658 #define itrunc(x,m)	((m)==SGILOGENCODE_NODITHER ? \
659 				(int)(x) : \
660 				(int)((x) + rand()*(1./RAND_MAX) - .5))
661 
662 #if !LOGLUV_PUBLIC
663 static
664 #endif
665 double
LogL16toY(int p16)666 LogL16toY(int p16)		/* compute luminance from 16-bit LogL */
667 {
668 	int	Le = p16 & 0x7fff;
669 	double	Y;
670 
671 	if (!Le)
672 		return (0.);
673 	Y = exp(M_LN2/256.*(Le+.5) - M_LN2*64.);
674 	return (!(p16 & 0x8000) ? Y : -Y);
675 }
676 
677 #ifdef PDFLIB_TIFFWRITE_SUPPORT
678 #if !LOGLUV_PUBLIC
679 static
680 #endif
681 int
LogL16fromY(double Y,int em)682 LogL16fromY(double Y, int em)	/* get 16-bit LogL from Y */
683 {
684 	if (Y >= 1.8371976e19)
685 		return (0x7fff);
686 	if (Y <= -1.8371976e19)
687 		return (0xffff);
688 	if (Y > 5.4136769e-20)
689 		return itrunc(256.*(log2(Y) + 64.), em);
690 	if (Y < -5.4136769e-20)
691 		return (~0x7fff | itrunc(256.*(log2(-Y) + 64.), em));
692 	return (0);
693 }
694 #endif /* PDFLIB_TIFFWRITE_SUPPORT */
695 
696 static void
L16toY(LogLuvState * sp,tidata_t op,int n)697 L16toY(LogLuvState* sp, tidata_t op, int n)
698 {
699 	int16* l16 = (int16*) sp->tbuf;
700 	float* yp = (float*) op;
701 
702 	while (n-- > 0)
703 		*yp++ = (float)LogL16toY(*l16++);
704 }
705 
706 static void
L16toGry(LogLuvState * sp,tidata_t op,int n)707 L16toGry(LogLuvState* sp, tidata_t op, int n)
708 {
709 	int16* l16 = (int16*) sp->tbuf;
710 	uint8* gp = (uint8*) op;
711 
712 	while (n-- > 0) {
713 	   double Y = LogL16toY(*l16++);
714 	   *gp++ = (uint8) ((Y <= 0.) ? 0 : (Y>=1.) ? 255:(int)(256.*sqrt(Y)));
715 	}
716 }
717 
718 #ifdef PDFLIB_TIFFWRITE_SUPPORT
719 static void
L16fromY(LogLuvState * sp,tidata_t op,int n)720 L16fromY(LogLuvState* sp, tidata_t op, int n)
721 {
722 	int16* l16 = (int16*) sp->tbuf;
723 	float* yp = (float*) op;
724 
725 	while (n-- > 0)
726 		*l16++ = (int16) (LogL16fromY(*yp++, sp->encode_meth));
727 }
728 #endif /* PDFLIB_TIFFWRITE_SUPPORT */
729 
730 #if !LOGLUV_PUBLIC
731 static
732 #endif
733 void
XYZtoRGB24(float xyz[3],uint8 rgb[3])734 XYZtoRGB24(float xyz[3], uint8 rgb[3])
735 {
736 	double	r, g, b;
737 					/* assume CCIR-709 primaries */
738 	r =  2.690*xyz[0] + -1.276*xyz[1] + -0.414*xyz[2];
739 	g = -1.022*xyz[0] +  1.978*xyz[1] +  0.044*xyz[2];
740 	b =  0.061*xyz[0] + -0.224*xyz[1] +  1.163*xyz[2];
741 					/* assume 2.0 gamma for speed */
742 	/* could use integer sqrt approx., but this is probably faster */
743 	rgb[0] = (uint8)((r<=0.) ? 0 : (r >= 1.) ? 255 : (int)(256.*sqrt(r)));
744 	rgb[1] = (uint8)((g<=0.) ? 0 : (g >= 1.) ? 255 : (int)(256.*sqrt(g)));
745 	rgb[2] = (uint8)((b<=0.) ? 0 : (b >= 1.) ? 255 : (int)(256.*sqrt(b)));
746 }
747 
748 #if !LOGLUV_PUBLIC
749 static
750 #endif
751 double
LogL10toY(int p10)752 LogL10toY(int p10)		/* compute luminance from 10-bit LogL */
753 {
754 	if (p10 == 0)
755 		return (0.);
756 	return (exp(M_LN2/64.*(p10+.5) - M_LN2*12.));
757 }
758 
759 #if !LOGLUV_PUBLIC
760 static
761 #endif
762 int
LogL10fromY(double Y,int em)763 LogL10fromY(double Y, int em)	/* get 10-bit LogL from Y */
764 {
765 	if (Y >= 15.742)
766 		return (0x3ff);
767 	else if (Y <= .00024283)
768 		return (0);
769 	else
770 		return itrunc(64.*(log2(Y) + 12.), em);
771 }
772 
773 #define NANGLES		100
774 #define uv2ang(u, v)	( (NANGLES*.499999999/M_PI) \
775 				* atan2((v)-V_NEU,(u)-U_NEU) + .5*NANGLES )
776 
777 static int
oog_encode(double u,double v)778 oog_encode(double u, double v)		/* encode out-of-gamut chroma */
779 {
780 	static int	oog_table[NANGLES];
781 	static int	initialized = 0;
782 	register int	i;
783 
784 	if (!initialized) {		/* set up perimeter table */
785 		double	eps[NANGLES], ua, va, ang, epsa;
786 		int	ui, vi, ustep;
787 		for (i = NANGLES; i--; )
788 			eps[i] = 2.;
789 		for (vi = UV_NVS; vi--; ) {
790 			va = UV_VSTART + (vi+.5)*UV_SQSIZ;
791 			ustep = uv_row[vi].nus-1;
792 			if (vi == UV_NVS-1 || vi == 0 || ustep <= 0)
793 				ustep = 1;
794 			for (ui = uv_row[vi].nus-1; ui >= 0; ui -= ustep) {
795 				ua = uv_row[vi].ustart + (ui+.5)*UV_SQSIZ;
796 				ang = uv2ang(ua, va);
797                                 i = (int) ang;
798 				epsa = fabs(ang - (i+.5));
799 				if (epsa < eps[i]) {
800 					oog_table[i] = uv_row[vi].ncum + ui;
801 					eps[i] = epsa;
802 				}
803 			}
804 		}
805 		for (i = NANGLES; i--; )	/* fill any holes */
806 			if (eps[i] > 1.5) {
807 				int	i1, i2;
808 				for (i1 = 1; i1 < NANGLES/2; i1++)
809 					if (eps[(i+i1)%NANGLES] < 1.5)
810 						break;
811 				for (i2 = 1; i2 < NANGLES/2; i2++)
812 					if (eps[(i+NANGLES-i2)%NANGLES] < 1.5)
813 						break;
814 				if (i1 < i2)
815 					oog_table[i] =
816 						oog_table[(i+i1)%NANGLES];
817 				else
818 					oog_table[i] =
819 					    oog_table[(i+NANGLES-i2)%NANGLES];
820 			}
821 		initialized = 1;
822 	}
823 	i = (int) uv2ang(u, v);		/* look up hue angle */
824 	return (oog_table[i]);
825 }
826 
827 #undef uv2ang
828 #undef NANGLES
829 
830 #if !LOGLUV_PUBLIC
831 static
832 #endif
833 int
uv_encode(double u,double v,int em)834 uv_encode(double u, double v, int em)	/* encode (u',v') coordinates */
835 {
836 	register int	vi, ui;
837 
838 	if (v < UV_VSTART)
839 		return oog_encode(u, v);
840 	vi = itrunc((v - UV_VSTART)*(1./UV_SQSIZ), em);
841 	if (vi >= UV_NVS)
842 		return oog_encode(u, v);
843 	if (u < uv_row[vi].ustart)
844 		return oog_encode(u, v);
845 	ui = itrunc((u - uv_row[vi].ustart)*(1./UV_SQSIZ), em);
846 	if (ui >= uv_row[vi].nus)
847 		return oog_encode(u, v);
848 
849 	return (uv_row[vi].ncum + ui);
850 }
851 
852 #if !LOGLUV_PUBLIC
853 static
854 #endif
855 int
uv_decode(double * up,double * vp,int c)856 uv_decode(double *up, double *vp, int c)	/* decode (u',v') index */
857 {
858 	int	upper, lower;
859 	register int	ui, vi;
860 
861 	if (c < 0 || c >= UV_NDIVS)
862 		return (-1);
863 	lower = 0;				/* binary search */
864 	upper = UV_NVS;
865 	while (upper - lower > 1) {
866 		vi = (lower + upper) >> 1;
867 		ui = c - uv_row[vi].ncum;
868 		if (ui > 0)
869 			lower = vi;
870 		else if (ui < 0)
871 			upper = vi;
872 		else {
873 			lower = vi;
874 			break;
875 		}
876 	}
877 	vi = lower;
878 	ui = c - uv_row[vi].ncum;
879 	*up = uv_row[vi].ustart + (ui+.5)*UV_SQSIZ;
880 	*vp = UV_VSTART + (vi+.5)*UV_SQSIZ;
881 	return (0);
882 }
883 
884 #if !LOGLUV_PUBLIC
885 static
886 #endif
887 void
LogLuv24toXYZ(uint32 p,float XYZ[3])888 LogLuv24toXYZ(uint32 p, float XYZ[3])
889 {
890 	int	Ce;
891 	double	L, u, v, s, x, y;
892 					/* decode luminance */
893 	L = LogL10toY(p>>14 & 0x3ff);
894 	if (L <= 0.) {
895 		XYZ[0] = XYZ[1] = XYZ[2] = 0.;
896 		return;
897 	}
898 					/* decode color */
899 	Ce = p & 0x3fff;
900 	if (uv_decode(&u, &v, Ce) < 0) {
901 		u = U_NEU; v = V_NEU;
902 	}
903 	s = 1./(6.*u - 16.*v + 12.);
904 	x = 9.*u * s;
905 	y = 4.*v * s;
906 					/* convert to XYZ */
907 	XYZ[0] = (float)(x/y * L);
908 	XYZ[1] = (float)L;
909 	XYZ[2] = (float)((1.-x-y)/y * L);
910 }
911 
912 #ifdef PDFLIB_TIFFWRITE_SUPPORT
913 #if !LOGLUV_PUBLIC
914 static
915 #endif
916 uint32
LogLuv24fromXYZ(float XYZ[3],int em)917 LogLuv24fromXYZ(float XYZ[3], int em)
918 {
919 	int	Le, Ce;
920 	double	u, v, s;
921 					/* encode luminance */
922 	Le = LogL10fromY(XYZ[1], em);
923 					/* encode color */
924 	s = XYZ[0] + 15.*XYZ[1] + 3.*XYZ[2];
925 	if (!Le || s <= 0.) {
926 		u = U_NEU;
927 		v = V_NEU;
928 	} else {
929 		u = 4.*XYZ[0] / s;
930 		v = 9.*XYZ[1] / s;
931 	}
932 	Ce = uv_encode(u, v, em);
933 	if (Ce < 0)			/* never happens */
934 		Ce = uv_encode(U_NEU, V_NEU, SGILOGENCODE_NODITHER);
935 					/* combine encodings */
936 	return (Le << 14 | Ce);
937 }
938 #endif /* PDFLIB_TIFFWRITE_SUPPORT */
939 
940 static void
Luv24toXYZ(LogLuvState * sp,tidata_t op,int n)941 Luv24toXYZ(LogLuvState* sp, tidata_t op, int n)
942 {
943 	uint32* luv = (uint32*) sp->tbuf;
944 	float* xyz = (float*) op;
945 
946 	while (n-- > 0) {
947 		LogLuv24toXYZ(*luv, xyz);
948 		xyz += 3;
949 		luv++;
950 	}
951 }
952 
953 static void
Luv24toLuv48(LogLuvState * sp,tidata_t op,int n)954 Luv24toLuv48(LogLuvState* sp, tidata_t op, int n)
955 {
956 	uint32* luv = (uint32*) sp->tbuf;
957 	int16* luv3 = (int16*) op;
958 
959 	while (n-- > 0) {
960 		double u, v;
961 
962 		*luv3++ = (int16)((*luv >> 12 & 0xffd) + 13314);
963 		if (uv_decode(&u, &v, *luv&0x3fff) < 0) {
964 			u = U_NEU;
965 			v = V_NEU;
966 		}
967 		*luv3++ = (int16)(u * (1L<<15));
968 		*luv3++ = (int16)(v * (1L<<15));
969 		luv++;
970 	}
971 }
972 
973 static void
Luv24toRGB(LogLuvState * sp,tidata_t op,int n)974 Luv24toRGB(LogLuvState* sp, tidata_t op, int n)
975 {
976 	uint32* luv = (uint32*) sp->tbuf;
977 	uint8* rgb = (uint8*) op;
978 
979 	while (n-- > 0) {
980 		float xyz[3];
981 
982 		LogLuv24toXYZ(*luv++, xyz);
983 		XYZtoRGB24(xyz, rgb);
984 		rgb += 3;
985 	}
986 }
987 
988 #ifdef PDFLIB_TIFFWRITE_SUPPORT
989 static void
Luv24fromXYZ(LogLuvState * sp,tidata_t op,int n)990 Luv24fromXYZ(LogLuvState* sp, tidata_t op, int n)
991 {
992 	uint32* luv = (uint32*) sp->tbuf;
993 	float* xyz = (float*) op;
994 
995 	while (n-- > 0) {
996 		*luv++ = LogLuv24fromXYZ(xyz, sp->encode_meth);
997 		xyz += 3;
998 	}
999 }
1000 #endif /* PDFLIB_TIFFWRITE_SUPPORT */
1001 
1002 #ifdef PDFLIB_TIFFWRITE_SUPPORT
1003 static void
Luv24fromLuv48(LogLuvState * sp,tidata_t op,int n)1004 Luv24fromLuv48(LogLuvState* sp, tidata_t op, int n)
1005 {
1006 	uint32* luv = (uint32*) sp->tbuf;
1007 	int16* luv3 = (int16*) op;
1008 
1009 	while (n-- > 0) {
1010 		int Le, Ce;
1011 
1012 		if (luv3[0] <= 0)
1013 			Le = 0;
1014 		else if (luv3[0] >= (1<<12)+3314)
1015 			Le = (1<<10) - 1;
1016 		else if (sp->encode_meth == SGILOGENCODE_NODITHER)
1017 			Le = (luv3[0]-3314) >> 2;
1018 		else
1019 			Le = itrunc(.25*(luv3[0]-3314.), sp->encode_meth);
1020 
1021 		Ce = uv_encode((luv3[1]+.5)/(1<<15), (luv3[2]+.5)/(1<<15),
1022 					sp->encode_meth);
1023 		if (Ce < 0)	/* never happens */
1024 			Ce = uv_encode(U_NEU, V_NEU, SGILOGENCODE_NODITHER);
1025 		*luv++ = (uint32)Le << 14 | Ce;
1026 		luv3 += 3;
1027 	}
1028 }
1029 #endif /* PDFLIB_TIFFWRITE_SUPPORT */
1030 
1031 #if !LOGLUV_PUBLIC
1032 static
1033 #endif
1034 void
LogLuv32toXYZ(uint32 p,float XYZ[3])1035 LogLuv32toXYZ(uint32 p, float XYZ[3])
1036 {
1037 	double	L, u, v, s, x, y;
1038 					/* decode luminance */
1039 	L = LogL16toY((int)p >> 16);
1040 	if (L <= 0.) {
1041 		XYZ[0] = XYZ[1] = XYZ[2] = 0.;
1042 		return;
1043 	}
1044 					/* decode color */
1045 	u = 1./UVSCALE * ((p>>8 & 0xff) + .5);
1046 	v = 1./UVSCALE * ((p & 0xff) + .5);
1047 	s = 1./(6.*u - 16.*v + 12.);
1048 	x = 9.*u * s;
1049 	y = 4.*v * s;
1050 					/* convert to XYZ */
1051 	XYZ[0] = (float)(x/y * L);
1052 	XYZ[1] = (float)L;
1053 	XYZ[2] = (float)((1.-x-y)/y * L);
1054 }
1055 
1056 #ifdef PDFLIB_TIFFWRITE_SUPPORT
1057 #if !LOGLUV_PUBLIC
1058 static
1059 #endif
1060 uint32
LogLuv32fromXYZ(float XYZ[3],int em)1061 LogLuv32fromXYZ(float XYZ[3], int em)
1062 {
1063 	unsigned int	Le, ue, ve;
1064 	double	u, v, s;
1065 					/* encode luminance */
1066 	Le = (unsigned int)LogL16fromY(XYZ[1], em);
1067 					/* encode color */
1068 	s = XYZ[0] + 15.*XYZ[1] + 3.*XYZ[2];
1069 	if (!Le || s <= 0.) {
1070 		u = U_NEU;
1071 		v = V_NEU;
1072 	} else {
1073 		u = 4.*XYZ[0] / s;
1074 		v = 9.*XYZ[1] / s;
1075 	}
1076 	if (u <= 0.) ue = 0;
1077 	else ue = itrunc(UVSCALE*u, em);
1078 	if (ue > 255) ue = 255;
1079 	if (v <= 0.) ve = 0;
1080 	else ve = itrunc(UVSCALE*v, em);
1081 	if (ve > 255) ve = 255;
1082 					/* combine encodings */
1083 	return (Le << 16 | ue << 8 | ve);
1084 }
1085 #endif /* PDFLIB_TIFFWRITE_SUPPORT */
1086 
1087 static void
Luv32toXYZ(LogLuvState * sp,tidata_t op,int n)1088 Luv32toXYZ(LogLuvState* sp, tidata_t op, int n)
1089 {
1090 	uint32* luv = (uint32*) sp->tbuf;
1091 	float* xyz = (float*) op;
1092 
1093 	while (n-- > 0) {
1094 		LogLuv32toXYZ(*luv++, xyz);
1095 		xyz += 3;
1096 	}
1097 }
1098 
1099 static void
Luv32toLuv48(LogLuvState * sp,tidata_t op,int n)1100 Luv32toLuv48(LogLuvState* sp, tidata_t op, int n)
1101 {
1102 	uint32* luv = (uint32*) sp->tbuf;
1103 	int16* luv3 = (int16*) op;
1104 
1105 	while (n-- > 0) {
1106 		double u, v;
1107 
1108 		*luv3++ = (int16)(*luv >> 16);
1109 		u = 1./UVSCALE * ((*luv>>8 & 0xff) + .5);
1110 		v = 1./UVSCALE * ((*luv & 0xff) + .5);
1111 		*luv3++ = (int16)(u * (1L<<15));
1112 		*luv3++ = (int16)(v * (1L<<15));
1113 		luv++;
1114 	}
1115 }
1116 
1117 static void
Luv32toRGB(LogLuvState * sp,tidata_t op,int n)1118 Luv32toRGB(LogLuvState* sp, tidata_t op, int n)
1119 {
1120 	uint32* luv = (uint32*) sp->tbuf;
1121 	uint8* rgb = (uint8*) op;
1122 
1123 	while (n-- > 0) {
1124 		float xyz[3];
1125 
1126 		LogLuv32toXYZ(*luv++, xyz);
1127 		XYZtoRGB24(xyz, rgb);
1128 		rgb += 3;
1129 	}
1130 }
1131 
1132 #ifdef PDFLIB_TIFFWRITE_SUPPORT
1133 static void
Luv32fromXYZ(LogLuvState * sp,tidata_t op,int n)1134 Luv32fromXYZ(LogLuvState* sp, tidata_t op, int n)
1135 {
1136 	uint32* luv = (uint32*) sp->tbuf;
1137 	float* xyz = (float*) op;
1138 
1139 	while (n-- > 0) {
1140 		*luv++ = LogLuv32fromXYZ(xyz, sp->encode_meth);
1141 		xyz += 3;
1142 	}
1143 }
1144 #endif /* PDFLIB_TIFFWRITE_SUPPORT */
1145 
1146 #ifdef PDFLIB_TIFFWRITE_SUPPORT
1147 static void
Luv32fromLuv48(LogLuvState * sp,tidata_t op,int n)1148 Luv32fromLuv48(LogLuvState* sp, tidata_t op, int n)
1149 {
1150 	uint32* luv = (uint32*) sp->tbuf;
1151 	int16* luv3 = (int16*) op;
1152 
1153 	if (sp->encode_meth == SGILOGENCODE_NODITHER) {
1154 		while (n-- > 0) {
1155 			*luv++ = (uint32)luv3[0] << 16 |
1156 				(luv3[1]*(uint32)(UVSCALE+.5) >> 7 & 0xff00) |
1157 				(luv3[2]*(uint32)(UVSCALE+.5) >> 15 & 0xff);
1158 			luv3 += 3;
1159 		}
1160 		return;
1161 	}
1162 	while (n-- > 0) {
1163 		*luv++ = (uint32)luv3[0] << 16 |
1164 	(itrunc(luv3[1]*(UVSCALE/(1<<15)), sp->encode_meth) << 8 & 0xff00) |
1165 		(itrunc(luv3[2]*(UVSCALE/(1<<15)), sp->encode_meth) & 0xff);
1166 		luv3 += 3;
1167 	}
1168 }
1169 #endif /* PDFLIB_TIFFWRITE_SUPPORT */
1170 
1171 static void
_logLuvNop(LogLuvState * sp,tidata_t op,int n)1172 _logLuvNop(LogLuvState* sp, tidata_t op, int n)
1173 {
1174 	(void) sp; (void) op; (void) n;
1175 }
1176 
1177 static int
LogL16GuessDataFmt(TIFFDirectory * td)1178 LogL16GuessDataFmt(TIFFDirectory *td)
1179 {
1180 #define	PACK(s,b,f)	(((b)<<6)|((s)<<3)|(f))
1181 	switch (PACK(td->td_samplesperpixel, td->td_bitspersample,
1182 			    td->td_sampleformat)) {
1183 	case PACK(1, 32, SAMPLEFORMAT_IEEEFP):
1184 		return (SGILOGDATAFMT_FLOAT);
1185 	case PACK(1, 16, SAMPLEFORMAT_VOID):
1186 	case PACK(1, 16, SAMPLEFORMAT_INT):
1187 	case PACK(1, 16, SAMPLEFORMAT_UINT):
1188 		return (SGILOGDATAFMT_16BIT);
1189 	case PACK(1,  8, SAMPLEFORMAT_VOID):
1190 	case PACK(1,  8, SAMPLEFORMAT_UINT):
1191 		return (SGILOGDATAFMT_8BIT);
1192 	}
1193 #undef PACK
1194 	return (SGILOGDATAFMT_UNKNOWN);
1195 }
1196 
1197 static uint32
multiply(size_t m1,size_t m2)1198 multiply(size_t m1, size_t m2)
1199 {
1200 	uint32	bytes = m1 * m2;
1201 
1202 	if (m1 && bytes / m1 != m2)
1203 		bytes = 0;
1204 
1205 	return bytes;
1206 }
1207 
1208 static int
LogL16InitState(TIFF * tif)1209 LogL16InitState(TIFF* tif)
1210 {
1211 	TIFFDirectory *td = &tif->tif_dir;
1212 	LogLuvState* sp = DecoderState(tif);
1213 	static const char module[] = "LogL16InitState";
1214 
1215 	assert(sp != NULL);
1216 	assert(td->td_photometric == PHOTOMETRIC_LOGL);
1217 
1218 	/* for some reason, we can't do this in TIFFInitLogL16 */
1219 	if (sp->user_datafmt == SGILOGDATAFMT_UNKNOWN)
1220 		sp->user_datafmt = LogL16GuessDataFmt(td);
1221 	switch (sp->user_datafmt) {
1222 	case SGILOGDATAFMT_FLOAT:
1223 		sp->pixel_size = sizeof (float);
1224 		break;
1225 	case SGILOGDATAFMT_16BIT:
1226 		sp->pixel_size = sizeof (int16);
1227 		break;
1228 	case SGILOGDATAFMT_8BIT:
1229 		sp->pixel_size = sizeof (uint8);
1230 		break;
1231 	default:
1232 		_TIFFError(tif, tif->tif_name,
1233 		    "No support for converting user data format to LogL");
1234 		return (0);
1235 	}
1236 	sp->tbuflen = multiply(td->td_imagewidth, td->td_rowsperstrip);
1237 	if (multiply(sp->tbuflen, sizeof (int16)) == 0 ||
1238 	    (sp->tbuf = (tidata_t*)
1239 			_TIFFmalloc(sp->tbuflen * sizeof (int16))) == NULL) {
1240 		_TIFFError(tif, module,
1241 			"%s: No space for SGILog translation buffer",
1242 			tif->tif_name);
1243 		return (0);
1244 	}
1245 	return (1);
1246 }
1247 
1248 static int
LogLuvGuessDataFmt(TIFFDirectory * td)1249 LogLuvGuessDataFmt(TIFFDirectory *td)
1250 {
1251 	int guess;
1252 
1253 	/*
1254 	 * If the user didn't tell us their datafmt,
1255 	 * take our best guess from the bitspersample.
1256 	 */
1257 #define	PACK(a,b)	(((a)<<3)|(b))
1258 	switch (PACK(td->td_bitspersample, td->td_sampleformat)) {
1259 	case PACK(32, SAMPLEFORMAT_IEEEFP):
1260 		guess = SGILOGDATAFMT_FLOAT;
1261 		break;
1262 	case PACK(32, SAMPLEFORMAT_VOID):
1263 	case PACK(32, SAMPLEFORMAT_UINT):
1264 	case PACK(32, SAMPLEFORMAT_INT):
1265 		guess = SGILOGDATAFMT_RAW;
1266 		break;
1267 	case PACK(16, SAMPLEFORMAT_VOID):
1268 	case PACK(16, SAMPLEFORMAT_INT):
1269 	case PACK(16, SAMPLEFORMAT_UINT):
1270 		guess = SGILOGDATAFMT_16BIT;
1271 		break;
1272 	case PACK( 8, SAMPLEFORMAT_VOID):
1273 	case PACK( 8, SAMPLEFORMAT_UINT):
1274 		guess = SGILOGDATAFMT_8BIT;
1275 		break;
1276 	default:
1277 		guess = SGILOGDATAFMT_UNKNOWN;
1278 		break;
1279 #undef PACK
1280 	}
1281 	/*
1282 	 * Double-check samples per pixel.
1283 	 */
1284 	switch (td->td_samplesperpixel) {
1285 	case 1:
1286 		if (guess != SGILOGDATAFMT_RAW)
1287 			guess = SGILOGDATAFMT_UNKNOWN;
1288 		break;
1289 	case 3:
1290 		if (guess == SGILOGDATAFMT_RAW)
1291 			guess = SGILOGDATAFMT_UNKNOWN;
1292 		break;
1293 	default:
1294 		guess = SGILOGDATAFMT_UNKNOWN;
1295 		break;
1296 	}
1297 	return (guess);
1298 }
1299 
1300 static int
LogLuvInitState(TIFF * tif)1301 LogLuvInitState(TIFF* tif)
1302 {
1303 	TIFFDirectory* td = &tif->tif_dir;
1304 	LogLuvState* sp = DecoderState(tif);
1305 	static const char module[] = "LogLuvInitState";
1306 
1307 	assert(sp != NULL);
1308 	assert(td->td_photometric == PHOTOMETRIC_LOGLUV);
1309 
1310 	/* for some reason, we can't do this in TIFFInitLogLuv */
1311 	if (td->td_planarconfig != PLANARCONFIG_CONTIG) {
1312 		_TIFFError(tif, module,
1313 		    "SGILog compression cannot handle non-contiguous data");
1314 		return (0);
1315 	}
1316 	if (sp->user_datafmt == SGILOGDATAFMT_UNKNOWN)
1317 		sp->user_datafmt = LogLuvGuessDataFmt(td);
1318 	switch (sp->user_datafmt) {
1319 	case SGILOGDATAFMT_FLOAT:
1320 		sp->pixel_size = 3*sizeof (float);
1321 		break;
1322 	case SGILOGDATAFMT_16BIT:
1323 		sp->pixel_size = 3*sizeof (int16);
1324 		break;
1325 	case SGILOGDATAFMT_RAW:
1326 		sp->pixel_size = sizeof (uint32);
1327 		break;
1328 	case SGILOGDATAFMT_8BIT:
1329 		sp->pixel_size = 3*sizeof (uint8);
1330 		break;
1331 	default:
1332 		_TIFFError(tif, tif->tif_name,
1333 		    "No support for converting user data format to LogLuv");
1334 		return (0);
1335 	}
1336 	sp->tbuflen = multiply(td->td_imagewidth, td->td_rowsperstrip);
1337 	if (multiply(sp->tbuflen, sizeof (uint32)) == 0 ||
1338 	    (sp->tbuf = (tidata_t*)
1339 			_TIFFmalloc(sp->tbuflen * sizeof (uint32))) == NULL) {
1340 		_TIFFError(tif, module,
1341 			"%s: No space for SGILog translation buffer",
1342 		    tif->tif_name);
1343 		return (0);
1344 	}
1345 	return (1);
1346 }
1347 
1348 static int
LogLuvSetupDecode(TIFF * tif)1349 LogLuvSetupDecode(TIFF* tif)
1350 {
1351 	LogLuvState* sp = DecoderState(tif);
1352 	TIFFDirectory* td = &tif->tif_dir;
1353 
1354 	tif->tif_postdecode = _TIFFNoPostDecode;
1355 	switch (td->td_photometric) {
1356 	case PHOTOMETRIC_LOGLUV:
1357 		if (!LogLuvInitState(tif))
1358 			break;
1359 		if (td->td_compression == COMPRESSION_SGILOG24) {
1360 			tif->tif_decoderow = LogLuvDecode24;
1361 			switch (sp->user_datafmt) {
1362 			case SGILOGDATAFMT_FLOAT:
1363 				sp->tfunc = Luv24toXYZ;
1364 				break;
1365 			case SGILOGDATAFMT_16BIT:
1366 				sp->tfunc = Luv24toLuv48;
1367 				break;
1368 			case SGILOGDATAFMT_8BIT:
1369 				sp->tfunc = Luv24toRGB;
1370 				break;
1371 			}
1372 		} else {
1373 			tif->tif_decoderow = LogLuvDecode32;
1374 			switch (sp->user_datafmt) {
1375 			case SGILOGDATAFMT_FLOAT:
1376 				sp->tfunc = Luv32toXYZ;
1377 				break;
1378 			case SGILOGDATAFMT_16BIT:
1379 				sp->tfunc = Luv32toLuv48;
1380 				break;
1381 			case SGILOGDATAFMT_8BIT:
1382 				sp->tfunc = Luv32toRGB;
1383 				break;
1384 			}
1385 		}
1386 		return (1);
1387 	case PHOTOMETRIC_LOGL:
1388 		if (!LogL16InitState(tif))
1389 			break;
1390 		tif->tif_decoderow = LogL16Decode;
1391 		switch (sp->user_datafmt) {
1392 		case SGILOGDATAFMT_FLOAT:
1393 			sp->tfunc = L16toY;
1394 			break;
1395 		case SGILOGDATAFMT_8BIT:
1396 			sp->tfunc = L16toGry;
1397 			break;
1398 		}
1399 		return (1);
1400 	default:
1401 		_TIFFError(tif, tif->tif_name,
1402     "Inappropriate photometric interpretation %d for SGILog compression; %s",
1403 		    td->td_photometric, "must be either LogLUV or LogL");
1404 		break;
1405 	}
1406 	return (0);
1407 }
1408 
1409 #ifdef PDFLIB_TIFFWRITE_SUPPORT
1410 static int
LogLuvSetupEncode(TIFF * tif)1411 LogLuvSetupEncode(TIFF* tif)
1412 {
1413 	LogLuvState* sp = EncoderState(tif);
1414 	TIFFDirectory* td = &tif->tif_dir;
1415 
1416 	switch (td->td_photometric) {
1417 	case PHOTOMETRIC_LOGLUV:
1418 		if (!LogLuvInitState(tif))
1419 			break;
1420 		if (td->td_compression == COMPRESSION_SGILOG24) {
1421 			tif->tif_encoderow = LogLuvEncode24;
1422 			switch (sp->user_datafmt) {
1423 			case SGILOGDATAFMT_FLOAT:
1424 				sp->tfunc = Luv24fromXYZ;
1425 				break;
1426 			case SGILOGDATAFMT_16BIT:
1427 				sp->tfunc = Luv24fromLuv48;
1428 				break;
1429 			case SGILOGDATAFMT_RAW:
1430 				break;
1431 			default:
1432 				goto notsupported;
1433 			}
1434 		} else {
1435 			tif->tif_encoderow = LogLuvEncode32;
1436 			switch (sp->user_datafmt) {
1437 			case SGILOGDATAFMT_FLOAT:
1438 				sp->tfunc = Luv32fromXYZ;
1439 				break;
1440 			case SGILOGDATAFMT_16BIT:
1441 				sp->tfunc = Luv32fromLuv48;
1442 				break;
1443 			case SGILOGDATAFMT_RAW:
1444 				break;
1445 			default:
1446 				goto notsupported;
1447 			}
1448 		}
1449 		break;
1450 	case PHOTOMETRIC_LOGL:
1451 		if (!LogL16InitState(tif))
1452 			break;
1453 		tif->tif_encoderow = LogL16Encode;
1454 		switch (sp->user_datafmt) {
1455 		case SGILOGDATAFMT_FLOAT:
1456 			sp->tfunc = L16fromY;
1457 			break;
1458 		case SGILOGDATAFMT_16BIT:
1459 			break;
1460 		default:
1461 			goto notsupported;
1462 		}
1463 		break;
1464 	default:
1465 		_TIFFError(tif, tif->tif_name,
1466     "Inappropriate photometric interpretation %d for SGILog compression; %s",
1467     		    td->td_photometric, "must be either LogLUV or LogL");
1468 		break;
1469 	}
1470 	return (1);
1471 notsupported:
1472 	_TIFFError(tif, tif->tif_name,
1473 	    "SGILog compression supported only for %s, or raw data",
1474 	    td->td_photometric == PHOTOMETRIC_LOGL ? "Y, L" : "XYZ, Luv");
1475 	return (0);
1476 }
1477 #endif /* PDFLIB_TIFFWRITE_SUPPORT */
1478 
1479 #ifdef PDFLIB_TIFFWRITE_SUPPORT
1480 static void
LogLuvClose(TIFF * tif)1481 LogLuvClose(TIFF* tif)
1482 {
1483 	TIFFDirectory *td = &tif->tif_dir;
1484 
1485 	/*
1486 	 * For consistency, we always want to write out the same
1487 	 * bitspersample and sampleformat for our TIFF file,
1488 	 * regardless of the data format being used by the application.
1489 	 * Since this routine is called after tags have been set but
1490 	 * before they have been recorded in the file, we reset them here.
1491 	 */
1492 	td->td_samplesperpixel =
1493 	    (td->td_photometric == PHOTOMETRIC_LOGL) ? 1 : 3;
1494 	td->td_bitspersample = 16;
1495 	td->td_sampleformat = SAMPLEFORMAT_INT;
1496 }
1497 #endif /* PDFLIB_TIFFWRITE_SUPPORT */
1498 
1499 static void
LogLuvCleanup(TIFF * tif)1500 LogLuvCleanup(TIFF* tif)
1501 {
1502 	LogLuvState* sp = (LogLuvState *)tif->tif_data;
1503 
1504 	if (sp) {
1505 		if (sp->tbuf)
1506 			_TIFFfree(sp->tbuf);
1507 		_TIFFfree(sp);
1508 		tif->tif_data = NULL;
1509 	}
1510 }
1511 
1512 static int
LogLuvVSetField(TIFF * tif,ttag_t tag,va_list ap)1513 LogLuvVSetField(TIFF* tif, ttag_t tag, va_list ap)
1514 {
1515 	LogLuvState* sp = DecoderState(tif);
1516 	int bps, fmt;
1517 
1518 	switch (tag) {
1519 	case TIFFTAG_SGILOGDATAFMT:
1520 		sp->user_datafmt = va_arg(ap, int);
1521 		/*
1522 		 * Tweak the TIFF header so that the rest of libtiff knows what
1523 		 * size of data will be passed between app and library, and
1524 		 * assume that the app knows what it is doing and is not
1525 		 * confused by these header manipulations...
1526 		 */
1527 		switch (sp->user_datafmt) {
1528 		case SGILOGDATAFMT_FLOAT:
1529 			bps = 32, fmt = SAMPLEFORMAT_IEEEFP;
1530 			break;
1531 		case SGILOGDATAFMT_16BIT:
1532 			bps = 16, fmt = SAMPLEFORMAT_INT;
1533 			break;
1534 		case SGILOGDATAFMT_RAW:
1535 			bps = 32, fmt = SAMPLEFORMAT_UINT;
1536 			TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1);
1537 			break;
1538 		case SGILOGDATAFMT_8BIT:
1539 			bps = 8, fmt = SAMPLEFORMAT_UINT;
1540 			break;
1541 		default:
1542 			_TIFFError(tif, tif->tif_name,
1543 			    "Unknown data format %d for LogLuv compression",
1544 			    sp->user_datafmt);
1545 			return (0);
1546 		}
1547 		TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps);
1548 		TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, fmt);
1549 		/*
1550 		 * Must recalculate sizes should bits/sample change.
1551 		 */
1552 		tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif)
1553 			: (tsize_t) -1;
1554 		tif->tif_scanlinesize = TIFFScanlineSize(tif);
1555 		return (1);
1556 	case TIFFTAG_SGILOGENCODE:
1557 		sp->encode_meth = va_arg(ap, int);
1558 		if (sp->encode_meth != SGILOGENCODE_NODITHER &&
1559 				sp->encode_meth != SGILOGENCODE_RANDITHER) {
1560 			_TIFFError(tif, tif->tif_name,
1561 				"Unknown encoding %d for LogLuv compression",
1562 				sp->encode_meth);
1563 			return (0);
1564 		}
1565 		return (1);
1566 	default:
1567 		return (*sp->vsetparent)(tif, tag, ap);
1568 	}
1569 }
1570 
1571 static int
LogLuvVGetField(TIFF * tif,ttag_t tag,va_list ap)1572 LogLuvVGetField(TIFF* tif, ttag_t tag, va_list ap)
1573 {
1574 	LogLuvState *sp = (LogLuvState *)tif->tif_data;
1575 
1576 	switch (tag) {
1577 	case TIFFTAG_SGILOGDATAFMT:
1578 		*va_arg(ap, int*) = sp->user_datafmt;
1579 		return (1);
1580 	default:
1581 		return (*sp->vgetparent)(tif, tag, ap);
1582 	}
1583 }
1584 
1585 static const TIFFFieldInfo LogLuvFieldInfo[] = {
1586     { TIFFTAG_SGILOGDATAFMT,	  0, 0,	TIFF_SHORT,	FIELD_PSEUDO,
1587       TRUE,	FALSE,	"SGILogDataFmt"},
1588     { TIFFTAG_SGILOGENCODE,	  0, 0, TIFF_SHORT,	FIELD_PSEUDO,
1589       TRUE,	FALSE,	"SGILogEncode"}
1590 };
1591 
1592 int
TIFFInitSGILog(TIFF * tif,int scheme)1593 TIFFInitSGILog(TIFF* tif, int scheme)
1594 {
1595 	static const char module[] = "TIFFInitSGILog";
1596 	LogLuvState* sp;
1597 
1598 	assert(scheme == COMPRESSION_SGILOG24 || scheme == COMPRESSION_SGILOG);
1599 
1600 	/*
1601 	 * Allocate state block so tag methods have storage to record values.
1602 	 */
1603 	tif->tif_data = (tidata_t) _TIFFmalloc(sizeof (LogLuvState));
1604 	if (tif->tif_data == NULL)
1605 		goto bad;
1606 	sp = (LogLuvState*) tif->tif_data;
1607 	_TIFFmemset((tdata_t)sp, 0, sizeof (*sp));
1608 	sp->user_datafmt = SGILOGDATAFMT_UNKNOWN;
1609 	sp->encode_meth = (scheme == COMPRESSION_SGILOG24) ?
1610 				SGILOGENCODE_RANDITHER : SGILOGENCODE_NODITHER;
1611 	sp->tfunc = _logLuvNop;
1612 
1613 	/*
1614 	 * Install codec methods.
1615 	 * NB: tif_decoderow & tif_encoderow are filled
1616 	 *     in at setup time.
1617 	 */
1618 	tif->tif_setupdecode = LogLuvSetupDecode;
1619 	tif->tif_decodestrip = LogLuvDecodeStrip;
1620 	tif->tif_decodetile = LogLuvDecodeTile;
1621 #ifdef PDFLIB_TIFFWRITE_SUPPORT
1622 	tif->tif_setupencode = LogLuvSetupEncode;
1623 	tif->tif_encodestrip = LogLuvEncodeStrip;
1624 	tif->tif_encodetile = LogLuvEncodeTile;
1625 	tif->tif_close = LogLuvClose;
1626 #endif /* PDFLIB_TIFFWRITE_SUPPORT */
1627 	tif->tif_cleanup = LogLuvCleanup;
1628 
1629 	/* override SetField so we can handle our private pseudo-tag */
1630 	TIFFMergeFieldInfo(tif, LogLuvFieldInfo, N(LogLuvFieldInfo));
1631 	sp->vgetparent = tif->tif_tagmethods.vgetfield;
1632 	tif->tif_tagmethods.vgetfield = LogLuvVGetField;/*hook for codec tags */
1633 	sp->vsetparent = tif->tif_tagmethods.vsetfield;
1634 	tif->tif_tagmethods.vsetfield = LogLuvVSetField;/*hook for codec tags */
1635 
1636 	return (1);
1637 bad:
1638 	_TIFFError(tif, module, "%s: No space for LogLuv state block",
1639 		tif->tif_name);
1640 	return (0);
1641 }
1642 #endif /* LOGLUV_SUPPORT */
1643 
1644 /* vim: set ts=8 sts=8 sw=8 noet: */
1645