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