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