LCOV - code coverage report
Current view: top level - frmts/gtiff/libtiff - tif_luv.c (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 164 989 16.6 %
Date: 2026-08-22 15:37:05 Functions: 15 61 24.6 %

          Line data    Source code
       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             : #define DecoderState(tif) ((LogLuvState *)(tif)->tif_data)
     176             : #define EncoderState(tif) ((LogLuvState *)(tif)->tif_data)
     177             : 
     178             : #define SGILOGDATAFMT_UNKNOWN -1
     179             : 
     180             : #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          40 : static int LogL16Decode(TIFF *tif, uint8_t *op, tmsize_t occ, uint16_t s)
     191             : {
     192             :     static const char module[] = "LogL16Decode";
     193          40 :     LogLuvState *sp = DecoderState(tif);
     194             :     int shft;
     195             :     tmsize_t i;
     196             :     tmsize_t npixels;
     197             :     unsigned char *bp;
     198             :     int16_t *tp;
     199             :     int16_t b;
     200             :     tmsize_t cc;
     201             :     int rc;
     202             : 
     203             :     (void)s;
     204          40 :     assert(s == 0);
     205          40 :     assert(sp != NULL);
     206             : 
     207          40 :     npixels = occ / sp->pixel_size;
     208             : 
     209          40 :     if (sp->tbuflen < npixels)
     210             :     {
     211           0 :         TIFFErrorExtR(tif, module, "Translation buffer too short");
     212           0 :         return (0);
     213             :     }
     214          40 :     tp = (int16_t *)sp->tbuf;
     215          40 :     _TIFFmemset((void *)tp, 0, (tmsize_t)((size_t)npixels * sizeof(tp[0])));
     216             : 
     217          40 :     bp = (unsigned char *)tif->tif_rawcp;
     218          40 :     cc = tif->tif_rawcc;
     219             :     /* get each byte string */
     220         120 :     for (shft = 8; shft >= 0; shft -= 8)
     221             :     {
     222         168 :         for (i = 0; i < npixels && cc > 0;)
     223             :         {
     224          88 :             if (*bp >= 128)
     225             :             { /* run */
     226          44 :                 if (cc < 2)
     227           0 :                     break;
     228          44 :                 rc = *bp++ + (2 - 128);
     229          44 :                 b = (int16_t)(*bp++ << shft);
     230          44 :                 cc -= 2;
     231         862 :                 while (rc-- && i < npixels)
     232         818 :                     tp[i++] |= b;
     233             :             }
     234             :             else
     235             :             {               /* non-run */
     236          44 :                 rc = *bp++; /* nul is noop */
     237         826 :                 while (--cc && rc-- && i < npixels)
     238         782 :                     tp[i++] |= (int16_t)(*bp++ << shft);
     239             :             }
     240             :         }
     241          80 :         if (i != npixels)
     242             :         {
     243           0 :             TIFFErrorExtR(tif, module,
     244             :                           "Not enough data at row %" PRIu32
     245             :                           " (short %" TIFF_SSIZE_FORMAT " pixels)",
     246             :                           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             :         }
     251             :     }
     252          40 :     if (sp->user_datafmt == SGILOGDATAFMT_16BIT)
     253          20 :         L16toL16(sp, op, npixels);
     254             :     else
     255          20 :         (*sp->tfunc)(sp, op, npixels);
     256          40 :     tif->tif_rawcp = (uint8_t *)bp;
     257          40 :     tif->tif_rawcc = cc;
     258          40 :     return (1);
     259             : }
     260             : 
     261             : /*
     262             :  * Decode a string of 24-bit pixels.
     263             :  */
     264           0 : static int LogLuvDecode24(TIFF *tif, uint8_t *op, tmsize_t occ, uint16_t s)
     265             : {
     266             :     static const char module[] = "LogLuvDecode24";
     267           0 :     LogLuvState *sp = DecoderState(tif);
     268             :     tmsize_t cc;
     269             :     tmsize_t i;
     270             :     tmsize_t npixels;
     271             :     unsigned char *bp;
     272             :     uint32_t *tp;
     273             : 
     274             :     (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             :     {
     282           0 :         TIFFErrorExtR(tif, module, "Translation buffer too short");
     283           0 :         return (0);
     284             :     }
     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             :     {
     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             :     }
     295           0 :     tif->tif_rawcp = (uint8_t *)bp;
     296           0 :     tif->tif_rawcc = cc;
     297           0 :     if (i != npixels)
     298             :     {
     299           0 :         TIFFErrorExtR(tif, module,
     300             :                       "Not enough data at row %" PRIu32
     301             :                       " (short %" TIFF_SSIZE_FORMAT " pixels)",
     302             :                       tif->tif_dir.td_row, npixels - i);
     303           0 :         return (0);
     304             :     }
     305           0 :     if (sp->user_datafmt == SGILOGDATAFMT_RAW)
     306           0 :         LuvRawToRaw(sp, op, npixels);
     307             :     else
     308           0 :         (*sp->tfunc)(sp, op, npixels);
     309           0 :     return (1);
     310             : }
     311             : 
     312             : /*
     313             :  * Decode a string of 32-bit pixels.
     314             :  */
     315           0 : static int LogLuvDecode32(TIFF *tif, uint8_t *op, tmsize_t occ, uint16_t s)
     316             : {
     317             :     static const char module[] = "LogLuvDecode32";
     318             :     LogLuvState *sp;
     319             :     int shft;
     320             :     tmsize_t i;
     321             :     tmsize_t npixels;
     322             :     unsigned char *bp;
     323             :     uint32_t *tp;
     324             :     uint32_t b;
     325             :     tmsize_t cc;
     326             :     int rc;
     327             : 
     328             :     (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             :     {
     337           0 :         TIFFErrorExtR(tif, module, "Translation buffer too short");
     338           0 :         return (0);
     339             :     }
     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             :     {
     348           0 :         for (i = 0; i < npixels && cc > 0;)
     349             :         {
     350           0 :             if (*bp >= 128)
     351             :             { /* 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             :             }
     360             :             else
     361             :             {               /* 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             :             }
     366             :         }
     367           0 :         if (i != npixels)
     368             :         {
     369           0 :             TIFFErrorExtR(tif, module,
     370             :                           "Not enough data at row %" PRIu32
     371             :                           " (short %" TIFF_SSIZE_FORMAT " pixels)",
     372             :                           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             :         }
     377             :     }
     378           0 :     if (sp->user_datafmt == SGILOGDATAFMT_RAW)
     379           0 :         LuvRawToRaw(sp, op, npixels);
     380             :     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             : }
     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           2 : static int LogLuvDecodeStrip(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
     393             : {
     394           2 :     tmsize_t rowlen = TIFFScanlineSize(tif);
     395             : 
     396           2 :     if (rowlen == 0)
     397           0 :         return 0;
     398             : 
     399           2 :     assert(cc % rowlen == 0);
     400          42 :     while (cc && (*tif->tif_decoderow)(tif, bp, rowlen, s))
     401             :     {
     402          40 :         bp += rowlen;
     403          40 :         cc -= rowlen;
     404             :     }
     405           2 :     return (cc == 0);
     406             : }
     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           0 : static int LogLuvDecodeTile(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
     414             : {
     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             :     {
     423           0 :         bp += rowlen;
     424           0 :         cc -= rowlen;
     425             :     }
     426           0 :     return (cc == 0);
     427             : }
     428             : 
     429             : /*
     430             :  * Encode a row of 16-bit pixels.
     431             :  */
     432           0 : static int LogL16Encode(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
     433             : {
     434             :     static const char module[] = "LogL16Encode";
     435           0 :     LogLuvState *sp = EncoderState(tif);
     436             :     int shft;
     437             :     tmsize_t i;
     438             :     tmsize_t j;
     439             :     tmsize_t npixels;
     440             :     uint8_t *op;
     441             :     int16_t *tp;
     442             :     int16_t b;
     443             :     tmsize_t occ;
     444           0 :     int rc = 0, mask;
     445             :     tmsize_t beg;
     446             : 
     447             :     (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             :     {
     455           0 :         TIFFErrorExtR(tif, module, "Translation buffer too short");
     456           0 :         return (0);
     457             :     }
     458           0 :     if (sp->user_datafmt == SGILOGDATAFMT_16BIT)
     459           0 :         L16fromL16(sp, bp, npixels);
     460             :     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             :     {
     467           0 :         for (i = 0; i < npixels; i += rc)
     468             :         {
     469           0 :             if (occ < 4)
     470             :             {
     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             :             }
     478           0 :             mask = 0xff << shft; /* find next run */
     479           0 :             for (beg = i; beg < npixels; beg += rc)
     480             :             {
     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             :             }
     489           0 :             if (beg - i > 1 && beg - i < MINRUN)
     490             :             {
     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             :                     {
     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             :                     }
     502             :             }
     503           0 :             while (i < beg)
     504             :             { /* write out non-run */
     505           0 :                 if ((j = beg - i) > 127)
     506           0 :                     j = 127;
     507           0 :                 if (occ < j + 3)
     508             :                 {
     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             :                 }
     516           0 :                 *op++ = (uint8_t)j;
     517           0 :                 occ--;
     518           0 :                 while (j--)
     519             :                 {
     520           0 :                     *op++ = (uint8_t)(tp[i++] >> shft & 0xff);
     521           0 :                     occ--;
     522             :                 }
     523             :             }
     524           0 :             if (rc >= MINRUN)
     525             :             { /* 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             :             }
     530             :             else
     531           0 :                 rc = 0;
     532             :         }
     533             :     }
     534           0 :     tif->tif_rawcp = op;
     535           0 :     tif->tif_rawcc = tif->tif_rawdatasize - occ;
     536             : 
     537           0 :     return (1);
     538             : }
     539             : 
     540             : /*
     541             :  * Encode a row of 24-bit pixels.
     542             :  */
     543           0 : static int LogLuvEncode24(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
     544             : {
     545             :     static const char module[] = "LogLuvEncode24";
     546           0 :     LogLuvState *sp = EncoderState(tif);
     547             :     tmsize_t i;
     548             :     tmsize_t npixels;
     549             :     tmsize_t occ;
     550             :     uint8_t *op;
     551             :     uint32_t *tp;
     552             : 
     553             :     (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             :     {
     561           0 :         TIFFErrorExtR(tif, module, "Translation buffer too short");
     562           0 :         return (0);
     563             :     }
     564           0 :     if (sp->user_datafmt == SGILOGDATAFMT_RAW)
     565           0 :         LuvRawFromRaw(sp, bp, npixels);
     566             :     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             :     {
     573           0 :         if (occ < 3)
     574             :         {
     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             :         }
     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             :     }
     587           0 :     tif->tif_rawcp = op;
     588           0 :     tif->tif_rawcc = tif->tif_rawdatasize - occ;
     589             : 
     590           0 :     return (1);
     591             : }
     592             : 
     593             : /*
     594             :  * Encode a row of 32-bit pixels.
     595             :  */
     596           0 : static int LogLuvEncode32(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
     597             : {
     598             :     static const char module[] = "LogLuvEncode32";
     599           0 :     LogLuvState *sp = EncoderState(tif);
     600             :     int shft;
     601             :     tmsize_t i;
     602             :     tmsize_t j;
     603             :     tmsize_t npixels;
     604             :     uint8_t *op;
     605             :     uint32_t *tp;
     606             :     uint32_t b;
     607             :     tmsize_t occ;
     608           0 :     int rc = 0;
     609             :     tmsize_t beg;
     610             : 
     611             :     (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             :     {
     620           0 :         TIFFErrorExtR(tif, module, "Translation buffer too short");
     621           0 :         return (0);
     622             :     }
     623           0 :     if (sp->user_datafmt == SGILOGDATAFMT_RAW)
     624           0 :         LuvRawFromRaw(sp, bp, npixels);
     625             :     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             :     {
     632           0 :         const uint32_t mask = 0xffU << shft; /* find next run */
     633           0 :         for (i = 0; i < npixels; i += rc)
     634             :         {
     635           0 :             if (occ < 4)
     636             :             {
     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             :             }
     644           0 :             for (beg = i; beg < npixels; beg += rc)
     645             :             {
     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             :             }
     654           0 :             if (beg - i > 1 && beg - i < MINRUN)
     655             :             {
     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             :                     {
     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             :                     }
     667             :             }
     668           0 :             while (i < beg)
     669             :             { /* write out non-run */
     670           0 :                 if ((j = beg - i) > 127)
     671           0 :                     j = 127;
     672           0 :                 if (occ < j + 3)
     673             :                 {
     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             :                 }
     681           0 :                 *op++ = (uint8_t)j;
     682           0 :                 occ--;
     683           0 :                 while (j--)
     684             :                 {
     685           0 :                     *op++ = (uint8_t)(tp[i++] >> shft & 0xff);
     686           0 :                     occ--;
     687             :                 }
     688             :             }
     689           0 :             if (rc >= MINRUN)
     690             :             { /* 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             :             }
     695             :             else
     696           0 :                 rc = 0;
     697             :         }
     698             :     }
     699           0 :     tif->tif_rawcp = op;
     700           0 :     tif->tif_rawcc = tif->tif_rawdatasize - occ;
     701             : 
     702           0 :     return (1);
     703             : }
     704             : 
     705             : /*
     706             :  * Encode a strip of pixels.  We break it into rows to
     707             :  * avoid encoding runs across row boundaries.
     708             :  */
     709           0 : static int LogLuvEncodeStrip(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
     710             : {
     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             :     {
     719           0 :         bp += rowlen;
     720           0 :         cc -= rowlen;
     721             :     }
     722           0 :     return (cc == 0);
     723             : }
     724             : 
     725             : /*
     726             :  * Encode a tile of pixels.  We break it into rows to
     727             :  * avoid encoding runs across row boundaries.
     728             :  */
     729           0 : static int LogLuvEncodeTile(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
     730             : {
     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             :     {
     739           0 :         bp += rowlen;
     740           0 :         cc -= rowlen;
     741             :     }
     742           0 :     return (cc == 0);
     743             : }
     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             : #define TIFF_RAND_MAX 32767
     765             : 
     766             : // From POSIX.1-2001 as an example of an implementation of rand()
     767           0 : static uint32_t _TIFFRand(void)
     768             : {
     769             :     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             : }
     778             : 
     779           0 : static int tiff_itrunc(double x, int m)
     780             : {
     781           0 :     if (m == SGILOGENCODE_NODITHER)
     782           0 :         return (int)x;
     783           0 :     return (int)(x + _TIFFRand() * (1. / TIFF_RAND_MAX) - .5);
     784             : }
     785             : 
     786             : #if !LOGLUV_PUBLIC
     787             : static
     788             : #endif
     789         400 :     double LogL16toY(int p16) /* compute luminance from 16-bit LogL */
     790             : {
     791         400 :     int Le = p16 & 0x7fff;
     792             :     double Y;
     793             : 
     794         400 :     if (!Le)
     795           0 :         return (0.);
     796         400 :     Y = exp(M_LN2 / 256. * (Le + .5) - M_LN2 * 64.);
     797         400 :     return (!(p16 & 0x8000) ? Y : -Y);
     798             : }
     799             : 
     800             : #if !LOGLUV_PUBLIC
     801             : static
     802             : #endif
     803           0 :     int LogL16fromY(double Y, int em) /* get 16-bit LogL from Y */
     804             : {
     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             : }
     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           0 : static float LogLuvLoadFloatNativeUnaligned(const uint8_t *cp)
     825             : {
     826             :     float v;
     827           0 :     memcpy(&v, cp, sizeof(v));
     828           0 :     return v;
     829             : }
     830             : 
     831           0 : static void LogLuvStoreFloatNativeUnaligned(uint8_t *cp, float v)
     832             : {
     833           0 :     memcpy(cp, &v, sizeof(v));
     834           0 : }
     835             : 
     836           0 : static int16_t LogLuvLoad16NativeUnaligned(const uint8_t *cp)
     837             : {
     838             :     int16_t v;
     839           0 :     memcpy(&v, cp, sizeof(v));
     840           0 :     return v;
     841             : }
     842             : 
     843         400 : static void LogLuvStore16NativeUnaligned(uint8_t *cp, int16_t v)
     844             : {
     845         400 :     memcpy(cp, &v, sizeof(v));
     846         400 : }
     847             : 
     848           0 : static uint32_t LogLuvLoad32NativeUnaligned(const uint8_t *cp)
     849             : {
     850             :     uint32_t v;
     851           0 :     memcpy(&v, cp, sizeof(v));
     852           0 :     return v;
     853             : }
     854             : 
     855           0 : static void LogLuvStore32NativeUnaligned(uint8_t *cp, uint32_t v)
     856             : {
     857           0 :     memcpy(cp, &v, sizeof(v));
     858           0 : }
     859             : 
     860          20 : static void L16toL16(LogLuvState *sp, uint8_t *op, tmsize_t n)
     861             : {
     862          20 :     int16_t *l16 = (int16_t *)sp->tbuf;
     863             : 
     864         420 :     while (n-- > 0)
     865             :     {
     866         400 :         LogLuvStore16NativeUnaligned(op, *l16++);
     867         400 :         op += sizeof(int16_t);
     868             :     }
     869          20 : }
     870             : 
     871           0 : static void L16fromL16(LogLuvState *sp, uint8_t *op, tmsize_t n)
     872             : {
     873           0 :     int16_t *l16 = (int16_t *)sp->tbuf;
     874             : 
     875           0 :     while (n-- > 0)
     876             :     {
     877           0 :         *l16++ = LogLuvLoad16NativeUnaligned(op);
     878           0 :         op += sizeof(int16_t);
     879             :     }
     880           0 : }
     881             : 
     882           0 : static void LuvRawToRaw(LogLuvState *sp, uint8_t *op, tmsize_t n)
     883             : {
     884           0 :     uint32_t *luv = (uint32_t *)sp->tbuf;
     885             : 
     886           0 :     while (n-- > 0)
     887             :     {
     888           0 :         LogLuvStore32NativeUnaligned(op, *luv++);
     889           0 :         op += sizeof(uint32_t);
     890             :     }
     891           0 : }
     892             : 
     893           0 : static void LuvRawFromRaw(LogLuvState *sp, uint8_t *op, tmsize_t n)
     894             : {
     895           0 :     uint32_t *luv = (uint32_t *)sp->tbuf;
     896             : 
     897           0 :     while (n-- > 0)
     898             :     {
     899           0 :         *luv++ = LogLuvLoad32NativeUnaligned(op);
     900           0 :         op += sizeof(uint32_t);
     901             :     }
     902           0 : }
     903             : 
     904           0 : static void L16toY(LogLuvState *sp, uint8_t *op, tmsize_t n)
     905             : {
     906           0 :     int16_t *l16 = (int16_t *)sp->tbuf;
     907             : 
     908           0 :     while (n-- > 0)
     909             :     {
     910           0 :         LogLuvStoreFloatNativeUnaligned(op, (float)LogL16toY(*l16++));
     911           0 :         op += sizeof(float);
     912             :     }
     913           0 : }
     914             : 
     915          20 : static void L16toGry(LogLuvState *sp, uint8_t *op, tmsize_t n)
     916             : {
     917          20 :     int16_t *l16 = (int16_t *)sp->tbuf;
     918          20 :     uint8_t *gp = (uint8_t *)op;
     919             : 
     920         420 :     while (n-- > 0)
     921             :     {
     922         400 :         double Y = LogL16toY(*l16++);
     923         800 :         *gp++ = (uint8_t)((Y <= 0.)   ? 0
     924             :                           : (Y >= 1.) ? 255
     925         400 :                                       : (int)(256. * sqrt(Y)));
     926             :     }
     927          20 : }
     928             : 
     929           0 : static void L16fromY(LogLuvState *sp, uint8_t *op, tmsize_t n)
     930             : {
     931           0 :     int16_t *l16 = (int16_t *)sp->tbuf;
     932             : 
     933           0 :     while (n-- > 0)
     934             :     {
     935           0 :         *l16++ = (int16_t)(LogL16fromY(
     936           0 :             (double)LogLuvLoadFloatNativeUnaligned(op), sp->encode_meth));
     937           0 :         op += sizeof(float);
     938             :     }
     939           0 : }
     940             : 
     941             : #if !LOGLUV_PUBLIC
     942             : static
     943             : #endif
     944           0 :     void XYZtoRGB24(float *xyz, uint8_t *rgb)
     945             : {
     946             :     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           0 :     double LogL10toY(int p10) /* compute luminance from 10-bit LogL */
     965             : {
     966           0 :     if (p10 == 0)
     967           0 :         return (0.);
     968           0 :     return (exp(M_LN2 / 64. * (p10 + .5) - M_LN2 * 12.));
     969             : }
     970             : 
     971             : #if !LOGLUV_PUBLIC
     972             : static
     973             : #endif
     974           0 :     int LogL10fromY(double Y, int em) /* get 10-bit LogL from Y */
     975             : {
     976           0 :     if (Y >= 15.742)
     977           0 :         return (0x3ff);
     978           0 :     else if (Y <= .00024283)
     979           0 :         return (0);
     980             :     else
     981           0 :         return tiff_itrunc(64. * (log2(Y) + 12.), em);
     982             : }
     983             : 
     984             : #define NANGLES 100
     985             : #define uv2ang(u, v)                                                           \
     986             :     ((NANGLES * .499999999 / M_PI) * atan2((v) - V_NEU, (u) - U_NEU) +         \
     987             :      .5 * NANGLES)
     988             : 
     989           0 : static int oog_encode(double u, double v) /* encode out-of-gamut chroma */
     990             : {
     991             :     static int oog_table[NANGLES];
     992             :     static int initialized = 0;
     993             :     int i;
     994             : 
     995           0 :     if (!initialized)
     996             :     { /* set up perimeter table */
     997             :         double eps[NANGLES], ua, va, ang, epsa;
     998             :         int ui, vi, ustep;
     999           0 :         for (i = NANGLES; i--;)
    1000           0 :             eps[i] = 2.;
    1001           0 :         for (vi = UV_NVS; vi--;)
    1002             :         {
    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             :             {
    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             :                 {
    1016           0 :                     oog_table[i] = uv_row[vi].ncum + ui;
    1017           0 :                     eps[i] = epsa;
    1018             :                 }
    1019             :             }
    1020             :         }
    1021           0 :         for (i = NANGLES; i--;) /* fill any holes */
    1022           0 :             if (eps[i] > 1.5)
    1023             :             {
    1024             :                 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             :                 else
    1034           0 :                     oog_table[i] = oog_table[(i + NANGLES - i2) % NANGLES];
    1035             :             }
    1036           0 :         initialized = 1;
    1037             :     }
    1038           0 :     i = (int)uv2ang(u, v); /* look up hue angle */
    1039           0 :     return (oog_table[i]);
    1040             : }
    1041             : 
    1042             : #undef uv2ang
    1043             : #undef NANGLES
    1044             : 
    1045             : #if !LOGLUV_PUBLIC
    1046             : static
    1047             : #endif
    1048           0 :     int uv_encode(double u, double v, int em) /* encode (u',v') coordinates */
    1049             : {
    1050             :     unsigned int vi;
    1051             :     int ui;
    1052             : 
    1053             :     /* check for NaN */
    1054           0 :     if (isnan(u) || isnan(v))
    1055             :     {
    1056           0 :         u = U_NEU;
    1057           0 :         v = V_NEU;
    1058             :     }
    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             : }
    1075             : 
    1076             : #if !LOGLUV_PUBLIC
    1077             : static
    1078             : #endif
    1079           0 :     int uv_decode(double *up, double *vp, int c) /* decode (u',v') index */
    1080             : {
    1081             :     unsigned int upper, lower;
    1082             :     int ui;
    1083             :     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             :     {
    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             :         else
    1098             :         {
    1099           0 :             lower = vi;
    1100           0 :             break;
    1101             :         }
    1102             :     }
    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             : }
    1109             : 
    1110             : #if !LOGLUV_PUBLIC
    1111             : static
    1112             : #endif
    1113           0 :     void LogLuv24toXYZ(uint32_t p, float *XYZ)
    1114             : {
    1115             :     int Ce;
    1116             :     double L, u, v, s, x, y;
    1117             :     /* decode luminance */
    1118           0 :     L = LogL10toY(p >> 14 & 0x3ff);
    1119           0 :     if (L <= 0.)
    1120             :     {
    1121           0 :         XYZ[0] = XYZ[1] = XYZ[2] = 0.;
    1122           0 :         return;
    1123             :     }
    1124             :     /* decode color */
    1125           0 :     Ce = p & 0x3fff;
    1126           0 :     if (uv_decode(&u, &v, Ce) < 0)
    1127             :     {
    1128           0 :         u = U_NEU;
    1129           0 :         v = V_NEU;
    1130             :     }
    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             : }
    1139             : 
    1140             : #if !LOGLUV_PUBLIC
    1141             : static
    1142             : #endif
    1143           0 :     uint32_t LogLuv24fromXYZ(float *XYZ, int em)
    1144             : {
    1145             :     int Le, Ce;
    1146             :     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             :     {
    1153           0 :         u = U_NEU;
    1154           0 :         v = V_NEU;
    1155             :     }
    1156             :     else
    1157             :     {
    1158           0 :         u = 4. * (double)XYZ[0] / s;
    1159           0 :         v = 9. * (double)XYZ[1] / s;
    1160             :     }
    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             : }
    1167             : 
    1168           0 : static void Luv24toXYZ(LogLuvState *sp, uint8_t *op, tmsize_t n)
    1169             : {
    1170           0 :     uint32_t *luv = (uint32_t *)sp->tbuf;
    1171             : 
    1172           0 :     while (n-- > 0)
    1173             :     {
    1174             :         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             :     }
    1182           0 : }
    1183             : 
    1184           0 : static void Luv24toLuv48(LogLuvState *sp, uint8_t *op, tmsize_t n)
    1185             : {
    1186           0 :     uint32_t *luv = (uint32_t *)sp->tbuf;
    1187             : 
    1188           0 :     while (n-- > 0)
    1189             :     {
    1190             :         double u, v;
    1191             :         int16_t luv0;
    1192             :         int16_t luv1;
    1193             :         int16_t luv2;
    1194             : 
    1195           0 :         luv0 = (int16_t)((*luv >> 12 & 0xffd) + 13314);
    1196           0 :         if (uv_decode(&u, &v, *luv & 0x3fff) < 0)
    1197             :         {
    1198           0 :             u = U_NEU;
    1199           0 :             v = V_NEU;
    1200             :         }
    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             :     }
    1209           0 : }
    1210             : 
    1211           0 : static void Luv24toRGB(LogLuvState *sp, uint8_t *op, tmsize_t n)
    1212             : {
    1213           0 :     uint32_t *luv = (uint32_t *)sp->tbuf;
    1214           0 :     uint8_t *rgb = (uint8_t *)op;
    1215             : 
    1216           0 :     while (n-- > 0)
    1217             :     {
    1218             :         float xyz[3];
    1219             : 
    1220           0 :         LogLuv24toXYZ(*luv++, xyz);
    1221           0 :         XYZtoRGB24(xyz, rgb);
    1222           0 :         rgb += 3;
    1223             :     }
    1224           0 : }
    1225             : 
    1226           0 : static void Luv24fromXYZ(LogLuvState *sp, uint8_t *op, tmsize_t n)
    1227             : {
    1228           0 :     uint32_t *luv = (uint32_t *)sp->tbuf;
    1229             : 
    1230           0 :     while (n-- > 0)
    1231             :     {
    1232             :         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             :     }
    1239           0 : }
    1240             : 
    1241           0 : static void Luv24fromLuv48(LogLuvState *sp, uint8_t *op, tmsize_t n)
    1242             : {
    1243           0 :     uint32_t *luv = (uint32_t *)sp->tbuf;
    1244             : 
    1245           0 :     while (n-- > 0)
    1246             :     {
    1247             :         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             :         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             :                        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             :     }
    1268           0 : }
    1269             : 
    1270             : #if !LOGLUV_PUBLIC
    1271             : static
    1272             : #endif
    1273           0 :     void LogLuv32toXYZ(uint32_t p, float *XYZ)
    1274             : {
    1275             :     double L, u, v, s, x, y;
    1276             :     /* decode luminance */
    1277           0 :     L = LogL16toY((int)p >> 16);
    1278           0 :     if (L <= 0.)
    1279             :     {
    1280           0 :         XYZ[0] = XYZ[1] = XYZ[2] = 0.;
    1281           0 :         return;
    1282             :     }
    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             : }
    1294             : 
    1295             : #if !LOGLUV_PUBLIC
    1296             : static
    1297             : #endif
    1298           0 :     uint32_t LogLuv32fromXYZ(float *XYZ, int em)
    1299             : {
    1300             :     unsigned int Le, ue, ve;
    1301             :     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             :     {
    1308           0 :         u = U_NEU;
    1309           0 :         v = V_NEU;
    1310             :     }
    1311             :     else
    1312             :     {
    1313           0 :         u = 4. * (double)XYZ[0] / s;
    1314           0 :         v = 9. * (double)XYZ[1] / s;
    1315             :     }
    1316           0 :     if (u <= 0.)
    1317           0 :         ue = 0;
    1318             :     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             :     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             : }
    1331             : 
    1332           0 : static void Luv32toXYZ(LogLuvState *sp, uint8_t *op, tmsize_t n)
    1333             : {
    1334           0 :     uint32_t *luv = (uint32_t *)sp->tbuf;
    1335             : 
    1336           0 :     while (n-- > 0)
    1337             :     {
    1338             :         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             :     }
    1345           0 : }
    1346             : 
    1347           0 : static void Luv32toLuv48(LogLuvState *sp, uint8_t *op, tmsize_t n)
    1348             : {
    1349           0 :     uint32_t *luv = (uint32_t *)sp->tbuf;
    1350             : 
    1351           0 :     while (n-- > 0)
    1352             :     {
    1353             :         double u, v;
    1354           0 :         int16_t luv0 = (int16_t)(*luv >> 16);
    1355             :         int16_t luv1;
    1356             :         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             :     }
    1368           0 : }
    1369             : 
    1370           0 : static void Luv32toRGB(LogLuvState *sp, uint8_t *op, tmsize_t n)
    1371             : {
    1372           0 :     uint32_t *luv = (uint32_t *)sp->tbuf;
    1373           0 :     uint8_t *rgb = (uint8_t *)op;
    1374             : 
    1375           0 :     while (n-- > 0)
    1376             :     {
    1377             :         float xyz[3];
    1378             : 
    1379           0 :         LogLuv32toXYZ(*luv++, xyz);
    1380           0 :         XYZtoRGB24(xyz, rgb);
    1381           0 :         rgb += 3;
    1382             :     }
    1383           0 : }
    1384             : 
    1385           0 : static void Luv32fromXYZ(LogLuvState *sp, uint8_t *op, tmsize_t n)
    1386             : {
    1387           0 :     uint32_t *luv = (uint32_t *)sp->tbuf;
    1388             : 
    1389           0 :     while (n-- > 0)
    1390             :     {
    1391             :         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             :     }
    1398           0 : }
    1399             : 
    1400           0 : static void Luv32fromLuv48(LogLuvState *sp, uint8_t *op, tmsize_t n)
    1401             : {
    1402           0 :     uint32_t *luv = (uint32_t *)sp->tbuf;
    1403             : 
    1404           0 :     if (sp->encode_meth == SGILOGENCODE_NODITHER)
    1405             :     {
    1406           0 :         while (n-- > 0)
    1407             :         {
    1408           0 :             int16_t luv0 = LogLuvLoad16NativeUnaligned(op);
    1409           0 :             int16_t luv1 = LogLuvLoad16NativeUnaligned(op + sizeof(int16_t));
    1410             :             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             :         }
    1417           0 :         return;
    1418             :     }
    1419           0 :     while (n-- > 0)
    1420             :     {
    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             :                                         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             :                   0xff);
    1432           0 :         op += 3 * sizeof(int16_t);
    1433             :     }
    1434             : }
    1435             : 
    1436           0 : static void _logLuvNop(LogLuvState *sp, uint8_t *op, tmsize_t n)
    1437             : {
    1438             :     (void)sp;
    1439             :     (void)op;
    1440             :     (void)n;
    1441           0 : }
    1442             : 
    1443           1 : static int LogL16GuessDataFmt(TIFFDirectory *td)
    1444             : {
    1445             : #define PACK(s, b, f) (((b) << 6) | ((s) << 3) | (f))
    1446           1 :     switch (
    1447           1 :         PACK(td->td_samplesperpixel, td->td_bitspersample, td->td_sampleformat))
    1448             :     {
    1449           0 :         case PACK(1, 32, SAMPLEFORMAT_IEEEFP):
    1450           0 :             return (SGILOGDATAFMT_FLOAT);
    1451           1 :         case PACK(1, 16, SAMPLEFORMAT_VOID):
    1452             :         case PACK(1, 16, SAMPLEFORMAT_INT):
    1453             :         case PACK(1, 16, SAMPLEFORMAT_UINT):
    1454           1 :             return (SGILOGDATAFMT_16BIT);
    1455           0 :         case PACK(1, 8, SAMPLEFORMAT_VOID):
    1456             :         case PACK(1, 8, SAMPLEFORMAT_UINT):
    1457           0 :             return (SGILOGDATAFMT_8BIT);
    1458           0 :         default:
    1459           0 :             break;
    1460             :     }
    1461             : #undef PACK
    1462           0 :     return (SGILOGDATAFMT_UNKNOWN);
    1463             : }
    1464             : 
    1465           4 : static tmsize_t multiply_ms(tmsize_t m1, tmsize_t m2)
    1466             : {
    1467           4 :     return _TIFFMultiplySSize(NULL, m1, m2, NULL);
    1468             : }
    1469             : 
    1470           2 : static int LogL16InitState(TIFF *tif)
    1471             : {
    1472             :     static const char module[] = "LogL16InitState";
    1473           2 :     TIFFDirectory *td = &tif->tif_dir;
    1474           2 :     LogLuvState *sp = DecoderState(tif);
    1475             : 
    1476           2 :     assert(sp != NULL);
    1477           2 :     assert(td->td_photometric == PHOTOMETRIC_LOGL);
    1478             : 
    1479           2 :     if (td->td_samplesperpixel != 1)
    1480             :     {
    1481           0 :         TIFFErrorExtR(tif, module,
    1482             :                       "Sorry, can not handle LogL image with %s=%" PRIu16,
    1483           0 :                       "Samples/pixel", td->td_samplesperpixel);
    1484           0 :         return 0;
    1485             :     }
    1486             : 
    1487             :     /* for some reason, we can't do this in TIFFInitLogL16 */
    1488           2 :     if (sp->user_datafmt == SGILOGDATAFMT_UNKNOWN)
    1489           1 :         sp->user_datafmt = LogL16GuessDataFmt(td);
    1490           2 :     switch (sp->user_datafmt)
    1491             :     {
    1492           0 :         case SGILOGDATAFMT_FLOAT:
    1493           0 :             sp->pixel_size = sizeof(float);
    1494           0 :             break;
    1495           1 :         case SGILOGDATAFMT_16BIT:
    1496           1 :             sp->pixel_size = sizeof(int16_t);
    1497           1 :             break;
    1498           1 :         case SGILOGDATAFMT_8BIT:
    1499           1 :             sp->pixel_size = sizeof(uint8_t);
    1500           1 :             break;
    1501           0 :         default:
    1502           0 :             TIFFErrorExtR(tif, module,
    1503             :                           "No support for converting user data format to LogL");
    1504           0 :             return (0);
    1505             :     }
    1506           2 :     if (isTiled(tif))
    1507           0 :         sp->tbuflen = multiply_ms(td->td_tilewidth, td->td_tilelength);
    1508           2 :     else if (td->td_rowsperstrip < td->td_imagelength)
    1509           0 :         sp->tbuflen = multiply_ms(td->td_imagewidth, td->td_rowsperstrip);
    1510             :     else
    1511           2 :         sp->tbuflen = multiply_ms(td->td_imagewidth, td->td_imagelength);
    1512           2 :     if (multiply_ms(sp->tbuflen, sizeof(int16_t)) == 0 ||
    1513           2 :         (sp->tbuf = (uint8_t *)_TIFFmallocExt(
    1514           2 :              tif, (tmsize_t)((size_t)sp->tbuflen * sizeof(int16_t)))) == NULL)
    1515             :     {
    1516           0 :         TIFFErrorExtR(tif, module, "No space for SGILog translation buffer");
    1517           0 :         return (0);
    1518             :     }
    1519           2 :     return (1);
    1520             : }
    1521             : 
    1522           0 : static int LogLuvGuessDataFmt(TIFFDirectory *td)
    1523             : {
    1524             :     int guess;
    1525             : 
    1526             :     /*
    1527             :      * If the user didn't tell us their datafmt,
    1528             :      * take our best guess from the bitspersample.
    1529             :      */
    1530             : #define PACK(a, b) (((a) << 3) | (b))
    1531           0 :     switch (PACK(td->td_bitspersample, td->td_sampleformat))
    1532             :     {
    1533           0 :         case PACK(32, SAMPLEFORMAT_IEEEFP):
    1534           0 :             guess = SGILOGDATAFMT_FLOAT;
    1535           0 :             break;
    1536           0 :         case PACK(32, SAMPLEFORMAT_VOID):
    1537             :         case PACK(32, SAMPLEFORMAT_UINT):
    1538             :         case PACK(32, SAMPLEFORMAT_INT):
    1539           0 :             guess = SGILOGDATAFMT_RAW;
    1540           0 :             break;
    1541           0 :         case PACK(16, SAMPLEFORMAT_VOID):
    1542             :         case PACK(16, SAMPLEFORMAT_INT):
    1543             :         case PACK(16, SAMPLEFORMAT_UINT):
    1544           0 :             guess = SGILOGDATAFMT_16BIT;
    1545           0 :             break;
    1546           0 :         case PACK(8, SAMPLEFORMAT_VOID):
    1547             :         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             : #undef PACK
    1554             :     }
    1555             :     /*
    1556             :      * Double-check samples per pixel.
    1557             :      */
    1558           0 :     switch (td->td_samplesperpixel)
    1559             :     {
    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             :     }
    1572           0 :     return (guess);
    1573             : }
    1574             : 
    1575           0 : static int LogLuvInitState(TIFF *tif)
    1576             : {
    1577             :     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             :     {
    1587           0 :         TIFFErrorExtR(tif, module,
    1588             :                       "SGILog compression cannot handle non-contiguous data");
    1589           0 :         return (0);
    1590             :     }
    1591           0 :     if (sp->user_datafmt == SGILOGDATAFMT_UNKNOWN)
    1592           0 :         sp->user_datafmt = LogLuvGuessDataFmt(td);
    1593           0 :     switch (sp->user_datafmt)
    1594             :     {
    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             :                 tif, module,
    1610             :                 "No support for converting user data format to LogLuv");
    1611           0 :             return (0);
    1612             :     }
    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             :     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             :     {
    1623           0 :         TIFFErrorExtR(tif, module, "No space for SGILog translation buffer");
    1624           0 :         return (0);
    1625             :     }
    1626           0 :     return (1);
    1627             : }
    1628             : 
    1629           3 : static int LogLuvFixupTags(TIFF *tif)
    1630             : {
    1631             :     (void)tif;
    1632           3 :     return (1);
    1633             : }
    1634             : 
    1635           2 : static int LogLuvSetupDecode(TIFF *tif)
    1636             : {
    1637             :     static const char module[] = "LogLuvSetupDecode";
    1638           2 :     LogLuvState *sp = DecoderState(tif);
    1639           2 :     TIFFDirectory *td = &tif->tif_dir;
    1640             : 
    1641           2 :     tif->tif_postdecode = _TIFFNoPostDecode;
    1642           2 :     switch (td->td_photometric)
    1643             :     {
    1644           0 :         case PHOTOMETRIC_LOGLUV:
    1645           0 :             if (!LogLuvInitState(tif))
    1646           0 :                 break;
    1647           0 :             if (td->td_compression == COMPRESSION_SGILOG24)
    1648             :             {
    1649           0 :                 tif->tif_decoderow = LogLuvDecode24;
    1650           0 :                 switch (sp->user_datafmt)
    1651             :                 {
    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             :                 }
    1664             :             }
    1665             :             else
    1666             :             {
    1667           0 :                 tif->tif_decoderow = LogLuvDecode32;
    1668           0 :                 switch (sp->user_datafmt)
    1669             :                 {
    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             :                 }
    1682             :             }
    1683           0 :             return (1);
    1684           2 :         case PHOTOMETRIC_LOGL:
    1685           2 :             if (!LogL16InitState(tif))
    1686           0 :                 break;
    1687           2 :             tif->tif_decoderow = LogL16Decode;
    1688           2 :             switch (sp->user_datafmt)
    1689             :             {
    1690           0 :                 case SGILOGDATAFMT_FLOAT:
    1691           0 :                     sp->tfunc = L16toY;
    1692           0 :                     break;
    1693           1 :                 case SGILOGDATAFMT_8BIT:
    1694           1 :                     sp->tfunc = L16toGry;
    1695           1 :                     break;
    1696           1 :                 default:
    1697           1 :                     break;
    1698             :             }
    1699           2 :             return (1);
    1700           0 :         default:
    1701           0 :             TIFFErrorExtR(tif, module,
    1702             :                           "Inappropriate photometric interpretation %" PRIu16
    1703             :                           " for SGILog compression; %s",
    1704           0 :                           td->td_photometric, "must be either LogLUV or LogL");
    1705           0 :             break;
    1706             :     }
    1707           0 :     return (0);
    1708             : }
    1709             : 
    1710           0 : static int LogLuvSetupEncode(TIFF *tif)
    1711             : {
    1712             :     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             :     {
    1718           0 :         case PHOTOMETRIC_LOGLUV:
    1719           0 :             if (!LogLuvInitState(tif))
    1720           0 :                 return (0);
    1721           0 :             if (td->td_compression == COMPRESSION_SGILOG24)
    1722             :             {
    1723           0 :                 tif->tif_encoderow = LogLuvEncode24;
    1724           0 :                 switch (sp->user_datafmt)
    1725             :                 {
    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             :                 }
    1737             :             }
    1738             :             else
    1739             :             {
    1740           0 :                 tif->tif_encoderow = LogLuvEncode32;
    1741           0 :                 switch (sp->user_datafmt)
    1742             :                 {
    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             :                 }
    1754             :             }
    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             :             {
    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             :             }
    1770           0 :             break;
    1771           0 :         default:
    1772           0 :             TIFFErrorExtR(tif, module,
    1773             :                           "Inappropriate photometric interpretation %" PRIu16
    1774             :                           " for SGILog compression; %s",
    1775           0 :                           td->td_photometric, "must be either LogLUV or LogL");
    1776           0 :             return (0);
    1777             :     }
    1778           0 :     sp->encoder_state = 1;
    1779           0 :     return (1);
    1780           0 : notsupported:
    1781           0 :     TIFFErrorExtR(tif, module,
    1782             :                   "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             : }
    1786             : 
    1787           0 : static void LogLuvClose(TIFF *tif)
    1788             : {
    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             :     {
    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             :     }
    1810           0 : }
    1811             : 
    1812           3 : static void LogLuvCleanup(TIFF *tif)
    1813             : {
    1814           3 :     LogLuvState *sp = (LogLuvState *)tif->tif_data;
    1815             : 
    1816           3 :     assert(sp != 0);
    1817             : 
    1818           3 :     tif->tif_tagmethods.vgetfield = sp->vgetparent;
    1819           3 :     tif->tif_tagmethods.vsetfield = sp->vsetparent;
    1820             : 
    1821           3 :     if (sp->tbuf)
    1822           2 :         _TIFFfreeExt(tif, sp->tbuf);
    1823           3 :     _TIFFfreeExt(tif, sp);
    1824           3 :     tif->tif_data = NULL;
    1825             : 
    1826           3 :     _TIFFSetDefaultCompressionState(tif);
    1827           3 : }
    1828             : 
    1829          27 : static int LogLuvVSetField(TIFF *tif, uint32_t tag, va_list ap)
    1830             : {
    1831             :     static const char module[] = "LogLuvVSetField";
    1832          27 :     LogLuvState *sp = DecoderState(tif);
    1833             :     int bps, fmt;
    1834             : 
    1835          27 :     switch (tag)
    1836             :     {
    1837           1 :         case TIFFTAG_SGILOGDATAFMT:
    1838           1 :             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           1 :             switch (sp->user_datafmt)
    1846             :             {
    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           1 :                 case SGILOGDATAFMT_8BIT:
    1861           1 :                     bps = 8;
    1862           1 :                     fmt = SAMPLEFORMAT_UINT;
    1863           1 :                     break;
    1864           0 :                 default:
    1865           0 :                     TIFFErrorExtR(
    1866           0 :                         tif, tif->tif_name,
    1867             :                         "Unknown data format %d for LogLuv compression",
    1868             :                         sp->user_datafmt);
    1869           0 :                     return (0);
    1870             :             }
    1871           1 :             TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps);
    1872           1 :             TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, fmt);
    1873             :             /*
    1874             :              * Must recalculate sizes should bits/sample change.
    1875             :              */
    1876           1 :             tif->tif_dir.td_tilesize =
    1877           1 :                 isTiled(tif) ? TIFFTileSize(tif) : (tmsize_t)-1;
    1878           1 :             tif->tif_dir.td_scanlinesize = TIFFScanlineSize(tif);
    1879           1 :             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             :             {
    1885           0 :                 TIFFErrorExtR(tif, module,
    1886             :                               "Unknown encoding %d for LogLuv compression",
    1887             :                               sp->encode_meth);
    1888           0 :                 return (0);
    1889             :             }
    1890           0 :             return (1);
    1891          26 :         default:
    1892          26 :             return (*sp->vsetparent)(tif, tag, ap);
    1893             :     }
    1894             : }
    1895             : 
    1896          49 : static int LogLuvVGetField(TIFF *tif, uint32_t tag, va_list ap)
    1897             : {
    1898          49 :     LogLuvState *sp = (LogLuvState *)tif->tif_data;
    1899             : 
    1900          49 :     switch (tag)
    1901             :     {
    1902           0 :         case TIFFTAG_SGILOGDATAFMT:
    1903           0 :             *va_arg(ap, int *) = sp->user_datafmt;
    1904           0 :             return (1);
    1905          49 :         default:
    1906          49 :             return (*sp->vgetparent)(tif, tag, ap);
    1907             :     }
    1908             : }
    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           3 : int TIFFInitSGILog(TIFF *tif, int scheme)
    1917             : {
    1918             :     static const char module[] = "TIFFInitSGILog";
    1919             :     LogLuvState *sp;
    1920             : 
    1921           3 :     assert(scheme == COMPRESSION_SGILOG24 || scheme == COMPRESSION_SGILOG);
    1922             : 
    1923             :     /*
    1924             :      * Merge codec-specific tag information.
    1925             :      */
    1926           3 :     if (!_TIFFMergeFields(tif, LogLuvFields, TIFFArrayCount(LogLuvFields)))
    1927             :     {
    1928           0 :         TIFFErrorExtR(tif, module, "Merging SGILog codec-specific tags failed");
    1929           0 :         return 0;
    1930             :     }
    1931             : 
    1932             :     /*
    1933             :      * Allocate state block so tag methods have storage to record values.
    1934             :      */
    1935           3 :     tif->tif_data = (uint8_t *)_TIFFmallocExt(tif, sizeof(LogLuvState));
    1936           3 :     if (tif->tif_data == NULL)
    1937           0 :         goto bad;
    1938           3 :     sp = (LogLuvState *)tif->tif_data;
    1939           3 :     _TIFFmemset((void *)sp, 0, sizeof(*sp));
    1940           3 :     sp->user_datafmt = SGILOGDATAFMT_UNKNOWN;
    1941           3 :     sp->encode_meth = (scheme == COMPRESSION_SGILOG24) ? SGILOGENCODE_RANDITHER
    1942           3 :                                                        : SGILOGENCODE_NODITHER;
    1943           3 :     sp->tfunc = _logLuvNop;
    1944             : 
    1945             :     /*
    1946             :      * Install codec methods.
    1947             :      * NB: tif_decoderow & tif_encoderow are filled
    1948             :      *     in at setup time.
    1949             :      */
    1950           3 :     tif->tif_fixuptags = LogLuvFixupTags;
    1951           3 :     tif->tif_setupdecode = LogLuvSetupDecode;
    1952           3 :     tif->tif_decodestrip = LogLuvDecodeStrip;
    1953           3 :     tif->tif_decodetile = LogLuvDecodeTile;
    1954           3 :     tif->tif_setupencode = LogLuvSetupEncode;
    1955           3 :     tif->tif_encodestrip = LogLuvEncodeStrip;
    1956           3 :     tif->tif_encodetile = LogLuvEncodeTile;
    1957           3 :     tif->tif_close = LogLuvClose;
    1958           3 :     tif->tif_cleanup = LogLuvCleanup;
    1959             : 
    1960             :     /*
    1961             :      * Override parent get/set field methods.
    1962             :      */
    1963           3 :     sp->vgetparent = tif->tif_tagmethods.vgetfield;
    1964           3 :     tif->tif_tagmethods.vgetfield = LogLuvVGetField; /* hook for codec tags */
    1965           3 :     sp->vsetparent = tif->tif_tagmethods.vsetfield;
    1966           3 :     tif->tif_tagmethods.vsetfield = LogLuvVSetField; /* hook for codec tags */
    1967             : 
    1968           3 :     return (1);
    1969           0 : bad:
    1970           0 :     TIFFErrorExtR(tif, module, "%s: No space for LogLuv state block",
    1971             :                   tif->tif_name);
    1972           0 :     return (0);
    1973             : }
    1974             : #endif /* LOGLUV_SUPPORT */

Generated by: LCOV version 1.14