Merge XFA to PDFium master at 4dc95e7 on 10/28/2014
[pdfium.git] / core / src / fxcodec / fx_tiff / tiff_v403 / tif_getimage.c
1 /* $Id: tif_getimage.c,v 1.82 2012-06-06 00:17:49 fwarmerdam Exp $ */
2
3 /*
4  * Copyright (c) 1991-1997 Sam Leffler
5  * Copyright (c) 1991-1997 Silicon Graphics, Inc.
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  * 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 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 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 /*
28  * TIFF Library
29  *
30  * Read and return a packed RGBA image.
31  */
32 #if (!defined(_FPDFAPI_MINI_) || defined(_TIFF_DECODER_)) && !defined(_USE_ADDIN_) && !defined _FX_NO_ANSIC_ && !defined(_FX_EMB_NOUSE_DECODER_)
33 #include "tiffiop.h"
34 #include <stdio.h>
35
36 static int gtTileContig(TIFFRGBAImage*, uint32*, uint32, uint32);
37 static int gtTileSeparate(TIFFRGBAImage*, uint32*, uint32, uint32);
38 static int gtStripContig(TIFFRGBAImage*, uint32*, uint32, uint32);
39 static int gtStripSeparate(TIFFRGBAImage*, uint32*, uint32, uint32);
40 static int PickContigCase(TIFFRGBAImage*);
41 static int PickSeparateCase(TIFFRGBAImage*);
42
43 static int BuildMapUaToAa(TIFFRGBAImage* img);
44 static int BuildMapBitdepth16To8(TIFFRGBAImage* img);
45
46 static const char photoTag[] = "PhotometricInterpretation";
47
48 /* 
49  * Helper constants used in Orientation tag handling
50  */
51 #define FLIP_VERTICALLY 0x01
52 #define FLIP_HORIZONTALLY 0x02
53
54 /*
55  * Color conversion constants. We will define display types here.
56  */
57
58 static const TIFFDisplay display_sRGB = {
59         {                       /* XYZ -> luminance matrix */
60                 {  3.2410F, -1.5374F, -0.4986F },
61                 {  -0.9692F, 1.8760F, 0.0416F },
62                 {  0.0556F, -0.2040F, 1.0570F }
63         },      
64         100.0F, 100.0F, 100.0F, /* Light o/p for reference white */
65         255, 255, 255,          /* Pixel values for ref. white */
66         1.0F, 1.0F, 1.0F,       /* Residual light o/p for black pixel */
67         2.4F, 2.4F, 2.4F,       /* Gamma values for the three guns */
68 };
69
70 /*
71  * Check the image to see if TIFFReadRGBAImage can deal with it.
72  * 1/0 is returned according to whether or not the image can
73  * be handled.  If 0 is returned, emsg contains the reason
74  * why it is being rejected.
75  */
76 int
77 TIFFRGBAImageOK(TIFF* tif, char emsg[1024])
78 {
79         TIFFDirectory* td = &tif->tif_dir;
80         uint16 photometric;
81         int colorchannels;
82
83         if (!tif->tif_decodestatus) {
84                 sprintf(emsg, "Sorry, requested compression method is not configured");
85                 return (0);
86         }
87         switch (td->td_bitspersample) {
88                 case 1:
89                 case 2:
90                 case 4:
91                 case 8:
92                 case 16:
93                         break;
94                 default:
95                         sprintf(emsg, "Sorry, can not handle images with %d-bit samples",
96                             td->td_bitspersample);
97                         return (0);
98         }
99         colorchannels = td->td_samplesperpixel - td->td_extrasamples;
100         if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometric)) {
101                 switch (colorchannels) {
102                         case 1:
103                                 photometric = PHOTOMETRIC_MINISBLACK;
104                                 break;
105                         case 3:
106                                 photometric = PHOTOMETRIC_RGB;
107                                 break;
108                         default:
109                                 sprintf(emsg, "Missing needed %s tag", photoTag);
110                                 return (0);
111                 }
112         }
113         switch (photometric) {
114                 case PHOTOMETRIC_MINISWHITE:
115                 case PHOTOMETRIC_MINISBLACK:
116                 case PHOTOMETRIC_PALETTE:
117                         if (td->td_planarconfig == PLANARCONFIG_CONTIG
118                             && td->td_samplesperpixel != 1
119                             && td->td_bitspersample < 8 ) {
120                                 sprintf(emsg,
121                                     "Sorry, can not handle contiguous data with %s=%d, "
122                                     "and %s=%d and Bits/Sample=%d",
123                                     photoTag, photometric,
124                                     "Samples/pixel", td->td_samplesperpixel,
125                                     td->td_bitspersample);
126                                 return (0);
127                         }
128                         /*
129                          * We should likely validate that any extra samples are either
130                          * to be ignored, or are alpha, and if alpha we should try to use
131                          * them.  But for now we won't bother with this.
132                         */
133                         break;
134                 case PHOTOMETRIC_YCBCR:
135                         /*
136                          * TODO: if at all meaningful and useful, make more complete
137                          * support check here, or better still, refactor to let supporting
138                          * code decide whether there is support and what meaningfull
139                          * error to return
140                          */
141                         break;
142                 case PHOTOMETRIC_RGB:
143                         if (colorchannels < 3) {
144                                 sprintf(emsg, "Sorry, can not handle RGB image with %s=%d",
145                                     "Color channels", colorchannels);
146                                 return (0);
147                         }
148                         break;
149                 case PHOTOMETRIC_SEPARATED:
150                         {
151                                 uint16 inkset;
152                                 TIFFGetFieldDefaulted(tif, TIFFTAG_INKSET, &inkset);
153                                 if (inkset != INKSET_CMYK) {
154                                         sprintf(emsg,
155                                             "Sorry, can not handle separated image with %s=%d",
156                                             "InkSet", inkset);
157                                         return 0;
158                                 }
159                                 if (td->td_samplesperpixel < 4) {
160                                         sprintf(emsg,
161                                             "Sorry, can not handle separated image with %s=%d",
162                                             "Samples/pixel", td->td_samplesperpixel);
163                                         return 0;
164                                 }
165                                 break;
166                         }
167                 case PHOTOMETRIC_LOGL:
168                         if (td->td_compression != COMPRESSION_SGILOG) {
169                                 sprintf(emsg, "Sorry, LogL data must have %s=%d",
170                                     "Compression", COMPRESSION_SGILOG);
171                                 return (0);
172                         }
173                         break;
174                 case PHOTOMETRIC_LOGLUV:
175                         if (td->td_compression != COMPRESSION_SGILOG &&
176                             td->td_compression != COMPRESSION_SGILOG24) {
177                                 sprintf(emsg, "Sorry, LogLuv data must have %s=%d or %d",
178                                     "Compression", COMPRESSION_SGILOG, COMPRESSION_SGILOG24);
179                                 return (0);
180                         }
181                         if (td->td_planarconfig != PLANARCONFIG_CONTIG) {
182                                 sprintf(emsg, "Sorry, can not handle LogLuv images with %s=%d",
183                                     "Planarconfiguration", td->td_planarconfig);
184                                 return (0);
185                         }
186                         break;
187                 case PHOTOMETRIC_CIELAB:
188                         break;
189                 default:
190                         sprintf(emsg, "Sorry, can not handle image with %s=%d",
191                             photoTag, photometric);
192                         return (0);
193         }
194         return (1);
195 }
196
197 void
198 TIFFRGBAImageEnd(TIFFRGBAImage* img)
199 {
200         if (img->Map)
201                 _TIFFfree(img->Map), img->Map = NULL;
202         if (img->BWmap)
203                 _TIFFfree(img->BWmap), img->BWmap = NULL;
204         if (img->PALmap)
205                 _TIFFfree(img->PALmap), img->PALmap = NULL;
206         if (img->ycbcr)
207                 _TIFFfree(img->ycbcr), img->ycbcr = NULL;
208         if (img->cielab)
209                 _TIFFfree(img->cielab), img->cielab = NULL;
210         if (img->UaToAa)
211                 _TIFFfree(img->UaToAa), img->UaToAa = NULL;
212         if (img->Bitdepth16To8)
213                 _TIFFfree(img->Bitdepth16To8), img->Bitdepth16To8 = NULL;
214
215         if( img->redcmap ) {
216                 _TIFFfree( img->redcmap );
217                 _TIFFfree( img->greencmap );
218                 _TIFFfree( img->bluecmap );
219                 img->redcmap = img->greencmap = img->bluecmap = NULL;
220         }
221 }
222
223 static int
224 isCCITTCompression(TIFF* tif)
225 {
226     uint16 compress;
227     TIFFGetField(tif, TIFFTAG_COMPRESSION, &compress);
228     return (compress == COMPRESSION_CCITTFAX3 ||
229             compress == COMPRESSION_CCITTFAX4 ||
230             compress == COMPRESSION_CCITTRLE ||
231             compress == COMPRESSION_CCITTRLEW);
232 }
233
234 int
235 TIFFRGBAImageBegin(TIFFRGBAImage* img, TIFF* tif, int stop, char emsg[1024])
236 {
237         uint16* sampleinfo;
238         uint16 extrasamples;
239         uint16 planarconfig;
240         uint16 compress;
241         int colorchannels;
242         uint16 *red_orig, *green_orig, *blue_orig;
243         int n_color;
244
245         /* Initialize to normal values */
246         img->row_offset = 0;
247         img->col_offset = 0;
248         img->redcmap = NULL;
249         img->greencmap = NULL;
250         img->bluecmap = NULL;
251         img->req_orientation = ORIENTATION_BOTLEFT;     /* It is the default */
252
253         img->tif = tif;
254         img->stoponerr = stop;
255         TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE, &img->bitspersample);
256         switch (img->bitspersample) {
257                 case 1:
258                 case 2:
259                 case 4:
260                 case 8:
261                 case 16:
262                         break;
263                 default:
264                         sprintf(emsg, "Sorry, can not handle images with %d-bit samples",
265                             img->bitspersample);
266                         goto fail_return;
267         }
268         img->alpha = 0;
269         TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &img->samplesperpixel);
270         TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES,
271             &extrasamples, &sampleinfo);
272         if (extrasamples >= 1)
273         {
274                 switch (sampleinfo[0]) {
275                         case EXTRASAMPLE_UNSPECIFIED:          /* Workaround for some images without */
276                                 if (img->samplesperpixel > 3)  /* correct info about alpha channel */
277                                         img->alpha = EXTRASAMPLE_ASSOCALPHA;
278                                 break;
279                         case EXTRASAMPLE_ASSOCALPHA:           /* data is pre-multiplied */
280                         case EXTRASAMPLE_UNASSALPHA:           /* data is not pre-multiplied */
281                                 img->alpha = sampleinfo[0];
282                                 break;
283                 }
284         }
285
286 #ifdef DEFAULT_EXTRASAMPLE_AS_ALPHA
287         if( !TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &img->photometric))
288                 img->photometric = PHOTOMETRIC_MINISWHITE;
289
290         if( extrasamples == 0
291             && img->samplesperpixel == 4
292             && img->photometric == PHOTOMETRIC_RGB )
293         {
294                 img->alpha = EXTRASAMPLE_ASSOCALPHA;
295                 extrasamples = 1;
296         }
297 #endif
298
299         colorchannels = img->samplesperpixel - extrasamples;
300         TIFFGetFieldDefaulted(tif, TIFFTAG_COMPRESSION, &compress);
301         TIFFGetFieldDefaulted(tif, TIFFTAG_PLANARCONFIG, &planarconfig);
302         if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &img->photometric)) {
303                 switch (colorchannels) {
304                         case 1:
305                                 if (isCCITTCompression(tif))
306                                         img->photometric = PHOTOMETRIC_MINISWHITE;
307                                 else
308                                         img->photometric = PHOTOMETRIC_MINISBLACK;
309                                 break;
310                         case 3:
311                                 img->photometric = PHOTOMETRIC_RGB;
312                                 break;
313                         default:
314                                 sprintf(emsg, "Missing needed %s tag", photoTag);
315                                 goto fail_return;
316                 }
317         }
318         switch (img->photometric) {
319                 case PHOTOMETRIC_PALETTE:
320                         if (!TIFFGetField(tif, TIFFTAG_COLORMAP,
321                             &red_orig, &green_orig, &blue_orig)) {
322                                 sprintf(emsg, "Missing required \"Colormap\" tag");
323                                 goto fail_return;
324                         }
325
326                         /* copy the colormaps so we can modify them */
327                         n_color = (1L << img->bitspersample);
328                         img->redcmap = (uint16 *) _TIFFmalloc(sizeof(uint16)*n_color);
329                         img->greencmap = (uint16 *) _TIFFmalloc(sizeof(uint16)*n_color);
330                         img->bluecmap = (uint16 *) _TIFFmalloc(sizeof(uint16)*n_color);
331                         if( !img->redcmap || !img->greencmap || !img->bluecmap ) {
332                                 sprintf(emsg, "Out of memory for colormap copy");
333                                 goto fail_return;
334                         }
335
336                         _TIFFmemcpy( img->redcmap, red_orig, n_color * 2 );
337                         _TIFFmemcpy( img->greencmap, green_orig, n_color * 2 );
338                         _TIFFmemcpy( img->bluecmap, blue_orig, n_color * 2 );
339
340                         /* fall thru... */
341                 case PHOTOMETRIC_MINISWHITE:
342                 case PHOTOMETRIC_MINISBLACK:
343                         if (planarconfig == PLANARCONFIG_CONTIG
344                             && img->samplesperpixel != 1
345                             && img->bitspersample < 8 ) {
346                                 sprintf(emsg,
347                                     "Sorry, can not handle contiguous data with %s=%d, "
348                                     "and %s=%d and Bits/Sample=%d",
349                                     photoTag, img->photometric,
350                                     "Samples/pixel", img->samplesperpixel,
351                                     img->bitspersample);
352                                 goto fail_return;
353                         }
354                         break;
355                 case PHOTOMETRIC_YCBCR:
356                         /* It would probably be nice to have a reality check here. */
357                         if (planarconfig == PLANARCONFIG_CONTIG)
358                                 /* can rely on libjpeg to convert to RGB */
359                                 /* XXX should restore current state on exit */
360                                 switch (compress) {
361                                         case COMPRESSION_JPEG:
362                                                 /*
363                                                  * TODO: when complete tests verify complete desubsampling
364                                                  * and YCbCr handling, remove use of TIFFTAG_JPEGCOLORMODE in
365                                                  * favor of tif_getimage.c native handling
366                                                  */
367                                                 TIFFSetField(tif, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
368                                                 img->photometric = PHOTOMETRIC_RGB;
369                                                 break;
370                                         default:
371                                                 /* do nothing */;
372                                                 break;
373                                 }
374                         /*
375                          * TODO: if at all meaningful and useful, make more complete
376                          * support check here, or better still, refactor to let supporting
377                          * code decide whether there is support and what meaningfull
378                          * error to return
379                          */
380                         break;
381                 case PHOTOMETRIC_RGB:
382                         if (colorchannels < 3) {
383                                 sprintf(emsg, "Sorry, can not handle RGB image with %s=%d",
384                                     "Color channels", colorchannels);
385                                 goto fail_return;
386                         }
387                         break;
388                 case PHOTOMETRIC_SEPARATED:
389                         {
390                                 uint16 inkset;
391                                 TIFFGetFieldDefaulted(tif, TIFFTAG_INKSET, &inkset);
392                                 if (inkset != INKSET_CMYK) {
393                                         sprintf(emsg, "Sorry, can not handle separated image with %s=%d",
394                                             "InkSet", inkset);
395                                         goto fail_return;
396                                 }
397                                 if (img->samplesperpixel < 4) {
398                                         sprintf(emsg, "Sorry, can not handle separated image with %s=%d",
399                                             "Samples/pixel", img->samplesperpixel);
400                                         goto fail_return;
401                                 }
402                         }
403                         break;
404                 case PHOTOMETRIC_LOGL:
405                         if (compress != COMPRESSION_SGILOG) {
406                                 sprintf(emsg, "Sorry, LogL data must have %s=%d",
407                                     "Compression", COMPRESSION_SGILOG);
408                                 goto fail_return;
409                         }
410                         TIFFSetField(tif, TIFFTAG_SGILOGDATAFMT, SGILOGDATAFMT_8BIT);
411                         img->photometric = PHOTOMETRIC_MINISBLACK;      /* little white lie */
412                         img->bitspersample = 8;
413                         break;
414                 case PHOTOMETRIC_LOGLUV:
415                         if (compress != COMPRESSION_SGILOG && compress != COMPRESSION_SGILOG24) {
416                                 sprintf(emsg, "Sorry, LogLuv data must have %s=%d or %d",
417                                     "Compression", COMPRESSION_SGILOG, COMPRESSION_SGILOG24);
418                                 goto fail_return;
419                         }
420                         if (planarconfig != PLANARCONFIG_CONTIG) {
421                                 sprintf(emsg, "Sorry, can not handle LogLuv images with %s=%d",
422                                     "Planarconfiguration", planarconfig);
423                                 return (0);
424                         }
425                         TIFFSetField(tif, TIFFTAG_SGILOGDATAFMT, SGILOGDATAFMT_8BIT);
426                         img->photometric = PHOTOMETRIC_RGB;             /* little white lie */
427                         img->bitspersample = 8;
428                         break;
429                 case PHOTOMETRIC_CIELAB:
430                         break;
431                 default:
432                         sprintf(emsg, "Sorry, can not handle image with %s=%d",
433                             photoTag, img->photometric);
434                         goto fail_return;
435         }
436         img->Map = NULL;
437         img->BWmap = NULL;
438         img->PALmap = NULL;
439         img->ycbcr = NULL;
440         img->cielab = NULL;
441         img->UaToAa = NULL;
442         img->Bitdepth16To8 = NULL;
443         TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &img->width);
444         TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &img->height);
445         TIFFGetFieldDefaulted(tif, TIFFTAG_ORIENTATION, &img->orientation);
446         img->isContig =
447             !(planarconfig == PLANARCONFIG_SEPARATE && img->samplesperpixel > 1);
448         if (img->isContig) {
449                 if (!PickContigCase(img)) {
450                         sprintf(emsg, "Sorry, can not handle image");
451                         goto fail_return;
452                 }
453         } else {
454                 if (!PickSeparateCase(img)) {
455                         sprintf(emsg, "Sorry, can not handle image");
456                         goto fail_return;
457                 }
458         }
459         return 1;
460
461   fail_return:
462         _TIFFfree( img->redcmap );
463         _TIFFfree( img->greencmap );
464         _TIFFfree( img->bluecmap );
465         img->redcmap = img->greencmap = img->bluecmap = NULL;
466         return 0;
467 }
468
469 int
470 TIFFRGBAImageGet(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h)
471 {
472     if (img->get == NULL) {
473                 TIFFErrorExt(img->tif->tif_clientdata, TIFFFileName(img->tif), "No \"get\" routine setup");
474                 return (0);
475         }
476         if (img->put.any == NULL) {
477                 TIFFErrorExt(img->tif->tif_clientdata, TIFFFileName(img->tif),
478                 "No \"put\" routine setupl; probably can not handle image format");
479                 return (0);
480     }
481     return (*img->get)(img, raster, w, h);
482 }
483
484 /*
485  * Read the specified image into an ABGR-format rastertaking in account
486  * specified orientation.
487  */
488 int
489 TIFFReadRGBAImageOriented(TIFF* tif,
490                           uint32 rwidth, uint32 rheight, uint32* raster,
491                           int orientation, int stop)
492 {
493     char emsg[1024] = "";
494     TIFFRGBAImage img;
495     int ok;
496
497         if (TIFFRGBAImageOK(tif, emsg) && TIFFRGBAImageBegin(&img, tif, stop, emsg)) {
498                 img.req_orientation = orientation;
499                 /* XXX verify rwidth and rheight against width and height */
500                 ok = TIFFRGBAImageGet(&img, raster+(rheight-img.height)*rwidth,
501                         rwidth, img.height);
502                 TIFFRGBAImageEnd(&img);
503         } else {
504                 TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "%s", emsg);
505                 ok = 0;
506     }
507     return (ok);
508 }
509
510 /*
511  * Read the specified image into an ABGR-format raster. Use bottom left
512  * origin for raster by default.
513  */
514 int
515 TIFFReadRGBAImage(TIFF* tif,
516                   uint32 rwidth, uint32 rheight, uint32* raster, int stop)
517 {
518         return TIFFReadRGBAImageOriented(tif, rwidth, rheight, raster,
519                                          ORIENTATION_BOTLEFT, stop);
520 }
521
522 static int 
523 setorientation(TIFFRGBAImage* img)
524 {
525         switch (img->orientation) {
526                 case ORIENTATION_TOPLEFT:
527                 case ORIENTATION_LEFTTOP:
528                         if (img->req_orientation == ORIENTATION_TOPRIGHT ||
529                             img->req_orientation == ORIENTATION_RIGHTTOP)
530                                 return FLIP_HORIZONTALLY;
531                         else if (img->req_orientation == ORIENTATION_BOTRIGHT ||
532                             img->req_orientation == ORIENTATION_RIGHTBOT)
533                                 return FLIP_HORIZONTALLY | FLIP_VERTICALLY;
534                         else if (img->req_orientation == ORIENTATION_BOTLEFT ||
535                             img->req_orientation == ORIENTATION_LEFTBOT)
536                                 return FLIP_VERTICALLY;
537                         else
538                                 return 0;
539                 case ORIENTATION_TOPRIGHT:
540                 case ORIENTATION_RIGHTTOP:
541                         if (img->req_orientation == ORIENTATION_TOPLEFT ||
542                             img->req_orientation == ORIENTATION_LEFTTOP)
543                                 return FLIP_HORIZONTALLY;
544                         else if (img->req_orientation == ORIENTATION_BOTRIGHT ||
545                             img->req_orientation == ORIENTATION_RIGHTBOT)
546                                 return FLIP_VERTICALLY;
547                         else if (img->req_orientation == ORIENTATION_BOTLEFT ||
548                             img->req_orientation == ORIENTATION_LEFTBOT)
549                                 return FLIP_HORIZONTALLY | FLIP_VERTICALLY;
550                         else
551                                 return 0;
552                 case ORIENTATION_BOTRIGHT:
553                 case ORIENTATION_RIGHTBOT:
554                         if (img->req_orientation == ORIENTATION_TOPLEFT ||
555                             img->req_orientation == ORIENTATION_LEFTTOP)
556                                 return FLIP_HORIZONTALLY | FLIP_VERTICALLY;
557                         else if (img->req_orientation == ORIENTATION_TOPRIGHT ||
558                             img->req_orientation == ORIENTATION_RIGHTTOP)
559                                 return FLIP_VERTICALLY;
560                         else if (img->req_orientation == ORIENTATION_BOTLEFT ||
561                             img->req_orientation == ORIENTATION_LEFTBOT)
562                                 return FLIP_HORIZONTALLY;
563                         else
564                                 return 0;
565                 case ORIENTATION_BOTLEFT:
566                 case ORIENTATION_LEFTBOT:
567                         if (img->req_orientation == ORIENTATION_TOPLEFT ||
568                             img->req_orientation == ORIENTATION_LEFTTOP)
569                                 return FLIP_VERTICALLY;
570                         else if (img->req_orientation == ORIENTATION_TOPRIGHT ||
571                             img->req_orientation == ORIENTATION_RIGHTTOP)
572                                 return FLIP_HORIZONTALLY | FLIP_VERTICALLY;
573                         else if (img->req_orientation == ORIENTATION_BOTRIGHT ||
574                             img->req_orientation == ORIENTATION_RIGHTBOT)
575                                 return FLIP_HORIZONTALLY;
576                         else
577                                 return 0;
578                 default:        /* NOTREACHED */
579                         return 0;
580         }
581 }
582
583 /*
584  * Get an tile-organized image that has
585  *      PlanarConfiguration contiguous if SamplesPerPixel > 1
586  * or
587  *      SamplesPerPixel == 1
588  */     
589 static int
590 gtTileContig(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h)
591 {
592     TIFF* tif = img->tif;
593     tileContigRoutine put = img->put.contig;
594     uint32 col, row, y, rowstoread;
595     tmsize_t pos;
596     uint32 tw, th;
597     unsigned char* buf;
598     int32 fromskew, toskew;
599     uint32 nrow;
600     int ret = 1, flip;
601
602     buf = (unsigned char*) _TIFFmalloc(TIFFTileSize(tif));
603     if (buf == 0) {
604                 TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "%s", "No space for tile buffer");
605                 return (0);
606     }
607     _TIFFmemset(buf, 0, TIFFTileSize(tif));
608     TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tw);
609     TIFFGetField(tif, TIFFTAG_TILELENGTH, &th);
610
611     flip = setorientation(img);
612     if (flip & FLIP_VERTICALLY) {
613             y = h - 1;
614             toskew = -(int32)(tw + w);
615     }
616     else {
617             y = 0;
618             toskew = -(int32)(tw - w);
619     }
620      
621     for (row = 0; row < h; row += nrow)
622     {
623         rowstoread = th - (row + img->row_offset) % th;
624         nrow = (row + rowstoread > h ? h - row : rowstoread);
625         for (col = 0; col < w; col += tw) 
626         {
627             if (TIFFReadTile(tif, buf, col+img->col_offset,  
628                              row+img->row_offset, 0, 0)==(tmsize_t)(-1) && img->stoponerr)
629             {
630                 ret = 0;
631                 break;
632             }
633             
634             pos = ((row+img->row_offset) % th) * TIFFTileRowSize(tif);  
635
636             if (col + tw > w) 
637             {
638                 /*
639                  * Tile is clipped horizontally.  Calculate
640                  * visible portion and skewing factors.
641                  */
642                 uint32 npix = w - col;
643                 fromskew = tw - npix;
644                 (*put)(img, raster+y*w+col, col, y,
645                        npix, nrow, fromskew, toskew + fromskew, buf + pos);
646             }
647             else 
648             {
649                 (*put)(img, raster+y*w+col, col, y, tw, nrow, 0, toskew, buf + pos);
650             }
651         }
652
653         y += (flip & FLIP_VERTICALLY ? -(int32) nrow : (int32) nrow);
654     }
655     _TIFFfree(buf);
656
657     if (flip & FLIP_HORIZONTALLY) {
658             uint32 line;
659
660             for (line = 0; line < h; line++) {
661                     uint32 *left = raster + (line * w);
662                     uint32 *right = left + w - 1;
663                     
664                     while ( left < right ) {
665                             uint32 temp = *left;
666                             *left = *right;
667                             *right = temp;
668                             left++, right--;
669                     }
670             }
671     }
672
673     return (ret);
674 }
675
676 /*
677  * Get an tile-organized image that has
678  *       SamplesPerPixel > 1
679  *       PlanarConfiguration separated
680  * We assume that all such images are RGB.
681  */     
682 static int
683 gtTileSeparate(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h)
684 {
685         TIFF* tif = img->tif;
686         tileSeparateRoutine put = img->put.separate;
687         uint32 col, row, y, rowstoread;
688         tmsize_t pos;
689         uint32 tw, th;
690         unsigned char* buf;
691         unsigned char* p0;
692         unsigned char* p1;
693         unsigned char* p2;
694         unsigned char* pa;
695         tmsize_t tilesize;
696         tmsize_t bufsize;
697         int32 fromskew, toskew;
698         int alpha = img->alpha;
699         uint32 nrow;
700         int ret = 1, flip;
701         int colorchannels;
702
703         tilesize = TIFFTileSize(tif);  
704         bufsize = TIFFSafeMultiply(tmsize_t,alpha?4:3,tilesize);
705         if (bufsize == 0) {
706                 TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "Integer overflow in %s", "gtTileSeparate");
707                 return (0);
708         }
709         buf = (unsigned char*) _TIFFmalloc(bufsize);
710         if (buf == 0) {
711                 TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "%s", "No space for tile buffer");
712                 return (0);
713         }
714         _TIFFmemset(buf, 0, bufsize);
715         p0 = buf;
716         p1 = p0 + tilesize;
717         p2 = p1 + tilesize;
718         pa = (alpha?(p2+tilesize):NULL);
719         TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tw);
720         TIFFGetField(tif, TIFFTAG_TILELENGTH, &th);
721
722         flip = setorientation(img);
723         if (flip & FLIP_VERTICALLY) {
724                 y = h - 1;
725                 toskew = -(int32)(tw + w);
726         }
727         else {
728                 y = 0;
729                 toskew = -(int32)(tw - w);
730         }
731
732         switch( img->photometric )
733         {
734           case PHOTOMETRIC_MINISWHITE:
735           case PHOTOMETRIC_MINISBLACK:
736           case PHOTOMETRIC_PALETTE:
737             colorchannels = 1;
738             p2 = p1 = p0;
739             break;
740
741           default:
742             colorchannels = 3;
743             break;
744         }
745
746         for (row = 0; row < h; row += nrow)
747         {
748                 rowstoread = th - (row + img->row_offset) % th;
749                 nrow = (row + rowstoread > h ? h - row : rowstoread);
750                 for (col = 0; col < w; col += tw)
751                 {
752                         if (TIFFReadTile(tif, p0, col+img->col_offset,  
753                             row+img->row_offset,0,0)==(tmsize_t)(-1) && img->stoponerr)
754                         {
755                                 ret = 0;
756                                 break;
757                         }
758                         if (colorchannels > 1 
759                             && TIFFReadTile(tif, p1, col+img->col_offset,  
760                                             row+img->row_offset,0,1) == (tmsize_t)(-1) 
761                             && img->stoponerr)
762                         {
763                                 ret = 0;
764                                 break;
765                         }
766                         if (colorchannels > 1 
767                             && TIFFReadTile(tif, p2, col+img->col_offset,  
768                                             row+img->row_offset,0,2) == (tmsize_t)(-1) 
769                             && img->stoponerr)
770                         {
771                                 ret = 0;
772                                 break;
773                         }
774                         if (alpha
775                             && TIFFReadTile(tif,pa,col+img->col_offset,  
776                                             row+img->row_offset,0,colorchannels) == (tmsize_t)(-1) 
777                             && img->stoponerr)
778                         {
779                             ret = 0;
780                             break;
781                         }
782
783                         pos = ((row+img->row_offset) % th) * TIFFTileRowSize(tif);  
784
785                         if (col + tw > w)
786                         {
787                                 /*
788                                  * Tile is clipped horizontally.  Calculate
789                                  * visible portion and skewing factors.
790                                  */
791                                 uint32 npix = w - col;
792                                 fromskew = tw - npix;
793                                 (*put)(img, raster+y*w+col, col, y,
794                                     npix, nrow, fromskew, toskew + fromskew,
795                                     p0 + pos, p1 + pos, p2 + pos, (alpha?(pa+pos):NULL));
796                         } else {
797                                 (*put)(img, raster+y*w+col, col, y,
798                                     tw, nrow, 0, toskew, p0 + pos, p1 + pos, p2 + pos, (alpha?(pa+pos):NULL));
799                         }
800                 }
801
802                 y += (flip & FLIP_VERTICALLY ?-(int32) nrow : (int32) nrow);
803         }
804
805         if (flip & FLIP_HORIZONTALLY) {
806                 uint32 line;
807
808                 for (line = 0; line < h; line++) {
809                         uint32 *left = raster + (line * w);
810                         uint32 *right = left + w - 1;
811
812                         while ( left < right ) {
813                                 uint32 temp = *left;
814                                 *left = *right;
815                                 *right = temp;
816                                 left++, right--;
817                         }
818                 }
819         }
820
821         _TIFFfree(buf);
822         return (ret);
823 }
824
825 /*
826  * Get a strip-organized image that has
827  *      PlanarConfiguration contiguous if SamplesPerPixel > 1
828  * or
829  *      SamplesPerPixel == 1
830  */     
831 static int
832 gtStripContig(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h)
833 {
834         TIFF* tif = img->tif;
835         tileContigRoutine put = img->put.contig;
836         uint32 row, y, nrow, nrowsub, rowstoread;
837         tmsize_t pos;
838         unsigned char* buf;
839         uint32 rowsperstrip;
840         uint16 subsamplinghor,subsamplingver;
841         uint32 imagewidth = img->width;
842         tmsize_t scanline;
843         int32 fromskew, toskew;
844         int ret = 1, flip;
845
846         buf = (unsigned char*) _TIFFmalloc(TIFFStripSize(tif));
847         if (buf == 0) {
848                 TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "No space for strip buffer");
849                 return (0);
850         }
851         _TIFFmemset(buf, 0, TIFFStripSize(tif));
852
853         flip = setorientation(img);
854         if (flip & FLIP_VERTICALLY) {
855                 y = h - 1;
856                 toskew = -(int32)(w + w);
857         } else {
858                 y = 0;
859                 toskew = -(int32)(w - w);
860         }
861
862         TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
863         TIFFGetFieldDefaulted(tif, TIFFTAG_YCBCRSUBSAMPLING, &subsamplinghor, &subsamplingver);
864         scanline = TIFFScanlineSize(tif);
865         fromskew = (w < imagewidth ? imagewidth - w : 0);
866         for (row = 0; row < h; row += nrow)
867         {
868                 rowstoread = rowsperstrip - (row + img->row_offset) % rowsperstrip;
869                 nrow = (row + rowstoread > h ? h - row : rowstoread);
870                 nrowsub = nrow;
871                 if ((nrowsub%subsamplingver)!=0)
872                         nrowsub+=subsamplingver-nrowsub%subsamplingver;
873                 if (TIFFReadEncodedStrip(tif,
874                     TIFFComputeStrip(tif,row+img->row_offset, 0),
875                     buf,
876                     ((row + img->row_offset)%rowsperstrip + nrowsub) * scanline)==(tmsize_t)(-1)
877                     && img->stoponerr)
878                 {
879                         ret = 0;
880                         break;
881                 }
882
883                 pos = ((row + img->row_offset) % rowsperstrip) * scanline;
884                 (*put)(img, raster+y*w, 0, y, w, nrow, fromskew, toskew, buf + pos);
885                 y += (flip & FLIP_VERTICALLY ? -(int32) nrow : (int32) nrow);
886         }
887
888         if (flip & FLIP_HORIZONTALLY) {
889                 uint32 line;
890
891                 for (line = 0; line < h; line++) {
892                         uint32 *left = raster + (line * w);
893                         uint32 *right = left + w - 1;
894
895                         while ( left < right ) {
896                                 uint32 temp = *left;
897                                 *left = *right;
898                                 *right = temp;
899                                 left++, right--;
900                         }
901                 }
902         }
903
904         _TIFFfree(buf);
905         return (ret);
906 }
907
908 /*
909  * Get a strip-organized image with
910  *       SamplesPerPixel > 1
911  *       PlanarConfiguration separated
912  * We assume that all such images are RGB.
913  */
914 static int
915 gtStripSeparate(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h)
916 {
917         TIFF* tif = img->tif;
918         tileSeparateRoutine put = img->put.separate;
919         unsigned char *buf;
920         unsigned char *p0, *p1, *p2, *pa;
921         uint32 row, y, nrow, rowstoread;
922         tmsize_t pos;
923         tmsize_t scanline;
924         uint32 rowsperstrip, offset_row;
925         uint32 imagewidth = img->width;
926         tmsize_t stripsize;
927         tmsize_t bufsize;
928         int32 fromskew, toskew;
929         int alpha = img->alpha;
930         int ret = 1, flip, colorchannels;
931
932         stripsize = TIFFStripSize(tif);  
933         bufsize = TIFFSafeMultiply(tmsize_t,alpha?4:3,stripsize);
934         if (bufsize == 0) {
935                 TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "Integer overflow in %s", "gtStripSeparate");
936                 return (0);
937         }
938         p0 = buf = (unsigned char *)_TIFFmalloc(bufsize);
939         if (buf == 0) {
940                 TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "No space for tile buffer");
941                 return (0);
942         }
943         _TIFFmemset(buf, 0, bufsize);
944         p1 = p0 + stripsize;
945         p2 = p1 + stripsize;
946         pa = (alpha?(p2+stripsize):NULL);
947
948         flip = setorientation(img);
949         if (flip & FLIP_VERTICALLY) {
950                 y = h - 1;
951                 toskew = -(int32)(w + w);
952         }
953         else {
954                 y = 0;
955                 toskew = -(int32)(w - w);
956         }
957
958         switch( img->photometric )
959         {
960           case PHOTOMETRIC_MINISWHITE:
961           case PHOTOMETRIC_MINISBLACK:
962           case PHOTOMETRIC_PALETTE:
963             colorchannels = 1;
964             p2 = p1 = p0;
965             break;
966
967           default:
968             colorchannels = 3;
969             break;
970         }
971
972         TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
973         scanline = TIFFScanlineSize(tif);  
974         fromskew = (w < imagewidth ? imagewidth - w : 0);
975         for (row = 0; row < h; row += nrow)
976         {
977                 rowstoread = rowsperstrip - (row + img->row_offset) % rowsperstrip;
978                 nrow = (row + rowstoread > h ? h - row : rowstoread);
979                 offset_row = row + img->row_offset;
980                 if (TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, offset_row, 0),
981                     p0, ((row + img->row_offset)%rowsperstrip + nrow) * scanline)==(tmsize_t)(-1)
982                     && img->stoponerr)
983                 {
984                         ret = 0;
985                         break;
986                 }
987                 if (colorchannels > 1 
988                     && TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, offset_row, 1),
989                                             p1, ((row + img->row_offset)%rowsperstrip + nrow) * scanline) == (tmsize_t)(-1)
990                     && img->stoponerr)
991                 {
992                         ret = 0;
993                         break;
994                 }
995                 if (colorchannels > 1 
996                     && TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, offset_row, 2),
997                                             p2, ((row + img->row_offset)%rowsperstrip + nrow) * scanline) == (tmsize_t)(-1)
998                     && img->stoponerr)
999                 {
1000                         ret = 0;
1001                         break;
1002                 }
1003                 if (alpha)
1004                 {
1005                         if (TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, offset_row, colorchannels),
1006                             pa, ((row + img->row_offset)%rowsperstrip + nrow) * scanline)==(tmsize_t)(-1)
1007                             && img->stoponerr)
1008                         {
1009                                 ret = 0;
1010                                 break;
1011                         }
1012                 }
1013
1014                 pos = ((row + img->row_offset) % rowsperstrip) * scanline;
1015                 (*put)(img, raster+y*w, 0, y, w, nrow, fromskew, toskew, p0 + pos, p1 + pos,
1016                     p2 + pos, (alpha?(pa+pos):NULL));
1017                 y += (flip & FLIP_VERTICALLY ? -(int32) nrow : (int32) nrow);
1018         }
1019
1020         if (flip & FLIP_HORIZONTALLY) {
1021                 uint32 line;
1022
1023                 for (line = 0; line < h; line++) {
1024                         uint32 *left = raster + (line * w);
1025                         uint32 *right = left + w - 1;
1026
1027                         while ( left < right ) {
1028                                 uint32 temp = *left;
1029                                 *left = *right;
1030                                 *right = temp;
1031                                 left++, right--;
1032                         }
1033                 }
1034         }
1035
1036         _TIFFfree(buf);
1037         return (ret);
1038 }
1039
1040 /*
1041  * The following routines move decoded data returned
1042  * from the TIFF library into rasters filled with packed
1043  * ABGR pixels (i.e. suitable for passing to lrecwrite.)
1044  *
1045  * The routines have been created according to the most
1046  * important cases and optimized.  PickContigCase and
1047  * PickSeparateCase analyze the parameters and select
1048  * the appropriate "get" and "put" routine to use.
1049  */
1050 #define REPEAT8(op)     REPEAT4(op); REPEAT4(op)
1051 #define REPEAT4(op)     REPEAT2(op); REPEAT2(op)
1052 #define REPEAT2(op)     op; op
1053 #define CASE8(x,op)                     \
1054     switch (x) {                        \
1055     case 7: op; case 6: op; case 5: op; \
1056     case 4: op; case 3: op; case 2: op; \
1057     case 1: op;                         \
1058     }
1059 #define CASE4(x,op)     switch (x) { case 3: op; case 2: op; case 1: op; }
1060 #define NOP
1061
1062 #define UNROLL8(w, op1, op2) {          \
1063     uint32 _x;                          \
1064     for (_x = w; _x >= 8; _x -= 8) {    \
1065         op1;                            \
1066         REPEAT8(op2);                   \
1067     }                                   \
1068     if (_x > 0) {                       \
1069         op1;                            \
1070         CASE8(_x,op2);                  \
1071     }                                   \
1072 }
1073 #define UNROLL4(w, op1, op2) {          \
1074     uint32 _x;                          \
1075     for (_x = w; _x >= 4; _x -= 4) {    \
1076         op1;                            \
1077         REPEAT4(op2);                   \
1078     }                                   \
1079     if (_x > 0) {                       \
1080         op1;                            \
1081         CASE4(_x,op2);                  \
1082     }                                   \
1083 }
1084 #define UNROLL2(w, op1, op2) {          \
1085     uint32 _x;                          \
1086     for (_x = w; _x >= 2; _x -= 2) {    \
1087         op1;                            \
1088         REPEAT2(op2);                   \
1089     }                                   \
1090     if (_x) {                           \
1091         op1;                            \
1092         op2;                            \
1093     }                                   \
1094 }
1095     
1096 #define SKEW(r,g,b,skew)        { r += skew; g += skew; b += skew; }
1097 #define SKEW4(r,g,b,a,skew)     { r += skew; g += skew; b += skew; a+= skew; }
1098
1099 #define A1 (((uint32)0xffL)<<24)
1100 #define PACK(r,g,b)     \
1101         ((uint32)(r)|((uint32)(g)<<8)|((uint32)(b)<<16)|A1)
1102 #define PACK4(r,g,b,a)  \
1103         ((uint32)(r)|((uint32)(g)<<8)|((uint32)(b)<<16)|((uint32)(a)<<24))
1104 #define W2B(v) (((v)>>8)&0xff)
1105 /* TODO: PACKW should have be made redundant in favor of Bitdepth16To8 LUT */
1106 #define PACKW(r,g,b)    \
1107         ((uint32)W2B(r)|((uint32)W2B(g)<<8)|((uint32)W2B(b)<<16)|A1)
1108 #define PACKW4(r,g,b,a) \
1109         ((uint32)W2B(r)|((uint32)W2B(g)<<8)|((uint32)W2B(b)<<16)|((uint32)W2B(a)<<24))
1110
1111 #define DECLAREContigPutFunc(name) \
1112 static void name(\
1113     TIFFRGBAImage* img, \
1114     uint32* cp, \
1115     uint32 x, uint32 y, \
1116     uint32 w, uint32 h, \
1117     int32 fromskew, int32 toskew, \
1118     unsigned char* pp \
1119 )
1120
1121 /*
1122  * 8-bit palette => colormap/RGB
1123  */
1124 DECLAREContigPutFunc(put8bitcmaptile)
1125 {
1126     uint32** PALmap = img->PALmap;
1127     int samplesperpixel = img->samplesperpixel;
1128
1129     (void) y;
1130     while (h-- > 0) {
1131         for (x = w; x-- > 0;)
1132         {
1133             *cp++ = PALmap[*pp][0];
1134             pp += samplesperpixel;
1135         }
1136         cp += toskew;
1137         pp += fromskew;
1138     }
1139 }
1140
1141 /*
1142  * 4-bit palette => colormap/RGB
1143  */
1144 DECLAREContigPutFunc(put4bitcmaptile)
1145 {
1146     uint32** PALmap = img->PALmap;
1147
1148     (void) x; (void) y;
1149     fromskew /= 2;
1150     while (h-- > 0) {
1151         uint32* bw;
1152         UNROLL2(w, bw = PALmap[*pp++], *cp++ = *bw++);
1153         cp += toskew;
1154         pp += fromskew;
1155     }
1156 }
1157
1158 /*
1159  * 2-bit palette => colormap/RGB
1160  */
1161 DECLAREContigPutFunc(put2bitcmaptile)
1162 {
1163     uint32** PALmap = img->PALmap;
1164
1165     (void) x; (void) y;
1166     fromskew /= 4;
1167     while (h-- > 0) {
1168         uint32* bw;
1169         UNROLL4(w, bw = PALmap[*pp++], *cp++ = *bw++);
1170         cp += toskew;
1171         pp += fromskew;
1172     }
1173 }
1174
1175 /*
1176  * 1-bit palette => colormap/RGB
1177  */
1178 DECLAREContigPutFunc(put1bitcmaptile)
1179 {
1180     uint32** PALmap = img->PALmap;
1181
1182     (void) x; (void) y;
1183     fromskew /= 8;
1184     while (h-- > 0) {
1185         uint32* bw;
1186         UNROLL8(w, bw = PALmap[*pp++], *cp++ = *bw++);
1187         cp += toskew;
1188         pp += fromskew;
1189     }
1190 }
1191
1192 /*
1193  * 8-bit greyscale => colormap/RGB
1194  */
1195 DECLAREContigPutFunc(putgreytile)
1196 {
1197     int samplesperpixel = img->samplesperpixel;
1198     uint32** BWmap = img->BWmap;
1199
1200     (void) y;
1201     while (h-- > 0) {
1202         for (x = w; x-- > 0;)
1203         {
1204             *cp++ = BWmap[*pp][0];
1205             pp += samplesperpixel;
1206         }
1207         cp += toskew;
1208         pp += fromskew;
1209     }
1210 }
1211
1212 /*
1213  * 8-bit greyscale with associated alpha => colormap/RGBA
1214  */
1215 DECLAREContigPutFunc(putagreytile)
1216 {
1217     int samplesperpixel = img->samplesperpixel;
1218     uint32** BWmap = img->BWmap;
1219
1220     (void) y;
1221     while (h-- > 0) {
1222         for (x = w; x-- > 0;)
1223         {
1224             *cp++ = BWmap[*pp][0] & (*(pp+1) << 24 | ~A1);
1225             pp += samplesperpixel;
1226         }
1227         cp += toskew;
1228         pp += fromskew;
1229     }
1230 }
1231
1232 /*
1233  * 16-bit greyscale => colormap/RGB
1234  */
1235 DECLAREContigPutFunc(put16bitbwtile)
1236 {
1237     int samplesperpixel = img->samplesperpixel;
1238     uint32** BWmap = img->BWmap;
1239
1240     (void) y;
1241     while (h-- > 0) {
1242         uint16 *wp = (uint16 *) pp;
1243
1244         for (x = w; x-- > 0;)
1245         {
1246             /* use high order byte of 16bit value */
1247
1248             *cp++ = BWmap[*wp >> 8][0];
1249             pp += 2 * samplesperpixel;
1250             wp += samplesperpixel;
1251         }
1252         cp += toskew;
1253         pp += fromskew;
1254     }
1255 }
1256
1257 /*
1258  * 1-bit bilevel => colormap/RGB
1259  */
1260 DECLAREContigPutFunc(put1bitbwtile)
1261 {
1262     uint32** BWmap = img->BWmap;
1263
1264     (void) x; (void) y;
1265     fromskew /= 8;
1266     while (h-- > 0) {
1267         uint32* bw;
1268         UNROLL8(w, bw = BWmap[*pp++], *cp++ = *bw++);
1269         cp += toskew;
1270         pp += fromskew;
1271     }
1272 }
1273
1274 /*
1275  * 2-bit greyscale => colormap/RGB
1276  */
1277 DECLAREContigPutFunc(put2bitbwtile)
1278 {
1279     uint32** BWmap = img->BWmap;
1280
1281     (void) x; (void) y;
1282     fromskew /= 4;
1283     while (h-- > 0) {
1284         uint32* bw;
1285         UNROLL4(w, bw = BWmap[*pp++], *cp++ = *bw++);
1286         cp += toskew;
1287         pp += fromskew;
1288     }
1289 }
1290
1291 /*
1292  * 4-bit greyscale => colormap/RGB
1293  */
1294 DECLAREContigPutFunc(put4bitbwtile)
1295 {
1296     uint32** BWmap = img->BWmap;
1297
1298     (void) x; (void) y;
1299     fromskew /= 2;
1300     while (h-- > 0) {
1301         uint32* bw;
1302         UNROLL2(w, bw = BWmap[*pp++], *cp++ = *bw++);
1303         cp += toskew;
1304         pp += fromskew;
1305     }
1306 }
1307
1308 /*
1309  * 8-bit packed samples, no Map => RGB
1310  */
1311 DECLAREContigPutFunc(putRGBcontig8bittile)
1312 {
1313     int samplesperpixel = img->samplesperpixel;
1314
1315     (void) x; (void) y;
1316     fromskew *= samplesperpixel;
1317     while (h-- > 0) {
1318         UNROLL8(w, NOP,
1319             *cp++ = PACK(pp[0], pp[1], pp[2]);
1320             pp += samplesperpixel);
1321         cp += toskew;
1322         pp += fromskew;
1323     }
1324 }
1325
1326 /*
1327  * 8-bit packed samples => RGBA w/ associated alpha
1328  * (known to have Map == NULL)
1329  */
1330 DECLAREContigPutFunc(putRGBAAcontig8bittile)
1331 {
1332     int samplesperpixel = img->samplesperpixel;
1333
1334     (void) x; (void) y;
1335     fromskew *= samplesperpixel;
1336     while (h-- > 0) {
1337         UNROLL8(w, NOP,
1338             *cp++ = PACK4(pp[0], pp[1], pp[2], pp[3]);
1339             pp += samplesperpixel);
1340         cp += toskew;
1341         pp += fromskew;
1342     }
1343 }
1344
1345 /*
1346  * 8-bit packed samples => RGBA w/ unassociated alpha
1347  * (known to have Map == NULL)
1348  */
1349 DECLAREContigPutFunc(putRGBUAcontig8bittile)
1350 {
1351         int samplesperpixel = img->samplesperpixel;
1352         (void) y;
1353         fromskew *= samplesperpixel;
1354         while (h-- > 0) {
1355                 uint32 r, g, b, a;
1356                 uint8* m;
1357                 for (x = w; x-- > 0;) {
1358                         a = pp[3];
1359                         m = img->UaToAa+(a<<8);
1360                         r = m[pp[0]];
1361                         g = m[pp[1]];
1362                         b = m[pp[2]];
1363                         *cp++ = PACK4(r,g,b,a);
1364                         pp += samplesperpixel;
1365                 }
1366                 cp += toskew;
1367                 pp += fromskew;
1368         }
1369 }
1370
1371 /*
1372  * 16-bit packed samples => RGB
1373  */
1374 DECLAREContigPutFunc(putRGBcontig16bittile)
1375 {
1376         int samplesperpixel = img->samplesperpixel;
1377         uint16 *wp = (uint16 *)pp;
1378         (void) y;
1379         fromskew *= samplesperpixel;
1380         while (h-- > 0) {
1381                 for (x = w; x-- > 0;) {
1382                         *cp++ = PACK(img->Bitdepth16To8[wp[0]],
1383                             img->Bitdepth16To8[wp[1]],
1384                             img->Bitdepth16To8[wp[2]]);
1385                         wp += samplesperpixel;
1386                 }
1387                 cp += toskew;
1388                 wp += fromskew;
1389         }
1390 }
1391
1392 /*
1393  * 16-bit packed samples => RGBA w/ associated alpha
1394  * (known to have Map == NULL)
1395  */
1396 DECLAREContigPutFunc(putRGBAAcontig16bittile)
1397 {
1398         int samplesperpixel = img->samplesperpixel;
1399         uint16 *wp = (uint16 *)pp;
1400         (void) y;
1401         fromskew *= samplesperpixel;
1402         while (h-- > 0) {
1403                 for (x = w; x-- > 0;) {
1404                         *cp++ = PACK4(img->Bitdepth16To8[wp[0]],
1405                             img->Bitdepth16To8[wp[1]],
1406                             img->Bitdepth16To8[wp[2]],
1407                             img->Bitdepth16To8[wp[3]]);
1408                         wp += samplesperpixel;
1409                 }
1410                 cp += toskew;
1411                 wp += fromskew;
1412         }
1413 }
1414
1415 /*
1416  * 16-bit packed samples => RGBA w/ unassociated alpha
1417  * (known to have Map == NULL)
1418  */
1419 DECLAREContigPutFunc(putRGBUAcontig16bittile)
1420 {
1421         int samplesperpixel = img->samplesperpixel;
1422         uint16 *wp = (uint16 *)pp;
1423         (void) y;
1424         fromskew *= samplesperpixel;
1425         while (h-- > 0) {
1426                 uint32 r,g,b,a;
1427                 uint8* m;
1428                 for (x = w; x-- > 0;) {
1429                         a = img->Bitdepth16To8[wp[3]];
1430                         m = img->UaToAa+(a<<8);
1431                         r = m[img->Bitdepth16To8[wp[0]]];
1432                         g = m[img->Bitdepth16To8[wp[1]]];
1433                         b = m[img->Bitdepth16To8[wp[2]]];
1434                         *cp++ = PACK4(r,g,b,a);
1435                         wp += samplesperpixel;
1436                 }
1437                 cp += toskew;
1438                 wp += fromskew;
1439         }
1440 }
1441
1442 /*
1443  * 8-bit packed CMYK samples w/o Map => RGB
1444  *
1445  * NB: The conversion of CMYK->RGB is *very* crude.
1446  */
1447 /*DECLAREContigPutFunc(putRGBcontig8bitCMYKtile)
1448 {
1449     int samplesperpixel = img->samplesperpixel;
1450     uint16 r, g, b, k;
1451         
1452     (void) x; (void) y;
1453     fromskew *= samplesperpixel;
1454     while (h-- > 0) {
1455                 UNROLL8(w, NOP,
1456                     k = 255 - pp[3];
1457                     r = (k*(255-pp[0]))/255;
1458                     g = (k*(255-pp[1]))/255;
1459                     b = (k*(255-pp[2]))/255;
1460                 *cp++ = PACK(r, g, b);
1461                 pp += samplesperpixel);
1462                 cp += toskew;
1463                 pp += fromskew;
1464 }*/
1465 /* Modify in 20090723 by Sunliang.Liu */
1466 DECLAREContigPutFunc(putRGBcontig8bitCMYKtile)
1467 {
1468         int samplesperpixel = img->samplesperpixel;
1469         uint8 r, g, b, k;
1470
1471         (void) x; (void) y;
1472         fromskew *= samplesperpixel;
1473         while (h-- > 0) {
1474                 UNROLL8(w, NOP,
1475                         if(!TIFFCmyk2Rgb(img->tif->tif_clientdata,pp[0],pp[1],pp[2],pp[3],
1476                                 &r,&g,&b)){
1477                                         k = 255 - pp[3];
1478                                         r = (k*(255-pp[0]))/255;
1479                                         g = (k*(255-pp[1]))/255;
1480                                         b = (k*(255-pp[2]))/255;
1481                         }
1482
1483                         *cp++ = PACK(r, g, b);
1484                         pp += samplesperpixel);
1485                         cp += toskew;
1486                         pp += fromskew;
1487         }
1488 }
1489
1490 /*
1491  * 16-bit packed CMYK samples w/o Map => RGB(8-bit)
1492  *
1493  * NB: The conversion of CMYK->RGB is *very* crude.
1494  */
1495 DECLAREContigPutFunc(putRGBcontig16bitCMYKtile)
1496 {
1497         int samplesperpixel = img->samplesperpixel;
1498         uint16* wp = (uint16*)pp;
1499         uint8 C, M, Y, K;
1500         uint8 r, g, b;
1501
1502         (void) x; (void) y;
1503         fromskew *= samplesperpixel;
1504         while (h-- > 0) {
1505                 UNROLL8(w, NOP,
1506                         C = wp[0]>>8;M = wp[1]>>8;Y = wp[2]>>8;K = wp[3]>>8;
1507                 if(!TIFFCmyk2Rgb(img->tif->tif_clientdata,C,M,Y,K,
1508                         &r,&g,&b)){
1509                                 K = 255 - K;
1510                                 r = (K*(255-C))/255;
1511                                 g = (K*(255-M))/255;
1512                                 b = (K*(255-Y))/255;
1513                 }
1514
1515                 *cp++ = PACK(r, g, b);
1516                 wp += samplesperpixel);
1517                 cp += toskew;
1518                 wp += fromskew;
1519         }
1520 }
1521
1522 /*
1523  * 8-bit packed CMYK samples w/Map => RGB
1524  *
1525  * NB: The conversion of CMYK->RGB is *very* crude.
1526  */
1527 /*
1528 DECLAREContigPutFunc(putRGBcontig8bitCMYKMaptile)
1529 {
1530     int samplesperpixel = img->samplesperpixel;
1531     TIFFRGBValue* Map = img->Map;
1532     uint16 r, g, b, k;
1533
1534     (void) y;
1535     fromskew *= samplesperpixel;
1536     while (h-- > 0) {
1537         for (x = w; x-- > 0;) {
1538             k = 255 - pp[3];
1539             r = (k*(255-pp[0]))/255;
1540             g = (k*(255-pp[1]))/255;
1541             b = (k*(255-pp[2]))/255;
1542             *cp++ = PACK(Map[r], Map[g], Map[b]);
1543             pp += samplesperpixel;
1544         }
1545         pp += fromskew;
1546         cp += toskew;
1547     }
1548 }*/
1549 /* Modify in 20090723 by Sunliang.Liu */
1550 DECLAREContigPutFunc(putRGBcontig8bitCMYKMaptile)
1551 {
1552         int samplesperpixel = img->samplesperpixel;
1553         TIFFRGBValue* Map = img->Map;
1554         uint8 r, g, b, k;
1555
1556         (void) y;
1557         fromskew *= samplesperpixel;
1558         while (h-- > 0) {
1559                 for (x = w; x-- > 0;) {
1560                         if(!TIFFCmyk2Rgb(img->tif->tif_clientdata,pp[0],pp[1],pp[2],pp[3],
1561                                 &r,&g,&b)){
1562                                         k = 255 - pp[3];
1563                                         r = (k*(255-pp[0]))/255;
1564                                         g = (k*(255-pp[1]))/255;
1565                                         b = (k*(255-pp[2]))/255;
1566                         }
1567                         *cp++ = PACK(Map[r], Map[g], Map[b]);
1568                         pp += samplesperpixel;
1569                 }
1570                 pp += fromskew;
1571                 cp += toskew;
1572         }
1573 }
1574
1575 /*
1576  * 16-bit packed CMYK samples w/Map => RGB(8-bit)
1577  *
1578  * NB: The conversion of CMYK->RGB is *very* crude.
1579  */
1580 DECLAREContigPutFunc(putRGBcontig16bitCMYKMaptile)
1581 {
1582         int samplesperpixel = img->samplesperpixel;
1583         TIFFRGBValue* Map = img->Map;
1584         uint16* wp = (uint16*)pp;
1585         uint8 C, M, Y, K;
1586         uint8 r, g, b;
1587
1588         (void) y;
1589         fromskew *= samplesperpixel;
1590         while (h-- > 0) {
1591                 for (x = w; x-- > 0;) {
1592                         C = wp[0]>>8;M = wp[1]>>8;Y = wp[2]>>8;K = wp[3]>>8;
1593                         if(!TIFFCmyk2Rgb(img->tif->tif_clientdata,C,M,Y,K,
1594                                 &r,&g,&b)){
1595                                         K = 255 - K;
1596                                         r = (K*(255-C))/255;
1597                                         g = (K*(255-M))/255;
1598                                         b = (K*(255-Y))/255;
1599                         }
1600                         *cp++ = PACK(Map[r], Map[g], Map[b]);
1601                         wp += samplesperpixel;
1602                 }
1603                 wp += fromskew;
1604                 cp += toskew;
1605         }
1606 }
1607
1608 #define DECLARESepPutFunc(name) \
1609 static void name(\
1610     TIFFRGBAImage* img,\
1611     uint32* cp,\
1612     uint32 x, uint32 y, \
1613     uint32 w, uint32 h,\
1614     int32 fromskew, int32 toskew,\
1615     unsigned char* r, unsigned char* g, unsigned char* b, unsigned char* a\
1616 )
1617
1618 /*
1619  * 8-bit unpacked samples => RGB
1620  */
1621 DECLARESepPutFunc(putRGBseparate8bittile)
1622 {
1623     (void) img; (void) x; (void) y; (void) a;
1624     while (h-- > 0) {
1625         UNROLL8(w, NOP, *cp++ = PACK(*r++, *g++, *b++));
1626         SKEW(r, g, b, fromskew);
1627         cp += toskew;
1628     }
1629 }
1630
1631 /*
1632  * 8-bit unpacked samples => RGBA w/ associated alpha
1633  */
1634 DECLARESepPutFunc(putRGBAAseparate8bittile)
1635 {
1636         (void) img; (void) x; (void) y; 
1637         while (h-- > 0) {
1638                 UNROLL8(w, NOP, *cp++ = PACK4(*r++, *g++, *b++, *a++));
1639                 SKEW4(r, g, b, a, fromskew);
1640                 cp += toskew;
1641         }
1642 }
1643
1644 /*
1645  * 8-bit unpacked CMYK samples => RGBA
1646  */
1647 DECLARESepPutFunc(putCMYKseparate8bittile)
1648 {
1649         (void) img; (void) y;
1650         while (h-- > 0) {
1651                 uint32 rv, gv, bv, kv;
1652                 for (x = w; x-- > 0;) {
1653                         kv = 255 - *a++;
1654                         rv = (kv*(255-*r++))/255;
1655                         gv = (kv*(255-*g++))/255;
1656                         bv = (kv*(255-*b++))/255;
1657                         *cp++ = PACK4(rv,gv,bv,255);
1658                 }
1659                 SKEW4(r, g, b, a, fromskew);
1660                 cp += toskew;
1661         }
1662 }
1663
1664 /*
1665  * 8-bit unpacked samples => RGBA w/ unassociated alpha
1666  */
1667 DECLARESepPutFunc(putRGBUAseparate8bittile)
1668 {
1669         (void) img; (void) y;
1670         while (h-- > 0) {
1671                 uint32 rv, gv, bv, av;
1672                 uint8* m;
1673                 for (x = w; x-- > 0;) {
1674                         av = *a++;
1675                         m = img->UaToAa+(av<<8);
1676                         rv = m[*r++];
1677                         gv = m[*g++];
1678                         bv = m[*b++];
1679                         *cp++ = PACK4(rv,gv,bv,av);
1680                 }
1681                 SKEW4(r, g, b, a, fromskew);
1682                 cp += toskew;
1683         }
1684 }
1685
1686 /*
1687  * 16-bit unpacked samples => RGB
1688  */
1689 DECLARESepPutFunc(putRGBseparate16bittile)
1690 {
1691         uint16 *wr = (uint16*) r;
1692         uint16 *wg = (uint16*) g;
1693         uint16 *wb = (uint16*) b;
1694         (void) img; (void) y; (void) a;
1695         while (h-- > 0) {
1696                 for (x = 0; x < w; x++)
1697                         *cp++ = PACK(img->Bitdepth16To8[*wr++],
1698                             img->Bitdepth16To8[*wg++],
1699                             img->Bitdepth16To8[*wb++]);
1700                 SKEW(wr, wg, wb, fromskew);
1701                 cp += toskew;
1702         }
1703 }
1704
1705 /*
1706  * 16-bit unpacked samples => RGBA w/ associated alpha
1707  */
1708 DECLARESepPutFunc(putRGBAAseparate16bittile)
1709 {
1710         uint16 *wr = (uint16*) r;
1711         uint16 *wg = (uint16*) g;
1712         uint16 *wb = (uint16*) b;
1713         uint16 *wa = (uint16*) a;
1714         (void) img; (void) y;
1715         while (h-- > 0) {
1716                 for (x = 0; x < w; x++)
1717                         *cp++ = PACK4(img->Bitdepth16To8[*wr++],
1718                             img->Bitdepth16To8[*wg++],
1719                             img->Bitdepth16To8[*wb++],
1720                             img->Bitdepth16To8[*wa++]);
1721                 SKEW4(wr, wg, wb, wa, fromskew);
1722                 cp += toskew;
1723         }
1724 }
1725
1726 /*
1727  * 16-bit unpacked samples => RGBA w/ unassociated alpha
1728  */
1729 DECLARESepPutFunc(putRGBUAseparate16bittile)
1730 {
1731         uint16 *wr = (uint16*) r;
1732         uint16 *wg = (uint16*) g;
1733         uint16 *wb = (uint16*) b;
1734         uint16 *wa = (uint16*) a;
1735         (void) img; (void) y;
1736         while (h-- > 0) {
1737                 uint32 r,g,b,a;
1738                 uint8* m;
1739                 for (x = w; x-- > 0;) {
1740                         a = img->Bitdepth16To8[*wa++];
1741                         m = img->UaToAa+(a<<8);
1742                         r = m[img->Bitdepth16To8[*wr++]];
1743                         g = m[img->Bitdepth16To8[*wg++]];
1744                         b = m[img->Bitdepth16To8[*wb++]];
1745                         *cp++ = PACK4(r,g,b,a);
1746                 }
1747                 SKEW4(wr, wg, wb, wa, fromskew);
1748                 cp += toskew;
1749         }
1750 }
1751
1752 /*
1753  * 8-bit packed CIE L*a*b 1976 samples => RGB
1754  */
1755 DECLAREContigPutFunc(putcontig8bitCIELab)
1756 {
1757         float X, Y, Z;
1758         uint32 r, g, b;
1759         (void) y;
1760         fromskew *= 3;
1761         while (h-- > 0) {
1762                 for (x = w; x-- > 0;) {
1763                         TIFFCIELabToXYZ(img->cielab,
1764                                         (unsigned char)pp[0],
1765                                         (signed char)pp[1],
1766                                         (signed char)pp[2],
1767                                         &X, &Y, &Z);
1768                         TIFFXYZToRGB(img->cielab, X, Y, Z, &r, &g, &b);
1769                         *cp++ = PACK(r, g, b);
1770                         pp += 3;
1771                 }
1772                 cp += toskew;
1773                 pp += fromskew;
1774         }
1775 }
1776
1777 /*
1778  * YCbCr -> RGB conversion and packing routines.
1779  */
1780
1781 #define YCbCrtoRGB(dst, Y) {                                            \
1782         uint32 r, g, b;                                                 \
1783         TIFFYCbCrtoRGB(img->ycbcr, (Y), Cb, Cr, &r, &g, &b);            \
1784         dst = PACK(r, g, b);                                            \
1785 }
1786
1787 /*
1788  * 8-bit packed YCbCr samples => RGB 
1789  * This function is generic for different sampling sizes, 
1790  * and can handle blocks sizes that aren't multiples of the
1791  * sampling size.  However, it is substantially less optimized
1792  * than the specific sampling cases.  It is used as a fallback
1793  * for difficult blocks.
1794  */
1795 #ifdef notdef
1796 static void putcontig8bitYCbCrGenericTile( 
1797     TIFFRGBAImage* img, 
1798     uint32* cp, 
1799     uint32 x, uint32 y, 
1800     uint32 w, uint32 h, 
1801     int32 fromskew, int32 toskew, 
1802     unsigned char* pp,
1803     int h_group, 
1804     int v_group )
1805
1806 {
1807     uint32* cp1 = cp+w+toskew;
1808     uint32* cp2 = cp1+w+toskew;
1809     uint32* cp3 = cp2+w+toskew;
1810     int32 incr = 3*w+4*toskew;
1811     int32   Cb, Cr;
1812     int     group_size = v_group * h_group + 2;
1813
1814     (void) y;
1815     fromskew = (fromskew * group_size) / h_group;
1816
1817     for( yy = 0; yy < h; yy++ )
1818     {
1819         unsigned char *pp_line;
1820         int     y_line_group = yy / v_group;
1821         int     y_remainder = yy - y_line_group * v_group;
1822
1823         pp_line = pp + v_line_group * 
1824
1825         
1826         for( xx = 0; xx < w; xx++ )
1827         {
1828             Cb = pp
1829         }
1830     }
1831     for (; h >= 4; h -= 4) {
1832         x = w>>2;
1833         do {
1834             Cb = pp[16];
1835             Cr = pp[17];
1836
1837             YCbCrtoRGB(cp [0], pp[ 0]);
1838             YCbCrtoRGB(cp [1], pp[ 1]);
1839             YCbCrtoRGB(cp [2], pp[ 2]);
1840             YCbCrtoRGB(cp [3], pp[ 3]);
1841             YCbCrtoRGB(cp1[0], pp[ 4]);
1842             YCbCrtoRGB(cp1[1], pp[ 5]);
1843             YCbCrtoRGB(cp1[2], pp[ 6]);
1844             YCbCrtoRGB(cp1[3], pp[ 7]);
1845             YCbCrtoRGB(cp2[0], pp[ 8]);
1846             YCbCrtoRGB(cp2[1], pp[ 9]);
1847             YCbCrtoRGB(cp2[2], pp[10]);
1848             YCbCrtoRGB(cp2[3], pp[11]);
1849             YCbCrtoRGB(cp3[0], pp[12]);
1850             YCbCrtoRGB(cp3[1], pp[13]);
1851             YCbCrtoRGB(cp3[2], pp[14]);
1852             YCbCrtoRGB(cp3[3], pp[15]);
1853
1854             cp += 4, cp1 += 4, cp2 += 4, cp3 += 4;
1855             pp += 18;
1856         } while (--x);
1857         cp += incr, cp1 += incr, cp2 += incr, cp3 += incr;
1858         pp += fromskew;
1859     }
1860 }
1861 #endif
1862
1863 /*
1864  * 8-bit packed YCbCr samples w/ 4,4 subsampling => RGB
1865  */
1866 DECLAREContigPutFunc(putcontig8bitYCbCr44tile)
1867 {
1868     uint32* cp1 = cp+w+toskew;
1869     uint32* cp2 = cp1+w+toskew;
1870     uint32* cp3 = cp2+w+toskew;
1871     int32 incr = 3*w+4*toskew;
1872
1873     (void) y;
1874     /* adjust fromskew */
1875     fromskew = (fromskew * 18) / 4;
1876     if ((h & 3) == 0 && (w & 3) == 0) {                                 
1877         for (; h >= 4; h -= 4) {
1878             x = w>>2;
1879             do {
1880                 int32 Cb = pp[16];
1881                 int32 Cr = pp[17];
1882
1883                 YCbCrtoRGB(cp [0], pp[ 0]);
1884                 YCbCrtoRGB(cp [1], pp[ 1]);
1885                 YCbCrtoRGB(cp [2], pp[ 2]);
1886                 YCbCrtoRGB(cp [3], pp[ 3]);
1887                 YCbCrtoRGB(cp1[0], pp[ 4]);
1888                 YCbCrtoRGB(cp1[1], pp[ 5]);
1889                 YCbCrtoRGB(cp1[2], pp[ 6]);
1890                 YCbCrtoRGB(cp1[3], pp[ 7]);
1891                 YCbCrtoRGB(cp2[0], pp[ 8]);
1892                 YCbCrtoRGB(cp2[1], pp[ 9]);
1893                 YCbCrtoRGB(cp2[2], pp[10]);
1894                 YCbCrtoRGB(cp2[3], pp[11]);
1895                 YCbCrtoRGB(cp3[0], pp[12]);
1896                 YCbCrtoRGB(cp3[1], pp[13]);
1897                 YCbCrtoRGB(cp3[2], pp[14]);
1898                 YCbCrtoRGB(cp3[3], pp[15]);
1899
1900                 cp += 4, cp1 += 4, cp2 += 4, cp3 += 4;
1901                 pp += 18;
1902             } while (--x);
1903             cp += incr, cp1 += incr, cp2 += incr, cp3 += incr;
1904             pp += fromskew;
1905         }
1906     } else {
1907         while (h > 0) {
1908             for (x = w; x > 0;) {
1909                 int32 Cb = pp[16];
1910                 int32 Cr = pp[17];
1911                 switch (x) {
1912                 default:
1913                     switch (h) {
1914                     default: YCbCrtoRGB(cp3[3], pp[15]); /* FALLTHROUGH */
1915                     case 3:  YCbCrtoRGB(cp2[3], pp[11]); /* FALLTHROUGH */
1916                     case 2:  YCbCrtoRGB(cp1[3], pp[ 7]); /* FALLTHROUGH */
1917                     case 1:  YCbCrtoRGB(cp [3], pp[ 3]); /* FALLTHROUGH */
1918                     }                                    /* FALLTHROUGH */
1919                 case 3:
1920                     switch (h) {
1921                     default: YCbCrtoRGB(cp3[2], pp[14]); /* FALLTHROUGH */
1922                     case 3:  YCbCrtoRGB(cp2[2], pp[10]); /* FALLTHROUGH */
1923                     case 2:  YCbCrtoRGB(cp1[2], pp[ 6]); /* FALLTHROUGH */
1924                     case 1:  YCbCrtoRGB(cp [2], pp[ 2]); /* FALLTHROUGH */
1925                     }                                    /* FALLTHROUGH */
1926                 case 2:
1927                     switch (h) {
1928                     default: YCbCrtoRGB(cp3[1], pp[13]); /* FALLTHROUGH */
1929                     case 3:  YCbCrtoRGB(cp2[1], pp[ 9]); /* FALLTHROUGH */
1930                     case 2:  YCbCrtoRGB(cp1[1], pp[ 5]); /* FALLTHROUGH */
1931                     case 1:  YCbCrtoRGB(cp [1], pp[ 1]); /* FALLTHROUGH */
1932                     }                                    /* FALLTHROUGH */
1933                 case 1:
1934                     switch (h) {
1935                     default: YCbCrtoRGB(cp3[0], pp[12]); /* FALLTHROUGH */
1936                     case 3:  YCbCrtoRGB(cp2[0], pp[ 8]); /* FALLTHROUGH */
1937                     case 2:  YCbCrtoRGB(cp1[0], pp[ 4]); /* FALLTHROUGH */
1938                     case 1:  YCbCrtoRGB(cp [0], pp[ 0]); /* FALLTHROUGH */
1939                     }                                    /* FALLTHROUGH */
1940                 }
1941                 if (x < 4) {
1942                     cp += x; cp1 += x; cp2 += x; cp3 += x;
1943                     x = 0;
1944                 }
1945                 else {
1946                     cp += 4; cp1 += 4; cp2 += 4; cp3 += 4;
1947                     x -= 4;
1948                 }
1949                 pp += 18;
1950             }
1951             if (h <= 4)
1952                 break;
1953             h -= 4;
1954             cp += incr, cp1 += incr, cp2 += incr, cp3 += incr;
1955             pp += fromskew;
1956         }
1957     }
1958 }
1959
1960 /*
1961  * 8-bit packed YCbCr samples w/ 4,2 subsampling => RGB
1962  */
1963 DECLAREContigPutFunc(putcontig8bitYCbCr42tile)
1964 {
1965     uint32* cp1 = cp+w+toskew;
1966     int32 incr = 2*toskew+w;
1967
1968     (void) y;
1969     fromskew = (fromskew * 10) / 4;
1970     if ((h & 3) == 0 && (w & 1) == 0) {
1971         for (; h >= 2; h -= 2) {
1972             x = w>>2;
1973             do {
1974                 int32 Cb = pp[8];
1975                 int32 Cr = pp[9];
1976                 
1977                 YCbCrtoRGB(cp [0], pp[0]);
1978                 YCbCrtoRGB(cp [1], pp[1]);
1979                 YCbCrtoRGB(cp [2], pp[2]);
1980                 YCbCrtoRGB(cp [3], pp[3]);
1981                 YCbCrtoRGB(cp1[0], pp[4]);
1982                 YCbCrtoRGB(cp1[1], pp[5]);
1983                 YCbCrtoRGB(cp1[2], pp[6]);
1984                 YCbCrtoRGB(cp1[3], pp[7]);
1985                 
1986                 cp += 4, cp1 += 4;
1987                 pp += 10;
1988             } while (--x);
1989             cp += incr, cp1 += incr;
1990             pp += fromskew;
1991         }
1992     } else {
1993         while (h > 0) {
1994             for (x = w; x > 0;) {
1995                 int32 Cb = pp[8];
1996                 int32 Cr = pp[9];
1997                 switch (x) {
1998                 default:
1999                     switch (h) {
2000                     default: YCbCrtoRGB(cp1[3], pp[ 7]); /* FALLTHROUGH */
2001                     case 1:  YCbCrtoRGB(cp [3], pp[ 3]); /* FALLTHROUGH */
2002                     }                                    /* FALLTHROUGH */
2003                 case 3:
2004                     switch (h) {
2005                     default: YCbCrtoRGB(cp1[2], pp[ 6]); /* FALLTHROUGH */
2006                     case 1:  YCbCrtoRGB(cp [2], pp[ 2]); /* FALLTHROUGH */
2007                     }                                    /* FALLTHROUGH */
2008                 case 2:
2009                     switch (h) {
2010                     default: YCbCrtoRGB(cp1[1], pp[ 5]); /* FALLTHROUGH */
2011                     case 1:  YCbCrtoRGB(cp [1], pp[ 1]); /* FALLTHROUGH */
2012                     }                                    /* FALLTHROUGH */
2013                 case 1:
2014                     switch (h) {
2015                     default: YCbCrtoRGB(cp1[0], pp[ 4]); /* FALLTHROUGH */
2016                     case 1:  YCbCrtoRGB(cp [0], pp[ 0]); /* FALLTHROUGH */
2017                     }                                    /* FALLTHROUGH */
2018                 }
2019                 if (x < 4) {
2020                     cp += x; cp1 += x;
2021                     x = 0;
2022                 }
2023                 else {
2024                     cp += 4; cp1 += 4;
2025                     x -= 4;
2026                 }
2027                 pp += 10;
2028             }
2029             if (h <= 2)
2030                 break;
2031             h -= 2;
2032             cp += incr, cp1 += incr;
2033             pp += fromskew;
2034         }
2035     }
2036 }
2037
2038 /*
2039  * 8-bit packed YCbCr samples w/ 4,1 subsampling => RGB
2040  */
2041 DECLAREContigPutFunc(putcontig8bitYCbCr41tile)
2042 {
2043     (void) y;
2044     /* XXX adjust fromskew */
2045     do {
2046         x = w>>2;
2047         do {
2048             int32 Cb = pp[4];
2049             int32 Cr = pp[5];
2050
2051             YCbCrtoRGB(cp [0], pp[0]);
2052             YCbCrtoRGB(cp [1], pp[1]);
2053             YCbCrtoRGB(cp [2], pp[2]);
2054             YCbCrtoRGB(cp [3], pp[3]);
2055
2056             cp += 4;
2057             pp += 6;
2058         } while (--x);
2059
2060         if( (w&3) != 0 )
2061         {
2062             int32 Cb = pp[4];
2063             int32 Cr = pp[5];
2064
2065             switch( (w&3) ) {
2066               case 3: YCbCrtoRGB(cp [2], pp[2]);
2067               case 2: YCbCrtoRGB(cp [1], pp[1]);
2068               case 1: YCbCrtoRGB(cp [0], pp[0]);
2069               case 0: break;
2070             }
2071
2072             cp += (w&3);
2073             pp += 6;
2074         }
2075
2076         cp += toskew;
2077         pp += fromskew;
2078     } while (--h);
2079
2080 }
2081
2082 /*
2083  * 8-bit packed YCbCr samples w/ 2,2 subsampling => RGB
2084  */
2085 DECLAREContigPutFunc(putcontig8bitYCbCr22tile)
2086 {
2087         uint32* cp2;
2088         int32 incr = 2*toskew+w;
2089         (void) y;
2090         fromskew = (fromskew / 2) * 6;
2091         cp2 = cp+w+toskew;
2092         while (h>=2) {
2093                 x = w;
2094                 while (x>=2) {
2095                         uint32 Cb = pp[4];
2096                         uint32 Cr = pp[5];
2097                         YCbCrtoRGB(cp[0], pp[0]);
2098                         YCbCrtoRGB(cp[1], pp[1]);
2099                         YCbCrtoRGB(cp2[0], pp[2]);
2100                         YCbCrtoRGB(cp2[1], pp[3]);
2101                         cp += 2;
2102                         cp2 += 2;
2103                         pp += 6;
2104                         x -= 2;
2105                 }
2106                 if (x==1) {
2107                         uint32 Cb = pp[4];
2108                         uint32 Cr = pp[5];
2109                         YCbCrtoRGB(cp[0], pp[0]);
2110                         YCbCrtoRGB(cp2[0], pp[2]);
2111                         cp ++ ;
2112                         cp2 ++ ;
2113                         pp += 6;
2114                 }
2115                 cp += incr;
2116                 cp2 += incr;
2117                 pp += fromskew;
2118                 h-=2;
2119         }
2120         if (h==1) {
2121                 x = w;
2122                 while (x>=2) {
2123                         uint32 Cb = pp[4];
2124                         uint32 Cr = pp[5];
2125                         YCbCrtoRGB(cp[0], pp[0]);
2126                         YCbCrtoRGB(cp[1], pp[1]);
2127                         cp += 2;
2128                         cp2 += 2;
2129                         pp += 6;
2130                         x -= 2;
2131                 }
2132                 if (x==1) {
2133                         uint32 Cb = pp[4];
2134                         uint32 Cr = pp[5];
2135                         YCbCrtoRGB(cp[0], pp[0]);
2136                 }
2137         }
2138 }
2139
2140 /*
2141  * 8-bit packed YCbCr samples w/ 2,1 subsampling => RGB
2142  */
2143 DECLAREContigPutFunc(putcontig8bitYCbCr21tile)
2144 {
2145         (void) y;
2146         fromskew = (fromskew * 4) / 2;
2147         do {
2148                 x = w>>1;
2149                 do {
2150                         int32 Cb = pp[2];
2151                         int32 Cr = pp[3];
2152
2153                         YCbCrtoRGB(cp[0], pp[0]);
2154                         YCbCrtoRGB(cp[1], pp[1]);
2155
2156                         cp += 2;
2157                         pp += 4;
2158                 } while (--x);
2159
2160                 if( (w&1) != 0 )
2161                 {
2162                         int32 Cb = pp[2];
2163                         int32 Cr = pp[3];
2164
2165                         YCbCrtoRGB(cp[0], pp[0]);
2166
2167                         cp += 1;
2168                         pp += 4;
2169                 }
2170
2171                 cp += toskew;
2172                 pp += fromskew;
2173         } while (--h);
2174 }
2175
2176 /*
2177  * 8-bit packed YCbCr samples w/ 1,2 subsampling => RGB
2178  */
2179 DECLAREContigPutFunc(putcontig8bitYCbCr12tile)
2180 {
2181         uint32* cp2;
2182         int32 incr = 2*toskew+w;
2183         (void) y;
2184         fromskew = (fromskew / 2) * 4;
2185         cp2 = cp+w+toskew;
2186         while (h>=2) {
2187                 x = w;
2188                 do {
2189                         uint32 Cb = pp[2];
2190                         uint32 Cr = pp[3];
2191                         YCbCrtoRGB(cp[0], pp[0]);
2192                         YCbCrtoRGB(cp2[0], pp[1]);
2193                         cp ++;
2194                         cp2 ++;
2195                         pp += 4;
2196                 } while (--x);
2197                 cp += incr;
2198                 cp2 += incr;
2199                 pp += fromskew;
2200                 h-=2;
2201         }
2202         if (h==1) {
2203                 x = w;
2204                 do {
2205                         uint32 Cb = pp[2];
2206                         uint32 Cr = pp[3];
2207                         YCbCrtoRGB(cp[0], pp[0]);
2208                         cp ++;
2209                         pp += 4;
2210                 } while (--x);
2211         }
2212 }
2213
2214 /*
2215  * 8-bit packed YCbCr samples w/ no subsampling => RGB
2216  */
2217 DECLAREContigPutFunc(putcontig8bitYCbCr11tile)
2218 {
2219         (void) y;
2220         fromskew *= 3;
2221         do {
2222                 x = w; /* was x = w>>1; patched 2000/09/25 warmerda@home.com */
2223                 do {
2224                         int32 Cb = pp[1];
2225                         int32 Cr = pp[2];
2226
2227                         YCbCrtoRGB(*cp++, pp[0]);
2228
2229                         pp += 3;
2230                 } while (--x);
2231                 cp += toskew;
2232                 pp += fromskew;
2233         } while (--h);
2234 }
2235
2236 /*
2237  * 8-bit packed YCbCr samples w/ no subsampling => RGB
2238  */
2239 DECLARESepPutFunc(putseparate8bitYCbCr11tile)
2240 {
2241         (void) y;
2242         (void) a;
2243         /* TODO: naming of input vars is still off, change obfuscating declaration inside define, or resolve obfuscation */
2244         while (h-- > 0) {
2245                 x = w;
2246                 do {
2247                         uint32 dr, dg, db;
2248                         TIFFYCbCrtoRGB(img->ycbcr,*r++,*g++,*b++,&dr,&dg,&db);
2249                         *cp++ = PACK(dr,dg,db);
2250                 } while (--x);
2251                 SKEW(r, g, b, fromskew);
2252                 cp += toskew;
2253         }
2254 }
2255 #undef YCbCrtoRGB
2256
2257 static int
2258 initYCbCrConversion(TIFFRGBAImage* img)
2259 {
2260         static const char module[] = "initYCbCrConversion";
2261
2262         float *luma, *refBlackWhite;
2263
2264         if (img->ycbcr == NULL) {
2265                 img->ycbcr = (TIFFYCbCrToRGB*) _TIFFmalloc(
2266                     TIFFroundup_32(sizeof (TIFFYCbCrToRGB), sizeof (long))  
2267                     + 4*256*sizeof (TIFFRGBValue)
2268                     + 2*256*sizeof (int)
2269                     + 3*256*sizeof (int32)
2270                     );
2271                 if (img->ycbcr == NULL) {
2272                         TIFFErrorExt(img->tif->tif_clientdata, module,
2273                             "No space for YCbCr->RGB conversion state");
2274                         return (0);
2275                 }
2276         }
2277
2278         TIFFGetFieldDefaulted(img->tif, TIFFTAG_YCBCRCOEFFICIENTS, &luma);
2279         TIFFGetFieldDefaulted(img->tif, TIFFTAG_REFERENCEBLACKWHITE,
2280             &refBlackWhite);
2281         if (TIFFYCbCrToRGBInit(img->ycbcr, luma, refBlackWhite) < 0)
2282                 return(0);
2283         return (1);
2284 }
2285
2286 static tileContigRoutine
2287 initCIELabConversion(TIFFRGBAImage* img)
2288 {
2289         static const char module[] = "initCIELabConversion";
2290
2291         float   *whitePoint;
2292         float   refWhite[3];
2293
2294         if (!img->cielab) {
2295                 img->cielab = (TIFFCIELabToRGB *)
2296                         _TIFFmalloc(sizeof(TIFFCIELabToRGB));
2297                 if (!img->cielab) {
2298                         TIFFErrorExt(img->tif->tif_clientdata, module,
2299                             "No space for CIE L*a*b*->RGB conversion state.");
2300                         return NULL;
2301                 }
2302         }
2303
2304         TIFFGetFieldDefaulted(img->tif, TIFFTAG_WHITEPOINT, &whitePoint);
2305         refWhite[1] = 100.0F;
2306         refWhite[0] = whitePoint[0] / whitePoint[1] * refWhite[1];
2307         refWhite[2] = (1.0F - whitePoint[0] - whitePoint[1])
2308                       / whitePoint[1] * refWhite[1];
2309         if (TIFFCIELabToRGBInit(img->cielab, &display_sRGB, refWhite) < 0) {
2310                 TIFFErrorExt(img->tif->tif_clientdata, module,
2311                     "Failed to initialize CIE L*a*b*->RGB conversion state.");
2312                 _TIFFfree(img->cielab);
2313                 return NULL;
2314         }
2315
2316         return (tileContigRoutine)putcontig8bitCIELab;
2317 }
2318
2319 /*
2320  * Greyscale images with less than 8 bits/sample are handled
2321  * with a table to avoid lots of shifts and masks.  The table
2322  * is setup so that put*bwtile (below) can retrieve 8/bitspersample
2323  * pixel values simply by indexing into the table with one
2324  * number.
2325  */
2326 static int
2327 makebwmap(TIFFRGBAImage* img)
2328 {
2329     TIFFRGBValue* Map = img->Map;
2330     int bitspersample = img->bitspersample;
2331     int nsamples = 8 / bitspersample;
2332     int i;
2333     uint32* p;
2334
2335     if( nsamples == 0 )
2336         nsamples = 1;
2337
2338     img->BWmap = (uint32**) _TIFFmalloc(
2339         256*sizeof (uint32 *)+(256*nsamples*sizeof(uint32)));
2340     if (img->BWmap == NULL) {
2341                 TIFFErrorExt(img->tif->tif_clientdata, TIFFFileName(img->tif), "No space for B&W mapping table");
2342                 return (0);
2343     }
2344     p = (uint32*)(img->BWmap + 256);
2345     for (i = 0; i < 256; i++) {
2346         TIFFRGBValue c;
2347         img->BWmap[i] = p;
2348         switch (bitspersample) {
2349 #define GREY(x) c = Map[x]; *p++ = PACK(c,c,c);
2350         case 1:
2351             GREY(i>>7);
2352             GREY((i>>6)&1);
2353             GREY((i>>5)&1);
2354             GREY((i>>4)&1);
2355             GREY((i>>3)&1);
2356             GREY((i>>2)&1);
2357             GREY((i>>1)&1);
2358             GREY(i&1);
2359             break;
2360         case 2:
2361             GREY(i>>6);
2362             GREY((i>>4)&3);
2363             GREY((i>>2)&3);
2364             GREY(i&3);
2365             break;
2366         case 4:
2367             GREY(i>>4);
2368             GREY(i&0xf);
2369             break;
2370         case 8:
2371         case 16:
2372             GREY(i);
2373             break;
2374         }
2375 #undef  GREY
2376     }
2377     return (1);
2378 }
2379
2380 /*
2381  * Construct a mapping table to convert from the range
2382  * of the data samples to [0,255] --for display.  This
2383  * process also handles inverting B&W images when needed.
2384  */ 
2385 static int
2386 setupMap(TIFFRGBAImage* img)
2387 {
2388     int32 x, range;
2389
2390     range = (int32)((1L<<img->bitspersample)-1);
2391     
2392     /* treat 16 bit the same as eight bit */
2393     if( img->bitspersample == 16 )
2394         range = (int32) 255;
2395
2396     img->Map = (TIFFRGBValue*) _TIFFmalloc((range+1) * sizeof (TIFFRGBValue));
2397     if (img->Map == NULL) {
2398                 TIFFErrorExt(img->tif->tif_clientdata, TIFFFileName(img->tif),
2399                         "No space for photometric conversion table");
2400                 return (0);
2401     }
2402     if (img->photometric == PHOTOMETRIC_MINISWHITE) {
2403         for (x = 0; x <= range; x++)
2404             img->Map[x] = (TIFFRGBValue) (((range - x) * 255) / range);
2405     } else {
2406         for (x = 0; x <= range; x++)
2407             img->Map[x] = (TIFFRGBValue) ((x * 255) / range);
2408     }
2409     if (img->bitspersample <= 16 &&
2410         (img->photometric == PHOTOMETRIC_MINISBLACK ||
2411          img->photometric == PHOTOMETRIC_MINISWHITE)) {
2412         /*
2413          * Use photometric mapping table to construct
2414          * unpacking tables for samples <= 8 bits.
2415          */
2416         if (!makebwmap(img))
2417             return (0);
2418         /* no longer need Map, free it */
2419         _TIFFfree(img->Map), img->Map = NULL;
2420     }
2421     return (1);
2422 }
2423
2424 static int
2425 checkcmap(TIFFRGBAImage* img)
2426 {
2427     uint16* r = img->redcmap;
2428     uint16* g = img->greencmap;
2429     uint16* b = img->bluecmap;
2430     long n = 1L<<img->bitspersample;
2431
2432     while (n-- > 0)
2433         if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256)
2434             return (16);
2435     return (8);
2436 }
2437
2438 static void
2439 cvtcmap(TIFFRGBAImage* img)
2440 {
2441     uint16* r = img->redcmap;
2442     uint16* g = img->greencmap;
2443     uint16* b = img->bluecmap;
2444     long i;
2445
2446     for (i = (1L<<img->bitspersample)-1; i >= 0; i--) {
2447 #define CVT(x)          ((uint16)((x)>>8))
2448         r[i] = CVT(r[i]);
2449         g[i] = CVT(g[i]);
2450         b[i] = CVT(b[i]);
2451 #undef  CVT
2452     }
2453 }
2454
2455 /*
2456  * Palette images with <= 8 bits/sample are handled
2457  * with a table to avoid lots of shifts and masks.  The table
2458  * is setup so that put*cmaptile (below) can retrieve 8/bitspersample
2459  * pixel values simply by indexing into the table with one
2460  * number.
2461  */
2462 static int
2463 makecmap(TIFFRGBAImage* img)
2464 {
2465     int bitspersample = img->bitspersample;
2466     int nsamples = 8 / bitspersample;
2467     uint16* r = img->redcmap;
2468     uint16* g = img->greencmap;
2469     uint16* b = img->bluecmap;
2470     uint32 *p;
2471     int i;
2472
2473     img->PALmap = (uint32**) _TIFFmalloc(
2474         256*sizeof (uint32 *)+(256*nsamples*sizeof(uint32)));
2475     if (img->PALmap == NULL) {
2476                 TIFFErrorExt(img->tif->tif_clientdata, TIFFFileName(img->tif), "No space for Palette mapping table");
2477                 return (0);
2478         }
2479     p = (uint32*)(img->PALmap + 256);
2480     for (i = 0; i < 256; i++) {
2481         TIFFRGBValue c;
2482         img->PALmap[i] = p;
2483 #define CMAP(x) c = (TIFFRGBValue) x; *p++ = PACK(r[c]&0xff, g[c]&0xff, b[c]&0xff);
2484         switch (bitspersample) {
2485         case 1:
2486             CMAP(i>>7);
2487             CMAP((i>>6)&1);
2488             CMAP((i>>5)&1);
2489             CMAP((i>>4)&1);
2490             CMAP((i>>3)&1);
2491             CMAP((i>>2)&1);
2492             CMAP((i>>1)&1);
2493             CMAP(i&1);
2494             break;
2495         case 2:
2496             CMAP(i>>6);
2497             CMAP((i>>4)&3);
2498             CMAP((i>>2)&3);
2499             CMAP(i&3);
2500             break;
2501         case 4:
2502             CMAP(i>>4);
2503             CMAP(i&0xf);
2504             break;
2505         case 8:
2506             CMAP(i);
2507             break;
2508         }
2509 #undef CMAP
2510     }
2511     return (1);
2512 }
2513
2514 /* 
2515  * Construct any mapping table used
2516  * by the associated put routine.
2517  */
2518 static int
2519 buildMap(TIFFRGBAImage* img)
2520 {
2521     switch (img->photometric) {
2522     case PHOTOMETRIC_RGB:
2523     case PHOTOMETRIC_YCBCR:
2524     case PHOTOMETRIC_SEPARATED:
2525         if (img->bitspersample == 8)
2526             break;
2527         /* fall thru... */
2528     case PHOTOMETRIC_MINISBLACK:
2529     case PHOTOMETRIC_MINISWHITE:
2530         if (!setupMap(img))
2531             return (0);
2532         break;
2533     case PHOTOMETRIC_PALETTE:
2534         /*
2535          * Convert 16-bit colormap to 8-bit (unless it looks
2536          * like an old-style 8-bit colormap).
2537          */
2538         if (checkcmap(img) == 16)
2539             cvtcmap(img);
2540         else
2541             TIFFWarningExt(img->tif->tif_clientdata, TIFFFileName(img->tif), "Assuming 8-bit colormap");
2542         /*
2543          * Use mapping table and colormap to construct
2544          * unpacking tables for samples < 8 bits.
2545          */
2546         if (img->bitspersample <= 8 && !makecmap(img))
2547             return (0);
2548         break;
2549     }
2550     return (1);
2551 }
2552
2553 /*
2554  * Select the appropriate conversion routine for packed data.
2555  */
2556 static int
2557 PickContigCase(TIFFRGBAImage* img)
2558 {
2559         img->get = TIFFIsTiled(img->tif) ? gtTileContig : gtStripContig;
2560         img->put.contig = NULL;
2561         switch (img->photometric) {
2562                 case PHOTOMETRIC_RGB:
2563                         switch (img->bitspersample) {
2564                                 case 8:
2565                                         if (img->alpha == EXTRASAMPLE_ASSOCALPHA)
2566                                                 img->put.contig = putRGBAAcontig8bittile;
2567                                         else if (img->alpha == EXTRASAMPLE_UNASSALPHA)
2568                                         {
2569                                                 if (BuildMapUaToAa(img))
2570                                                         img->put.contig = putRGBUAcontig8bittile;
2571                                         }
2572                                         else
2573                                                 img->put.contig = putRGBcontig8bittile;
2574                                         break;
2575                                 case 16:
2576                                         if (img->alpha == EXTRASAMPLE_ASSOCALPHA)
2577                                         {
2578                                                 if (BuildMapBitdepth16To8(img))
2579                                                         img->put.contig = putRGBAAcontig16bittile;
2580                                         }
2581                                         else if (img->alpha == EXTRASAMPLE_UNASSALPHA)
2582                                         {
2583                                                 if (BuildMapBitdepth16To8(img) &&
2584                                                     BuildMapUaToAa(img))
2585                                                         img->put.contig = putRGBUAcontig16bittile;
2586                                         }
2587                                         else
2588                                         {
2589                                                 if (BuildMapBitdepth16To8(img))
2590                                                         img->put.contig = putRGBcontig16bittile;
2591                                         }
2592                                         break;
2593                         }
2594                         break;
2595                 case PHOTOMETRIC_SEPARATED:
2596                         if (buildMap(img)) {
2597                                 if (img->bitspersample == 8) {
2598                                 if (!img->Map)
2599                                         img->put.contig = putRGBcontig8bitCMYKtile;
2600                                 else
2601                                         img->put.contig = putRGBcontig8bitCMYKMaptile;
2602                         }
2603                         else if(img->bitspersample == 16) /*LiuSunliang added 16bpp CMYK support.*/
2604                         {
2605                                 if (!img->Map)
2606                                         img->put.contig = putRGBcontig16bitCMYKtile;
2607                                 else
2608                                         img->put.contig = putRGBcontig16bitCMYKMaptile;
2609                         }
2610                 }
2611                 break;
2612         case PHOTOMETRIC_PALETTE:
2613                         if (buildMap(img)) {
2614                                 switch (img->bitspersample) {
2615                                         case 8:
2616                                                 img->put.contig = put8bitcmaptile;
2617                                                 break;
2618                                         case 4:
2619                                                 img->put.contig = put4bitcmaptile;
2620                                                 break;
2621                                         case 2:
2622                                                 img->put.contig = put2bitcmaptile;
2623                                                 break;
2624                                         case 1:
2625                                                 img->put.contig = put1bitcmaptile;
2626                                                 break;
2627                                 }
2628                         }
2629                         break;
2630                 case PHOTOMETRIC_MINISWHITE:
2631                 case PHOTOMETRIC_MINISBLACK:
2632                         if (buildMap(img)) {
2633                                 switch (img->bitspersample) {
2634                                         case 16:
2635                                                 img->put.contig = put16bitbwtile;
2636                                                 break;
2637                                         case 8:
2638                                                 if (img->alpha && img->samplesperpixel == 2)
2639                                                         img->put.contig = putagreytile;
2640                                                 else
2641                                                         img->put.contig = putgreytile;
2642                                                 break;
2643                                         case 4:
2644                                                 img->put.contig = put4bitbwtile;
2645                                                 break;
2646                                         case 2:
2647                                                 img->put.contig = put2bitbwtile;
2648                                                 break;
2649                                         case 1:
2650                                                 img->put.contig = put1bitbwtile;
2651                                                 break;
2652                                 }
2653                         }
2654                         break;
2655                 case PHOTOMETRIC_YCBCR:
2656                         if ((img->bitspersample==8) && (img->samplesperpixel==3))
2657                         {
2658                                 if (initYCbCrConversion(img)!=0)
2659                                 {
2660                                         /*
2661                                          * The 6.0 spec says that subsampling must be
2662                                          * one of 1, 2, or 4, and that vertical subsampling
2663                                          * must always be <= horizontal subsampling; so
2664                                          * there are only a few possibilities and we just
2665                                          * enumerate the cases.
2666                                          * Joris: added support for the [1,2] case, nonetheless, to accomodate
2667                                          * some OJPEG files
2668                                          */
2669                                         uint16 SubsamplingHor;
2670                                         uint16 SubsamplingVer;
2671                                         TIFFGetFieldDefaulted(img->tif, TIFFTAG_YCBCRSUBSAMPLING, &SubsamplingHor, &SubsamplingVer);
2672                                         switch ((SubsamplingHor<<4)|SubsamplingVer) {
2673                                                 case 0x44:
2674                                                         img->put.contig = putcontig8bitYCbCr44tile;
2675                                                         break;
2676                                                 case 0x42:
2677                                                         img->put.contig = putcontig8bitYCbCr42tile;
2678                                                         break;
2679                                                 case 0x41:
2680                                                         img->put.contig = putcontig8bitYCbCr41tile;
2681                                                         break;
2682                                                 case 0x22:
2683                                                         img->put.contig = putcontig8bitYCbCr22tile;
2684                                                         break;
2685                                                 case 0x21:
2686                                                         img->put.contig = putcontig8bitYCbCr21tile;
2687                                                         break;
2688                                                 case 0x12:
2689                                                         img->put.contig = putcontig8bitYCbCr12tile;
2690                                                         break;
2691                                                 case 0x11:
2692                                                         img->put.contig = putcontig8bitYCbCr11tile;
2693                                                         break;
2694                                         }
2695                                 }
2696                         }
2697                         break;
2698                 case PHOTOMETRIC_CIELAB:
2699                         if (buildMap(img)) {
2700                                 if (img->bitspersample == 8)
2701                                         img->put.contig = initCIELabConversion(img);
2702                                 break;
2703                         }
2704         }
2705         return ((img->get!=NULL) && (img->put.contig!=NULL));
2706 }
2707
2708 /*
2709  * Select the appropriate conversion routine for unpacked data.
2710  *
2711  * NB: we assume that unpacked single channel data is directed
2712  *       to the "packed routines.
2713  */
2714 static int
2715 PickSeparateCase(TIFFRGBAImage* img)
2716 {
2717         img->get = TIFFIsTiled(img->tif) ? gtTileSeparate : gtStripSeparate;
2718         img->put.separate = NULL;
2719         switch (img->photometric) {
2720         case PHOTOMETRIC_MINISWHITE:
2721         case PHOTOMETRIC_MINISBLACK:
2722                 /* greyscale images processed pretty much as RGB by gtTileSeparate */
2723         case PHOTOMETRIC_RGB:
2724                 switch (img->bitspersample) {
2725                 case 8:
2726                         if (img->alpha == EXTRASAMPLE_ASSOCALPHA)
2727                                 img->put.separate = putRGBAAseparate8bittile;
2728                         else if (img->alpha == EXTRASAMPLE_UNASSALPHA)
2729                         {
2730                                 if (BuildMapUaToAa(img))
2731                                         img->put.separate = putRGBUAseparate8bittile;
2732                         }
2733                         else
2734                                 img->put.separate = putRGBseparate8bittile;
2735                         break;
2736                 case 16:
2737                         if (img->alpha == EXTRASAMPLE_ASSOCALPHA)
2738                         {
2739                                 if (BuildMapBitdepth16To8(img))
2740                                         img->put.separate = putRGBAAseparate16bittile;
2741                         }
2742                         else if (img->alpha == EXTRASAMPLE_UNASSALPHA)
2743                         {
2744                                 if (BuildMapBitdepth16To8(img) &&
2745                                     BuildMapUaToAa(img))
2746                                         img->put.separate = putRGBUAseparate16bittile;
2747                         }
2748                         else
2749                         {
2750                                 if (BuildMapBitdepth16To8(img))
2751                                         img->put.separate = putRGBseparate16bittile;
2752                         }
2753                         break;
2754                 }
2755                 break;
2756         case PHOTOMETRIC_SEPARATED:
2757                 if (img->bitspersample == 8 && img->samplesperpixel == 4)
2758                 {
2759                         img->alpha = 1; // Not alpha, but seems like the only way to get 4th band
2760                         img->put.separate = putCMYKseparate8bittile;
2761                 }
2762                 break;
2763         case PHOTOMETRIC_YCBCR:
2764                 if ((img->bitspersample==8) && (img->samplesperpixel==3))
2765                 {
2766                         if (initYCbCrConversion(img)!=0)
2767                         {
2768                                 uint16 hs, vs;
2769                                 TIFFGetFieldDefaulted(img->tif, TIFFTAG_YCBCRSUBSAMPLING, &hs, &vs);
2770                                 switch ((hs<<4)|vs) {
2771                                 case 0x11:
2772                                         img->put.separate = putseparate8bitYCbCr11tile;
2773                                         break;
2774                                         /* TODO: add other cases here */
2775                                 }
2776                         }
2777                 }
2778                 break;
2779         }
2780         return ((img->get!=NULL) && (img->put.separate!=NULL));
2781 }
2782
2783 static int
2784 BuildMapUaToAa(TIFFRGBAImage* img)
2785 {
2786         static const char module[]="BuildMapUaToAa";
2787         uint8* m;
2788         uint16 na,nv;
2789         assert(img->UaToAa==NULL);
2790         img->UaToAa=_TIFFmalloc(65536);
2791         if (img->UaToAa==NULL)
2792         {
2793                 TIFFErrorExt(img->tif->tif_clientdata,module,"Out of memory");
2794                 return(0);
2795         }
2796         m=img->UaToAa;
2797         for (na=0; na<256; na++)
2798         {
2799                 for (nv=0; nv<256; nv++)
2800                         *m++=(nv*na+127)/255;
2801         }
2802         return(1);
2803 }
2804
2805 static int
2806 BuildMapBitdepth16To8(TIFFRGBAImage* img)
2807 {
2808         static const char module[]="BuildMapBitdepth16To8";
2809         uint8* m;
2810         uint32 n;
2811         assert(img->Bitdepth16To8==NULL);
2812         img->Bitdepth16To8=_TIFFmalloc(65536);
2813         if (img->Bitdepth16To8==NULL)
2814         {
2815                 TIFFErrorExt(img->tif->tif_clientdata,module,"Out of memory");
2816                 return(0);
2817         }
2818         m=img->Bitdepth16To8;
2819         for (n=0; n<65536; n++)
2820                 *m++=(n+128)/257;
2821         return(1);
2822 }
2823
2824
2825 /*
2826  * Read a whole strip off data from the file, and convert to RGBA form.
2827  * If this is the last strip, then it will only contain the portion of
2828  * the strip that is actually within the image space.  The result is
2829  * organized in bottom to top form.
2830  */
2831
2832
2833 int
2834 TIFFReadRGBAStrip(TIFF* tif, uint32 row, uint32 * raster )
2835
2836 {
2837     char        emsg[1024] = "";
2838     TIFFRGBAImage img;
2839     int         ok;
2840     uint32      rowsperstrip, rows_to_read;
2841
2842     if( TIFFIsTiled( tif ) )
2843     {
2844                 TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif),
2845                   "Can't use TIFFReadRGBAStrip() with tiled file.");
2846         return (0);
2847     }
2848     
2849     TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
2850     if( (row % rowsperstrip) != 0 )
2851     {
2852                 TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif),
2853                                 "Row passed to TIFFReadRGBAStrip() must be first in a strip.");
2854                 return (0);
2855     }
2856
2857     if (TIFFRGBAImageOK(tif, emsg) && TIFFRGBAImageBegin(&img, tif, 0, emsg)) {
2858
2859         img.row_offset = row;
2860         img.col_offset = 0;
2861
2862         if( row + rowsperstrip > img.height )
2863             rows_to_read = img.height - row;
2864         else
2865             rows_to_read = rowsperstrip;
2866         
2867         ok = TIFFRGBAImageGet(&img, raster, img.width, rows_to_read );
2868         
2869         TIFFRGBAImageEnd(&img);
2870     } else {
2871                 TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "%s", emsg);
2872                 ok = 0;
2873     }
2874     
2875     return (ok);
2876 }
2877
2878 /*
2879  * Read a whole tile off data from the file, and convert to RGBA form.
2880  * The returned RGBA data is organized from bottom to top of tile,
2881  * and may include zeroed areas if the tile extends off the image.
2882  */
2883
2884 int
2885 TIFFReadRGBATile(TIFF* tif, uint32 col, uint32 row, uint32 * raster)
2886
2887 {
2888     char        emsg[1024] = "";
2889     TIFFRGBAImage img;
2890     int         ok;
2891     uint32      tile_xsize, tile_ysize;
2892     uint32      read_xsize, read_ysize;
2893     uint32      i_row;
2894
2895     /*
2896      * Verify that our request is legal - on a tile file, and on a
2897      * tile boundary.
2898      */
2899     
2900     if( !TIFFIsTiled( tif ) )
2901     {
2902                 TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif),
2903                                   "Can't use TIFFReadRGBATile() with stripped file.");
2904                 return (0);
2905     }
2906     
2907     TIFFGetFieldDefaulted(tif, TIFFTAG_TILEWIDTH, &tile_xsize);
2908     TIFFGetFieldDefaulted(tif, TIFFTAG_TILELENGTH, &tile_ysize);
2909     if( (col % tile_xsize) != 0 || (row % tile_ysize) != 0 )
2910     {
2911                 TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif),
2912                   "Row/col passed to TIFFReadRGBATile() must be top"
2913                   "left corner of a tile.");
2914         return (0);
2915     }
2916
2917     /*
2918      * Setup the RGBA reader.
2919      */
2920     
2921     if (!TIFFRGBAImageOK(tif, emsg) 
2922         || !TIFFRGBAImageBegin(&img, tif, 0, emsg)) {
2923             TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "%s", emsg);
2924             return( 0 );
2925     }
2926
2927     /*
2928      * The TIFFRGBAImageGet() function doesn't allow us to get off the
2929      * edge of the image, even to fill an otherwise valid tile.  So we
2930      * figure out how much we can read, and fix up the tile buffer to
2931      * a full tile configuration afterwards.
2932      */
2933
2934     if( row + tile_ysize > img.height )
2935         read_ysize = img.height - row;
2936     else
2937         read_ysize = tile_ysize;
2938     
2939     if( col + tile_xsize > img.width )
2940         read_xsize = img.width - col;
2941     else
2942         read_xsize = tile_xsize;
2943
2944     /*
2945      * Read the chunk of imagery.
2946      */
2947     
2948     img.row_offset = row;
2949     img.col_offset = col;
2950
2951     ok = TIFFRGBAImageGet(&img, raster, read_xsize, read_ysize );
2952         
2953     TIFFRGBAImageEnd(&img);
2954
2955     /*
2956      * If our read was incomplete we will need to fix up the tile by
2957      * shifting the data around as if a full tile of data is being returned.
2958      *
2959      * This is all the more complicated because the image is organized in
2960      * bottom to top format. 
2961      */
2962
2963     if( read_xsize == tile_xsize && read_ysize == tile_ysize )
2964         return( ok );
2965
2966     for( i_row = 0; i_row < read_ysize; i_row++ ) {
2967         memmove( raster + (tile_ysize - i_row - 1) * tile_xsize,
2968                  raster + (read_ysize - i_row - 1) * read_xsize,
2969                  read_xsize * sizeof(uint32) );
2970         _TIFFmemset( raster + (tile_ysize - i_row - 1) * tile_xsize+read_xsize,
2971