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