tif_luv.c 48.2 KB
Newer Older
1
/* $Id: tif_luv.c,v 1.35 2011-04-02 20:54:09 bfriesen Exp $ */
2 3 4 5 6

/*
 * Copyright (c) 1997 Greg Ward Larson
 * Copyright (c) 1997 Silicon Graphics, Inc.
 *
7
 * Permission to use, copy, modify, distribute, and sell this software and
8 9 10 11 12 13
 * its documentation for any purpose is hereby granted without fee, provided
 * that (i) the above copyright notices and this permission notice appear in
 * all copies of the software and related documentation, and (ii) the names of
 * Sam Leffler, Greg Larson and Silicon Graphics may not be used in any
 * advertising or publicity relating to the software without the specific,
 * prior written permission of Sam Leffler, Greg Larson and Silicon Graphics.
14 15 16 17 18
 *
 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
 *
19 20 21
 * IN NO EVENT SHALL SAM LEFFLER, GREG LARSON OR SILICON GRAPHICS BE LIABLE
 * FOR ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
22 23
 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
 * OF THIS SOFTWARE.
 */

#include "tiffiop.h"
#ifdef LOGLUV_SUPPORT

/*
 * TIFF Library.
 * LogLuv compression support for high dynamic range images.
 *
 * Contributed by Greg Larson.
 *
 * LogLuv image support uses the TIFF library to store 16 or 10-bit
 * log luminance values with 8 bits each of u and v or a 14-bit index.
 *
39
 * The codec can take as input and produce as output 32-bit IEEE float values
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
 * as well as 16-bit integer values.  A 16-bit luminance is interpreted
 * as a sign bit followed by a 15-bit integer that is converted
 * to and from a linear magnitude using the transformation:
 *
 *	L = 2^( (Le+.5)/256 - 64 )		# real from 15-bit
 *
 *	Le = floor( 256*(log2(L) + 64) )	# 15-bit from real
 *
 * The actual conversion to world luminance units in candelas per sq. meter
 * requires an additional multiplier, which is stored in the TIFFTAG_STONITS.
 * This value is usually set such that a reasonable exposure comes from
 * clamping decoded luminances above 1 to 1 in the displayed image.
 *
 * The 16-bit values for u and v may be converted to real values by dividing
 * each by 32768.  (This allows for negative values, which aren't useful as
 * far as we know, but are left in case of future improvements in human
 * color vision.)
 *
 * Conversion from (u,v), which is actually the CIE (u',v') system for
 * you color scientists, is accomplished by the following transformation:
 *
 *	u = 4*x / (-2*x + 12*y + 3)
 *	v = 9*y / (-2*x + 12*y + 3)
 *
 *	x = 9*u / (6*u - 16*v + 12)
 *	y = 4*v / (6*u - 16*v + 12)
 *
 * This process is greatly simplified by passing 32-bit IEEE floats
 * for each of three CIE XYZ coordinates.  The codec then takes care
 * of conversion to and from LogLuv, though the application is still
 * responsible for interpreting the TIFFTAG_STONITS calibration factor.
 *
 * By definition, a CIE XYZ vector of [1 1 1] corresponds to a neutral white
 * point of (x,y)=(1/3,1/3).  However, most color systems assume some other
 * white point, such as D65, and an absolute color conversion to XYZ then
 * to another color space with a different white point may introduce an
 * unwanted color cast to the image.  It is often desirable, therefore, to
 * perform a white point conversion that maps the input white to [1 1 1]
 * in XYZ, then record the original white point using the TIFFTAG_WHITEPOINT
 * tag value.  A decoder that demands absolute color calibration may use
 * this white point tag to get back the original colors, but usually it
 * will be ignored and the new white point will be used instead that
 * matches the output color space.
 *
 * Pixel information is compressed into one of two basic encodings, depending
 * on the setting of the compression tag, which is one of COMPRESSION_SGILOG
 * or COMPRESSION_SGILOG24.  For COMPRESSION_SGILOG, greyscale data is
 * stored as:
 *
 *	 1       15
 *	|-+---------------|
 *
 * COMPRESSION_SGILOG color data is stored as:
 *
 *	 1       15           8        8
 *	|-+---------------|--------+--------|
 *	 S       Le           ue       ve
 *
 * For the 24-bit COMPRESSION_SGILOG24 color format, the data is stored as:
 *
 *	     10           14
 *	|----------|--------------|
 *	     Le'          Ce
 *
 * There is no sign bit in the 24-bit case, and the (u,v) chromaticity is
 * encoded as an index for optimal color resolution.  The 10 log bits are
 * defined by the following conversions:
 *
 *	L = 2^((Le'+.5)/64 - 12)		# real from 10-bit
 *
 *	Le' = floor( 64*(log2(L) + 12) )	# 10-bit from real
 *
 * The 10 bits of the smaller format may be converted into the 15 bits of
 * the larger format by multiplying by 4 and adding 13314.  Obviously,
 * a smaller range of magnitudes is covered (about 5 orders of magnitude
 * instead of 38), and the lack of a sign bit means that negative luminances
 * are not allowed.  (Well, they aren't allowed in the real world, either,
 * but they are useful for certain types of image processing.)
 *
 * The desired user format is controlled by the setting the internal
 * pseudo tag TIFFTAG_SGILOGDATAFMT to one of:
 *  SGILOGDATAFMT_FLOAT       = IEEE 32-bit float XYZ values
 *  SGILOGDATAFMT_16BIT	      = 16-bit integer encodings of logL, u and v
 * Raw data i/o is also possible using:
 *  SGILOGDATAFMT_RAW         = 32-bit unsigned integer with encoded pixel
 * In addition, the following decoding is provided for ease of display:
 *  SGILOGDATAFMT_8BIT        = 8-bit default RGB gamma-corrected values
 *
 * For grayscale images, we provide the following data formats:
 *  SGILOGDATAFMT_FLOAT       = IEEE 32-bit float Y values
 *  SGILOGDATAFMT_16BIT       = 16-bit integer w/ encoded luminance
 *  SGILOGDATAFMT_8BIT        = 8-bit gray monitor values
 *
 * Note that the COMPRESSION_SGILOG applies a simple run-length encoding
 * scheme by separating the logL, u and v bytes for each row and applying
 * a PackBits type of compression.  Since the 24-bit encoding is not
 * adaptive, the 32-bit color format takes less space in many cases.
 *
 * Further control is provided over the conversion from higher-resolution
 * formats to final encoded values through the pseudo tag
 * TIFFTAG_SGILOGENCODE:
 *  SGILOGENCODE_NODITHER     = do not dither encoded values
 *  SGILOGENCODE_RANDITHER    = apply random dithering during encoding
 *
 * The default value of this tag is SGILOGENCODE_NODITHER for
 * COMPRESSION_SGILOG to maximize run-length encoding and
 * SGILOGENCODE_RANDITHER for COMPRESSION_SGILOG24 to turn
 * quantization errors into noise.
 */

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

/*
 * State block for each open TIFF
 * file using LogLuv compression/decompression.
 */
158
typedef struct logLuvState LogLuvState;
159 160

struct logLuvState {
161 162 163
    int                     user_datafmt;   /* user data format */
    int                     encode_meth;    /* encoding method */
    int                     pixel_size;     /* bytes per pixel */
164

165 166 167
    uint8*                  tbuf;           /* translation buffer */
    tmsize_t                tbuflen;        /* buffer length */
    void (*tfunc)(LogLuvState*, uint8*, tmsize_t);
168

169 170
    TIFFVSetMethod          vgetparent;     /* super-class method */
    TIFFVSetMethod          vsetparent;     /* super-class method */
171 172
};

173 174
#define DecoderState(tif)	((LogLuvState*) (tif)->tif_data)
#define EncoderState(tif)	((LogLuvState*) (tif)->tif_data)
175

176
#define SGILOGDATAFMT_UNKNOWN -1
177

178
#define MINRUN 4 /* minimum run length */
179 180 181 182 183

/*
 * Decode a string of 16-bit gray pixels.
 */
static int
184
LogL16Decode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)
185
{
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
    static const char module[] = "LogL16Decode";
    LogLuvState* sp = DecoderState(tif);
    int shft;
    tmsize_t i;
    tmsize_t npixels;
    unsigned char* bp;
    int16* tp;
    int16 b;
    tmsize_t cc;
    int rc;

    assert(s == 0);
    assert(sp != NULL);

    npixels = occ / sp->pixel_size;

    if (sp->user_datafmt == SGILOGDATAFMT_16BIT)
        tp = (int16*) op;
    else {
        assert(sp->tbuflen >= npixels);
        tp = (int16*) sp->tbuf;
    }
    _TIFFmemset((void*) tp, 0, npixels*sizeof (tp[0]));

    bp = (unsigned char*) tif->tif_rawcp;
    cc = tif->tif_rawcc;
    /* get each byte string */
    for (shft = 2*8; (shft -= 8) >= 0; ) {
        for (i = 0; i < npixels && cc > 0; )
            if (*bp >= 128) {		/* run */
                rc = *bp++ + (2-128);   /* TODO: potential input buffer overrun when decoding corrupt or truncated data */
                b = (int16)(*bp++ << shft);
                cc -= 2;
                while (rc-- && i < npixels)
                    tp[i++] |= b;
            } else {			/* non-run */
                rc = *bp++;		/* nul is noop */
                while (--cc && rc-- && i < npixels)
                    tp[i++] |= (int16)*bp++ << shft;
            }
        if (i != npixels) {
227
#if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
228 229 230 231
            TIFFErrorExt(tif->tif_clientdata, module,
                "Not enough data at row %lu (short %I64d pixels)",
                     (unsigned long) tif->tif_row,
                     (unsigned __int64) (npixels - i));
232
#else
233 234 235 236
            TIFFErrorExt(tif->tif_clientdata, module,
                "Not enough data at row %lu (short %llu pixels)",
                     (unsigned long) tif->tif_row,
                     (unsigned long long) (npixels - i));
237
#endif
238 239 240 241 242 243 244 245 246
            tif->tif_rawcp = (uint8*) bp;
            tif->tif_rawcc = cc;
            return (0);
        }
    }
    (*sp->tfunc)(sp, op, npixels);
    tif->tif_rawcp = (uint8*) bp;
    tif->tif_rawcc = cc;
    return (1);
247 248 249 250 251 252
}

/*
 * Decode a string of 24-bit pixels.
 */
static int
253
LogLuvDecode24(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)
254
{
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
    static const char module[] = "LogLuvDecode24";
    LogLuvState* sp = DecoderState(tif);
    tmsize_t cc;
    tmsize_t i;
    tmsize_t npixels;
    unsigned char* bp;
    uint32* tp;

    assert(s == 0);
    assert(sp != NULL);

    npixels = occ / sp->pixel_size;

    if (sp->user_datafmt == SGILOGDATAFMT_RAW)
        tp = (uint32 *)op;
    else {
        assert(sp->tbuflen >= npixels);
        tp = (uint32 *) sp->tbuf;
    }
    /* copy to array of uint32 */
    bp = (unsigned char*) tif->tif_rawcp;
    cc = tif->tif_rawcc;
    for (i = 0; i < npixels && cc > 0; i++) {
        tp[i] = bp[0] << 16 | bp[1] << 8 | bp[2];
        bp += 3;
        cc -= 3;
    }
    tif->tif_rawcp = (uint8*) bp;
    tif->tif_rawcc = cc;
    if (i != npixels) {
285
#if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
286 287 288 289
        TIFFErrorExt(tif->tif_clientdata, module,
            "Not enough data at row %lu (short %I64d pixels)",
                 (unsigned long) tif->tif_row,
                 (unsigned __int64) (npixels - i));
290
#else
291 292 293 294
        TIFFErrorExt(tif->tif_clientdata, module,
            "Not enough data at row %lu (short %llu pixels)",
                 (unsigned long) tif->tif_row,
                 (unsigned long long) (npixels - i));
295
#endif
296 297 298 299
        return (0);
    }
    (*sp->tfunc)(sp, op, npixels);
    return (1);
300 301 302 303 304 305
}

/*
 * Decode a string of 32-bit pixels.
 */
static int
306
LogLuvDecode32(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)
307
{
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
    static const char module[] = "LogLuvDecode32";
    LogLuvState* sp;
    int shft;
    tmsize_t i;
    tmsize_t npixels;
    unsigned char* bp;
    uint32* tp;
    uint32 b;
    tmsize_t cc;
    int rc;

    assert(s == 0);
    sp = DecoderState(tif);
    assert(sp != NULL);

    npixels = occ / sp->pixel_size;

    if (sp->user_datafmt == SGILOGDATAFMT_RAW)
        tp = (uint32*) op;
    else {
        assert(sp->tbuflen >= npixels);
        tp = (uint32*) sp->tbuf;
    }
    _TIFFmemset((void*) tp, 0, npixels*sizeof (tp[0]));

    bp = (unsigned char*) tif->tif_rawcp;
    cc = tif->tif_rawcc;
    /* get each byte string */
    for (shft = 4*8; (shft -= 8) >= 0; ) {
        for (i = 0; i < npixels && cc > 0; )
            if (*bp >= 128) {		/* run */
                rc = *bp++ + (2-128);
                b = (uint32)*bp++ << shft;
                cc -= 2;                /* TODO: potential input buffer overrun when decoding corrupt or truncated data */
                while (rc-- && i < npixels)
                    tp[i++] |= b;
            } else {			/* non-run */
                rc = *bp++;		/* nul is noop */
                while (--cc && rc-- && i < npixels)
                    tp[i++] |= (uint32)*bp++ << shft;
            }
        if (i != npixels) {
350
#if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
351 352 353 354
            TIFFErrorExt(tif->tif_clientdata, module,
            "Not enough data at row %lu (short %I64d pixels)",
                     (unsigned long) tif->tif_row,
                     (unsigned __int64) (npixels - i));
355
#else
356 357 358 359
            TIFFErrorExt(tif->tif_clientdata, module,
            "Not enough data at row %lu (short %llu pixels)",
                     (unsigned long) tif->tif_row,
                     (unsigned long long) (npixels - i));
360
#endif
361 362 363 364 365 366 367 368 369
            tif->tif_rawcp = (uint8*) bp;
            tif->tif_rawcc = cc;
            return (0);
        }
    }
    (*sp->tfunc)(sp, op, npixels);
    tif->tif_rawcp = (uint8*) bp;
    tif->tif_rawcc = cc;
    return (1);
370 371 372 373 374 375 376 377
}

/*
 * Decode a strip of pixels.  We break it into rows to
 * maintain synchrony with the encode algorithm, which
 * is row by row.
 */
static int
378
LogLuvDecodeStrip(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
379
{
380
    tmsize_t rowlen = TIFFScanlineSize(tif);
381

382 383 384 385
    assert(cc%rowlen == 0);
    while (cc && (*tif->tif_decoderow)(tif, bp, rowlen, s))
        bp += rowlen, cc -= rowlen;
    return (cc == 0);
386 387 388 389 390 391 392 393
}

/*
 * Decode a tile of pixels.  We break it into rows to
 * maintain synchrony with the encode algorithm, which
 * is row by row.
 */
static int
394
LogLuvDecodeTile(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
395
{
396
    tmsize_t rowlen = TIFFTileRowSize(tif);
397

398 399 400 401
    assert(cc%rowlen == 0);
    while (cc && (*tif->tif_decoderow)(tif, bp, rowlen, s))
        bp += rowlen, cc -= rowlen;
    return (cc == 0);
402 403 404 405 406 407
}

/*
 * Encode a row of 16-bit pixels.
 */
static int
408
LogL16Encode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
409
{
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
    LogLuvState* sp = EncoderState(tif);
    int shft;
    tmsize_t i;
    tmsize_t j;
    tmsize_t npixels;
    uint8* op;
    int16* tp;
    int16 b;
    tmsize_t occ;
    int rc=0, mask;
    tmsize_t beg;

    assert(s == 0);
    assert(sp != NULL);
    npixels = cc / sp->pixel_size;

    if (sp->user_datafmt == SGILOGDATAFMT_16BIT)
        tp = (int16*) bp;
    else {
        tp = (int16*) sp->tbuf;
        assert(sp->tbuflen >= npixels);
        (*sp->tfunc)(sp, bp, npixels);
    }
    /* compress each byte string */
    op = tif->tif_rawcp;
    occ = tif->tif_rawdatasize - tif->tif_rawcc;
    for (shft = 2*8; (shft -= 8) >= 0; )
        for (i = 0; i < npixels; i += rc) {
            if (occ < 4) {
                tif->tif_rawcp = op;
                tif->tif_rawcc = tif->tif_rawdatasize - occ;
                if (!TIFFFlushData1(tif))
                    return (-1);
                op = tif->tif_rawcp;
                occ = tif->tif_rawdatasize - tif->tif_rawcc;
            }
            mask = 0xff << shft;		/* find next run */
            for (beg = i; beg < npixels; beg += rc) {
                b = (int16) (tp[beg] & mask);
                rc = 1;
                while (rc < 127+2 && beg+rc < npixels &&
                    (tp[beg+rc] & mask) == b)
                    rc++;
                if (rc >= MINRUN)
                    break;		/* long enough */
            }
            if (beg-i > 1 && beg-i < MINRUN) {
                b = (int16) (tp[i] & mask);/*check short run */
                j = i+1;
                while ((tp[j++] & mask) == b)
                    if (j == beg) {
                        *op++ = (uint8)(128-2+j-i);
                        *op++ = (uint8)(b >> shft);
                        occ -= 2;
                        i = beg;
                        break;
                    }
            }
            while (i < beg) {		/* write out non-run */
                if ((j = beg-i) > 127) j = 127;
                if (occ < j+3) {
                    tif->tif_rawcp = op;
                    tif->tif_rawcc = tif->tif_rawdatasize - occ;
                    if (!TIFFFlushData1(tif))
                        return (-1);
                    op = tif->tif_rawcp;
                    occ = tif->tif_rawdatasize - tif->tif_rawcc;
                }
                *op++ = (uint8) j; occ--;
                while (j--) {
                    *op++ = (uint8) (tp[i++] >> shft & 0xff);
                    occ--;
                }
            }
            if (rc >= MINRUN) {		/* write out run */
                *op++ = (uint8) (128-2+rc);
                *op++ = (uint8) (tp[beg] >> shft & 0xff);
                occ -= 2;
            } else
                rc = 0;
        }
    tif->tif_rawcp = op;
    tif->tif_rawcc = tif->tif_rawdatasize - occ;

    return (1);
495 496 497 498 499 500
}

/*
 * Encode a row of 24-bit pixels.
 */
static int
501
LogLuvEncode24(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
502
{
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
    LogLuvState* sp = EncoderState(tif);
    tmsize_t i;
    tmsize_t npixels;
    tmsize_t occ;
    uint8* op;
    uint32* tp;

    assert(s == 0);
    assert(sp != NULL);
    npixels = cc / sp->pixel_size;

    if (sp->user_datafmt == SGILOGDATAFMT_RAW)
        tp = (uint32*) bp;
    else {
        tp = (uint32*) sp->tbuf;
        assert(sp->tbuflen >= npixels);
        (*sp->tfunc)(sp, bp, npixels);
    }
    /* write out encoded pixels */
    op = tif->tif_rawcp;
    occ = tif->tif_rawdatasize - tif->tif_rawcc;
    for (i = npixels; i--; ) {
        if (occ < 3) {
            tif->tif_rawcp = op;
            tif->tif_rawcc = tif->tif_rawdatasize - occ;
            if (!TIFFFlushData1(tif))
                return (-1);
            op = tif->tif_rawcp;
            occ = tif->tif_rawdatasize - tif->tif_rawcc;
        }
        *op++ = (uint8)(*tp >> 16);
        *op++ = (uint8)(*tp >> 8 & 0xff);
        *op++ = (uint8)(*tp++ & 0xff);
        occ -= 3;
    }
    tif->tif_rawcp = op;
    tif->tif_rawcc = tif->tif_rawdatasize - occ;

    return (1);
542 543 544 545 546 547
}

/*
 * Encode a row of 32-bit pixels.
 */
static int
548
LogLuvEncode32(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
549
{
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
    LogLuvState* sp = EncoderState(tif);
    int shft;
    tmsize_t i;
    tmsize_t j;
    tmsize_t npixels;
    uint8* op;
    uint32* tp;
    uint32 b;
    tmsize_t occ;
    int rc=0, mask;
    tmsize_t beg;

    assert(s == 0);
    assert(sp != NULL);

    npixels = cc / sp->pixel_size;

    if (sp->user_datafmt == SGILOGDATAFMT_RAW)
        tp = (uint32*) bp;
    else {
        tp = (uint32*) sp->tbuf;
        assert(sp->tbuflen >= npixels);
        (*sp->tfunc)(sp, bp, npixels);
    }
    /* compress each byte string */
    op = tif->tif_rawcp;
    occ = tif->tif_rawdatasize - tif->tif_rawcc;
    for (shft = 4*8; (shft -= 8) >= 0; )
        for (i = 0; i < npixels; i += rc) {
            if (occ < 4) {
                tif->tif_rawcp = op;
                tif->tif_rawcc = tif->tif_rawdatasize - occ;
                if (!TIFFFlushData1(tif))
                    return (-1);
                op = tif->tif_rawcp;
                occ = tif->tif_rawdatasize - tif->tif_rawcc;
            }
            mask = 0xff << shft;		/* find next run */
            for (beg = i; beg < npixels; beg += rc) {
                b = tp[beg] & mask;
                rc = 1;
                while (rc < 127+2 && beg+rc < npixels &&
                        (tp[beg+rc] & mask) == b)
                    rc++;
                if (rc >= MINRUN)
                    break;		/* long enough */
            }
            if (beg-i > 1 && beg-i < MINRUN) {
                b = tp[i] & mask;	/* check short run */
                j = i+1;
                while ((tp[j++] & mask) == b)
                    if (j == beg) {
                        *op++ = (uint8)(128-2+j-i);
                        *op++ = (uint8)(b >> shft);
                        occ -= 2;
                        i = beg;
                        break;
                    }
            }
            while (i < beg) {		/* write out non-run */
                if ((j = beg-i) > 127) j = 127;
                if (occ < j+3) {
                    tif->tif_rawcp = op;
                    tif->tif_rawcc = tif->tif_rawdatasize - occ;
                    if (!TIFFFlushData1(tif))
                        return (-1);
                    op = tif->tif_rawcp;
                    occ = tif->tif_rawdatasize - tif->tif_rawcc;
                }
                *op++ = (uint8) j; occ--;
                while (j--) {
                    *op++ = (uint8)(tp[i++] >> shft & 0xff);
                    occ--;
                }
            }
            if (rc >= MINRUN) {		/* write out run */
                *op++ = (uint8) (128-2+rc);
                *op++ = (uint8)(tp[beg] >> shft & 0xff);
                occ -= 2;
            } else
                rc = 0;
        }
    tif->tif_rawcp = op;
    tif->tif_rawcc = tif->tif_rawdatasize - occ;

    return (1);
636 637 638 639 640 641 642
}

/*
 * Encode a strip of pixels.  We break it into rows to
 * avoid encoding runs across row boundaries.
 */
static int
643
LogLuvEncodeStrip(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
644
{
645
    tmsize_t rowlen = TIFFScanlineSize(tif);
646

647 648 649 650
    assert(cc%rowlen == 0);
    while (cc && (*tif->tif_encoderow)(tif, bp, rowlen, s) == 1)
        bp += rowlen, cc -= rowlen;
    return (cc == 0);
651 652 653 654 655 656 657
}

/*
 * Encode a tile of pixels.  We break it into rows to
 * avoid encoding runs across row boundaries.
 */
static int
658
LogLuvEncodeTile(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
659
{
660
    tmsize_t rowlen = TIFFTileRowSize(tif);
661

662 663 664 665
    assert(cc%rowlen == 0);
    while (cc && (*tif->tif_encoderow)(tif, bp, rowlen, s) == 1)
        bp += rowlen, cc -= rowlen;
    return (cc == 0);
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
}

/*
 * Encode/Decode functions for converting to and from user formats.
 */

#include "uvcode.h"

#ifndef UVSCALE
#define U_NEU		0.210526316
#define V_NEU		0.473684211
#define UVSCALE		410.
#endif

#ifndef	M_LN2
#define M_LN2		0.69314718055994530942
#endif
#ifndef M_PI
#define M_PI		3.14159265358979323846
#endif
#define log2(x)		((1./M_LN2)*log(x))
#define exp2(x)		exp(M_LN2*(x))

#define itrunc(x,m)	((m)==SGILOGENCODE_NODITHER ? \
690 691
                (int)(x) : \
                (int)((x) + rand()*(1./RAND_MAX) - .5))
692 693 694 695 696 697 698

#if !LOGLUV_PUBLIC
static
#endif
double
LogL16toY(int p16)		/* compute luminance from 16-bit LogL */
{
699 700
    int	Le = p16 & 0x7fff;
    double	Y;
701

702 703 704 705
    if (!Le)
        return (0.);
    Y = exp(M_LN2/256.*(Le+.5) - M_LN2*64.);
    return (!(p16 & 0x8000) ? Y : -Y);
706 707 708 709 710 711 712 713
}

#if !LOGLUV_PUBLIC
static
#endif
int
LogL16fromY(double Y, int em)	/* get 16-bit LogL from Y */
{
714 715 716 717 718 719 720 721 722
    if (Y >= 1.8371976e19)
        return (0x7fff);
    if (Y <= -1.8371976e19)
        return (0xffff);
    if (Y > 5.4136769e-20)
        return itrunc(256.*(log2(Y) + 64.), em);
    if (Y < -5.4136769e-20)
        return (~0x7fff | itrunc(256.*(log2(-Y) + 64.), em));
    return (0);
723 724 725
}

static void
726
L16toY(LogLuvState* sp, uint8* op, tmsize_t n)
727
{
728 729
    int16* l16 = (int16*) sp->tbuf;
    float* yp = (float*) op;
730

731 732
    while (n-- > 0)
        *yp++ = (float)LogL16toY(*l16++);
733 734 735
}

static void
736
L16toGry(LogLuvState* sp, uint8* op, tmsize_t n)
737
{
738 739
    int16* l16 = (int16*) sp->tbuf;
    uint8* gp = (uint8*) op;
740

741 742 743 744
    while (n-- > 0) {
        double Y = LogL16toY(*l16++);
        *gp++ = (uint8) ((Y <= 0.) ? 0 : (Y >= 1.) ? 255 : (int)(256.*sqrt(Y)));
    }
745 746 747
}

static void
748
L16fromY(LogLuvState* sp, uint8* op, tmsize_t n)
749
{
750 751
    int16* l16 = (int16*) sp->tbuf;
    float* yp = (float*) op;
752

753 754
    while (n-- > 0)
        *l16++ = (int16) (LogL16fromY(*yp++, sp->encode_meth));
755 756 757 758 759 760 761 762
}

#if !LOGLUV_PUBLIC
static
#endif
void
XYZtoRGB24(float xyz[3], uint8 rgb[3])
{
763 764 765 766 767 768 769 770 771 772
    double	r, g, b;
                    /* assume CCIR-709 primaries */
    r =  2.690*xyz[0] + -1.276*xyz[1] + -0.414*xyz[2];
    g = -1.022*xyz[0] +  1.978*xyz[1] +  0.044*xyz[2];
    b =  0.061*xyz[0] + -0.224*xyz[1] +  1.163*xyz[2];
                    /* assume 2.0 gamma for speed */
    /* could use integer sqrt approx., but this is probably faster */
    rgb[0] = (uint8)((r<=0.) ? 0 : (r >= 1.) ? 255 : (int)(256.*sqrt(r)));
    rgb[1] = (uint8)((g<=0.) ? 0 : (g >= 1.) ? 255 : (int)(256.*sqrt(g)));
    rgb[2] = (uint8)((b<=0.) ? 0 : (b >= 1.) ? 255 : (int)(256.*sqrt(b)));
773 774 775 776 777 778 779 780
}

#if !LOGLUV_PUBLIC
static
#endif
double
LogL10toY(int p10)		/* compute luminance from 10-bit LogL */
{
781 782 783
    if (p10 == 0)
        return (0.);
    return (exp(M_LN2/64.*(p10+.5) - M_LN2*12.));
784 785 786 787 788 789 790 791
}

#if !LOGLUV_PUBLIC
static
#endif
int
LogL10fromY(double Y, int em)	/* get 10-bit LogL from Y */
{
792 793 794 795 796 797
    if (Y >= 15.742)
        return (0x3ff);
    else if (Y <= .00024283)
        return (0);
    else
        return itrunc(64.*(log2(Y) + 12.), em);
798 799 800 801
}

#define NANGLES		100
#define uv2ang(u, v)	( (NANGLES*.499999999/M_PI) \
802
                * atan2((v)-V_NEU,(u)-U_NEU) + .5*NANGLES )
803 804 805 806

static int
oog_encode(double u, double v)		/* encode out-of-gamut chroma */
{
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
    static int	oog_table[NANGLES];
    static int	initialized = 0;
    register int	i;

    if (!initialized) {		/* set up perimeter table */
        double	eps[NANGLES], ua, va, ang, epsa;
        int	ui, vi, ustep;
        for (i = NANGLES; i--; )
            eps[i] = 2.;
        for (vi = UV_NVS; vi--; ) {
            va = UV_VSTART + (vi+.5)*UV_SQSIZ;
            ustep = uv_row[vi].nus-1;
            if (vi == UV_NVS-1 || vi == 0 || ustep <= 0)
                ustep = 1;
            for (ui = uv_row[vi].nus-1; ui >= 0; ui -= ustep) {
                ua = uv_row[vi].ustart + (ui+.5)*UV_SQSIZ;
                ang = uv2ang(ua, va);
                i = (int) ang;
                epsa = fabs(ang - (i+.5));
                if (epsa < eps[i]) {
                    oog_table[i] = uv_row[vi].ncum + ui;
                    eps[i] = epsa;
                }
            }
        }
        for (i = NANGLES; i--; )	/* fill any holes */
            if (eps[i] > 1.5) {
                int	i1, i2;
                for (i1 = 1; i1 < NANGLES/2; i1++)
                    if (eps[(i+i1)%NANGLES] < 1.5)
                        break;
                for (i2 = 1; i2 < NANGLES/2; i2++)
                    if (eps[(i+NANGLES-i2)%NANGLES] < 1.5)
                        break;
                if (i1 < i2)
                    oog_table[i] =
                        oog_table[(i+i1)%NANGLES];
                else
                    oog_table[i] =
                        oog_table[(i+NANGLES-i2)%NANGLES];
            }
        initialized = 1;
    }
    i = (int) uv2ang(u, v);		/* look up hue angle */
    return (oog_table[i]);
852 853 854 855 856 857 858 859 860 861 862
}

#undef uv2ang
#undef NANGLES

#if !LOGLUV_PUBLIC
static
#endif
int
uv_encode(double u, double v, int em)	/* encode (u',v') coordinates */
{
863 864 865 866 867 868 869 870 871 872 873 874 875 876
    register int	vi, ui;

    if (v < UV_VSTART)
        return oog_encode(u, v);
    vi = itrunc((v - UV_VSTART)*(1./UV_SQSIZ), em);
    if (vi >= UV_NVS)
        return oog_encode(u, v);
    if (u < uv_row[vi].ustart)
        return oog_encode(u, v);
    ui = itrunc((u - uv_row[vi].ustart)*(1./UV_SQSIZ), em);
    if (ui >= uv_row[vi].nus)
        return oog_encode(u, v);

    return (uv_row[vi].ncum + ui);
877 878 879 880 881 882 883 884
}

#if !LOGLUV_PUBLIC
static
#endif
int
uv_decode(double *up, double *vp, int c)	/* decode (u',v') index */
{
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
    int	upper, lower;
    register int	ui, vi;

    if (c < 0 || c >= UV_NDIVS)
        return (-1);
    lower = 0;				/* binary search */
    upper = UV_NVS;
    while (upper - lower > 1) {
        vi = (lower + upper) >> 1;
        ui = c - uv_row[vi].ncum;
        if (ui > 0)
            lower = vi;
        else if (ui < 0)
            upper = vi;
        else {
            lower = vi;
            break;
        }
    }
    vi = lower;
    ui = c - uv_row[vi].ncum;
    *up = uv_row[vi].ustart + (ui+.5)*UV_SQSIZ;
    *vp = UV_VSTART + (vi+.5)*UV_SQSIZ;
    return (0);
909 910 911 912 913 914 915 916
}

#if !LOGLUV_PUBLIC
static
#endif
void
LogLuv24toXYZ(uint32 p, float XYZ[3])
{
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
    int	Ce;
    double	L, u, v, s, x, y;
                    /* decode luminance */
    L = LogL10toY(p>>14 & 0x3ff);
    if (L <= 0.) {
        XYZ[0] = XYZ[1] = XYZ[2] = 0.;
        return;
    }
                    /* decode color */
    Ce = p & 0x3fff;
    if (uv_decode(&u, &v, Ce) < 0) {
        u = U_NEU; v = V_NEU;
    }
    s = 1./(6.*u - 16.*v + 12.);
    x = 9.*u * s;
    y = 4.*v * s;
                    /* convert to XYZ */
    XYZ[0] = (float)(x/y * L);
    XYZ[1] = (float)L;
    XYZ[2] = (float)((1.-x-y)/y * L);
937 938 939 940 941 942 943 944
}

#if !LOGLUV_PUBLIC
static
#endif
uint32
LogLuv24fromXYZ(float XYZ[3], int em)
{
945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
    int	Le, Ce;
    double	u, v, s;
                    /* encode luminance */
    Le = LogL10fromY(XYZ[1], em);
                    /* encode color */
    s = XYZ[0] + 15.*XYZ[1] + 3.*XYZ[2];
    if (!Le || s <= 0.) {
        u = U_NEU;
        v = V_NEU;
    } else {
        u = 4.*XYZ[0] / s;
        v = 9.*XYZ[1] / s;
    }
    Ce = uv_encode(u, v, em);
    if (Ce < 0)			/* never happens */
        Ce = uv_encode(U_NEU, V_NEU, SGILOGENCODE_NODITHER);
                    /* combine encodings */
    return (Le << 14 | Ce);
963 964 965
}

static void
966
Luv24toXYZ(LogLuvState* sp, uint8* op, tmsize_t n)
967
{
968 969 970 971 972 973 974 975
    uint32* luv = (uint32*) sp->tbuf;
    float* xyz = (float*) op;

    while (n-- > 0) {
        LogLuv24toXYZ(*luv, xyz);
        xyz += 3;
        luv++;
    }
976 977 978
}

static void
979
Luv24toLuv48(LogLuvState* sp, uint8* op, tmsize_t n)
980
{
981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
    uint32* luv = (uint32*) sp->tbuf;
    int16* luv3 = (int16*) op;

    while (n-- > 0) {
        double u, v;

        *luv3++ = (int16)((*luv >> 12 & 0xffd) + 13314);
        if (uv_decode(&u, &v, *luv&0x3fff) < 0) {
            u = U_NEU;
            v = V_NEU;
        }
        *luv3++ = (int16)(u * (1L<<15));
        *luv3++ = (int16)(v * (1L<<15));
        luv++;
    }
996 997 998
}

static void
999
Luv24toRGB(LogLuvState* sp, uint8* op, tmsize_t n)
1000
{
1001 1002
    uint32* luv = (uint32*) sp->tbuf;
    uint8* rgb = (uint8*) op;
1003

1004 1005
    while (n-- > 0) {
        float xyz[3];
1006

1007 1008 1009 1010
        LogLuv24toXYZ(*luv++, xyz);
        XYZtoRGB24(xyz, rgb);
        rgb += 3;
    }
1011 1012 1013
}

static void
1014
Luv24fromXYZ(LogLuvState* sp, uint8* op, tmsize_t n)
1015
{
1016 1017
    uint32* luv = (uint32*) sp->tbuf;
    float* xyz = (float*) op;
1018

1019 1020 1021 1022
    while (n-- > 0) {
        *luv++ = LogLuv24fromXYZ(xyz, sp->encode_meth);
        xyz += 3;
    }
1023 1024 1025
}

static void
1026
Luv24fromLuv48(LogLuvState* sp, uint8* op, tmsize_t n)
1027
{
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
    uint32* luv = (uint32*) sp->tbuf;
    int16* luv3 = (int16*) op;

    while (n-- > 0) {
        int Le, Ce;

        if (luv3[0] <= 0)
            Le = 0;
        else if (luv3[0] >= (1<<12)+3314)
            Le = (1<<10) - 1;
        else if (sp->encode_meth == SGILOGENCODE_NODITHER)
            Le = (luv3[0]-3314) >> 2;
        else
            Le = itrunc(.25*(luv3[0]-3314.), sp->encode_meth);

        Ce = uv_encode((luv3[1]+.5)/(1<<15), (luv3[2]+.5)/(1<<15),
                    sp->encode_meth);
        if (Ce < 0)	/* never happens */
            Ce = uv_encode(U_NEU, V_NEU, SGILOGENCODE_NODITHER);
        *luv++ = (uint32)Le << 14 | Ce;
        luv3 += 3;
    }
1050 1051 1052 1053 1054 1055 1056 1057
}

#if !LOGLUV_PUBLIC
static
#endif
void
LogLuv32toXYZ(uint32 p, float XYZ[3])
{
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
    double	L, u, v, s, x, y;
                    /* decode luminance */
    L = LogL16toY((int)p >> 16);
    if (L <= 0.) {
        XYZ[0] = XYZ[1] = XYZ[2] = 0.;
        return;
    }
                    /* decode color */
    u = 1./UVSCALE * ((p>>8 & 0xff) + .5);
    v = 1./UVSCALE * ((p & 0xff) + .5);
    s = 1./(6.*u - 16.*v + 12.);
    x = 9.*u * s;
    y = 4.*v * s;
                    /* convert to XYZ */
    XYZ[0] = (float)(x/y * L);
    XYZ[1] = (float)L;
    XYZ[2] = (float)((1.-x-y)/y * L);
1075 1076 1077 1078 1079 1080 1081 1082
}

#if !LOGLUV_PUBLIC
static
#endif
uint32
LogLuv32fromXYZ(float XYZ[3], int em)
{
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
    unsigned int	Le, ue, ve;
    double	u, v, s;
                    /* encode luminance */
    Le = (unsigned int)LogL16fromY(XYZ[1], em);
                    /* encode color */
    s = XYZ[0] + 15.*XYZ[1] + 3.*XYZ[2];
    if (!Le || s <= 0.) {
        u = U_NEU;
        v = V_NEU;
    } else {
        u = 4.*XYZ[0] / s;
        v = 9.*XYZ[1] / s;
    }
    if (u <= 0.) ue = 0;
    else ue = itrunc(UVSCALE*u, em);
    if (ue > 255) ue = 255;
    if (v <= 0.) ve = 0;
    else ve = itrunc(UVSCALE*v, em);
    if (ve > 255) ve = 255;
                    /* combine encodings */
    return (Le << 16 | ue << 8 | ve);
1104 1105 1106
}

static void
1107
Luv32toXYZ(LogLuvState* sp, uint8* op, tmsize_t n)
1108
{
1109 1110
    uint32* luv = (uint32*) sp->tbuf;
    float* xyz = (float*) op;
1111

1112 1113 1114 1115
    while (n-- > 0) {
        LogLuv32toXYZ(*luv++, xyz);
        xyz += 3;
    }
1116 1117 1118
}

static void
1119
Luv32toLuv48(LogLuvState* sp, uint8* op, tmsize_t n)
1120
{
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
    uint32* luv = (uint32*) sp->tbuf;
    int16* luv3 = (int16*) op;

    while (n-- > 0) {
        double u, v;

        *luv3++ = (int16)(*luv >> 16);
        u = 1./UVSCALE * ((*luv>>8 & 0xff) + .5);
        v = 1./UVSCALE * ((*luv & 0xff) + .5);
        *luv3++ = (int16)(u * (1L<<15));
        *luv3++ = (int16)(v * (1L<<15));
        luv++;
    }
1134 1135 1136
}

static void
1137
Luv32toRGB(LogLuvState* sp, uint8* op, tmsize_t n)
1138
{
1139 1140
    uint32* luv = (uint32*) sp->tbuf;
    uint8* rgb = (uint8*) op;
1141

1142 1143
    while (n-- > 0) {
        float xyz[3];
1144

1145 1146 1147 1148
        LogLuv32toXYZ(*luv++, xyz);
        XYZtoRGB24(xyz, rgb);
        rgb += 3;
    }
1149 1150 1151
}

static void
1152
Luv32fromXYZ(LogLuvState* sp, uint8* op, tmsize_t n)
1153
{
1154 1155
    uint32* luv = (uint32*) sp->tbuf;
    float* xyz = (float*) op;
1156

1157 1158 1159 1160
    while (n-- > 0) {
        *luv++ = LogLuv32fromXYZ(xyz, sp->encode_meth);
        xyz += 3;
    }
1161 1162 1163
}

static void
1164
Luv32fromLuv48(LogLuvState* sp, uint8* op, tmsize_t n)
1165
{
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
    uint32* luv = (uint32*) sp->tbuf;
    int16* luv3 = (int16*) op;

    if (sp->encode_meth == SGILOGENCODE_NODITHER) {
        while (n-- > 0) {
            *luv++ = (uint32)luv3[0] << 16 |
                (luv3[1]*(uint32)(UVSCALE+.5) >> 7 & 0xff00) |
                (luv3[2]*(uint32)(UVSCALE+.5) >> 15 & 0xff);
            luv3 += 3;
        }
        return;
    }
    while (n-- > 0) {
        *luv++ = (uint32)luv3[0] << 16 |
    (itrunc(luv3[1]*(UVSCALE/(1<<15)), sp->encode_meth) << 8 & 0xff00) |
        (itrunc(luv3[2]*(UVSCALE/(1<<15)), sp->encode_meth) & 0xff);
        luv3 += 3;
    }
1184 1185 1186
}

static void
1187
_logLuvNop(LogLuvState* sp, uint8* op, tmsize_t n)
1188
{
1189
    (void) sp; (void) op; (void) n;
1190 1191 1192 1193 1194 1195
}

static int
LogL16GuessDataFmt(TIFFDirectory *td)
{
#define	PACK(s,b,f)	(((b)<<6)|((s)<<3)|(f))
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
    switch (PACK(td->td_samplesperpixel, td->td_bitspersample, td->td_sampleformat)) {
    case PACK(1, 32, SAMPLEFORMAT_IEEEFP):
        return (SGILOGDATAFMT_FLOAT);
    case PACK(1, 16, SAMPLEFORMAT_VOID):
    case PACK(1, 16, SAMPLEFORMAT_INT):
    case PACK(1, 16, SAMPLEFORMAT_UINT):
        return (SGILOGDATAFMT_16BIT);
    case PACK(1,  8, SAMPLEFORMAT_VOID):
    case PACK(1,  8, SAMPLEFORMAT_UINT):
        return (SGILOGDATAFMT_8BIT);
    }
1207
#undef PACK
1208
    return (SGILOGDATAFMT_UNKNOWN);
1209 1210
}

1211 1212
static tmsize_t
multiply_ms(tmsize_t m1, tmsize_t m2)
1213
{
1214
    tmsize_t bytes = m1 * m2;
1215

1216 1217
    if (m1 && bytes / m1 != m2)
        bytes = 0;
1218

1219
    return bytes;
1220 1221 1222 1223 1224
}

static int
LogL16InitState(TIFF* tif)
{
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
    static const char module[] = "LogL16InitState";
    TIFFDirectory *td = &tif->tif_dir;
    LogLuvState* sp = DecoderState(tif);

    assert(sp != NULL);
    assert(td->td_photometric == PHOTOMETRIC_LOGL);

    /* for some reason, we can't do this in TIFFInitLogL16 */
    if (sp->user_datafmt == SGILOGDATAFMT_UNKNOWN)
        sp->user_datafmt = LogL16GuessDataFmt(td);
    switch (sp->user_datafmt) {
    case SGILOGDATAFMT_FLOAT:
        sp->pixel_size = sizeof (float);
        break;
    case SGILOGDATAFMT_16BIT:
        sp->pixel_size = sizeof (int16);
        break;
    case SGILOGDATAFMT_8BIT:
        sp->pixel_size = sizeof (uint8);
        break;
    default:
        TIFFErrorExt(tif->tif_clientdata, module,
            "No support for converting user data format to LogL");
        return (0);
    }
1250
        if( isTiled(tif) )
1251
            sp->tbuflen = multiply_ms(td->td_tilewidth, td->td_tilelength);
1252
        else
1253
            sp->tbuflen = multiply_ms(td->td_imagewidth, td->td_rowsperstrip);
1254 1255 1256 1257 1258 1259
    if (multiply_ms(sp->tbuflen, sizeof (int16)) == 0 ||
        (sp->tbuf = (uint8*) _TIFFmalloc(sp->tbuflen * sizeof (int16))) == NULL) {
        TIFFErrorExt(tif->tif_clientdata, module, "No space for SGILog translation buffer");
        return (0);
    }
    return (1);
1260 1261 1262 1263 1264
}

static int
LogLuvGuessDataFmt(TIFFDirectory *td)
{
1265
    int guess;
1266

1267 1268 1269 1270
    /*
     * If the user didn't tell us their datafmt,
     * take our best guess from the bitspersample.
     */
1271
#define	PACK(a,b)	(((a)<<3)|(b))
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
    switch (PACK(td->td_bitspersample, td->td_sampleformat)) {
    case PACK(32, SAMPLEFORMAT_IEEEFP):
        guess = SGILOGDATAFMT_FLOAT;
        break;
    case PACK(32, SAMPLEFORMAT_VOID):
    case PACK(32, SAMPLEFORMAT_UINT):
    case PACK(32, SAMPLEFORMAT_INT):
        guess = SGILOGDATAFMT_RAW;
        break;
    case PACK(16, SAMPLEFORMAT_VOID):
    case PACK(16, SAMPLEFORMAT_INT):
    case PACK(16, SAMPLEFORMAT_UINT):
        guess = SGILOGDATAFMT_16BIT;
        break;
    case PACK( 8, SAMPLEFORMAT_VOID):
    case PACK( 8, SAMPLEFORMAT_UINT):
        guess = SGILOGDATAFMT_8BIT;
        break;
    default:
        guess = SGILOGDATAFMT_UNKNOWN;
        break;
1293
#undef PACK
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
    }
    /*
     * Double-check samples per pixel.
     */
    switch (td->td_samplesperpixel) {
    case 1:
        if (guess != SGILOGDATAFMT_RAW)
            guess = SGILOGDATAFMT_UNKNOWN;
        break;
    case 3:
        if (guess == SGILOGDATAFMT_RAW)
            guess = SGILOGDATAFMT_UNKNOWN;
        break;
    default:
        guess = SGILOGDATAFMT_UNKNOWN;
        break;
    }
    return (guess);
1312 1313 1314 1315 1316
}

static int
LogLuvInitState(TIFF* tif)
{
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
    static const char module[] = "LogLuvInitState";
    TIFFDirectory* td = &tif->tif_dir;
    LogLuvState* sp = DecoderState(tif);

    assert(sp != NULL);
    assert(td->td_photometric == PHOTOMETRIC_LOGLUV);

    /* for some reason, we can't do this in TIFFInitLogLuv */
    if (td->td_planarconfig != PLANARCONFIG_CONTIG) {
        TIFFErrorExt(tif->tif_clientdata, module,
            "SGILog compression cannot handle non-contiguous data");
        return (0);
    }
    if (sp->user_datafmt == SGILOGDATAFMT_UNKNOWN)
        sp->user_datafmt = LogLuvGuessDataFmt(td);
    switch (sp->user_datafmt) {
    case SGILOGDATAFMT_FLOAT:
        sp->pixel_size = 3*sizeof (float);
        break;
    case SGILOGDATAFMT_16BIT:
        sp->pixel_size = 3*sizeof (int16);
        break;
    case SGILOGDATAFMT_RAW:
        sp->pixel_size = sizeof (uint32);
        break;
    case SGILOGDATAFMT_8BIT:
        sp->pixel_size = 3*sizeof (uint8);
        break;
    default:
        TIFFErrorExt(tif->tif_clientdata, module,
            "No support for converting user data format to LogLuv");
        return (0);
    }
1350
        if( isTiled(tif) )
1351
            sp->tbuflen = multiply_ms(td->td_tilewidth, td->td_tilelength);
1352
        else
1353
            sp->tbuflen = multiply_ms(td->td_imagewidth, td->td_rowsperstrip);
1354 1355 1356 1357 1358 1359
    if (multiply_ms(sp->tbuflen, sizeof (uint32)) == 0 ||
        (sp->tbuf = (uint8*) _TIFFmalloc(sp->tbuflen * sizeof (uint32))) == NULL) {
        TIFFErrorExt(tif->tif_clientdata, module, "No space for SGILog translation buffer");
        return (0);
    }
    return (1);
1360 1361
}

1362 1363 1364
static int
LogLuvFixupTags(TIFF* tif)
{
1365 1366
    (void) tif;
    return (1);
1367 1368
}

1369 1370 1371
static int
LogLuvSetupDecode(TIFF* tif)
{
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
    static const char module[] = "LogLuvSetupDecode";
    LogLuvState* sp = DecoderState(tif);
    TIFFDirectory* td = &tif->tif_dir;

    tif->tif_postdecode = _TIFFNoPostDecode;
    switch (td->td_photometric) {
    case PHOTOMETRIC_LOGLUV:
        if (!LogLuvInitState(tif))
            break;
        if (td->td_compression == COMPRESSION_SGILOG24) {
            tif->tif_decoderow = LogLuvDecode24;
            switch (sp->user_datafmt) {
            case SGILOGDATAFMT_FLOAT:
                sp->tfunc = Luv24toXYZ;
                break;
            case SGILOGDATAFMT_16BIT:
                sp->tfunc = Luv24toLuv48;
                break;
            case SGILOGDATAFMT_8BIT:
                sp->tfunc = Luv24toRGB;
                break;
            }
        } else {
            tif->tif_decoderow = LogLuvDecode32;
            switch (sp->user_datafmt) {
            case SGILOGDATAFMT_FLOAT:
                sp->tfunc = Luv32toXYZ;
                break;
            case SGILOGDATAFMT_16BIT:
                sp->tfunc = Luv32toLuv48;
                break;
            case SGILOGDATAFMT_8BIT:
                sp->tfunc = Luv32toRGB;
                break;
            }
        }
        return (1);
    case PHOTOMETRIC_LOGL:
        if (!LogL16InitState(tif))
            break;
        tif->tif_decoderow = LogL16Decode;
        switch (sp->user_datafmt) {
        case SGILOGDATAFMT_FLOAT:
            sp->tfunc = L16toY;
            break;
        case SGILOGDATAFMT_8BIT:
            sp->tfunc = L16toGry;
            break;
        }
        return (1);
    default:
        TIFFErrorExt(tif->tif_clientdata, module,
            "Inappropriate photometric interpretation %d for SGILog compression; %s",
            td->td_photometric, "must be either LogLUV or LogL");
        break;
    }
    return (0);
1429 1430 1431 1432 1433
}

static int
LogLuvSetupEncode(TIFF* tif)
{
1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
    static const char module[] = "LogLuvSetupEncode";
    LogLuvState* sp = EncoderState(tif);
    TIFFDirectory* td = &tif->tif_dir;

    switch (td->td_photometric) {
    case PHOTOMETRIC_LOGLUV:
        if (!LogLuvInitState(tif))
            break;
        if (td->td_compression == COMPRESSION_SGILOG24) {
            tif->tif_encoderow = LogLuvEncode24;
            switch (sp->user_datafmt) {
            case SGILOGDATAFMT_FLOAT:
                sp->tfunc = Luv24fromXYZ;
                break;
            case SGILOGDATAFMT_16BIT:
                sp->tfunc = Luv24fromLuv48;
                break;
            case SGILOGDATAFMT_RAW:
                break;
            default:
                goto notsupported;
            }
        } else {
            tif->tif_encoderow = LogLuvEncode32;
            switch (sp->user_datafmt) {
            case SGILOGDATAFMT_FLOAT:
                sp->tfunc = Luv32fromXYZ;
                break;
            case SGILOGDATAFMT_16BIT:
                sp->tfunc = Luv32fromLuv48;
                break;
            case SGILOGDATAFMT_RAW:
                break;
            default:
                goto notsupported;
            }
        }
        break;
    case PHOTOMETRIC_LOGL:
        if (!LogL16InitState(tif))
            break;
        tif->tif_encoderow = LogL16Encode;
        switch (sp->user_datafmt) {
        case SGILOGDATAFMT_FLOAT:
            sp->tfunc = L16fromY;
            break;
        case SGILOGDATAFMT_16BIT:
            break;
        default:
            goto notsupported;
        }
        break;
    default:
        TIFFErrorExt(tif->tif_clientdata, module,
            "Inappropriate photometric interpretation %d for SGILog compression; %s",
            td->td_photometric, "must be either LogLUV or LogL");
        break;
    }
    return (1);
1493
notsupported:
1494 1495 1496 1497
    TIFFErrorExt(tif->tif_clientdata, module,
        "SGILog compression supported only for %s, or raw data",
        td->td_photometric == PHOTOMETRIC_LOGL ? "Y, L" : "XYZ, Luv");
    return (0);
1498 1499 1500 1501 1502
}

static void
LogLuvClose(TIFF* tif)
{
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
    TIFFDirectory *td = &tif->tif_dir;

    /*
     * For consistency, we always want to write out the same
     * bitspersample and sampleformat for our TIFF file,
     * regardless of the data format being used by the application.
     * Since this routine is called after tags have been set but
     * before they have been recorded in the file, we reset them here.
     */
    td->td_samplesperpixel =
        (td->td_photometric == PHOTOMETRIC_LOGL) ? 1 : 3;
    td->td_bitspersample = 16;
    td->td_sampleformat = SAMPLEFORMAT_INT;
1516 1517 1518 1519 1520
}

static void
LogLuvCleanup(TIFF* tif)
{
1521
    LogLuvState* sp = (LogLuvState *)tif->tif_data;
1522

1523
    assert(sp != 0);
1524

1525 1526
    tif->tif_tagmethods.vgetfield = sp->vgetparent;
    tif->tif_tagmethods.vsetfield = sp->vsetparent;
1527

1528 1529 1530 1531
    if (sp->tbuf)
        _TIFFfree(sp->tbuf);
    _TIFFfree(sp);
    tif->tif_data = NULL;
1532

1533
    _TIFFSetDefaultCompressionState(tif);
1534 1535 1536
}

static int
1537
LogLuvVSetField(TIFF* tif, uint32 tag, va_list ap)
1538
{
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592
    static const char module[] = "LogLuvVSetField";
    LogLuvState* sp = DecoderState(tif);
    int bps, fmt;

    switch (tag) {
    case TIFFTAG_SGILOGDATAFMT:
        sp->user_datafmt = (int) va_arg(ap, int);
        /*
         * Tweak the TIFF header so that the rest of libtiff knows what
         * size of data will be passed between app and library, and
         * assume that the app knows what it is doing and is not
         * confused by these header manipulations...
         */
        switch (sp->user_datafmt) {
        case SGILOGDATAFMT_FLOAT:
            bps = 32, fmt = SAMPLEFORMAT_IEEEFP;
            break;
        case SGILOGDATAFMT_16BIT:
            bps = 16, fmt = SAMPLEFORMAT_INT;
            break;
        case SGILOGDATAFMT_RAW:
            bps = 32, fmt = SAMPLEFORMAT_UINT;
            TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1);
            break;
        case SGILOGDATAFMT_8BIT:
            bps = 8, fmt = SAMPLEFORMAT_UINT;
            break;
        default:
            TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
                "Unknown data format %d for LogLuv compression",
                sp->user_datafmt);
            return (0);
        }
        TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps);
        TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, fmt);
        /*
         * Must recalculate sizes should bits/sample change.
         */
        tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tmsize_t) -1;
        tif->tif_scanlinesize = TIFFScanlineSize(tif);
        return (1);
    case TIFFTAG_SGILOGENCODE:
        sp->encode_meth = (int) va_arg(ap, int);
        if (sp->encode_meth != SGILOGENCODE_NODITHER &&
            sp->encode_meth != SGILOGENCODE_RANDITHER) {
            TIFFErrorExt(tif->tif_clientdata, module,
                "Unknown encoding %d for LogLuv compression",
                sp->encode_meth);
            return (0);
        }
        return (1);
    default:
        return (*sp->vsetparent)(tif, tag, ap);
    }
1593 1594 1595
}

static int
1596
LogLuvVGetField(TIFF* tif, uint32 tag, va_list ap)
1597
{
1598 1599 1600 1601 1602 1603 1604 1605 1606
    LogLuvState *sp = (LogLuvState *)tif->tif_data;

    switch (tag) {
    case TIFFTAG_SGILOGDATAFMT:
        *va_arg(ap, int*) = sp->user_datafmt;
        return (1);
    default:
        return (*sp->vgetparent)(tif, tag, ap);
    }
1607 1608
}

1609 1610 1611
static const TIFFField LogLuvFields[] = {
    { TIFFTAG_SGILOGDATAFMT, 0, 0, TIFF_SHORT, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, TRUE, FALSE, "SGILogDataFmt", NULL},
    { TIFFTAG_SGILOGENCODE, 0, 0, TIFF_SHORT, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, TRUE, FALSE, "SGILogEncode", NULL}
1612 1613 1614 1615 1616
};

int
TIFFInitSGILog(TIFF* tif, int scheme)
{
1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668
    static const char module[] = "TIFFInitSGILog";
    LogLuvState* sp;

    assert(scheme == COMPRESSION_SGILOG24 || scheme == COMPRESSION_SGILOG);

    /*
     * Merge codec-specific tag information.
     */
    if (!_TIFFMergeFields(tif, LogLuvFields,
                  TIFFArrayCount(LogLuvFields))) {
        TIFFErrorExt(tif->tif_clientdata, module,
            "Merging SGILog codec-specific tags failed");
        return 0;
    }

    /*
     * Allocate state block so tag methods have storage to record values.
     */
    tif->tif_data = (uint8*) _TIFFmalloc(sizeof (LogLuvState));
    if (tif->tif_data == NULL)
        goto bad;
    sp = (LogLuvState*) tif->tif_data;
    _TIFFmemset((void*)sp, 0, sizeof (*sp));
    sp->user_datafmt = SGILOGDATAFMT_UNKNOWN;
    sp->encode_meth = (scheme == COMPRESSION_SGILOG24) ?
        SGILOGENCODE_RANDITHER : SGILOGENCODE_NODITHER;
    sp->tfunc = _logLuvNop;

    /*
     * Install codec methods.
     * NB: tif_decoderow & tif_encoderow are filled
     *     in at setup time.
     */
    tif->tif_fixuptags = LogLuvFixupTags;
    tif->tif_setupdecode = LogLuvSetupDecode;
    tif->tif_decodestrip = LogLuvDecodeStrip;
    tif->tif_decodetile = LogLuvDecodeTile;
    tif->tif_setupencode = LogLuvSetupEncode;
    tif->tif_encodestrip = LogLuvEncodeStrip;
    tif->tif_encodetile = LogLuvEncodeTile;
    tif->tif_close = LogLuvClose;
    tif->tif_cleanup = LogLuvCleanup;

    /*
     * Override parent get/set field methods.
     */
    sp->vgetparent = tif->tif_tagmethods.vgetfield;
    tif->tif_tagmethods.vgetfield = LogLuvVGetField;   /* hook for codec tags */
    sp->vsetparent = tif->tif_tagmethods.vsetfield;
    tif->tif_tagmethods.vsetfield = LogLuvVSetField;   /* hook for codec tags */

    return (1);
1669
bad:
1670 1671 1672
    TIFFErrorExt(tif->tif_clientdata, module,
             "%s: No space for LogLuv state block", tif->tif_name);
    return (0);
1673 1674 1675 1676
}
#endif /* LOGLUV_SUPPORT */

/* vim: set ts=8 sts=8 sw=8 noet: */
1677 1678 1679 1680 1681 1682 1683
/*
 * Local Variables:
 * mode: c
 * c-basic-offset: 8
 * fill-column: 78
 * End:
 */