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