Home | History | Annotate | Download | only in libtiff
      1 /* $Id: tif_pixarlog.c,v 1.39 2012-12-10 17:27:13 tgl Exp $ */
      2 
      3 /*
      4  * Copyright (c) 1996-1997 Sam Leffler
      5  * Copyright (c) 1996 Pixar
      6  *
      7  * Permission to use, copy, modify, distribute, and sell this software and
      8  * its documentation for any purpose is hereby granted without fee, provided
      9  * that (i) the above copyright notices and this permission notice appear in
     10  * all copies of the software and related documentation, and (ii) the names of
     11  * Pixar, Sam Leffler and Silicon Graphics may not be used in any advertising or
     12  * publicity relating to the software without the specific, prior written
     13  * permission of Pixar, Sam Leffler and Silicon Graphics.
     14  *
     15  * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
     16  * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
     17  * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
     18  *
     19  * IN NO EVENT SHALL PIXAR, SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
     20  * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
     21  * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
     22  * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
     23  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
     24  * OF THIS SOFTWARE.
     25  */
     26 
     27 #include "tiffiop.h"
     28 #ifdef PIXARLOG_SUPPORT
     29 
     30 /*
     31  * TIFF Library.
     32  * PixarLog Compression Support
     33  *
     34  * Contributed by Dan McCoy.
     35  *
     36  * PixarLog film support uses the TIFF library to store companded
     37  * 11 bit values into a tiff file, which are compressed using the
     38  * zip compressor.
     39  *
     40  * The codec can take as input and produce as output 32-bit IEEE float values
     41  * as well as 16-bit or 8-bit unsigned integer values.
     42  *
     43  * On writing any of the above are converted into the internal
     44  * 11-bit log format.   In the case of  8 and 16 bit values, the
     45  * input is assumed to be unsigned linear color values that represent
     46  * the range 0-1.  In the case of IEEE values, the 0-1 range is assumed to
     47  * be the normal linear color range, in addition over 1 values are
     48  * accepted up to a value of about 25.0 to encode "hot" hightlights and such.
     49  * The encoding is lossless for 8-bit values, slightly lossy for the
     50  * other bit depths.  The actual color precision should be better
     51  * than the human eye can perceive with extra room to allow for
     52  * error introduced by further image computation.  As with any quantized
     53  * color format, it is possible to perform image calculations which
     54  * expose the quantization error. This format should certainly be less
     55  * susceptable to such errors than standard 8-bit encodings, but more
     56  * susceptable than straight 16-bit or 32-bit encodings.
     57  *
     58  * On reading the internal format is converted to the desired output format.
     59  * The program can request which format it desires by setting the internal
     60  * pseudo tag TIFFTAG_PIXARLOGDATAFMT to one of these possible values:
     61  *  PIXARLOGDATAFMT_FLOAT     = provide IEEE float values.
     62  *  PIXARLOGDATAFMT_16BIT     = provide unsigned 16-bit integer values
     63  *  PIXARLOGDATAFMT_8BIT      = provide unsigned 8-bit integer values
     64  *
     65  * alternately PIXARLOGDATAFMT_8BITABGR provides unsigned 8-bit integer
     66  * values with the difference that if there are exactly three or four channels
     67  * (rgb or rgba) it swaps the channel order (bgr or abgr).
     68  *
     69  * PIXARLOGDATAFMT_11BITLOG provides the internal encoding directly
     70  * packed in 16-bit values.   However no tools are supplied for interpreting
     71  * these values.
     72  *
     73  * "hot" (over 1.0) areas written in floating point get clamped to
     74  * 1.0 in the integer data types.
     75  *
     76  * When the file is closed after writing, the bit depth and sample format
     77  * are set always to appear as if 8-bit data has been written into it.
     78  * That way a naive program unaware of the particulars of the encoding
     79  * gets the format it is most likely able to handle.
     80  *
     81  * The codec does it's own horizontal differencing step on the coded
     82  * values so the libraries predictor stuff should be turned off.
     83  * The codec also handle byte swapping the encoded values as necessary
     84  * since the library does not have the information necessary
     85  * to know the bit depth of the raw unencoded buffer.
     86  *
     87  * NOTE: This decoder does not appear to update tif_rawcp, and tif_rawcc.
     88  * This can cause problems with the implementation of CHUNKY_STRIP_READ_SUPPORT
     89  * as noted in http://trac.osgeo.org/gdal/ticket/3894.   FrankW - Jan'11
     90  */
     91 
     92 #include "tif_predict.h"
     93 #include "../zlib_v128/zlib.h"
     94 
     95 #include <stdio.h>
     96 #include <stdlib.h>
     97 #include <math.h>
     98 
     99 /* Tables for converting to/from 11 bit coded values */
    100 
    101 #define  TSIZE	 2048		/* decode table size (11-bit tokens) */
    102 #define  TSIZEP1 2049		/* Plus one for slop */
    103 #define  ONE	 1250		/* token value of 1.0 exactly */
    104 #define  RATIO	 1.004		/* nominal ratio for log part */
    105 
    106 #define CODE_MASK 0x7ff         /* 11 bits. */
    107 
    108 static float  Fltsize;
    109 static float  LogK1, LogK2;
    110 
    111 #define REPEAT(n, op)   { int i; i=n; do { i--; op; } while (i>0); }
    112 
    113 static void
    114 horizontalAccumulateF(uint16 *wp, int n, int stride, float *op,
    115 	float *ToLinearF)
    116 {
    117     register unsigned int  cr, cg, cb, ca, mask;
    118     register float  t0, t1, t2, t3;
    119 
    120     if (n >= stride) {
    121 	mask = CODE_MASK;
    122 	if (stride == 3) {
    123 	    t0 = ToLinearF[cr = (wp[0] & mask)];
    124 	    t1 = ToLinearF[cg = (wp[1] & mask)];
    125 	    t2 = ToLinearF[cb = (wp[2] & mask)];
    126 	    op[0] = t0;
    127 	    op[1] = t1;
    128 	    op[2] = t2;
    129 	    n -= 3;
    130 	    while (n > 0) {
    131 		wp += 3;
    132 		op += 3;
    133 		n -= 3;
    134 		t0 = ToLinearF[(cr += wp[0]) & mask];
    135 		t1 = ToLinearF[(cg += wp[1]) & mask];
    136 		t2 = ToLinearF[(cb += wp[2]) & mask];
    137 		op[0] = t0;
    138 		op[1] = t1;
    139 		op[2] = t2;
    140 	    }
    141 	} else if (stride == 4) {
    142 	    t0 = ToLinearF[cr = (wp[0] & mask)];
    143 	    t1 = ToLinearF[cg = (wp[1] & mask)];
    144 	    t2 = ToLinearF[cb = (wp[2] & mask)];
    145 	    t3 = ToLinearF[ca = (wp[3] & mask)];
    146 	    op[0] = t0;
    147 	    op[1] = t1;
    148 	    op[2] = t2;
    149 	    op[3] = t3;
    150 	    n -= 4;
    151 	    while (n > 0) {
    152 		wp += 4;
    153 		op += 4;
    154 		n -= 4;
    155 		t0 = ToLinearF[(cr += wp[0]) & mask];
    156 		t1 = ToLinearF[(cg += wp[1]) & mask];
    157 		t2 = ToLinearF[(cb += wp[2]) & mask];
    158 		t3 = ToLinearF[(ca += wp[3]) & mask];
    159 		op[0] = t0;
    160 		op[1] = t1;
    161 		op[2] = t2;
    162 		op[3] = t3;
    163 	    }
    164 	} else {
    165 	    REPEAT(stride, *op = ToLinearF[*wp&mask]; wp++; op++)
    166 	    n -= stride;
    167 	    while (n > 0) {
    168 		REPEAT(stride,
    169 		    wp[stride] += *wp; *op = ToLinearF[*wp&mask]; wp++; op++)
    170 		n -= stride;
    171 	    }
    172 	}
    173     }
    174 }
    175 
    176 static void
    177 horizontalAccumulate12(uint16 *wp, int n, int stride, int16 *op,
    178 	float *ToLinearF)
    179 {
    180     register unsigned int  cr, cg, cb, ca, mask;
    181     register float  t0, t1, t2, t3;
    182 
    183 #define SCALE12 2048.0F
    184 #define CLAMP12(t) (((t) < 3071) ? (uint16) (t) : 3071)
    185 
    186     if (n >= stride) {
    187 	mask = CODE_MASK;
    188 	if (stride == 3) {
    189 	    t0 = ToLinearF[cr = (wp[0] & mask)] * SCALE12;
    190 	    t1 = ToLinearF[cg = (wp[1] & mask)] * SCALE12;
    191 	    t2 = ToLinearF[cb = (wp[2] & mask)] * SCALE12;
    192 	    op[0] = CLAMP12(t0);
    193 	    op[1] = CLAMP12(t1);
    194 	    op[2] = CLAMP12(t2);
    195 	    n -= 3;
    196 	    while (n > 0) {
    197 		wp += 3;
    198 		op += 3;
    199 		n -= 3;
    200 		t0 = ToLinearF[(cr += wp[0]) & mask] * SCALE12;
    201 		t1 = ToLinearF[(cg += wp[1]) & mask] * SCALE12;
    202 		t2 = ToLinearF[(cb += wp[2]) & mask] * SCALE12;
    203 		op[0] = CLAMP12(t0);
    204 		op[1] = CLAMP12(t1);
    205 		op[2] = CLAMP12(t2);
    206 	    }
    207 	} else if (stride == 4) {
    208 	    t0 = ToLinearF[cr = (wp[0] & mask)] * SCALE12;
    209 	    t1 = ToLinearF[cg = (wp[1] & mask)] * SCALE12;
    210 	    t2 = ToLinearF[cb = (wp[2] & mask)] * SCALE12;
    211 	    t3 = ToLinearF[ca = (wp[3] & mask)] * SCALE12;
    212 	    op[0] = CLAMP12(t0);
    213 	    op[1] = CLAMP12(t1);
    214 	    op[2] = CLAMP12(t2);
    215 	    op[3] = CLAMP12(t3);
    216 	    n -= 4;
    217 	    while (n > 0) {
    218 		wp += 4;
    219 		op += 4;
    220 		n -= 4;
    221 		t0 = ToLinearF[(cr += wp[0]) & mask] * SCALE12;
    222 		t1 = ToLinearF[(cg += wp[1]) & mask] * SCALE12;
    223 		t2 = ToLinearF[(cb += wp[2]) & mask] * SCALE12;
    224 		t3 = ToLinearF[(ca += wp[3]) & mask] * SCALE12;
    225 		op[0] = CLAMP12(t0);
    226 		op[1] = CLAMP12(t1);
    227 		op[2] = CLAMP12(t2);
    228 		op[3] = CLAMP12(t3);
    229 	    }
    230 	} else {
    231 	    REPEAT(stride, t0 = ToLinearF[*wp&mask] * SCALE12;
    232                            *op = CLAMP12(t0); wp++; op++)
    233 	    n -= stride;
    234 	    while (n > 0) {
    235 		REPEAT(stride,
    236 		    wp[stride] += *wp; t0 = ToLinearF[wp[stride]&mask]*SCALE12;
    237 		    *op = CLAMP12(t0);  wp++; op++)
    238 		n -= stride;
    239 	    }
    240 	}
    241     }
    242 }
    243 
    244 static void
    245 horizontalAccumulate16(uint16 *wp, int n, int stride, uint16 *op,
    246 	uint16 *ToLinear16)
    247 {
    248     register unsigned int  cr, cg, cb, ca, mask;
    249 
    250     if (n >= stride) {
    251 	mask = CODE_MASK;
    252 	if (stride == 3) {
    253 	    op[0] = ToLinear16[cr = (wp[0] & mask)];
    254 	    op[1] = ToLinear16[cg = (wp[1] & mask)];
    255 	    op[2] = ToLinear16[cb = (wp[2] & mask)];
    256 	    n -= 3;
    257 	    while (n > 0) {
    258 		wp += 3;
    259 		op += 3;
    260 		n -= 3;
    261 		op[0] = ToLinear16[(cr += wp[0]) & mask];
    262 		op[1] = ToLinear16[(cg += wp[1]) & mask];
    263 		op[2] = ToLinear16[(cb += wp[2]) & mask];
    264 	    }
    265 	} else if (stride == 4) {
    266 	    op[0] = ToLinear16[cr = (wp[0] & mask)];
    267 	    op[1] = ToLinear16[cg = (wp[1] & mask)];
    268 	    op[2] = ToLinear16[cb = (wp[2] & mask)];
    269 	    op[3] = ToLinear16[ca = (wp[3] & mask)];
    270 	    n -= 4;
    271 	    while (n > 0) {
    272 		wp += 4;
    273 		op += 4;
    274 		n -= 4;
    275 		op[0] = ToLinear16[(cr += wp[0]) & mask];
    276 		op[1] = ToLinear16[(cg += wp[1]) & mask];
    277 		op[2] = ToLinear16[(cb += wp[2]) & mask];
    278 		op[3] = ToLinear16[(ca += wp[3]) & mask];
    279 	    }
    280 	} else {
    281 	    REPEAT(stride, *op = ToLinear16[*wp&mask]; wp++; op++)
    282 	    n -= stride;
    283 	    while (n > 0) {
    284 		REPEAT(stride,
    285 		    wp[stride] += *wp; *op = ToLinear16[*wp&mask]; wp++; op++)
    286 		n -= stride;
    287 	    }
    288 	}
    289     }
    290 }
    291 
    292 /*
    293  * Returns the log encoded 11-bit values with the horizontal
    294  * differencing undone.
    295  */
    296 static void
    297 horizontalAccumulate11(uint16 *wp, int n, int stride, uint16 *op)
    298 {
    299     register unsigned int  cr, cg, cb, ca, mask;
    300 
    301     if (n >= stride) {
    302 	mask = CODE_MASK;
    303 	if (stride == 3) {
    304 	    op[0] = cr = wp[0];  op[1] = cg = wp[1];  op[2] = cb = wp[2];
    305 	    n -= 3;
    306 	    while (n > 0) {
    307 		wp += 3;
    308 		op += 3;
    309 		n -= 3;
    310 		op[0] = (cr += wp[0]) & mask;
    311 		op[1] = (cg += wp[1]) & mask;
    312 		op[2] = (cb += wp[2]) & mask;
    313 	    }
    314 	} else if (stride == 4) {
    315 	    op[0] = cr = wp[0];  op[1] = cg = wp[1];
    316 	    op[2] = cb = wp[2];  op[3] = ca = wp[3];
    317 	    n -= 4;
    318 	    while (n > 0) {
    319 		wp += 4;
    320 		op += 4;
    321 		n -= 4;
    322 		op[0] = (cr += wp[0]) & mask;
    323 		op[1] = (cg += wp[1]) & mask;
    324 		op[2] = (cb += wp[2]) & mask;
    325 		op[3] = (ca += wp[3]) & mask;
    326 	    }
    327 	} else {
    328 	    REPEAT(stride, *op = *wp&mask; wp++; op++)
    329 	    n -= stride;
    330 	    while (n > 0) {
    331 		REPEAT(stride,
    332 		    wp[stride] += *wp; *op = *wp&mask; wp++; op++)
    333 		n -= stride;
    334 	    }
    335 	}
    336     }
    337 }
    338 
    339 static void
    340 horizontalAccumulate8(uint16 *wp, int n, int stride, unsigned char *op,
    341 	unsigned char *ToLinear8)
    342 {
    343     register unsigned int  cr, cg, cb, ca, mask;
    344 
    345     if (n >= stride) {
    346 	mask = CODE_MASK;
    347 	if (stride == 3) {
    348 	    op[0] = ToLinear8[cr = (wp[0] & mask)];
    349 	    op[1] = ToLinear8[cg = (wp[1] & mask)];
    350 	    op[2] = ToLinear8[cb = (wp[2] & mask)];
    351 	    n -= 3;
    352 	    while (n > 0) {
    353 		n -= 3;
    354 		wp += 3;
    355 		op += 3;
    356 		op[0] = ToLinear8[(cr += wp[0]) & mask];
    357 		op[1] = ToLinear8[(cg += wp[1]) & mask];
    358 		op[2] = ToLinear8[(cb += wp[2]) & mask];
    359 	    }
    360 	} else if (stride == 4) {
    361 	    op[0] = ToLinear8[cr = (wp[0] & mask)];
    362 	    op[1] = ToLinear8[cg = (wp[1] & mask)];
    363 	    op[2] = ToLinear8[cb = (wp[2] & mask)];
    364 	    op[3] = ToLinear8[ca = (wp[3] & mask)];
    365 	    n -= 4;
    366 	    while (n > 0) {
    367 		n -= 4;
    368 		wp += 4;
    369 		op += 4;
    370 		op[0] = ToLinear8[(cr += wp[0]) & mask];
    371 		op[1] = ToLinear8[(cg += wp[1]) & mask];
    372 		op[2] = ToLinear8[(cb += wp[2]) & mask];
    373 		op[3] = ToLinear8[(ca += wp[3]) & mask];
    374 	    }
    375 	} else {
    376 	    REPEAT(stride, *op = ToLinear8[*wp&mask]; wp++; op++)
    377 	    n -= stride;
    378 	    while (n > 0) {
    379 		REPEAT(stride,
    380 		    wp[stride] += *wp; *op = ToLinear8[*wp&mask]; wp++; op++)
    381 		n -= stride;
    382 	    }
    383 	}
    384     }
    385 }
    386 
    387 
    388 static void
    389 horizontalAccumulate8abgr(uint16 *wp, int n, int stride, unsigned char *op,
    390 	unsigned char *ToLinear8)
    391 {
    392     register unsigned int  cr, cg, cb, ca, mask;
    393     register unsigned char  t0, t1, t2, t3;
    394 
    395     if (n >= stride) {
    396 	mask = CODE_MASK;
    397 	if (stride == 3) {
    398 	    op[0] = 0;
    399 	    t1 = ToLinear8[cb = (wp[2] & mask)];
    400 	    t2 = ToLinear8[cg = (wp[1] & mask)];
    401 	    t3 = ToLinear8[cr = (wp[0] & mask)];
    402 	    op[1] = t1;
    403 	    op[2] = t2;
    404 	    op[3] = t3;
    405 	    n -= 3;
    406 	    while (n > 0) {
    407 		n -= 3;
    408 		wp += 3;
    409 		op += 4;
    410 		op[0] = 0;
    411 		t1 = ToLinear8[(cb += wp[2]) & mask];
    412 		t2 = ToLinear8[(cg += wp[1]) & mask];
    413 		t3 = ToLinear8[(cr += wp[0]) & mask];
    414 		op[1] = t1;
    415 		op[2] = t2;
    416 		op[3] = t3;
    417 	    }
    418 	} else if (stride == 4) {
    419 	    t0 = ToLinear8[ca = (wp[3] & mask)];
    420 	    t1 = ToLinear8[cb = (wp[2] & mask)];
    421 	    t2 = ToLinear8[cg = (wp[1] & mask)];
    422 	    t3 = ToLinear8[cr = (wp[0] & mask)];
    423 	    op[0] = t0;
    424 	    op[1] = t1;
    425 	    op[2] = t2;
    426 	    op[3] = t3;
    427 	    n -= 4;
    428 	    while (n > 0) {
    429 		n -= 4;
    430 		wp += 4;
    431 		op += 4;
    432 		t0 = ToLinear8[(ca += wp[3]) & mask];
    433 		t1 = ToLinear8[(cb += wp[2]) & mask];
    434 		t2 = ToLinear8[(cg += wp[1]) & mask];
    435 		t3 = ToLinear8[(cr += wp[0]) & mask];
    436 		op[0] = t0;
    437 		op[1] = t1;
    438 		op[2] = t2;
    439 		op[3] = t3;
    440 	    }
    441 	} else {
    442 	    REPEAT(stride, *op = ToLinear8[*wp&mask]; wp++; op++)
    443 	    n -= stride;
    444 	    while (n > 0) {
    445 		REPEAT(stride,
    446 		    wp[stride] += *wp; *op = ToLinear8[*wp&mask]; wp++; op++)
    447 		n -= stride;
    448 	    }
    449 	}
    450     }
    451 }
    452 
    453 /*
    454  * State block for each open TIFF
    455  * file using PixarLog compression/decompression.
    456  */
    457 typedef	struct {
    458 	TIFFPredictorState	predict;
    459 	z_stream		stream;
    460 	tmsize_t		tbuf_size; /* only set/used on reading for now */
    461 	uint16			*tbuf;
    462 	uint16			stride;
    463 	int			state;
    464 	int			user_datafmt;
    465 	int			quality;
    466 #define PLSTATE_INIT 1
    467 
    468 	TIFFVSetMethod		vgetparent;	/* super-class method */
    469 	TIFFVSetMethod		vsetparent;	/* super-class method */
    470 
    471 	float *ToLinearF;
    472 	uint16 *ToLinear16;
    473 	unsigned char *ToLinear8;
    474 	uint16  *FromLT2;
    475 	uint16  *From14; /* Really for 16-bit data, but we shift down 2 */
    476 	uint16  *From8;
    477 
    478 } PixarLogState;
    479 
    480 static int
    481 PixarLogMakeTables(PixarLogState *sp)
    482 {
    483 
    484 /*
    485  *    We make several tables here to convert between various external
    486  *    representations (float, 16-bit, and 8-bit) and the internal
    487  *    11-bit companded representation.  The 11-bit representation has two
    488  *    distinct regions.  A linear bottom end up through .018316 in steps
    489  *    of about .000073, and a region of constant ratio up to about 25.
    490  *    These floating point numbers are stored in the main table ToLinearF.
    491  *    All other tables are derived from this one.  The tables (and the
    492  *    ratios) are continuous at the internal seam.
    493  */
    494 
    495     int  nlin, lt2size;
    496     int  i, j;
    497     double  b, c, linstep, v;
    498     float *ToLinearF;
    499     uint16 *ToLinear16;
    500     unsigned char *ToLinear8;
    501     uint16  *FromLT2;
    502     uint16  *From14; /* Really for 16-bit data, but we shift down 2 */
    503     uint16  *From8;
    504 
    505     c = log(RATIO);
    506     nlin = (int)(1./c);	/* nlin must be an integer */
    507     c = 1./nlin;
    508     b = exp(-c*ONE);	/* multiplicative scale factor [b*exp(c*ONE) = 1] */
    509     linstep = b*c*exp(1.);
    510 
    511     LogK1 = (float)(1./c);	/* if (v >= 2)  token = k1*log(v*k2) */
    512     LogK2 = (float)(1./b);
    513     lt2size = (int)(2./linstep) + 1;
    514     FromLT2 = (uint16 *)_TIFFmalloc(lt2size*sizeof(uint16));
    515     From14 = (uint16 *)_TIFFmalloc(16384*sizeof(uint16));
    516     From8 = (uint16 *)_TIFFmalloc(256*sizeof(uint16));
    517     ToLinearF = (float *)_TIFFmalloc(TSIZEP1 * sizeof(float));
    518     ToLinear16 = (uint16 *)_TIFFmalloc(TSIZEP1 * sizeof(uint16));
    519     ToLinear8 = (unsigned char *)_TIFFmalloc(TSIZEP1 * sizeof(unsigned char));
    520     if (FromLT2 == NULL || From14  == NULL || From8   == NULL ||
    521 	 ToLinearF == NULL || ToLinear16 == NULL || ToLinear8 == NULL) {
    522 	if (FromLT2) _TIFFfree(FromLT2);
    523 	if (From14) _TIFFfree(From14);
    524 	if (From8) _TIFFfree(From8);
    525 	if (ToLinearF) _TIFFfree(ToLinearF);
    526 	if (ToLinear16) _TIFFfree(ToLinear16);
    527 	if (ToLinear8) _TIFFfree(ToLinear8);
    528 	sp->FromLT2 = NULL;
    529 	sp->From14 = NULL;
    530 	sp->From8 = NULL;
    531 	sp->ToLinearF = NULL;
    532 	sp->ToLinear16 = NULL;
    533 	sp->ToLinear8 = NULL;
    534 	return 0;
    535     }
    536 
    537     j = 0;
    538 
    539     for (i = 0; i < nlin; i++)  {
    540 	v = i * linstep;
    541 	ToLinearF[j++] = (float)v;
    542     }
    543 
    544     for (i = nlin; i < TSIZE; i++)
    545 	ToLinearF[j++] = (float)(b*exp(c*i));
    546 
    547     ToLinearF[2048] = ToLinearF[2047];
    548 
    549     for (i = 0; i < TSIZEP1; i++)  {
    550 	v = ToLinearF[i]*65535.0 + 0.5;
    551 	ToLinear16[i] = (v > 65535.0) ? 65535 : (uint16)v;
    552 	v = ToLinearF[i]*255.0  + 0.5;
    553 	ToLinear8[i]  = (v > 255.0) ? 255 : (unsigned char)v;
    554     }
    555 
    556     j = 0;
    557     for (i = 0; i < lt2size; i++)  {
    558 	if ((i*linstep)*(i*linstep) > ToLinearF[j]*ToLinearF[j+1])
    559 	    j++;
    560 	FromLT2[i] = j;
    561     }
    562 
    563     /*
    564      * Since we lose info anyway on 16-bit data, we set up a 14-bit
    565      * table and shift 16-bit values down two bits on input.
    566      * saves a little table space.
    567      */
    568     j = 0;
    569     for (i = 0; i < 16384; i++)  {
    570 	while ((i/16383.)*(i/16383.) > ToLinearF[j]*ToLinearF[j+1])
    571 	    j++;
    572 	From14[i] = j;
    573     }
    574 
    575     j = 0;
    576     for (i = 0; i < 256; i++)  {
    577 	while ((i/255.)*(i/255.) > ToLinearF[j]*ToLinearF[j+1])
    578 	    j++;
    579 	From8[i] = j;
    580     }
    581 
    582     Fltsize = (float)(lt2size/2);
    583 
    584     sp->ToLinearF = ToLinearF;
    585     sp->ToLinear16 = ToLinear16;
    586     sp->ToLinear8 = ToLinear8;
    587     sp->FromLT2 = FromLT2;
    588     sp->From14 = From14;
    589     sp->From8 = From8;
    590 
    591     return 1;
    592 }
    593 
    594 #define DecoderState(tif)	((PixarLogState*) (tif)->tif_data)
    595 #define EncoderState(tif)	((PixarLogState*) (tif)->tif_data)
    596 
    597 static int PixarLogEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s);
    598 static int PixarLogDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s);
    599 
    600 #define PIXARLOGDATAFMT_UNKNOWN	-1
    601 
    602 static int
    603 PixarLogGuessDataFmt(TIFFDirectory *td)
    604 {
    605 	int guess = PIXARLOGDATAFMT_UNKNOWN;
    606 	int format = td->td_sampleformat;
    607 
    608 	/* If the user didn't tell us his datafmt,
    609 	 * take our best guess from the bitspersample.
    610 	 */
    611 	switch (td->td_bitspersample) {
    612 	 case 32:
    613 		if (format == SAMPLEFORMAT_IEEEFP)
    614 			guess = PIXARLOGDATAFMT_FLOAT;
    615 		break;
    616 	 case 16:
    617 		if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT)
    618 			guess = PIXARLOGDATAFMT_16BIT;
    619 		break;
    620 	 case 12:
    621 		if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_INT)
    622 			guess = PIXARLOGDATAFMT_12BITPICIO;
    623 		break;
    624 	 case 11:
    625 		if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT)
    626 			guess = PIXARLOGDATAFMT_11BITLOG;
    627 		break;
    628 	 case 8:
    629 		if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT)
    630 			guess = PIXARLOGDATAFMT_8BIT;
    631 		break;
    632 	}
    633 
    634 	return guess;
    635 }
    636 
    637 static tmsize_t
    638 multiply_ms(tmsize_t m1, tmsize_t m2)
    639 {
    640 	tmsize_t bytes = m1 * m2;
    641 
    642 	if (m1 && bytes / m1 != m2)
    643 		bytes = 0;
    644 
    645 	return bytes;
    646 }
    647 
    648 static tmsize_t
    649 add_ms(tmsize_t m1, tmsize_t m2)
    650 {
    651 	tmsize_t bytes = m1 + m2;
    652 
    653 	/* if either input is zero, assume overflow already occurred */
    654 	if (m1 == 0 || m2 == 0)
    655 		bytes = 0;
    656 	else if (bytes <= m1 || bytes <= m2)
    657 		bytes = 0;
    658 
    659 	return bytes;
    660 }
    661 
    662 static int
    663 PixarLogFixupTags(TIFF* tif)
    664 {
    665 	(void) tif;
    666 	return (1);
    667 }
    668 
    669 static int
    670 PixarLogSetupDecode(TIFF* tif)
    671 {
    672 	static const char module[] = "PixarLogSetupDecode";
    673 	TIFFDirectory *td = &tif->tif_dir;
    674 	PixarLogState* sp = DecoderState(tif);
    675 	tmsize_t tbuf_size;
    676 
    677 	assert(sp != NULL);
    678 
    679 	/* Make sure no byte swapping happens on the data
    680 	 * after decompression. */
    681 	tif->tif_postdecode = _TIFFNoPostDecode;
    682 
    683 	/* for some reason, we can't do this in TIFFInitPixarLog */
    684 
    685 	sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ?
    686 	    td->td_samplesperpixel : 1);
    687 	tbuf_size = multiply_ms(multiply_ms(multiply_ms(sp->stride, td->td_imagewidth),
    688 				      td->td_rowsperstrip), sizeof(uint16));
    689 	/* add one more stride in case input ends mid-stride */
    690 	tbuf_size = add_ms(tbuf_size, sizeof(uint16) * sp->stride);
    691 	if (tbuf_size == 0)
    692 		return (0);   /* TODO: this is an error return without error report through TIFFErrorExt */
    693 	sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size);
    694 	if (sp->tbuf == NULL)
    695 		return (0);
    696 	sp->tbuf_size = tbuf_size;
    697 	if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN)
    698 		sp->user_datafmt = PixarLogGuessDataFmt(td);
    699 	if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) {
    700 		TIFFErrorExt(tif->tif_clientdata, module,
    701 			"PixarLog compression can't handle bits depth/data format combination (depth: %d)",
    702 			td->td_bitspersample);
    703 		return (0);
    704 	}
    705 
    706 	if (inflateInit(&sp->stream) != Z_OK) {
    707 		TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg);
    708 		return (0);
    709 	} else {
    710 		sp->state |= PLSTATE_INIT;
    711 		return (1);
    712 	}
    713 }
    714 
    715 /*
    716  * Setup state for decoding a strip.
    717  */
    718 static int
    719 PixarLogPreDecode(TIFF* tif, uint16 s)
    720 {
    721 	static const char module[] = "PixarLogPreDecode";
    722 	PixarLogState* sp = DecoderState(tif);
    723 
    724 	(void) s;
    725 	assert(sp != NULL);
    726 	sp->stream.next_in = tif->tif_rawdata;
    727 	assert(sizeof(sp->stream.avail_in)==4);  /* if this assert gets raised,
    728 	    we need to simplify this code to reflect a ZLib that is likely updated
    729 	    to deal with 8byte memory sizes, though this code will respond
    730 	    apropriately even before we simplify it */
    731 	sp->stream.avail_in = (uInt) tif->tif_rawcc;
    732 	if ((tmsize_t)sp->stream.avail_in != tif->tif_rawcc)
    733 	{
    734 		TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
    735 		return (0);
    736 	}
    737 	return (inflateReset(&sp->stream) == Z_OK);
    738 }
    739 
    740 static int
    741 PixarLogDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)
    742 {
    743 	static const char module[] = "PixarLogDecode";
    744 	TIFFDirectory *td = &tif->tif_dir;
    745 	PixarLogState* sp = DecoderState(tif);
    746 	tmsize_t i;
    747 	tmsize_t nsamples;
    748 	int llen;
    749 	uint16 *up;
    750 
    751 	switch (sp->user_datafmt) {
    752 	case PIXARLOGDATAFMT_FLOAT:
    753 		nsamples = occ / sizeof(float);	/* XXX float == 32 bits */
    754 		break;
    755 	case PIXARLOGDATAFMT_16BIT:
    756 	case PIXARLOGDATAFMT_12BITPICIO:
    757 	case PIXARLOGDATAFMT_11BITLOG:
    758 		nsamples = occ / sizeof(uint16); /* XXX uint16 == 16 bits */
    759 		break;
    760 	case PIXARLOGDATAFMT_8BIT:
    761 	case PIXARLOGDATAFMT_8BITABGR:
    762 		nsamples = occ;
    763 		break;
    764 	default:
    765 		TIFFErrorExt(tif->tif_clientdata, module,
    766 			"%d bit input not supported in PixarLog",
    767 			td->td_bitspersample);
    768 		return 0;
    769 	}
    770 
    771 	llen = sp->stride * td->td_imagewidth;
    772 
    773 	(void) s;
    774 	assert(sp != NULL);
    775 	sp->stream.next_out = (unsigned char *) sp->tbuf;
    776 	assert(sizeof(sp->stream.avail_out)==4);  /* if this assert gets raised,
    777 	    we need to simplify this code to reflect a ZLib that is likely updated
    778 	    to deal with 8byte memory sizes, though this code will respond
    779 	    apropriately even before we simplify it */
    780 	sp->stream.avail_out = (uInt) (nsamples * sizeof(uint16));
    781 	if (sp->stream.avail_out != nsamples * sizeof(uint16))
    782 	{
    783 		TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
    784 		return (0);
    785 	}
    786 	/* Check that we will not fill more than what was allocated */
    787 	if ((tmsize_t)sp->stream.avail_out > sp->tbuf_size)
    788 	{
    789 		TIFFErrorExt(tif->tif_clientdata, module, "sp->stream.avail_out > sp->tbuf_size");
    790 		return (0);
    791 	}
    792 	do {
    793 		int state = inflate(&sp->stream, Z_PARTIAL_FLUSH);
    794 		if (state == Z_STREAM_END) {
    795 			break;			/* XXX */
    796 		}
    797 		if (state == Z_DATA_ERROR) {
    798 			TIFFErrorExt(tif->tif_clientdata, module,
    799 			    "Decoding error at scanline %lu, %s",
    800 			    (unsigned long) tif->tif_row, sp->stream.msg);
    801 			if (inflateSync(&sp->stream) != Z_OK)
    802 				return (0);
    803 			continue;
    804 		}
    805 		if (state != Z_OK) {
    806 			TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
    807 			    sp->stream.msg);
    808 			return (0);
    809 		}
    810 	} while (sp->stream.avail_out > 0);
    811 
    812 	/* hopefully, we got all the bytes we needed */
    813 	if (sp->stream.avail_out != 0) {
    814 		TIFFErrorExt(tif->tif_clientdata, module,
    815 		    "Not enough data at scanline %lu (short " TIFF_UINT64_FORMAT " bytes)",
    816 		    (unsigned long) tif->tif_row, (TIFF_UINT64_T) sp->stream.avail_out);
    817 		return (0);
    818 	}
    819 
    820 	up = sp->tbuf;
    821 	/* Swap bytes in the data if from a different endian machine. */
    822 	if (tif->tif_flags & TIFF_SWAB)
    823 		TIFFSwabArrayOfShort(up, nsamples);
    824 
    825 	/*
    826 	 * if llen is not an exact multiple of nsamples, the decode operation
    827 	 * may overflow the output buffer, so truncate it enough to prevent
    828 	 * that but still salvage as much data as possible.
    829 	 */
    830 	if (nsamples % llen) {
    831 		TIFFWarningExt(tif->tif_clientdata, module,
    832 			"stride %lu is not a multiple of sample count, "
    833 			"%lu, data truncated.", (unsigned long) llen, (unsigned long) nsamples);
    834 		nsamples -= nsamples % llen;
    835 	}
    836 
    837 	for (i = 0; i < nsamples; i += llen, up += llen) {
    838 		switch (sp->user_datafmt)  {
    839 		case PIXARLOGDATAFMT_FLOAT:
    840 			horizontalAccumulateF(up, llen, sp->stride,
    841 					(float *)op, sp->ToLinearF);
    842 			op += llen * sizeof(float);
    843 			break;
    844 		case PIXARLOGDATAFMT_16BIT:
    845 			horizontalAccumulate16(up, llen, sp->stride,
    846 					(uint16 *)op, sp->ToLinear16);
    847 			op += llen * sizeof(uint16);
    848 			break;
    849 		case PIXARLOGDATAFMT_12BITPICIO:
    850 			horizontalAccumulate12(up, llen, sp->stride,
    851 					(int16 *)op, sp->ToLinearF);
    852 			op += llen * sizeof(int16);
    853 			break;
    854 		case PIXARLOGDATAFMT_11BITLOG:
    855 			horizontalAccumulate11(up, llen, sp->stride,
    856 					(uint16 *)op);
    857 			op += llen * sizeof(uint16);
    858 			break;
    859 		case PIXARLOGDATAFMT_8BIT:
    860 			horizontalAccumulate8(up, llen, sp->stride,
    861 					(unsigned char *)op, sp->ToLinear8);
    862 			op += llen * sizeof(unsigned char);
    863 			break;
    864 		case PIXARLOGDATAFMT_8BITABGR:
    865 			horizontalAccumulate8abgr(up, llen, sp->stride,
    866 					(unsigned char *)op, sp->ToLinear8);
    867 			op += llen * sizeof(unsigned char);
    868 			break;
    869 		default:
    870 			TIFFErrorExt(tif->tif_clientdata, module,
    871 				  "Unsupported bits/sample: %d",
    872 				  td->td_bitspersample);
    873 			return (0);
    874 		}
    875 	}
    876 
    877 	return (1);
    878 }
    879 
    880 static int
    881 PixarLogSetupEncode(TIFF* tif)
    882 {
    883 	static const char module[] = "PixarLogSetupEncode";
    884 	TIFFDirectory *td = &tif->tif_dir;
    885 	PixarLogState* sp = EncoderState(tif);
    886 	tmsize_t tbuf_size;
    887 
    888 	assert(sp != NULL);
    889 
    890 	/* for some reason, we can't do this in TIFFInitPixarLog */
    891 
    892 	sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ?
    893 	    td->td_samplesperpixel : 1);
    894 	tbuf_size = multiply_ms(multiply_ms(multiply_ms(sp->stride, td->td_imagewidth),
    895 				      td->td_rowsperstrip), sizeof(uint16));
    896 	if (tbuf_size == 0)
    897 		return (0);  /* TODO: this is an error return without error report through TIFFErrorExt */
    898 	sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size);
    899 	if (sp->tbuf == NULL)
    900 		return (0);
    901 	if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN)
    902 		sp->user_datafmt = PixarLogGuessDataFmt(td);
    903 	if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) {
    904 		TIFFErrorExt(tif->tif_clientdata, module, "PixarLog compression can't handle %d bit linear encodings", td->td_bitspersample);
    905 		return (0);
    906 	}
    907 
    908 	if (deflateInit(&sp->stream, sp->quality) != Z_OK) {
    909 		TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg);
    910 		return (0);
    911 	} else {
    912 		sp->state |= PLSTATE_INIT;
    913 		return (1);
    914 	}
    915 }
    916 
    917 /*
    918  * Reset encoding state at the start of a strip.
    919  */
    920 static int
    921 PixarLogPreEncode(TIFF* tif, uint16 s)
    922 {
    923 	static const char module[] = "PixarLogPreEncode";
    924 	PixarLogState *sp = EncoderState(tif);
    925 
    926 	(void) s;
    927 	assert(sp != NULL);
    928 	sp->stream.next_out = tif->tif_rawdata;
    929 	assert(sizeof(sp->stream.avail_out)==4);  /* if this assert gets raised,
    930 	    we need to simplify this code to reflect a ZLib that is likely updated
    931 	    to deal with 8byte memory sizes, though this code will respond
    932 	    apropriately even before we simplify it */
    933 	sp->stream.avail_out = tif->tif_rawdatasize;
    934 	if ((tmsize_t)sp->stream.avail_out != tif->tif_rawdatasize)
    935 	{
    936 		TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
    937 		return (0);
    938 	}
    939 	return (deflateReset(&sp->stream) == Z_OK);
    940 }
    941 
    942 static void
    943 horizontalDifferenceF(float *ip, int n, int stride, uint16 *wp, uint16 *FromLT2)
    944 {
    945     int32 r1, g1, b1, a1, r2, g2, b2, a2, mask;
    946     float fltsize = Fltsize;
    947 
    948 #define  CLAMP(v) ( (v<(float)0.)   ? 0				\
    949 		  : (v<(float)2.)   ? FromLT2[(int)(v*fltsize)]	\
    950 		  : (v>(float)24.2) ? 2047			\
    951 		  : LogK1*log(v*LogK2) + 0.5 )
    952 
    953     mask = CODE_MASK;
    954     if (n >= stride) {
    955 	if (stride == 3) {
    956 	    r2 = wp[0] = (uint16) CLAMP(ip[0]);
    957 	    g2 = wp[1] = (uint16) CLAMP(ip[1]);
    958 	    b2 = wp[2] = (uint16) CLAMP(ip[2]);
    959 	    n -= 3;
    960 	    while (n > 0) {
    961 		n -= 3;
    962 		wp += 3;
    963 		ip += 3;
    964 		r1 = (int32) CLAMP(ip[0]); wp[0] = (r1-r2) & mask; r2 = r1;
    965 		g1 = (int32) CLAMP(ip[1]); wp[1] = (g1-g2) & mask; g2 = g1;
    966 		b1 = (int32) CLAMP(ip[2]); wp[2] = (b1-b2) & mask; b2 = b1;
    967 	    }
    968 	} else if (stride == 4) {
    969 	    r2 = wp[0] = (uint16) CLAMP(ip[0]);
    970 	    g2 = wp[1] = (uint16) CLAMP(ip[1]);
    971 	    b2 = wp[2] = (uint16) CLAMP(ip[2]);
    972 	    a2 = wp[3] = (uint16) CLAMP(ip[3]);
    973 	    n -= 4;
    974 	    while (n > 0) {
    975 		n -= 4;
    976 		wp += 4;
    977 		ip += 4;
    978 		r1 = (int32) CLAMP(ip[0]); wp[0] = (r1-r2) & mask; r2 = r1;
    979 		g1 = (int32) CLAMP(ip[1]); wp[1] = (g1-g2) & mask; g2 = g1;
    980 		b1 = (int32) CLAMP(ip[2]); wp[2] = (b1-b2) & mask; b2 = b1;
    981 		a1 = (int32) CLAMP(ip[3]); wp[3] = (a1-a2) & mask; a2 = a1;
    982 	    }
    983 	} else {
    984 	    ip += n - 1;	/* point to last one */
    985 	    wp += n - 1;	/* point to last one */
    986 	    n -= stride;
    987 	    while (n > 0) {
    988 		REPEAT(stride, wp[0] = (uint16) CLAMP(ip[0]);
    989 				wp[stride] -= wp[0];
    990 				wp[stride] &= mask;
    991 				wp--; ip--)
    992 		n -= stride;
    993 	    }
    994 	    REPEAT(stride, wp[0] = (uint16) CLAMP(ip[0]); wp--; ip--)
    995 	}
    996     }
    997 }
    998 
    999 static void
   1000 horizontalDifference16(unsigned short *ip, int n, int stride,
   1001 	unsigned short *wp, uint16 *From14)
   1002 {
   1003     register int  r1, g1, b1, a1, r2, g2, b2, a2, mask;
   1004 
   1005 /* assumption is unsigned pixel values */
   1006 #undef   CLAMP
   1007 #define  CLAMP(v) From14[(v) >> 2]
   1008 
   1009     mask = CODE_MASK;
   1010     if (n >= stride) {
   1011 	if (stride == 3) {
   1012 	    r2 = wp[0] = CLAMP(ip[0]);  g2 = wp[1] = CLAMP(ip[1]);
   1013 	    b2 = wp[2] = CLAMP(ip[2]);
   1014 	    n -= 3;
   1015 	    while (n > 0) {
   1016 		n -= 3;
   1017 		wp += 3;
   1018 		ip += 3;
   1019 		r1 = CLAMP(ip[0]); wp[0] = (r1-r2) & mask; r2 = r1;
   1020 		g1 = CLAMP(ip[1]); wp[1] = (g1-g2) & mask; g2 = g1;
   1021 		b1 = CLAMP(ip[2]); wp[2] = (b1-b2) & mask; b2 = b1;
   1022 	    }
   1023 	} else if (stride == 4) {
   1024 	    r2 = wp[0] = CLAMP(ip[0]);  g2 = wp[1] = CLAMP(ip[1]);
   1025 	    b2 = wp[2] = CLAMP(ip[2]);  a2 = wp[3] = CLAMP(ip[3]);
   1026 	    n -= 4;
   1027 	    while (n > 0) {
   1028 		n -= 4;
   1029 		wp += 4;
   1030 		ip += 4;
   1031 		r1 = CLAMP(ip[0]); wp[0] = (r1-r2) & mask; r2 = r1;
   1032 		g1 = CLAMP(ip[1]); wp[1] = (g1-g2) & mask; g2 = g1;
   1033 		b1 = CLAMP(ip[2]); wp[2] = (b1-b2) & mask; b2 = b1;
   1034 		a1 = CLAMP(ip[3]); wp[3] = (a1-a2) & mask; a2 = a1;
   1035 	    }
   1036 	} else {
   1037 	    ip += n - 1;	/* point to last one */
   1038 	    wp += n - 1;	/* point to last one */
   1039 	    n -= stride;
   1040 	    while (n > 0) {
   1041 		REPEAT(stride, wp[0] = CLAMP(ip[0]);
   1042 				wp[stride] -= wp[0];
   1043 				wp[stride] &= mask;
   1044 				wp--; ip--)
   1045 		n -= stride;
   1046 	    }
   1047 	    REPEAT(stride, wp[0] = CLAMP(ip[0]); wp--; ip--)
   1048 	}
   1049     }
   1050 }
   1051 
   1052 
   1053 static void
   1054 horizontalDifference8(unsigned char *ip, int n, int stride,
   1055 	unsigned short *wp, uint16 *From8)
   1056 {
   1057     register int  r1, g1, b1, a1, r2, g2, b2, a2, mask;
   1058 
   1059 #undef	 CLAMP
   1060 #define  CLAMP(v) (From8[(v)])
   1061 
   1062     mask = CODE_MASK;
   1063     if (n >= stride) {
   1064 	if (stride == 3) {
   1065 	    r2 = wp[0] = CLAMP(ip[0]);  g2 = wp[1] = CLAMP(ip[1]);
   1066 	    b2 = wp[2] = CLAMP(ip[2]);
   1067 	    n -= 3;
   1068 	    while (n > 0) {
   1069 		n -= 3;
   1070 		r1 = CLAMP(ip[3]); wp[3] = (r1-r2) & mask; r2 = r1;
   1071 		g1 = CLAMP(ip[4]); wp[4] = (g1-g2) & mask; g2 = g1;
   1072 		b1 = CLAMP(ip[5]); wp[5] = (b1-b2) & mask; b2 = b1;
   1073 		wp += 3;
   1074 		ip += 3;
   1075 	    }
   1076 	} else if (stride == 4) {
   1077 	    r2 = wp[0] = CLAMP(ip[0]);  g2 = wp[1] = CLAMP(ip[1]);
   1078 	    b2 = wp[2] = CLAMP(ip[2]);  a2 = wp[3] = CLAMP(ip[3]);
   1079 	    n -= 4;
   1080 	    while (n > 0) {
   1081 		n -= 4;
   1082 		r1 = CLAMP(ip[4]); wp[4] = (r1-r2) & mask; r2 = r1;
   1083 		g1 = CLAMP(ip[5]); wp[5] = (g1-g2) & mask; g2 = g1;
   1084 		b1 = CLAMP(ip[6]); wp[6] = (b1-b2) & mask; b2 = b1;
   1085 		a1 = CLAMP(ip[7]); wp[7] = (a1-a2) & mask; a2 = a1;
   1086 		wp += 4;
   1087 		ip += 4;
   1088 	    }
   1089 	} else {
   1090 	    wp += n + stride - 1;	/* point to last one */
   1091 	    ip += n + stride - 1;	/* point to last one */
   1092 	    n -= stride;
   1093 	    while (n > 0) {
   1094 		REPEAT(stride, wp[0] = CLAMP(ip[0]);
   1095 				wp[stride] -= wp[0];
   1096 				wp[stride] &= mask;
   1097 				wp--; ip--)
   1098 		n -= stride;
   1099 	    }
   1100 	    REPEAT(stride, wp[0] = CLAMP(ip[0]); wp--; ip--)
   1101 	}
   1102     }
   1103 }
   1104 
   1105 /*
   1106  * Encode a chunk of pixels.
   1107  */
   1108 static int
   1109 PixarLogEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
   1110 {
   1111 	static const char module[] = "PixarLogEncode";
   1112 	TIFFDirectory *td = &tif->tif_dir;
   1113 	PixarLogState *sp = EncoderState(tif);
   1114 	tmsize_t i;
   1115 	tmsize_t n;
   1116 	int llen;
   1117 	unsigned short * up;
   1118 
   1119 	(void) s;
   1120 
   1121 	switch (sp->user_datafmt) {
   1122 	case PIXARLOGDATAFMT_FLOAT:
   1123 		n = cc / sizeof(float);		/* XXX float == 32 bits */
   1124 		break;
   1125 	case PIXARLOGDATAFMT_16BIT:
   1126 	case PIXARLOGDATAFMT_12BITPICIO:
   1127 	case PIXARLOGDATAFMT_11BITLOG:
   1128 		n = cc / sizeof(uint16);	/* XXX uint16 == 16 bits */
   1129 		break;
   1130 	case PIXARLOGDATAFMT_8BIT:
   1131 	case PIXARLOGDATAFMT_8BITABGR:
   1132 		n = cc;
   1133 		break;
   1134 	default:
   1135 		TIFFErrorExt(tif->tif_clientdata, module,
   1136 			"%d bit input not supported in PixarLog",
   1137 			td->td_bitspersample);
   1138 		return 0;
   1139 	}
   1140 
   1141 	llen = sp->stride * td->td_imagewidth;
   1142 
   1143 	for (i = 0, up = sp->tbuf; i < n; i += llen, up += llen) {
   1144 		switch (sp->user_datafmt)  {
   1145 		case PIXARLOGDATAFMT_FLOAT:
   1146 			horizontalDifferenceF((float *)bp, llen,
   1147 				sp->stride, up, sp->FromLT2);
   1148 			bp += llen * sizeof(float);
   1149 			break;
   1150 		case PIXARLOGDATAFMT_16BIT:
   1151 			horizontalDifference16((uint16 *)bp, llen,
   1152 				sp->stride, up, sp->From14);
   1153 			bp += llen * sizeof(uint16);
   1154 			break;
   1155 		case PIXARLOGDATAFMT_8BIT:
   1156 			horizontalDifference8((unsigned char *)bp, llen,
   1157 				sp->stride, up, sp->From8);
   1158 			bp += llen * sizeof(unsigned char);
   1159 			break;
   1160 		default:
   1161 			TIFFErrorExt(tif->tif_clientdata, module,
   1162 				"%d bit input not supported in PixarLog",
   1163 				td->td_bitspersample);
   1164 			return 0;
   1165 		}
   1166 	}
   1167 
   1168 	sp->stream.next_in = (unsigned char *) sp->tbuf;
   1169 	assert(sizeof(sp->stream.avail_in)==4);  /* if this assert gets raised,
   1170 	    we need to simplify this code to reflect a ZLib that is likely updated
   1171 	    to deal with 8byte memory sizes, though this code will respond
   1172 	    apropriately even before we simplify it */
   1173 	sp->stream.avail_in = (uInt) (n * sizeof(uint16));
   1174 	if ((sp->stream.avail_in / sizeof(uint16)) != (uInt) n)
   1175 	{
   1176 		TIFFErrorExt(tif->tif_clientdata, module,
   1177 			     "ZLib cannot deal with buffers this size");
   1178 		return (0);
   1179 	}
   1180 
   1181 	do {
   1182 		if (deflate(&sp->stream, Z_NO_FLUSH) != Z_OK) {
   1183 			TIFFErrorExt(tif->tif_clientdata, module, "Encoder error: %s",
   1184 			    sp->stream.msg);
   1185 			return (0);
   1186 		}
   1187 		if (sp->stream.avail_out == 0) {
   1188 			tif->tif_rawcc = tif->tif_rawdatasize;
   1189 			TIFFFlushData1(tif);
   1190 			sp->stream.next_out = tif->tif_rawdata;
   1191 			sp->stream.avail_out = (uInt) tif->tif_rawdatasize;  /* this is a safe typecast, as check is made already in PixarLogPreEncode */
   1192 		}
   1193 	} while (sp->stream.avail_in > 0);
   1194 	return (1);
   1195 }
   1196 
   1197 /*
   1198  * Finish off an encoded strip by flushing the last
   1199  * string and tacking on an End Of Information code.
   1200  */
   1201 
   1202 static int
   1203 PixarLogPostEncode(TIFF* tif)
   1204 {
   1205 	static const char module[] = "PixarLogPostEncode";
   1206 	PixarLogState *sp = EncoderState(tif);
   1207 	int state;
   1208 
   1209 	sp->stream.avail_in = 0;
   1210 
   1211 	do {
   1212 		state = deflate(&sp->stream, Z_FINISH);
   1213 		switch (state) {
   1214 		case Z_STREAM_END:
   1215 		case Z_OK:
   1216 		    if ((tmsize_t)sp->stream.avail_out != tif->tif_rawdatasize) {
   1217 			    tif->tif_rawcc =
   1218 				tif->tif_rawdatasize - sp->stream.avail_out;
   1219 			    TIFFFlushData1(tif);
   1220 			    sp->stream.next_out = tif->tif_rawdata;
   1221 			    sp->stream.avail_out = (uInt) tif->tif_rawdatasize;  /* this is a safe typecast, as check is made already in PixarLogPreEncode */
   1222 		    }
   1223 		    break;
   1224 		default:
   1225 			TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
   1226 			sp->stream.msg);
   1227 		    return (0);
   1228 		}
   1229 	} while (state != Z_STREAM_END);
   1230 	return (1);
   1231 }
   1232 
   1233 static void
   1234 PixarLogClose(TIFF* tif)
   1235 {
   1236 	TIFFDirectory *td = &tif->tif_dir;
   1237 
   1238 	/* In a really sneaky (and really incorrect, and untruthfull, and
   1239 	 * troublesome, and error-prone) maneuver that completely goes against
   1240 	 * the spirit of TIFF, and breaks TIFF, on close, we covertly
   1241 	 * modify both bitspersample and sampleformat in the directory to
   1242 	 * indicate 8-bit linear.  This way, the decode "just works" even for
   1243 	 * readers that don't know about PixarLog, or how to set
   1244 	 * the PIXARLOGDATFMT pseudo-tag.
   1245 	 */
   1246 	td->td_bitspersample = 8;
   1247 	td->td_sampleformat = SAMPLEFORMAT_UINT;
   1248 }
   1249 
   1250 static void
   1251 PixarLogCleanup(TIFF* tif)
   1252 {
   1253 	PixarLogState* sp = (PixarLogState*) tif->tif_data;
   1254 
   1255 	assert(sp != 0);
   1256 
   1257 	(void)TIFFPredictorCleanup(tif);
   1258 
   1259 	tif->tif_tagmethods.vgetfield = sp->vgetparent;
   1260 	tif->tif_tagmethods.vsetfield = sp->vsetparent;
   1261 
   1262 	if (sp->FromLT2) _TIFFfree(sp->FromLT2);
   1263 	if (sp->From14) _TIFFfree(sp->From14);
   1264 	if (sp->From8) _TIFFfree(sp->From8);
   1265 	if (sp->ToLinearF) _TIFFfree(sp->ToLinearF);
   1266 	if (sp->ToLinear16) _TIFFfree(sp->ToLinear16);
   1267 	if (sp->ToLinear8) _TIFFfree(sp->ToLinear8);
   1268 	if (sp->state&PLSTATE_INIT) {
   1269 		if (tif->tif_mode == O_RDONLY)
   1270 			inflateEnd(&sp->stream);
   1271 		else
   1272 			deflateEnd(&sp->stream);
   1273 	}
   1274 	if (sp->tbuf)
   1275 		_TIFFfree(sp->tbuf);
   1276 	_TIFFfree(sp);
   1277 	tif->tif_data = NULL;
   1278 
   1279 	_TIFFSetDefaultCompressionState(tif);
   1280 }
   1281 
   1282 static int
   1283 PixarLogVSetField(TIFF* tif, uint32 tag, va_list ap)
   1284 {
   1285     static const char module[] = "PixarLogVSetField";
   1286     PixarLogState *sp = (PixarLogState *)tif->tif_data;
   1287     int result;
   1288 
   1289     switch (tag) {
   1290      case TIFFTAG_PIXARLOGQUALITY:
   1291 		sp->quality = (int) va_arg(ap, int);
   1292 		if (tif->tif_mode != O_RDONLY && (sp->state&PLSTATE_INIT)) {
   1293 			if (deflateParams(&sp->stream,
   1294 			    sp->quality, Z_DEFAULT_STRATEGY) != Z_OK) {
   1295 				TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
   1296 					sp->stream.msg);
   1297 				return (0);
   1298 			}
   1299 		}
   1300 		return (1);
   1301      case TIFFTAG_PIXARLOGDATAFMT:
   1302 	sp->user_datafmt = (int) va_arg(ap, int);
   1303 	/* Tweak the TIFF header so that the rest of libtiff knows what
   1304 	 * size of data will be passed between app and library, and
   1305 	 * assume that the app knows what it is doing and is not
   1306 	 * confused by these header manipulations...
   1307 	 */
   1308 	switch (sp->user_datafmt) {
   1309 	 case PIXARLOGDATAFMT_8BIT:
   1310 	 case PIXARLOGDATAFMT_8BITABGR:
   1311 	    TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8);
   1312 	    TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
   1313 	    break;
   1314 	 case PIXARLOGDATAFMT_11BITLOG:
   1315 	    TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16);
   1316 	    TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
   1317 	    break;
   1318 	 case PIXARLOGDATAFMT_12BITPICIO:
   1319 	    TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16);
   1320 	    TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_INT);
   1321 	    break;
   1322 	 case PIXARLOGDATAFMT_16BIT:
   1323 	    TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16);
   1324 	    TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
   1325 	    break;
   1326 	 case PIXARLOGDATAFMT_FLOAT:
   1327 	    TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 32);
   1328 	    TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP);
   1329 	    break;
   1330 	}
   1331 	/*
   1332 	 * Must recalculate sizes should bits/sample change.
   1333 	 */
   1334 	tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tmsize_t)(-1);
   1335 	tif->tif_scanlinesize = TIFFScanlineSize(tif);
   1336 	result = 1;		/* NB: pseudo tag */
   1337 	break;
   1338      default:
   1339 	result = (*sp->vsetparent)(tif, tag, ap);
   1340     }
   1341     return (result);
   1342 }
   1343 
   1344 static int
   1345 PixarLogVGetField(TIFF* tif, uint32 tag, va_list ap)
   1346 {
   1347     PixarLogState *sp = (PixarLogState *)tif->tif_data;
   1348 
   1349     switch (tag) {
   1350      case TIFFTAG_PIXARLOGQUALITY:
   1351 	*va_arg(ap, int*) = sp->quality;
   1352 	break;
   1353      case TIFFTAG_PIXARLOGDATAFMT:
   1354 	*va_arg(ap, int*) = sp->user_datafmt;
   1355 	break;
   1356      default:
   1357 	return (*sp->vgetparent)(tif, tag, ap);
   1358     }
   1359     return (1);
   1360 }
   1361 
   1362 static const TIFFField pixarlogFields[] = {
   1363     {TIFFTAG_PIXARLOGDATAFMT, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL},
   1364     {TIFFTAG_PIXARLOGQUALITY, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL}
   1365 };
   1366 
   1367 int
   1368 TIFFInitPixarLog(TIFF* tif, int scheme)
   1369 {
   1370 	static const char module[] = "TIFFInitPixarLog";
   1371 
   1372 	PixarLogState* sp;
   1373 
   1374 	assert(scheme == COMPRESSION_PIXARLOG);
   1375 
   1376 	/*
   1377 	 * Merge codec-specific tag information.
   1378 	 */
   1379 	if (!_TIFFMergeFields(tif, pixarlogFields,
   1380 			      TIFFArrayCount(pixarlogFields))) {
   1381 		TIFFErrorExt(tif->tif_clientdata, module,
   1382 			     "Merging PixarLog codec-specific tags failed");
   1383 		return 0;
   1384 	}
   1385 
   1386 	/*
   1387 	 * Allocate state block so tag methods have storage to record values.
   1388 	 */
   1389 	tif->tif_data = (uint8*) _TIFFmalloc(sizeof (PixarLogState));
   1390 	if (tif->tif_data == NULL)
   1391 		goto bad;
   1392 	sp = (PixarLogState*) tif->tif_data;
   1393 	_TIFFmemset(sp, 0, sizeof (*sp));
   1394 	sp->stream.data_type = Z_BINARY;
   1395 	sp->user_datafmt = PIXARLOGDATAFMT_UNKNOWN;
   1396 
   1397 	/*
   1398 	 * Install codec methods.
   1399 	 */
   1400 	tif->tif_fixuptags = PixarLogFixupTags;
   1401 	tif->tif_setupdecode = PixarLogSetupDecode;
   1402 	tif->tif_predecode = PixarLogPreDecode;
   1403 	tif->tif_decoderow = PixarLogDecode;
   1404 	tif->tif_decodestrip = PixarLogDecode;
   1405 	tif->tif_decodetile = PixarLogDecode;
   1406 	tif->tif_setupencode = PixarLogSetupEncode;
   1407 	tif->tif_preencode = PixarLogPreEncode;
   1408 	tif->tif_postencode = PixarLogPostEncode;
   1409 	tif->tif_encoderow = PixarLogEncode;
   1410 	tif->tif_encodestrip = PixarLogEncode;
   1411 	tif->tif_encodetile = PixarLogEncode;
   1412 	tif->tif_close = PixarLogClose;
   1413 	tif->tif_cleanup = PixarLogCleanup;
   1414 
   1415 	/* Override SetField so we can handle our private pseudo-tag */
   1416 	sp->vgetparent = tif->tif_tagmethods.vgetfield;
   1417 	tif->tif_tagmethods.vgetfield = PixarLogVGetField;   /* hook for codec tags */
   1418 	sp->vsetparent = tif->tif_tagmethods.vsetfield;
   1419 	tif->tif_tagmethods.vsetfield = PixarLogVSetField;   /* hook for codec tags */
   1420 
   1421 	/* Default values for codec-specific fields */
   1422 	sp->quality = Z_DEFAULT_COMPRESSION; /* default comp. level */
   1423 	sp->state = 0;
   1424 
   1425 	/* we don't wish to use the predictor,
   1426 	 * the default is none, which predictor value 1
   1427 	 */
   1428 	(void) TIFFPredictorInit(tif);
   1429 
   1430 	/*
   1431 	 * build the companding tables
   1432 	 */
   1433 	PixarLogMakeTables(sp);
   1434 
   1435 	return (1);
   1436 bad:
   1437 	TIFFErrorExt(tif->tif_clientdata, module,
   1438 		     "No space for PixarLog state block");
   1439 	return (0);
   1440 }
   1441 #endif /* PIXARLOG_SUPPORT */
   1442 
   1443 /* vim: set ts=8 sts=8 sw=8 noet: */
   1444 /*
   1445  * Local Variables:
   1446  * mode: c
   1447  * c-basic-offset: 8
   1448  * fill-column: 78
   1449  * End:
   1450  */
   1451