Coverage Report

Created: 2026-11-12 06:47

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libtiff/libtiff/tif_luv.c
Line
Count
Source
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 <limits.h>
149
#include <math.h>
150
#include <stdio.h>
151
#include <stdlib.h>
152
#include <time.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
{
162
    int encoder_state; /* 1 if encoder correctly initialized */
163
    int user_datafmt;  /* user data format */
164
    int encode_meth;   /* encoding method */
165
    int pixel_size;    /* bytes per pixel */
166
167
    uint8_t *tbuf;    /* translation buffer */
168
    tmsize_t tbuflen; /* buffer length */
169
    void (*tfunc)(LogLuvState *, uint8_t *, tmsize_t);
170
171
    TIFFVSetMethod vgetparent; /* super-class method */
172
    TIFFVSetMethod vsetparent; /* super-class method */
173
};
174
175
0
#define DecoderState(tif) ((LogLuvState *)(tif)->tif_data)
176
0
#define EncoderState(tif) ((LogLuvState *)(tif)->tif_data)
177
178
0
#define SGILOGDATAFMT_UNKNOWN -1
179
180
0
#define MINRUN 4 /* minimum run length */
181
182
static void L16toL16(LogLuvState *sp, uint8_t *op, tmsize_t n);
183
static void L16fromL16(LogLuvState *sp, uint8_t *op, tmsize_t n);
184
static void LuvRawToRaw(LogLuvState *sp, uint8_t *op, tmsize_t n);
185
static void LuvRawFromRaw(LogLuvState *sp, uint8_t *op, tmsize_t n);
186
187
/*
188
 * Decode a string of 16-bit gray pixels.
189
 */
190
static int LogL16Decode(TIFF *tif, uint8_t *op, tmsize_t occ, uint16_t s)
191
0
{
192
0
    static const char module[] = "LogL16Decode";
193
0
    LogLuvState *sp = DecoderState(tif);
194
0
    int shft;
195
0
    tmsize_t i;
196
0
    tmsize_t npixels;
197
0
    unsigned char *bp;
198
0
    int16_t *tp;
199
0
    int16_t b;
200
0
    tmsize_t cc;
201
0
    int rc;
202
203
0
    (void)s;
204
0
    assert(s == 0);
205
0
    assert(sp != NULL);
206
207
0
    npixels = occ / sp->pixel_size;
208
209
0
    if (sp->tbuflen < npixels)
210
0
    {
211
0
        TIFFErrorExtR(tif, module, "Translation buffer too short");
212
0
        return (0);
213
0
    }
214
0
    tp = (int16_t *)sp->tbuf;
215
0
    _TIFFmemset((void *)tp, 0, (tmsize_t)((size_t)npixels * sizeof(tp[0])));
216
217
0
    bp = (unsigned char *)tif->tif_rawcp;
218
0
    cc = tif->tif_rawcc;
219
    /* get each byte string */
220
0
    for (shft = 8; shft >= 0; shft -= 8)
221
0
    {
222
0
        for (i = 0; i < npixels && cc > 0;)
223
0
        {
224
0
            if (*bp >= 128)
225
0
            { /* run */
226
0
                if (cc < 2)
227
0
                    break;
228
0
                rc = *bp++ + (2 - 128);
229
0
                b = (int16_t)(*bp++ << shft);
230
0
                cc -= 2;
231
0
                while (rc-- && i < npixels)
232
0
                    tp[i++] |= b;
233
0
            }
234
0
            else
235
0
            {               /* non-run */
236
0
                rc = *bp++; /* nul is noop */
237
0
                while (--cc && rc-- && i < npixels)
238
0
                    tp[i++] |= (int16_t)(*bp++ << shft);
239
0
            }
240
0
        }
241
0
        if (i != npixels)
242
0
        {
243
0
            TIFFErrorExtR(tif, module,
244
0
                          "Not enough data at row %" PRIu32
245
0
                          " (short %" TIFF_SSIZE_FORMAT " pixels)",
246
0
                          tif->tif_dir.td_row, npixels - i);
247
0
            tif->tif_rawcp = (uint8_t *)bp;
248
0
            tif->tif_rawcc = cc;
249
0
            return (0);
250
0
        }
251
0
    }
252
0
    if (sp->user_datafmt == SGILOGDATAFMT_16BIT)
253
0
        L16toL16(sp, op, npixels);
254
0
    else
255
0
        (*sp->tfunc)(sp, op, npixels);
256
0
    tif->tif_rawcp = (uint8_t *)bp;
257
0
    tif->tif_rawcc = cc;
258
0
    return (1);
259
0
}
260
261
/*
262
 * Decode a string of 24-bit pixels.
263
 */
264
static int LogLuvDecode24(TIFF *tif, uint8_t *op, tmsize_t occ, uint16_t s)
265
0
{
266
0
    static const char module[] = "LogLuvDecode24";
267
0
    LogLuvState *sp = DecoderState(tif);
268
0
    tmsize_t cc;
269
0
    tmsize_t i;
270
0
    tmsize_t npixels;
271
0
    unsigned char *bp;
272
0
    uint32_t *tp;
273
274
0
    (void)s;
275
0
    assert(s == 0);
276
0
    assert(sp != NULL);
277
278
0
    npixels = occ / sp->pixel_size;
279
280
0
    if (sp->tbuflen < npixels)
281
0
    {
282
0
        TIFFErrorExtR(tif, module, "Translation buffer too short");
283
0
        return (0);
284
0
    }
285
0
    tp = (uint32_t *)sp->tbuf;
286
    /* copy to array of uint32_t */
287
0
    bp = (unsigned char *)tif->tif_rawcp;
288
0
    cc = tif->tif_rawcc;
289
0
    for (i = 0; i < npixels && cc >= 3; i++)
290
0
    {
291
0
        tp[i] = (uint32_t)bp[0] << 16 | (uint32_t)bp[1] << 8 | bp[2];
292
0
        bp += 3;
293
0
        cc -= 3;
294
0
    }
295
0
    tif->tif_rawcp = (uint8_t *)bp;
296
0
    tif->tif_rawcc = cc;
297
0
    if (i != npixels)
298
0
    {
299
0
        TIFFErrorExtR(tif, module,
300
0
                      "Not enough data at row %" PRIu32
301
0
                      " (short %" TIFF_SSIZE_FORMAT " pixels)",
302
0
                      tif->tif_dir.td_row, npixels - i);
303
0
        return (0);
304
0
    }
305
0
    if (sp->user_datafmt == SGILOGDATAFMT_RAW)
306
0
        LuvRawToRaw(sp, op, npixels);
307
0
    else
308
0
        (*sp->tfunc)(sp, op, npixels);
309
0
    return (1);
310
0
}
311
312
/*
313
 * Decode a string of 32-bit pixels.
314
 */
315
static int LogLuvDecode32(TIFF *tif, uint8_t *op, tmsize_t occ, uint16_t s)
316
0
{
317
0
    static const char module[] = "LogLuvDecode32";
318
0
    LogLuvState *sp;
319
0
    int shft;
320
0
    tmsize_t i;
321
0
    tmsize_t npixels;
322
0
    unsigned char *bp;
323
0
    uint32_t *tp;
324
0
    uint32_t b;
325
0
    tmsize_t cc;
326
0
    int rc;
327
328
0
    (void)s;
329
0
    assert(s == 0);
330
0
    sp = DecoderState(tif);
331
0
    assert(sp != NULL);
332
333
0
    npixels = occ / sp->pixel_size;
334
335
0
    if (sp->tbuflen < npixels)
336
0
    {
337
0
        TIFFErrorExtR(tif, module, "Translation buffer too short");
338
0
        return (0);
339
0
    }
340
0
    tp = (uint32_t *)sp->tbuf;
341
0
    _TIFFmemset((void *)tp, 0, (tmsize_t)((size_t)npixels * sizeof(tp[0])));
342
343
0
    bp = (unsigned char *)tif->tif_rawcp;
344
0
    cc = tif->tif_rawcc;
345
    /* get each byte string */
346
0
    for (shft = 24; shft >= 0; shft -= 8)
347
0
    {
348
0
        for (i = 0; i < npixels && cc > 0;)
349
0
        {
350
0
            if (*bp >= 128)
351
0
            { /* run */
352
0
                if (cc < 2)
353
0
                    break;
354
0
                rc = *bp++ + (2 - 128);
355
0
                b = (uint32_t)*bp++ << shft;
356
0
                cc -= 2;
357
0
                while (rc-- && i < npixels)
358
0
                    tp[i++] |= b;
359
0
            }
360
0
            else
361
0
            {               /* non-run */
362
0
                rc = *bp++; /* nul is noop */
363
0
                while (--cc && rc-- && i < npixels)
364
0
                    tp[i++] |= (uint32_t)*bp++ << shft;
365
0
            }
366
0
        }
367
0
        if (i != npixels)
368
0
        {
369
0
            TIFFErrorExtR(tif, module,
370
0
                          "Not enough data at row %" PRIu32
371
0
                          " (short %" TIFF_SSIZE_FORMAT " pixels)",
372
0
                          tif->tif_dir.td_row, npixels - i);
373
0
            tif->tif_rawcp = (uint8_t *)bp;
374
0
            tif->tif_rawcc = cc;
375
0
            return (0);
376
0
        }
377
0
    }
378
0
    if (sp->user_datafmt == SGILOGDATAFMT_RAW)
379
0
        LuvRawToRaw(sp, op, npixels);
380
0
    else
381
0
        (*sp->tfunc)(sp, op, npixels);
382
0
    tif->tif_rawcp = (uint8_t *)bp;
383
0
    tif->tif_rawcc = cc;
384
0
    return (1);
385
0
}
386
387
/*
388
 * Decode a strip of pixels.  We break it into rows to
389
 * maintain synchrony with the encode algorithm, which
390
 * is row by row.
391
 */
392
static int LogLuvDecodeStrip(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
393
0
{
394
0
    tmsize_t rowlen = TIFFScanlineSize(tif);
395
396
0
    if (rowlen == 0)
397
0
        return 0;
398
399
0
    if (cc % rowlen != 0)
400
0
    {
401
0
        TIFFErrorExtR(tif, "LogLuvDecodeStrip",
402
0
                      "Fractional scanline cannot be read");
403
0
        return 0;
404
0
    }
405
0
    while (cc && (*tif->tif_decoderow)(tif, bp, rowlen, s))
406
0
    {
407
0
        bp += rowlen;
408
0
        cc -= rowlen;
409
0
    }
410
0
    return (cc == 0);
411
0
}
412
413
/*
414
 * Decode a tile of pixels.  We break it into rows to
415
 * maintain synchrony with the encode algorithm, which
416
 * is row by row.
417
 */
418
static int LogLuvDecodeTile(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
419
0
{
420
0
    tmsize_t rowlen = TIFFTileRowSize(tif);
421
422
0
    if (rowlen == 0)
423
0
        return 0;
424
425
0
    if (cc % rowlen != 0)
426
0
    {
427
0
        TIFFErrorExtR(tif, "LogLuvDecodeTile",
428
0
                      "Fractional scanline cannot be read");
429
0
        return 0;
430
0
    }
431
0
    while (cc && (*tif->tif_decoderow)(tif, bp, rowlen, s))
432
0
    {
433
0
        bp += rowlen;
434
0
        cc -= rowlen;
435
0
    }
436
0
    return (cc == 0);
437
0
}
438
439
/*
440
 * Encode a row of 16-bit pixels.
441
 */
442
static int LogL16Encode(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
443
0
{
444
0
    static const char module[] = "LogL16Encode";
445
0
    LogLuvState *sp = EncoderState(tif);
446
0
    int shft;
447
0
    tmsize_t i;
448
0
    tmsize_t j;
449
0
    tmsize_t npixels;
450
0
    uint8_t *op;
451
0
    int16_t *tp;
452
0
    int16_t b;
453
0
    tmsize_t occ;
454
0
    int rc = 0, mask;
455
0
    tmsize_t beg;
456
457
0
    (void)s;
458
0
    assert(s == 0);
459
0
    assert(sp != NULL);
460
0
    npixels = cc / sp->pixel_size;
461
462
0
    tp = (int16_t *)sp->tbuf;
463
0
    if (sp->tbuflen < npixels)
464
0
    {
465
0
        TIFFErrorExtR(tif, module, "Translation buffer too short");
466
0
        return (0);
467
0
    }
468
0
    if (sp->user_datafmt == SGILOGDATAFMT_16BIT)
469
0
        L16fromL16(sp, bp, npixels);
470
0
    else
471
0
        (*sp->tfunc)(sp, bp, npixels);
472
    /* compress each byte string */
473
0
    op = tif->tif_rawcp;
474
0
    occ = tif->tif_rawdatasize - tif->tif_rawcc;
475
0
    for (shft = 8; shft >= 0; shft -= 8)
476
0
    {
477
0
        for (i = 0; i < npixels; i += rc)
478
0
        {
479
0
            if (occ < 4)
480
0
            {
481
0
                tif->tif_rawcp = op;
482
0
                tif->tif_rawcc = tif->tif_rawdatasize - occ;
483
0
                if (!TIFFFlushData1(tif))
484
0
                    return (0);
485
0
                op = tif->tif_rawcp;
486
0
                occ = tif->tif_rawdatasize - tif->tif_rawcc;
487
0
            }
488
0
            mask = 0xff << shft; /* find next run */
489
0
            for (beg = i; beg < npixels; beg += rc)
490
0
            {
491
0
                b = (int16_t)(tp[beg] & mask);
492
0
                rc = 1;
493
0
                while (rc < 127 + 2 && beg + rc < npixels &&
494
0
                       (tp[beg + rc] & mask) == b)
495
0
                    rc++;
496
0
                if (rc >= MINRUN)
497
0
                    break; /* long enough */
498
0
            }
499
0
            if (beg - i > 1 && beg - i < MINRUN)
500
0
            {
501
0
                b = (int16_t)(tp[i] & mask); /*check short run */
502
0
                j = i + 1;
503
0
                while ((tp[j++] & mask) == b)
504
0
                    if (j == beg)
505
0
                    {
506
0
                        *op++ = (uint8_t)(128 - 2 + j - i);
507
0
                        *op++ = (uint8_t)(b >> shft);
508
0
                        occ -= 2;
509
0
                        i = beg;
510
0
                        break;
511
0
                    }
512
0
            }
513
0
            while (i < beg)
514
0
            { /* write out non-run */
515
0
                if ((j = beg - i) > 127)
516
0
                    j = 127;
517
0
                if (occ < j + 3)
518
0
                {
519
0
                    tif->tif_rawcp = op;
520
0
                    tif->tif_rawcc = tif->tif_rawdatasize - occ;
521
0
                    if (!TIFFFlushData1(tif))
522
0
                        return (0);
523
0
                    op = tif->tif_rawcp;
524
0
                    occ = tif->tif_rawdatasize - tif->tif_rawcc;
525
0
                }
526
0
                *op++ = (uint8_t)j;
527
0
                occ--;
528
0
                while (j--)
529
0
                {
530
0
                    *op++ = (uint8_t)(tp[i++] >> shft & 0xff);
531
0
                    occ--;
532
0
                }
533
0
            }
534
0
            if (rc >= MINRUN)
535
0
            { /* write out run */
536
0
                *op++ = (uint8_t)(128 - 2 + rc);
537
0
                *op++ = (uint8_t)(tp[beg] >> shft & 0xff);
538
0
                occ -= 2;
539
0
            }
540
0
            else
541
0
                rc = 0;
542
0
        }
543
0
    }
544
0
    tif->tif_rawcp = op;
545
0
    tif->tif_rawcc = tif->tif_rawdatasize - occ;
546
547
0
    return (1);
548
0
}
549
550
/*
551
 * Encode a row of 24-bit pixels.
552
 */
553
static int LogLuvEncode24(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
554
0
{
555
0
    static const char module[] = "LogLuvEncode24";
556
0
    LogLuvState *sp = EncoderState(tif);
557
0
    tmsize_t i;
558
0
    tmsize_t npixels;
559
0
    tmsize_t occ;
560
0
    uint8_t *op;
561
0
    uint32_t *tp;
562
563
0
    (void)s;
564
0
    assert(s == 0);
565
0
    assert(sp != NULL);
566
0
    npixels = cc / sp->pixel_size;
567
568
0
    tp = (uint32_t *)sp->tbuf;
569
0
    if (sp->tbuflen < npixels)
570
0
    {
571
0
        TIFFErrorExtR(tif, module, "Translation buffer too short");
572
0
        return (0);
573
0
    }
574
0
    if (sp->user_datafmt == SGILOGDATAFMT_RAW)
575
0
        LuvRawFromRaw(sp, bp, npixels);
576
0
    else
577
0
        (*sp->tfunc)(sp, bp, npixels);
578
    /* write out encoded pixels */
579
0
    op = tif->tif_rawcp;
580
0
    occ = tif->tif_rawdatasize - tif->tif_rawcc;
581
0
    for (i = npixels; i--;)
582
0
    {
583
0
        if (occ < 3)
584
0
        {
585
0
            tif->tif_rawcp = op;
586
0
            tif->tif_rawcc = tif->tif_rawdatasize - occ;
587
0
            if (!TIFFFlushData1(tif))
588
0
                return (0);
589
0
            op = tif->tif_rawcp;
590
0
            occ = tif->tif_rawdatasize - tif->tif_rawcc;
591
0
        }
592
0
        *op++ = (uint8_t)(*tp >> 16);
593
0
        *op++ = (uint8_t)(*tp >> 8 & 0xff);
594
0
        *op++ = (uint8_t)(*tp++ & 0xff);
595
0
        occ -= 3;
596
0
    }
597
0
    tif->tif_rawcp = op;
598
0
    tif->tif_rawcc = tif->tif_rawdatasize - occ;
599
600
0
    return (1);
601
0
}
602
603
/*
604
 * Encode a row of 32-bit pixels.
605
 */
606
static int LogLuvEncode32(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
607
0
{
608
0
    static const char module[] = "LogLuvEncode32";
609
0
    LogLuvState *sp = EncoderState(tif);
610
0
    int shft;
611
0
    tmsize_t i;
612
0
    tmsize_t j;
613
0
    tmsize_t npixels;
614
0
    uint8_t *op;
615
0
    uint32_t *tp;
616
0
    uint32_t b;
617
0
    tmsize_t occ;
618
0
    int rc = 0;
619
0
    tmsize_t beg;
620
621
0
    (void)s;
622
0
    assert(s == 0);
623
0
    assert(sp != NULL);
624
625
0
    npixels = cc / sp->pixel_size;
626
627
0
    tp = (uint32_t *)sp->tbuf;
628
0
    if (sp->tbuflen < npixels)
629
0
    {
630
0
        TIFFErrorExtR(tif, module, "Translation buffer too short");
631
0
        return (0);
632
0
    }
633
0
    if (sp->user_datafmt == SGILOGDATAFMT_RAW)
634
0
        LuvRawFromRaw(sp, bp, npixels);
635
0
    else
636
0
        (*sp->tfunc)(sp, bp, npixels);
637
    /* compress each byte string */
638
0
    op = tif->tif_rawcp;
639
0
    occ = tif->tif_rawdatasize - tif->tif_rawcc;
640
0
    for (shft = 24; shft >= 0; shft -= 8)
641
0
    {
642
0
        const uint32_t mask = 0xffU << shft; /* find next run */
643
0
        for (i = 0; i < npixels; i += rc)
644
0
        {
645
0
            if (occ < 4)
646
0
            {
647
0
                tif->tif_rawcp = op;
648
0
                tif->tif_rawcc = tif->tif_rawdatasize - occ;
649
0
                if (!TIFFFlushData1(tif))
650
0
                    return (0);
651
0
                op = tif->tif_rawcp;
652
0
                occ = tif->tif_rawdatasize - tif->tif_rawcc;
653
0
            }
654
0
            for (beg = i; beg < npixels; beg += rc)
655
0
            {
656
0
                b = tp[beg] & mask;
657
0
                rc = 1;
658
0
                while (rc < 127 + 2 && beg + rc < npixels &&
659
0
                       (tp[beg + rc] & mask) == b)
660
0
                    rc++;
661
0
                if (rc >= MINRUN)
662
0
                    break; /* long enough */
663
0
            }
664
0
            if (beg - i > 1 && beg - i < MINRUN)
665
0
            {
666
0
                b = tp[i] & mask; /* check short run */
667
0
                j = i + 1;
668
0
                while ((tp[j++] & mask) == b)
669
0
                    if (j == beg)
670
0
                    {
671
0
                        *op++ = (uint8_t)(128 - 2 + j - i);
672
0
                        *op++ = (uint8_t)(b >> shft);
673
0
                        occ -= 2;
674
0
                        i = beg;
675
0
                        break;
676
0
                    }
677
0
            }
678
0
            while (i < beg)
679
0
            { /* write out non-run */
680
0
                if ((j = beg - i) > 127)
681
0
                    j = 127;
682
0
                if (occ < j + 3)
683
0
                {
684
0
                    tif->tif_rawcp = op;
685
0
                    tif->tif_rawcc = tif->tif_rawdatasize - occ;
686
0
                    if (!TIFFFlushData1(tif))
687
0
                        return (0);
688
0
                    op = tif->tif_rawcp;
689
0
                    occ = tif->tif_rawdatasize - tif->tif_rawcc;
690
0
                }
691
0
                *op++ = (uint8_t)j;
692
0
                occ--;
693
0
                while (j--)
694
0
                {
695
0
                    *op++ = (uint8_t)(tp[i++] >> shft & 0xff);
696
0
                    occ--;
697
0
                }
698
0
            }
699
0
            if (rc >= MINRUN)
700
0
            { /* write out run */
701
0
                *op++ = (uint8_t)(128 - 2 + rc);
702
0
                *op++ = (uint8_t)(tp[beg] >> shft & 0xff);
703
0
                occ -= 2;
704
0
            }
705
0
            else
706
0
                rc = 0;
707
0
        }
708
0
    }
709
0
    tif->tif_rawcp = op;
710
0
    tif->tif_rawcc = tif->tif_rawdatasize - occ;
711
712
0
    return (1);
713
0
}
714
715
/*
716
 * Encode a strip of pixels.  We break it into rows to
717
 * avoid encoding runs across row boundaries.
718
 */
719
static int LogLuvEncodeStrip(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
720
0
{
721
0
    tmsize_t rowlen = TIFFScanlineSize(tif);
722
723
0
    if (rowlen == 0)
724
0
        return 0;
725
726
0
    if (cc % rowlen != 0)
727
0
    {
728
0
        TIFFErrorExtR(tif, "LogLuvEncodeStrip",
729
0
                      "Fractional scanline cannot be written");
730
0
        return 0;
731
0
    }
732
0
    while (cc && (*tif->tif_encoderow)(tif, bp, rowlen, s) == 1)
733
0
    {
734
0
        bp += rowlen;
735
0
        cc -= rowlen;
736
0
    }
737
0
    return (cc == 0);
738
0
}
739
740
/*
741
 * Encode a tile of pixels.  We break it into rows to
742
 * avoid encoding runs across row boundaries.
743
 */
744
static int LogLuvEncodeTile(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
745
0
{
746
0
    tmsize_t rowlen = TIFFTileRowSize(tif);
747
748
0
    if (rowlen == 0)
749
0
        return 0;
750
751
0
    if (cc % rowlen != 0)
752
0
    {
753
0
        TIFFErrorExtR(tif, "LogLuvEncodeTile",
754
0
                      "Fractional scanline cannot be written");
755
0
        return 0;
756
0
    }
757
0
    while (cc && (*tif->tif_encoderow)(tif, bp, rowlen, s) == 1)
758
0
    {
759
0
        bp += rowlen;
760
0
        cc -= rowlen;
761
0
    }
762
0
    return (cc == 0);
763
0
}
764
765
/*
766
 * Encode/Decode functions for converting to and from user formats.
767
 */
768
769
#include "uvcode.h"
770
771
#ifndef UVSCALE
772
#define U_NEU 0.210526316
773
#define V_NEU 0.473684211
774
#define UVSCALE 410.
775
#endif
776
777
#ifndef M_LN2
778
#define M_LN2 0.69314718055994530942
779
#endif
780
#ifndef M_PI
781
#define M_PI 3.14159265358979323846
782
#endif
783
784
0
#define TIFF_RAND_MAX 32767
785
786
// From POSIX.1-2001 as an example of an implementation of rand()
787
static uint32_t _TIFFRand(void)
788
0
{
789
0
    static uint32_t nCounter = 0;
790
0
    if (!nCounter)
791
0
        nCounter = (uint32_t)(time(NULL) & UINT32_MAX);
792
0
    ++nCounter;
793
0
    uint32_t nCounterLocal =
794
0
        (uint32_t)(((uint64_t)(nCounter) * 1103515245U + 12345U) & UINT32_MAX);
795
0
    nCounter = nCounterLocal;
796
0
    return (nCounterLocal / 65536U) % (TIFF_RAND_MAX + 1);
797
0
}
798
799
static int tiff_itrunc(double x, int m)
800
0
{
801
0
    if (m == SGILOGENCODE_NODITHER)
802
0
        return (int)x;
803
0
    return (int)(x + _TIFFRand() * (1. / TIFF_RAND_MAX) - .5);
804
0
}
805
806
#if !LOGLUV_PUBLIC
807
static
808
#endif
809
    double LogL16toY(int p16) /* compute luminance from 16-bit LogL */
810
0
{
811
0
    int Le = p16 & 0x7fff;
812
0
    double Y;
813
814
0
    if (!Le)
815
0
        return (0.);
816
0
    Y = exp(M_LN2 / 256. * (Le + .5) - M_LN2 * 64.);
817
0
    return (!(p16 & 0x8000) ? Y : -Y);
818
0
}
819
820
#if !LOGLUV_PUBLIC
821
static
822
#endif
823
    int LogL16fromY(double Y, int em) /* get 16-bit LogL from Y */
824
0
{
825
0
    if (Y >= 1.8371976e19)
826
0
        return (0x7fff);
827
0
    if (Y <= -1.8371976e19)
828
0
        return (0xffff);
829
0
    if (Y > 5.4136769e-20)
830
0
        return tiff_itrunc(256. * (log2(Y) + 64.), em);
831
0
    if (Y < -5.4136769e-20)
832
0
        return (~0x7fff | tiff_itrunc(256. * (log2(-Y) + 64.), em));
833
0
    return (0);
834
0
}
835
836
/*
837
 * SGILOGDATAFMT_* buffers are application-facing user data buffers in native
838
 * byte order.  The helpers below do not perform TIFF file byte-order
839
 * conversion; they only avoid unaligned typed access to public byte buffers.
840
 * Use fixed-size memcpy() calls directly so optimizing compilers can expand
841
 * them in these per-pixel paths.  _TIFFmemcpy() is an out-of-line wrapper in
842
 * non-LTO builds.
843
 */
844
static float LogLuvLoadFloatNativeUnaligned(const uint8_t *cp)
845
0
{
846
0
    float v;
847
0
    memcpy(&v, cp, sizeof(v));
848
0
    return v;
849
0
}
850
851
static void LogLuvStoreFloatNativeUnaligned(uint8_t *cp, float v)
852
0
{
853
0
    memcpy(cp, &v, sizeof(v));
854
0
}
855
856
static int16_t LogLuvLoad16NativeUnaligned(const uint8_t *cp)
857
0
{
858
0
    int16_t v;
859
0
    memcpy(&v, cp, sizeof(v));
860
0
    return v;
861
0
}
862
863
static void LogLuvStore16NativeUnaligned(uint8_t *cp, int16_t v)
864
0
{
865
0
    memcpy(cp, &v, sizeof(v));
866
0
}
867
868
static uint32_t LogLuvLoad32NativeUnaligned(const uint8_t *cp)
869
0
{
870
0
    uint32_t v;
871
0
    memcpy(&v, cp, sizeof(v));
872
0
    return v;
873
0
}
874
875
static void LogLuvStore32NativeUnaligned(uint8_t *cp, uint32_t v)
876
0
{
877
0
    memcpy(cp, &v, sizeof(v));
878
0
}
879
880
static void L16toL16(LogLuvState *sp, uint8_t *op, tmsize_t n)
881
0
{
882
0
    int16_t *l16 = (int16_t *)sp->tbuf;
883
884
0
    while (n-- > 0)
885
0
    {
886
0
        LogLuvStore16NativeUnaligned(op, *l16++);
887
0
        op += sizeof(int16_t);
888
0
    }
889
0
}
890
891
static void L16fromL16(LogLuvState *sp, uint8_t *op, tmsize_t n)
892
0
{
893
0
    int16_t *l16 = (int16_t *)sp->tbuf;
894
895
0
    while (n-- > 0)
896
0
    {
897
0
        *l16++ = LogLuvLoad16NativeUnaligned(op);
898
0
        op += sizeof(int16_t);
899
0
    }
900
0
}
901
902
static void LuvRawToRaw(LogLuvState *sp, uint8_t *op, tmsize_t n)
903
0
{
904
0
    uint32_t *luv = (uint32_t *)sp->tbuf;
905
906
0
    while (n-- > 0)
907
0
    {
908
0
        LogLuvStore32NativeUnaligned(op, *luv++);
909
0
        op += sizeof(uint32_t);
910
0
    }
911
0
}
912
913
static void LuvRawFromRaw(LogLuvState *sp, uint8_t *op, tmsize_t n)
914
0
{
915
0
    uint32_t *luv = (uint32_t *)sp->tbuf;
916
917
0
    while (n-- > 0)
918
0
    {
919
0
        *luv++ = LogLuvLoad32NativeUnaligned(op);
920
0
        op += sizeof(uint32_t);
921
0
    }
922
0
}
923
924
static void L16toY(LogLuvState *sp, uint8_t *op, tmsize_t n)
925
0
{
926
0
    int16_t *l16 = (int16_t *)sp->tbuf;
927
928
0
    while (n-- > 0)
929
0
    {
930
0
        LogLuvStoreFloatNativeUnaligned(op, (float)LogL16toY(*l16++));
931
0
        op += sizeof(float);
932
0
    }
933
0
}
934
935
static void L16toGry(LogLuvState *sp, uint8_t *op, tmsize_t n)
936
0
{
937
0
    int16_t *l16 = (int16_t *)sp->tbuf;
938
0
    uint8_t *gp = (uint8_t *)op;
939
940
0
    while (n-- > 0)
941
0
    {
942
0
        double Y = LogL16toY(*l16++);
943
0
        *gp++ = (uint8_t)((Y <= 0.)   ? 0
944
0
                          : (Y >= 1.) ? 255
945
0
                                      : (int)(256. * sqrt(Y)));
946
0
    }
947
0
}
948
949
static void L16fromY(LogLuvState *sp, uint8_t *op, tmsize_t n)
950
0
{
951
0
    int16_t *l16 = (int16_t *)sp->tbuf;
952
953
0
    while (n-- > 0)
954
0
    {
955
0
        *l16++ = (int16_t)(LogL16fromY(
956
0
            (double)LogLuvLoadFloatNativeUnaligned(op), sp->encode_meth));
957
0
        op += sizeof(float);
958
0
    }
959
0
}
960
961
#if !LOGLUV_PUBLIC
962
static
963
#endif
964
    void XYZtoRGB24(float *xyz, uint8_t *rgb)
965
0
{
966
0
    double r, g, b;
967
    /* assume CCIR-709 primaries */
968
0
    r = 2.690 * (double)xyz[0] + -1.276 * (double)xyz[1] +
969
0
        -0.414 * (double)xyz[2];
970
0
    g = -1.022 * (double)xyz[0] + 1.978 * (double)xyz[1] +
971
0
        0.044 * (double)xyz[2];
972
0
    b = 0.061 * (double)xyz[0] + -0.224 * (double)xyz[1] +
973
0
        1.163 * (double)xyz[2];
974
    /* assume 2.0 gamma for speed */
975
    /* could use integer sqrt approx., but this is probably faster */
976
0
    rgb[0] = (uint8_t)((r <= 0.) ? 0 : (r >= 1.) ? 255 : (int)(256. * sqrt(r)));
977
0
    rgb[1] = (uint8_t)((g <= 0.) ? 0 : (g >= 1.) ? 255 : (int)(256. * sqrt(g)));
978
0
    rgb[2] = (uint8_t)((b <= 0.) ? 0 : (b >= 1.) ? 255 : (int)(256. * sqrt(b)));
979
0
}
980
981
#if !LOGLUV_PUBLIC
982
static
983
#endif
984
    double LogL10toY(int p10) /* compute luminance from 10-bit LogL */
985
0
{
986
0
    if (p10 == 0)
987
0
        return (0.);
988
0
    return (exp(M_LN2 / 64. * (p10 + .5) - M_LN2 * 12.));
989
0
}
990
991
#if !LOGLUV_PUBLIC
992
static
993
#endif
994
    int LogL10fromY(double Y, int em) /* get 10-bit LogL from Y */
995
0
{
996
0
    if (Y >= 15.742)
997
0
        return (0x3ff);
998
0
    else if (Y <= .00024283)
999
0
        return (0);
1000
0
    else
1001
0
        return tiff_itrunc(64. * (log2(Y) + 12.), em);
1002
0
}
1003
1004
0
#define NANGLES 100
1005
#define uv2ang(u, v)                                                           \
1006
0
    ((NANGLES * .499999999 / M_PI) * atan2((v) - V_NEU, (u) - U_NEU) +         \
1007
0
     .5 * NANGLES)
1008
1009
static int oog_encode(double u, double v) /* encode out-of-gamut chroma */
1010
0
{
1011
0
    static int oog_table[NANGLES];
1012
0
    static int initialized = 0;
1013
0
    int i;
1014
1015
0
    if (!initialized)
1016
0
    { /* set up perimeter table */
1017
0
        double eps[NANGLES], ua, va, ang, epsa;
1018
0
        int ui, vi, ustep;
1019
0
        for (i = NANGLES; i--;)
1020
0
            eps[i] = 2.;
1021
0
        for (vi = UV_NVS; vi--;)
1022
0
        {
1023
0
            va = (double)UV_VSTART + ((double)vi + .5) * (double)UV_SQSIZ;
1024
0
            ustep = uv_row[vi].nus - 1;
1025
0
            if (vi == UV_NVS - 1 || vi == 0 || ustep <= 0)
1026
0
                ustep = 1;
1027
0
            for (ui = uv_row[vi].nus - 1; ui >= 0; ui -= ustep)
1028
0
            {
1029
0
                ua = (double)uv_row[vi].ustart +
1030
0
                     ((double)ui + .5) * (double)UV_SQSIZ;
1031
0
                ang = uv2ang(ua, va);
1032
0
                i = (int)ang;
1033
0
                epsa = fabs(ang - (i + .5));
1034
0
                if (epsa < eps[i])
1035
0
                {
1036
0
                    oog_table[i] = uv_row[vi].ncum + ui;
1037
0
                    eps[i] = epsa;
1038
0
                }
1039
0
            }
1040
0
        }
1041
0
        for (i = NANGLES; i--;) /* fill any holes */
1042
0
            if (eps[i] > 1.5)
1043
0
            {
1044
0
                int i1, i2;
1045
0
                for (i1 = 1; i1 < NANGLES / 2; i1++)
1046
0
                    if (eps[(i + i1) % NANGLES] < 1.5)
1047
0
                        break;
1048
0
                for (i2 = 1; i2 < NANGLES / 2; i2++)
1049
0
                    if (eps[(i + NANGLES - i2) % NANGLES] < 1.5)
1050
0
                        break;
1051
0
                if (i1 < i2)
1052
0
                    oog_table[i] = oog_table[(i + i1) % NANGLES];
1053
0
                else
1054
0
                    oog_table[i] = oog_table[(i + NANGLES - i2) % NANGLES];
1055
0
            }
1056
0
        initialized = 1;
1057
0
    }
1058
0
    i = (int)uv2ang(u, v); /* look up hue angle */
1059
0
    return (oog_table[i]);
1060
0
}
1061
1062
#undef uv2ang
1063
#undef NANGLES
1064
1065
#if !LOGLUV_PUBLIC
1066
static
1067
#endif
1068
    int uv_encode(double u, double v, int em) /* encode (u',v') coordinates */
1069
0
{
1070
0
    unsigned int vi;
1071
0
    int ui;
1072
1073
    /* check for NaN */
1074
0
    if (isnan(u) || isnan(v))
1075
0
    {
1076
0
        u = U_NEU;
1077
0
        v = V_NEU;
1078
0
    }
1079
1080
0
    if ((double)v < (double)UV_VSTART)
1081
0
        return oog_encode(u, v);
1082
0
    vi = (unsigned int)tiff_itrunc(
1083
0
        ((double)v - (double)UV_VSTART) * (1. / (double)UV_SQSIZ), em);
1084
0
    if (vi >= UV_NVS)
1085
0
        return oog_encode(u, v);
1086
0
    if ((double)u < (double)uv_row[vi].ustart)
1087
0
        return oog_encode(u, v);
1088
0
    ui = tiff_itrunc(
1089
0
        ((double)u - (double)uv_row[vi].ustart) * (1. / (double)UV_SQSIZ), em);
1090
0
    if (ui >= uv_row[vi].nus)
1091
0
        return oog_encode(u, v);
1092
1093
0
    return (uv_row[vi].ncum + ui);
1094
0
}
1095
1096
#if !LOGLUV_PUBLIC
1097
static
1098
#endif
1099
    int uv_decode(double *up, double *vp, int c) /* decode (u',v') index */
1100
0
{
1101
0
    unsigned int upper, lower;
1102
0
    int ui;
1103
0
    unsigned int vi;
1104
1105
0
    if (c < 0 || c >= UV_NDIVS)
1106
0
        return (-1);
1107
0
    lower = 0; /* binary search */
1108
0
    upper = UV_NVS;
1109
0
    while (upper - lower > 1)
1110
0
    {
1111
0
        vi = (lower + upper) >> 1;
1112
0
        ui = c - uv_row[vi].ncum;
1113
0
        if (ui > 0)
1114
0
            lower = vi;
1115
0
        else if (ui < 0)
1116
0
            upper = vi;
1117
0
        else
1118
0
        {
1119
0
            lower = vi;
1120
0
            break;
1121
0
        }
1122
0
    }
1123
0
    vi = lower;
1124
0
    ui = c - uv_row[vi].ncum;
1125
0
    *up = (double)uv_row[vi].ustart + ((double)ui + .5) * (double)UV_SQSIZ;
1126
0
    *vp = (double)UV_VSTART + ((double)vi + .5) * (double)UV_SQSIZ;
1127
0
    return (0);
1128
0
}
1129
1130
#if !LOGLUV_PUBLIC
1131
static
1132
#endif
1133
    void LogLuv24toXYZ(uint32_t p, float *XYZ)
1134
0
{
1135
0
    int Ce;
1136
0
    double L, u, v, s, x, y;
1137
    /* decode luminance */
1138
0
    L = LogL10toY(p >> 14 & 0x3ff);
1139
0
    if (L <= 0.)
1140
0
    {
1141
0
        XYZ[0] = XYZ[1] = XYZ[2] = 0.;
1142
0
        return;
1143
0
    }
1144
    /* decode color */
1145
0
    Ce = p & 0x3fff;
1146
0
    if (uv_decode(&u, &v, Ce) < 0)
1147
0
    {
1148
0
        u = U_NEU;
1149
0
        v = V_NEU;
1150
0
    }
1151
0
    s = 1. / (6. * u - 16. * v + 12.);
1152
0
    x = 9. * u * s;
1153
0
    y = 4. * v * s;
1154
    /* convert to XYZ */
1155
0
    XYZ[0] = (float)(x / y * L);
1156
0
    XYZ[1] = (float)L;
1157
0
    XYZ[2] = (float)((1. - x - y) / y * L);
1158
0
}
1159
1160
#if !LOGLUV_PUBLIC
1161
static
1162
#endif
1163
    uint32_t LogLuv24fromXYZ(float *XYZ, int em)
1164
0
{
1165
0
    int Le, Ce;
1166
0
    double u, v, s;
1167
    /* encode luminance */
1168
0
    Le = LogL10fromY((double)XYZ[1], em);
1169
    /* encode color */
1170
0
    s = (double)XYZ[0] + 15. * (double)XYZ[1] + 3. * (double)XYZ[2];
1171
0
    if (!Le || s <= 0.)
1172
0
    {
1173
0
        u = U_NEU;
1174
0
        v = V_NEU;
1175
0
    }
1176
0
    else
1177
0
    {
1178
0
        u = 4. * (double)XYZ[0] / s;
1179
0
        v = 9. * (double)XYZ[1] / s;
1180
0
    }
1181
0
    Ce = uv_encode(u, v, em);
1182
0
    if (Ce < 0) /* never happens */
1183
0
        Ce = uv_encode(U_NEU, V_NEU, SGILOGENCODE_NODITHER);
1184
    /* combine encodings */
1185
0
    return (uint32_t)Le << 14 | (uint32_t)Ce;
1186
0
}
1187
1188
static void Luv24toXYZ(LogLuvState *sp, uint8_t *op, tmsize_t n)
1189
0
{
1190
0
    uint32_t *luv = (uint32_t *)sp->tbuf;
1191
1192
0
    while (n-- > 0)
1193
0
    {
1194
0
        float xyz[3];
1195
0
        LogLuv24toXYZ(*luv, xyz);
1196
0
        LogLuvStoreFloatNativeUnaligned(op, xyz[0]);
1197
0
        LogLuvStoreFloatNativeUnaligned(op + sizeof(float), xyz[1]);
1198
0
        LogLuvStoreFloatNativeUnaligned(op + 2 * sizeof(float), xyz[2]);
1199
0
        op += 3 * sizeof(float);
1200
0
        luv++;
1201
0
    }
1202
0
}
1203
1204
static void Luv24toLuv48(LogLuvState *sp, uint8_t *op, tmsize_t n)
1205
0
{
1206
0
    uint32_t *luv = (uint32_t *)sp->tbuf;
1207
1208
0
    while (n-- > 0)
1209
0
    {
1210
0
        double u, v;
1211
0
        int16_t luv0;
1212
0
        int16_t luv1;
1213
0
        int16_t luv2;
1214
1215
0
        luv0 = (int16_t)((*luv >> 12 & 0xffd) + 13314);
1216
0
        if (uv_decode(&u, &v, *luv & 0x3fff) < 0)
1217
0
        {
1218
0
            u = U_NEU;
1219
0
            v = V_NEU;
1220
0
        }
1221
0
        luv1 = (int16_t)(u * (1 << 15));
1222
0
        luv2 = (int16_t)(v * (1 << 15));
1223
0
        LogLuvStore16NativeUnaligned(op, luv0);
1224
0
        LogLuvStore16NativeUnaligned(op + sizeof(int16_t), luv1);
1225
0
        LogLuvStore16NativeUnaligned(op + 2 * sizeof(int16_t), luv2);
1226
0
        op += 3 * sizeof(int16_t);
1227
0
        luv++;
1228
0
    }
1229
0
}
1230
1231
static void Luv24toRGB(LogLuvState *sp, uint8_t *op, tmsize_t n)
1232
0
{
1233
0
    uint32_t *luv = (uint32_t *)sp->tbuf;
1234
0
    uint8_t *rgb = (uint8_t *)op;
1235
1236
0
    while (n-- > 0)
1237
0
    {
1238
0
        float xyz[3];
1239
1240
0
        LogLuv24toXYZ(*luv++, xyz);
1241
0
        XYZtoRGB24(xyz, rgb);
1242
0
        rgb += 3;
1243
0
    }
1244
0
}
1245
1246
static void Luv24fromXYZ(LogLuvState *sp, uint8_t *op, tmsize_t n)
1247
0
{
1248
0
    uint32_t *luv = (uint32_t *)sp->tbuf;
1249
1250
0
    while (n-- > 0)
1251
0
    {
1252
0
        float xyz[3];
1253
0
        xyz[0] = LogLuvLoadFloatNativeUnaligned(op);
1254
0
        xyz[1] = LogLuvLoadFloatNativeUnaligned(op + sizeof(float));
1255
0
        xyz[2] = LogLuvLoadFloatNativeUnaligned(op + 2 * sizeof(float));
1256
0
        *luv++ = LogLuv24fromXYZ(xyz, sp->encode_meth);
1257
0
        op += 3 * sizeof(float);
1258
0
    }
1259
0
}
1260
1261
static void Luv24fromLuv48(LogLuvState *sp, uint8_t *op, tmsize_t n)
1262
0
{
1263
0
    uint32_t *luv = (uint32_t *)sp->tbuf;
1264
1265
0
    while (n-- > 0)
1266
0
    {
1267
0
        int Le, Ce;
1268
0
        int16_t luv0 = LogLuvLoad16NativeUnaligned(op);
1269
0
        int16_t luv1 = LogLuvLoad16NativeUnaligned(op + sizeof(int16_t));
1270
0
        int16_t luv2 = LogLuvLoad16NativeUnaligned(op + 2 * sizeof(int16_t));
1271
1272
0
        if (luv0 <= 0)
1273
0
            Le = 0;
1274
0
        else if (luv0 >= (1 << 12) + 3314)
1275
0
            Le = (1 << 10) - 1;
1276
0
        else if (sp->encode_meth == SGILOGENCODE_NODITHER)
1277
0
            Le = (luv0 - 3314) >> 2;
1278
0
        else
1279
0
            Le = tiff_itrunc(.25 * (luv0 - 3314.), sp->encode_meth);
1280
1281
0
        Ce = uv_encode((luv1 + .5) / (1 << 15), (luv2 + .5) / (1 << 15),
1282
0
                       sp->encode_meth);
1283
0
        if (Ce < 0) /* never happens */
1284
0
            Ce = uv_encode(U_NEU, V_NEU, SGILOGENCODE_NODITHER);
1285
0
        *luv++ = (uint32_t)Le << 14 | (uint32_t)Ce;
1286
0
        op += 3 * sizeof(int16_t);
1287
0
    }
1288
0
}
1289
1290
#if !LOGLUV_PUBLIC
1291
static
1292
#endif
1293
    void LogLuv32toXYZ(uint32_t p, float *XYZ)
1294
0
{
1295
0
    double L, u, v, s, x, y;
1296
    /* decode luminance */
1297
0
    L = LogL16toY((int)p >> 16);
1298
0
    if (L <= 0.)
1299
0
    {
1300
0
        XYZ[0] = XYZ[1] = XYZ[2] = 0.;
1301
0
        return;
1302
0
    }
1303
    /* decode color */
1304
0
    u = 1. / UVSCALE * ((p >> 8 & 0xff) + .5);
1305
0
    v = 1. / UVSCALE * ((p & 0xff) + .5);
1306
0
    s = 1. / (6. * u - 16. * v + 12.);
1307
0
    x = 9. * u * s;
1308
0
    y = 4. * v * s;
1309
    /* convert to XYZ */
1310
0
    XYZ[0] = (float)(x / y * L);
1311
0
    XYZ[1] = (float)L;
1312
0
    XYZ[2] = (float)((1. - x - y) / y * L);
1313
0
}
1314
1315
#if !LOGLUV_PUBLIC
1316
static
1317
#endif
1318
    uint32_t LogLuv32fromXYZ(float *XYZ, int em)
1319
0
{
1320
0
    unsigned int Le, ue, ve;
1321
0
    double u, v, s;
1322
    /* encode luminance */
1323
0
    Le = (unsigned int)LogL16fromY((double)XYZ[1], em);
1324
    /* encode color */
1325
0
    s = (double)XYZ[0] + 15. * (double)XYZ[1] + 3. * (double)XYZ[2];
1326
0
    if (!Le || s <= 0.)
1327
0
    {
1328
0
        u = U_NEU;
1329
0
        v = V_NEU;
1330
0
    }
1331
0
    else
1332
0
    {
1333
0
        u = 4. * (double)XYZ[0] / s;
1334
0
        v = 9. * (double)XYZ[1] / s;
1335
0
    }
1336
0
    if (u <= 0.)
1337
0
        ue = 0;
1338
0
    else
1339
0
        ue = (unsigned int)tiff_itrunc(UVSCALE * u, em);
1340
0
    if (ue > 255)
1341
0
        ue = 255;
1342
0
    if (v <= 0.)
1343
0
        ve = 0;
1344
0
    else
1345
0
        ve = (unsigned int)tiff_itrunc(UVSCALE * v, em);
1346
0
    if (ve > 255)
1347
0
        ve = 255;
1348
    /* combine encodings */
1349
0
    return (Le << 16 | ue << 8 | ve);
1350
0
}
1351
1352
static void Luv32toXYZ(LogLuvState *sp, uint8_t *op, tmsize_t n)
1353
0
{
1354
0
    uint32_t *luv = (uint32_t *)sp->tbuf;
1355
1356
0
    while (n-- > 0)
1357
0
    {
1358
0
        float xyz[3];
1359
0
        LogLuv32toXYZ(*luv++, xyz);
1360
0
        LogLuvStoreFloatNativeUnaligned(op, xyz[0]);
1361
0
        LogLuvStoreFloatNativeUnaligned(op + sizeof(float), xyz[1]);
1362
0
        LogLuvStoreFloatNativeUnaligned(op + 2 * sizeof(float), xyz[2]);
1363
0
        op += 3 * sizeof(float);
1364
0
    }
1365
0
}
1366
1367
static void Luv32toLuv48(LogLuvState *sp, uint8_t *op, tmsize_t n)
1368
0
{
1369
0
    uint32_t *luv = (uint32_t *)sp->tbuf;
1370
1371
0
    while (n-- > 0)
1372
0
    {
1373
0
        double u, v;
1374
0
        int16_t luv0 = (int16_t)(*luv >> 16);
1375
0
        int16_t luv1;
1376
0
        int16_t luv2;
1377
1378
0
        u = 1. / UVSCALE * ((*luv >> 8 & 0xff) + .5);
1379
0
        v = 1. / UVSCALE * ((*luv & 0xff) + .5);
1380
0
        luv1 = (int16_t)(u * (1 << 15));
1381
0
        luv2 = (int16_t)(v * (1 << 15));
1382
0
        LogLuvStore16NativeUnaligned(op, luv0);
1383
0
        LogLuvStore16NativeUnaligned(op + sizeof(int16_t), luv1);
1384
0
        LogLuvStore16NativeUnaligned(op + 2 * sizeof(int16_t), luv2);
1385
0
        op += 3 * sizeof(int16_t);
1386
0
        luv++;
1387
0
    }
1388
0
}
1389
1390
static void Luv32toRGB(LogLuvState *sp, uint8_t *op, tmsize_t n)
1391
0
{
1392
0
    uint32_t *luv = (uint32_t *)sp->tbuf;
1393
0
    uint8_t *rgb = (uint8_t *)op;
1394
1395
0
    while (n-- > 0)
1396
0
    {
1397
0
        float xyz[3];
1398
1399
0
        LogLuv32toXYZ(*luv++, xyz);
1400
0
        XYZtoRGB24(xyz, rgb);
1401
0
        rgb += 3;
1402
0
    }
1403
0
}
1404
1405
static void Luv32fromXYZ(LogLuvState *sp, uint8_t *op, tmsize_t n)
1406
0
{
1407
0
    uint32_t *luv = (uint32_t *)sp->tbuf;
1408
1409
0
    while (n-- > 0)
1410
0
    {
1411
0
        float xyz[3];
1412
0
        xyz[0] = LogLuvLoadFloatNativeUnaligned(op);
1413
0
        xyz[1] = LogLuvLoadFloatNativeUnaligned(op + sizeof(float));
1414
0
        xyz[2] = LogLuvLoadFloatNativeUnaligned(op + 2 * sizeof(float));
1415
0
        *luv++ = LogLuv32fromXYZ(xyz, sp->encode_meth);
1416
0
        op += 3 * sizeof(float);
1417
0
    }
1418
0
}
1419
1420
static void Luv32fromLuv48(LogLuvState *sp, uint8_t *op, tmsize_t n)
1421
0
{
1422
0
    uint32_t *luv = (uint32_t *)sp->tbuf;
1423
1424
0
    if (sp->encode_meth == SGILOGENCODE_NODITHER)
1425
0
    {
1426
0
        while (n-- > 0)
1427
0
        {
1428
0
            int16_t luv0 = LogLuvLoad16NativeUnaligned(op);
1429
0
            int16_t luv1 = LogLuvLoad16NativeUnaligned(op + sizeof(int16_t));
1430
0
            int16_t luv2 =
1431
0
                LogLuvLoad16NativeUnaligned(op + 2 * sizeof(int16_t));
1432
0
            *luv++ = (uint32_t)luv0 << 16 |
1433
0
                     ((uint32_t)luv1 * (uint32_t)(UVSCALE + .5) >> 7 & 0xff00) |
1434
0
                     ((uint32_t)luv2 * (uint32_t)(UVSCALE + .5) >> 15 & 0xff);
1435
0
            op += 3 * sizeof(int16_t);
1436
0
        }
1437
0
        return;
1438
0
    }
1439
0
    while (n-- > 0)
1440
0
    {
1441
0
        int16_t luv0 = LogLuvLoad16NativeUnaligned(op);
1442
0
        int16_t luv1 = LogLuvLoad16NativeUnaligned(op + sizeof(int16_t));
1443
0
        int16_t luv2 = LogLuvLoad16NativeUnaligned(op + 2 * sizeof(int16_t));
1444
0
        *luv++ = (uint32_t)luv0 << 16 |
1445
0
                 ((uint32_t)tiff_itrunc(luv1 * (UVSCALE / (1 << 15)),
1446
0
                                        sp->encode_meth)
1447
0
                      << 8 &
1448
0
                  0xff00) |
1449
0
                 ((uint32_t)tiff_itrunc(luv2 * (UVSCALE / (1 << 15)),
1450
0
                                        sp->encode_meth) &
1451
0
                  0xff);
1452
0
        op += 3 * sizeof(int16_t);
1453
0
    }
1454
0
}
1455
1456
static void _logLuvNop(LogLuvState *sp, uint8_t *op, tmsize_t n)
1457
0
{
1458
0
    (void)sp;
1459
0
    (void)op;
1460
0
    (void)n;
1461
0
}
1462
1463
static int LogL16GuessDataFmt(TIFFDirectory *td)
1464
0
{
1465
0
#define PACK(s, b, f) (((b) << 6) | ((s) << 3) | (f))
1466
0
    switch (
1467
0
        PACK(td->td_samplesperpixel, td->td_bitspersample, td->td_sampleformat))
1468
0
    {
1469
0
        case PACK(1, 32, SAMPLEFORMAT_IEEEFP):
1470
0
            return (SGILOGDATAFMT_FLOAT);
1471
0
        case PACK(1, 16, SAMPLEFORMAT_VOID):
1472
0
        case PACK(1, 16, SAMPLEFORMAT_INT):
1473
0
        case PACK(1, 16, SAMPLEFORMAT_UINT):
1474
0
            return (SGILOGDATAFMT_16BIT);
1475
0
        case PACK(1, 8, SAMPLEFORMAT_VOID):
1476
0
        case PACK(1, 8, SAMPLEFORMAT_UINT):
1477
0
            return (SGILOGDATAFMT_8BIT);
1478
0
        default:
1479
0
            break;
1480
0
    }
1481
0
#undef PACK
1482
0
    return (SGILOGDATAFMT_UNKNOWN);
1483
0
}
1484
1485
static tmsize_t multiply_ms(tmsize_t m1, tmsize_t m2)
1486
0
{
1487
0
    return _TIFFMultiplySSize(NULL, m1, m2, NULL);
1488
0
}
1489
1490
static int LogL16InitState(TIFF *tif)
1491
0
{
1492
0
    static const char module[] = "LogL16InitState";
1493
0
    TIFFDirectory *td = &tif->tif_dir;
1494
0
    LogLuvState *sp = DecoderState(tif);
1495
1496
0
    assert(sp != NULL);
1497
0
    assert(td->td_photometric == PHOTOMETRIC_LOGL);
1498
1499
0
    if (td->td_samplesperpixel != 1)
1500
0
    {
1501
0
        TIFFErrorExtR(tif, module,
1502
0
                      "Sorry, can not handle LogL image with %s=%" PRIu16,
1503
0
                      "Samples/pixel", td->td_samplesperpixel);
1504
0
        return 0;
1505
0
    }
1506
1507
    /* for some reason, we can't do this in TIFFInitLogL16 */
1508
0
    if (sp->user_datafmt == SGILOGDATAFMT_UNKNOWN)
1509
0
        sp->user_datafmt = LogL16GuessDataFmt(td);
1510
0
    switch (sp->user_datafmt)
1511
0
    {
1512
0
        case SGILOGDATAFMT_FLOAT:
1513
0
            sp->pixel_size = sizeof(float);
1514
0
            break;
1515
0
        case SGILOGDATAFMT_16BIT:
1516
0
            sp->pixel_size = sizeof(int16_t);
1517
0
            break;
1518
0
        case SGILOGDATAFMT_8BIT:
1519
0
            sp->pixel_size = sizeof(uint8_t);
1520
0
            break;
1521
0
        default:
1522
0
            TIFFErrorExtR(tif, module,
1523
0
                          "No support for converting user data format to LogL");
1524
0
            return (0);
1525
0
    }
1526
0
    if (isTiled(tif))
1527
0
        sp->tbuflen = multiply_ms(td->td_tilewidth, td->td_tilelength);
1528
0
    else if (td->td_rowsperstrip < td->td_imagelength)
1529
0
        sp->tbuflen = multiply_ms(td->td_imagewidth, td->td_rowsperstrip);
1530
0
    else
1531
0
        sp->tbuflen = multiply_ms(td->td_imagewidth, td->td_imagelength);
1532
0
    if (multiply_ms(sp->tbuflen, sizeof(int16_t)) == 0 ||
1533
0
        (sp->tbuf = (uint8_t *)_TIFFmallocExt(
1534
0
             tif, (tmsize_t)((size_t)sp->tbuflen * sizeof(int16_t)))) == NULL)
1535
0
    {
1536
0
        TIFFErrorExtR(tif, module, "No space for SGILog translation buffer");
1537
0
        return (0);
1538
0
    }
1539
0
    return (1);
1540
0
}
1541
1542
static int LogLuvGuessDataFmt(TIFFDirectory *td)
1543
0
{
1544
0
    int guess;
1545
1546
    /*
1547
     * If the user didn't tell us their datafmt,
1548
     * take our best guess from the bitspersample.
1549
     */
1550
0
#define PACK(a, b) (((a) << 3) | (b))
1551
0
    switch (PACK(td->td_bitspersample, td->td_sampleformat))
1552
0
    {
1553
0
        case PACK(32, SAMPLEFORMAT_IEEEFP):
1554
0
            guess = SGILOGDATAFMT_FLOAT;
1555
0
            break;
1556
0
        case PACK(32, SAMPLEFORMAT_VOID):
1557
0
        case PACK(32, SAMPLEFORMAT_UINT):
1558
0
        case PACK(32, SAMPLEFORMAT_INT):
1559
0
            guess = SGILOGDATAFMT_RAW;
1560
0
            break;
1561
0
        case PACK(16, SAMPLEFORMAT_VOID):
1562
0
        case PACK(16, SAMPLEFORMAT_INT):
1563
0
        case PACK(16, SAMPLEFORMAT_UINT):
1564
0
            guess = SGILOGDATAFMT_16BIT;
1565
0
            break;
1566
0
        case PACK(8, SAMPLEFORMAT_VOID):
1567
0
        case PACK(8, SAMPLEFORMAT_UINT):
1568
0
            guess = SGILOGDATAFMT_8BIT;
1569
0
            break;
1570
0
        default:
1571
0
            guess = SGILOGDATAFMT_UNKNOWN;
1572
0
            break;
1573
0
#undef PACK
1574
0
    }
1575
    /*
1576
     * Double-check samples per pixel.
1577
     */
1578
0
    switch (td->td_samplesperpixel)
1579
0
    {
1580
0
        case 1:
1581
0
            if (guess != SGILOGDATAFMT_RAW)
1582
0
                guess = SGILOGDATAFMT_UNKNOWN;
1583
0
            break;
1584
0
        case 3:
1585
0
            if (guess == SGILOGDATAFMT_RAW)
1586
0
                guess = SGILOGDATAFMT_UNKNOWN;
1587
0
            break;
1588
0
        default:
1589
0
            guess = SGILOGDATAFMT_UNKNOWN;
1590
0
            break;
1591
0
    }
1592
0
    return (guess);
1593
0
}
1594
1595
static int LogLuvInitState(TIFF *tif)
1596
0
{
1597
0
    static const char module[] = "LogLuvInitState";
1598
0
    TIFFDirectory *td = &tif->tif_dir;
1599
0
    LogLuvState *sp = DecoderState(tif);
1600
1601
0
    assert(sp != NULL);
1602
0
    assert(td->td_photometric == PHOTOMETRIC_LOGLUV);
1603
1604
    /* for some reason, we can't do this in TIFFInitLogLuv */
1605
0
    if (td->td_planarconfig != PLANARCONFIG_CONTIG)
1606
0
    {
1607
0
        TIFFErrorExtR(tif, module,
1608
0
                      "SGILog compression cannot handle non-contiguous data");
1609
0
        return (0);
1610
0
    }
1611
0
    if (sp->user_datafmt == SGILOGDATAFMT_UNKNOWN)
1612
0
        sp->user_datafmt = LogLuvGuessDataFmt(td);
1613
0
    switch (sp->user_datafmt)
1614
0
    {
1615
0
        case SGILOGDATAFMT_FLOAT:
1616
0
            sp->pixel_size = 3 * sizeof(float);
1617
0
            break;
1618
0
        case SGILOGDATAFMT_16BIT:
1619
0
            sp->pixel_size = 3 * sizeof(int16_t);
1620
0
            break;
1621
0
        case SGILOGDATAFMT_RAW:
1622
0
            sp->pixel_size = sizeof(uint32_t);
1623
0
            break;
1624
0
        case SGILOGDATAFMT_8BIT:
1625
0
            sp->pixel_size = 3 * sizeof(uint8_t);
1626
0
            break;
1627
0
        default:
1628
0
            TIFFErrorExtR(
1629
0
                tif, module,
1630
0
                "No support for converting user data format to LogLuv");
1631
0
            return (0);
1632
0
    }
1633
0
    if (isTiled(tif))
1634
0
        sp->tbuflen = multiply_ms(td->td_tilewidth, td->td_tilelength);
1635
0
    else if (td->td_rowsperstrip < td->td_imagelength)
1636
0
        sp->tbuflen = multiply_ms(td->td_imagewidth, td->td_rowsperstrip);
1637
0
    else
1638
0
        sp->tbuflen = multiply_ms(td->td_imagewidth, td->td_imagelength);
1639
0
    if (multiply_ms(sp->tbuflen, sizeof(uint32_t)) == 0 ||
1640
0
        (sp->tbuf = (uint8_t *)_TIFFmallocExt(
1641
0
             tif, (tmsize_t)((size_t)sp->tbuflen * sizeof(uint32_t)))) == NULL)
1642
0
    {
1643
0
        TIFFErrorExtR(tif, module, "No space for SGILog translation buffer");
1644
0
        return (0);
1645
0
    }
1646
0
    return (1);
1647
0
}
1648
1649
static int LogLuvFixupTags(TIFF *tif)
1650
0
{
1651
0
    (void)tif;
1652
0
    return (1);
1653
0
}
1654
1655
static int LogLuvSetupDecode(TIFF *tif)
1656
0
{
1657
0
    static const char module[] = "LogLuvSetupDecode";
1658
0
    LogLuvState *sp = DecoderState(tif);
1659
0
    TIFFDirectory *td = &tif->tif_dir;
1660
1661
0
    tif->tif_postdecode = _TIFFNoPostDecode;
1662
0
    switch (td->td_photometric)
1663
0
    {
1664
0
        case PHOTOMETRIC_LOGLUV:
1665
0
            if (!LogLuvInitState(tif))
1666
0
                break;
1667
0
            if (td->td_compression == COMPRESSION_SGILOG24)
1668
0
            {
1669
0
                tif->tif_decoderow = LogLuvDecode24;
1670
0
                switch (sp->user_datafmt)
1671
0
                {
1672
0
                    case SGILOGDATAFMT_FLOAT:
1673
0
                        sp->tfunc = Luv24toXYZ;
1674
0
                        break;
1675
0
                    case SGILOGDATAFMT_16BIT:
1676
0
                        sp->tfunc = Luv24toLuv48;
1677
0
                        break;
1678
0
                    case SGILOGDATAFMT_8BIT:
1679
0
                        sp->tfunc = Luv24toRGB;
1680
0
                        break;
1681
0
                    default:
1682
0
                        break;
1683
0
                }
1684
0
            }
1685
0
            else
1686
0
            {
1687
0
                tif->tif_decoderow = LogLuvDecode32;
1688
0
                switch (sp->user_datafmt)
1689
0
                {
1690
0
                    case SGILOGDATAFMT_FLOAT:
1691
0
                        sp->tfunc = Luv32toXYZ;
1692
0
                        break;
1693
0
                    case SGILOGDATAFMT_16BIT:
1694
0
                        sp->tfunc = Luv32toLuv48;
1695
0
                        break;
1696
0
                    case SGILOGDATAFMT_8BIT:
1697
0
                        sp->tfunc = Luv32toRGB;
1698
0
                        break;
1699
0
                    default:
1700
0
                        break;
1701
0
                }
1702
0
            }
1703
0
            return (1);
1704
0
        case PHOTOMETRIC_LOGL:
1705
0
            if (!LogL16InitState(tif))
1706
0
                break;
1707
0
            tif->tif_decoderow = LogL16Decode;
1708
0
            switch (sp->user_datafmt)
1709
0
            {
1710
0
                case SGILOGDATAFMT_FLOAT:
1711
0
                    sp->tfunc = L16toY;
1712
0
                    break;
1713
0
                case SGILOGDATAFMT_8BIT:
1714
0
                    sp->tfunc = L16toGry;
1715
0
                    break;
1716
0
                default:
1717
0
                    break;
1718
0
            }
1719
0
            return (1);
1720
0
        default:
1721
0
            TIFFErrorExtR(tif, module,
1722
0
                          "Inappropriate photometric interpretation %" PRIu16
1723
0
                          " for SGILog compression; %s",
1724
0
                          td->td_photometric, "must be either LogLUV or LogL");
1725
0
            break;
1726
0
    }
1727
0
    return (0);
1728
0
}
1729
1730
static int LogLuvSetupEncode(TIFF *tif)
1731
0
{
1732
0
    static const char module[] = "LogLuvSetupEncode";
1733
0
    LogLuvState *sp = EncoderState(tif);
1734
0
    TIFFDirectory *td = &tif->tif_dir;
1735
1736
0
    switch (td->td_photometric)
1737
0
    {
1738
0
        case PHOTOMETRIC_LOGLUV:
1739
0
            if (!LogLuvInitState(tif))
1740
0
                return (0);
1741
0
            if (td->td_compression == COMPRESSION_SGILOG24)
1742
0
            {
1743
0
                tif->tif_encoderow = LogLuvEncode24;
1744
0
                switch (sp->user_datafmt)
1745
0
                {
1746
0
                    case SGILOGDATAFMT_FLOAT:
1747
0
                        sp->tfunc = Luv24fromXYZ;
1748
0
                        break;
1749
0
                    case SGILOGDATAFMT_16BIT:
1750
0
                        sp->tfunc = Luv24fromLuv48;
1751
0
                        break;
1752
0
                    case SGILOGDATAFMT_RAW:
1753
0
                        break;
1754
0
                    default:
1755
0
                        goto notsupported;
1756
0
                }
1757
0
            }
1758
0
            else
1759
0
            {
1760
0
                tif->tif_encoderow = LogLuvEncode32;
1761
0
                switch (sp->user_datafmt)
1762
0
                {
1763
0
                    case SGILOGDATAFMT_FLOAT:
1764
0
                        sp->tfunc = Luv32fromXYZ;
1765
0
                        break;
1766
0
                    case SGILOGDATAFMT_16BIT:
1767
0
                        sp->tfunc = Luv32fromLuv48;
1768
0
                        break;
1769
0
                    case SGILOGDATAFMT_RAW:
1770
0
                        break;
1771
0
                    default:
1772
0
                        goto notsupported;
1773
0
                }
1774
0
            }
1775
0
            break;
1776
0
        case PHOTOMETRIC_LOGL:
1777
0
            if (!LogL16InitState(tif))
1778
0
                return (0);
1779
0
            tif->tif_encoderow = LogL16Encode;
1780
0
            switch (sp->user_datafmt)
1781
0
            {
1782
0
                case SGILOGDATAFMT_FLOAT:
1783
0
                    sp->tfunc = L16fromY;
1784
0
                    break;
1785
0
                case SGILOGDATAFMT_16BIT:
1786
0
                    break;
1787
0
                default:
1788
0
                    goto notsupported;
1789
0
            }
1790
0
            break;
1791
0
        default:
1792
0
            TIFFErrorExtR(tif, module,
1793
0
                          "Inappropriate photometric interpretation %" PRIu16
1794
0
                          " for SGILog compression; %s",
1795
0
                          td->td_photometric, "must be either LogLUV or LogL");
1796
0
            return (0);
1797
0
    }
1798
0
    sp->encoder_state = 1;
1799
0
    return (1);
1800
0
notsupported:
1801
0
    TIFFErrorExtR(tif, module,
1802
0
                  "SGILog compression supported only for %s, or raw data",
1803
0
                  td->td_photometric == PHOTOMETRIC_LOGL ? "Y, L" : "XYZ, Luv");
1804
0
    return (0);
1805
0
}
1806
1807
static void LogLuvClose(TIFF *tif)
1808
0
{
1809
0
    LogLuvState *sp = (LogLuvState *)tif->tif_data;
1810
0
    TIFFDirectory *td = &tif->tif_dir;
1811
1812
0
    assert(sp != 0);
1813
    /*
1814
     * For consistency, we always want to write out the same
1815
     * bitspersample and sampleformat for our TIFF file,
1816
     * regardless of the data format being used by the application.
1817
     * Since this routine is called after tags have been set but
1818
     * before they have been recorded in the file, we reset them here.
1819
     * Note: this is really a nasty approach. See PixarLogClose
1820
     */
1821
0
    if (sp->encoder_state)
1822
0
    {
1823
        /* See PixarLogClose. Might avoid issues with tags whose size depends
1824
         * on those below, but not completely sure this is enough. */
1825
0
        td->td_samplesperpixel =
1826
0
            (td->td_photometric == PHOTOMETRIC_LOGL) ? 1 : 3;
1827
0
        td->td_bitspersample = 16;
1828
0
        td->td_sampleformat = SAMPLEFORMAT_INT;
1829
0
    }
1830
0
}
1831
1832
static void LogLuvCleanup(TIFF *tif)
1833
0
{
1834
0
    LogLuvState *sp = (LogLuvState *)tif->tif_data;
1835
1836
0
    assert(sp != 0);
1837
1838
0
    tif->tif_tagmethods.vgetfield = sp->vgetparent;
1839
0
    tif->tif_tagmethods.vsetfield = sp->vsetparent;
1840
1841
0
    if (sp->tbuf)
1842
0
        _TIFFfreeExt(tif, sp->tbuf);
1843
0
    _TIFFfreeExt(tif, sp);
1844
0
    tif->tif_data = NULL;
1845
1846
0
    _TIFFSetDefaultCompressionState(tif);
1847
0
}
1848
1849
static int LogLuvVSetField(TIFF *tif, uint32_t tag, va_list ap)
1850
0
{
1851
0
    static const char module[] = "LogLuvVSetField";
1852
0
    LogLuvState *sp = DecoderState(tif);
1853
0
    int bps, fmt;
1854
1855
0
    switch (tag)
1856
0
    {
1857
0
        case TIFFTAG_SGILOGDATAFMT:
1858
0
            sp->user_datafmt = (int)va_arg(ap, int);
1859
            /*
1860
             * Tweak the TIFF header so that the rest of libtiff knows what
1861
             * size of data will be passed between app and library, and
1862
             * assume that the app knows what it is doing and is not
1863
             * confused by these header manipulations...
1864
             */
1865
0
            switch (sp->user_datafmt)
1866
0
            {
1867
0
                case SGILOGDATAFMT_FLOAT:
1868
0
                    bps = 32;
1869
0
                    fmt = SAMPLEFORMAT_IEEEFP;
1870
0
                    break;
1871
0
                case SGILOGDATAFMT_16BIT:
1872
0
                    bps = 16;
1873
0
                    fmt = SAMPLEFORMAT_INT;
1874
0
                    break;
1875
0
                case SGILOGDATAFMT_RAW:
1876
0
                    bps = 32;
1877
0
                    fmt = SAMPLEFORMAT_UINT;
1878
0
                    TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1);
1879
0
                    break;
1880
0
                case SGILOGDATAFMT_8BIT:
1881
0
                    bps = 8;
1882
0
                    fmt = SAMPLEFORMAT_UINT;
1883
0
                    break;
1884
0
                default:
1885
0
                    TIFFErrorExtR(
1886
0
                        tif, tif->tif_name,
1887
0
                        "Unknown data format %d for LogLuv compression",
1888
0
                        sp->user_datafmt);
1889
0
                    return (0);
1890
0
            }
1891
0
            TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps);
1892
0
            TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, fmt);
1893
            /*
1894
             * Must recalculate sizes should bits/sample change.
1895
             */
1896
0
            tif->tif_dir.td_tilesize =
1897
0
                isTiled(tif) ? TIFFTileSize(tif) : (tmsize_t)-1;
1898
0
            tif->tif_dir.td_scanlinesize = TIFFScanlineSize(tif);
1899
0
            return (1);
1900
0
        case TIFFTAG_SGILOGENCODE:
1901
0
            sp->encode_meth = (int)va_arg(ap, int);
1902
0
            if (sp->encode_meth != SGILOGENCODE_NODITHER &&
1903
0
                sp->encode_meth != SGILOGENCODE_RANDITHER)
1904
0
            {
1905
0
                TIFFErrorExtR(tif, module,
1906
0
                              "Unknown encoding %d for LogLuv compression",
1907
0
                              sp->encode_meth);
1908
0
                return (0);
1909
0
            }
1910
0
            return (1);
1911
0
        default:
1912
0
            return (*sp->vsetparent)(tif, tag, ap);
1913
0
    }
1914
0
}
1915
1916
static int LogLuvVGetField(TIFF *tif, uint32_t tag, va_list ap)
1917
0
{
1918
0
    LogLuvState *sp = (LogLuvState *)tif->tif_data;
1919
1920
0
    switch (tag)
1921
0
    {
1922
0
        case TIFFTAG_SGILOGDATAFMT:
1923
0
            *va_arg(ap, int *) = sp->user_datafmt;
1924
0
            return (1);
1925
0
        default:
1926
0
            return (*sp->vgetparent)(tif, tag, ap);
1927
0
    }
1928
0
}
1929
1930
static const TIFFField LogLuvFields[] = {
1931
    {TIFFTAG_SGILOGDATAFMT, 0, 0, TIFF_SHORT, 0, TIFF_SETGET_INT, FIELD_PSEUDO,
1932
     TRUE, FALSE, "SGILogDataFmt", NULL},
1933
    {TIFFTAG_SGILOGENCODE, 0, 0, TIFF_SHORT, 0, TIFF_SETGET_INT, FIELD_PSEUDO,
1934
     TRUE, FALSE, "SGILogEncode", NULL}};
1935
1936
int TIFFInitSGILog(TIFF *tif, int scheme)
1937
0
{
1938
0
    static const char module[] = "TIFFInitSGILog";
1939
0
    LogLuvState *sp;
1940
1941
0
    assert(scheme == COMPRESSION_SGILOG24 || scheme == COMPRESSION_SGILOG);
1942
1943
    /*
1944
     * Merge codec-specific tag information.
1945
     */
1946
0
    if (!_TIFFMergeFields(tif, LogLuvFields, TIFFArrayCount(LogLuvFields)))
1947
0
    {
1948
0
        TIFFErrorExtR(tif, module, "Merging SGILog codec-specific tags failed");
1949
0
        return 0;
1950
0
    }
1951
1952
    /*
1953
     * Allocate state block so tag methods have storage to record values.
1954
     */
1955
0
    tif->tif_data = (uint8_t *)_TIFFmallocExt(tif, sizeof(LogLuvState));
1956
0
    if (tif->tif_data == NULL)
1957
0
        goto bad;
1958
0
    sp = (LogLuvState *)tif->tif_data;
1959
0
    _TIFFmemset((void *)sp, 0, sizeof(*sp));
1960
0
    sp->user_datafmt = SGILOGDATAFMT_UNKNOWN;
1961
0
    sp->encode_meth = (scheme == COMPRESSION_SGILOG24) ? SGILOGENCODE_RANDITHER
1962
0
                                                       : SGILOGENCODE_NODITHER;
1963
0
    sp->tfunc = _logLuvNop;
1964
1965
    /*
1966
     * Install codec methods.
1967
     * NB: tif_decoderow & tif_encoderow are filled
1968
     *     in at setup time.
1969
     */
1970
0
    tif->tif_fixuptags = LogLuvFixupTags;
1971
0
    tif->tif_setupdecode = LogLuvSetupDecode;
1972
0
    tif->tif_decodestrip = LogLuvDecodeStrip;
1973
0
    tif->tif_decodetile = LogLuvDecodeTile;
1974
0
    tif->tif_setupencode = LogLuvSetupEncode;
1975
0
    tif->tif_encodestrip = LogLuvEncodeStrip;
1976
0
    tif->tif_encodetile = LogLuvEncodeTile;
1977
0
    tif->tif_close = LogLuvClose;
1978
0
    tif->tif_cleanup = LogLuvCleanup;
1979
1980
    /*
1981
     * Override parent get/set field methods.
1982
     */
1983
0
    sp->vgetparent = tif->tif_tagmethods.vgetfield;
1984
0
    tif->tif_tagmethods.vgetfield = LogLuvVGetField; /* hook for codec tags */
1985
0
    sp->vsetparent = tif->tif_tagmethods.vsetfield;
1986
0
    tif->tif_tagmethods.vsetfield = LogLuvVSetField; /* hook for codec tags */
1987
1988
0
    return (1);
1989
0
bad:
1990
0
    TIFFErrorExtR(tif, module, "%s: No space for LogLuv state block",
1991
0
                  tif->tif_name);
1992
0
    return (0);
1993
0
}
1994
#endif /* LOGLUV_SUPPORT */