Coverage Report

Created: 2026-09-14 06:50

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