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