1 /*---------------------------------------------------------------------------*
2  |              PDFlib - A library for generating PDF on the fly             |
3  +---------------------------------------------------------------------------+
4  | Copyright (c) 1997-2006 Thomas Merz and PDFlib GmbH. All rights reserved. |
5  +---------------------------------------------------------------------------+
6  |                                                                           |
7  |    This software is subject to the PDFlib license. It is NOT in the       |
8  |    public domain. Extended versions and commercial licenses are           |
9  |    available, please check http://www.pdflib.com.                         |
10  |                                                                           |
11  *---------------------------------------------------------------------------*/
12 
13 /* $Id: p_tiff.c,v 1.134.2.41 2010/01/14 11:04:03 tm Exp $
14  *
15  * TIFF processing for PDFlib
16  *
17  */
18 
19 #include "p_intern.h"
20 #include "p_color.h"
21 #include "p_image.h"
22 
23 #ifndef HAVE_LIBTIFF
24 
25 pdc_bool
pdf_is_TIFF_file(PDF * p,pdc_file * fp,pdf_tiff_info * tiff,pdc_bool check)26 pdf_is_TIFF_file(PDF *p, pdc_file *fp, pdf_tiff_info *tiff, pdc_bool check)
27 {
28     (void) p;
29     (void) fp;
30     (void) tiff;
31     (void) check;
32 
33     return pdc_false;
34 }
35 
36 int
pdf_process_TIFF_data(PDF * p,int imageslot)37 pdf_process_TIFF_data(
38     PDF *p,
39     int imageslot)
40 {
41     (void) imageslot;
42 
43     pdc_set_errmsg(p->pdc, PDF_E_UNSUPP_IMAGE, "TIFF", 0, 0, 0);
44 
45     return -1;
46 }
47 
48 #else
49 
50 #include "tiffiop.h"
51 static tsize_t
pdf_libtiff_read(void * fd,tdata_t buf,tsize_t size)52 pdf_libtiff_read(void* fd, tdata_t buf, tsize_t size)
53 {
54     pdc_file *fp = (pdc_file *) fd;
55 
56     return ((tsize_t) pdc_fread(buf, 1, (size_t) size, fp));
57 }
58 
59 static toff_t
pdf_libtiff_seek(void * fd,toff_t off,int whence)60 pdf_libtiff_seek(void* fd, toff_t off, int whence)
61 {
62     pdc_file *fp = (pdc_file *) fd;
63 
64     return ((toff_t) pdc_fseek(fp, (long) off, whence));
65 }
66 
67 static int
pdf_libtiff_close(void * fd)68 pdf_libtiff_close(void* fd)
69 {
70     (void) fd;
71 
72     /* pdc_fclose(fp); this happens in caller function */
73 
74     return 0;
75 }
76 
77 static toff_t
pdf_libtiff_size(void * fd)78 pdf_libtiff_size(void* fd)
79 {
80     pdc_file *fp = (pdc_file *) fd;
81 
82     return (toff_t) pdc_file_size(fp);
83 }
84 
85 static void *
pdf_libtiff_malloc(TIFF * t,tsize_t size)86 pdf_libtiff_malloc(TIFF *t, tsize_t size)
87 {
88     PDF *p = (PDF*) t->pdflib_opaque;
89     return pdc_calloc(p->pdc, (size_t)size, "libtiff");
90 }
91 
92 static void *
pdf_libtiff_realloc(TIFF * t,tdata_t mem,tsize_t size)93 pdf_libtiff_realloc(TIFF *t, tdata_t mem, tsize_t size)
94 {
95     PDF *p = (PDF*) t->pdflib_opaque;
96     return(pdc_realloc(p->pdc, (void*)mem, (size_t)size, "libtiff"));
97 }
98 
99 static void
pdf_libtiff_free(TIFF * t,tdata_t mem)100 pdf_libtiff_free(TIFF *t, tdata_t mem)
101 {
102     PDF *p = (PDF*) t->pdflib_opaque;
103     pdc_free(p->pdc, (void*)mem);
104 }
105 
106 #define PDF_TIFF_LENGTH_MAX 512
107 static void
pdf_libtiff_error(TIFF * t,const char * module,const char * fmt,va_list ap)108 pdf_libtiff_error(TIFF *t, const char* module, const char* fmt, va_list ap)
109 {
110     PDF *p = (PDF*) t->pdflib_opaque;
111 
112     if (pdc_logg_is_enabled(p->pdc, 5, trc_image))
113     {
114         char buffer[PDF_TIFF_LENGTH_MAX];
115 
116         /* Create the message */
117         pdc_vsnprintf(p->pdc, buffer, PDF_TIFF_LENGTH_MAX, fmt, ap);
118         pdc_logg(p->pdc, "\tlibtiff(%s): %s\n", module, buffer);
119     }
120 }
121 
122 static void
pdf_data_source_TIFF_init(PDF * p,PDF_data_source * src)123 pdf_data_source_TIFF_init(PDF *p, PDF_data_source *src)
124 {
125     static const char *fn = "pdf_data_source_TIFF_init";
126     pdf_image	*image;
127 
128     image = (pdf_image *) src->private_data;
129 
130     if (image->strips == 1)
131 	image->info.tiff.cur_line = 0;
132 
133     if (image->use_raw)
134     {
135 	/* malloc is done in the fill function */
136 	src->buffer_length = (size_t) 0;
137 	src->buffer_start = (pdc_byte *) NULL;
138     }
139     else
140     {
141 	if (image->bpc == 1)
142 	    src->buffer_length =
143 		(size_t) (image->components * ((int) image->width+7)/8);
144 	else
145 	    src->buffer_length =
146 		(size_t) (image->components * image->width);
147 
148 	src->buffer_start = (pdc_byte *)
149 	    pdc_malloc(p->pdc, src->buffer_length, fn);
150     }
151 }
152 
153 /* Convert the a and b samples of Lab data from signed to unsigned. */
154 
155 static void
pdf_signed_to_unsigned(pdc_byte * buf,size_t count)156 pdf_signed_to_unsigned(pdc_byte *buf, size_t count)
157 {
158     size_t i;
159 
160     for(i=0; i < count; i+=3)
161     {
162 	buf[i+1] ^= 0x80;
163 	buf[i+2] ^= 0x80;
164     }
165 }
166 
167 #define MYTIFF		image->info.tiff.tif
168 
169 static pdc_bool
pdf_data_source_TIFF_fill(PDF * p,PDF_data_source * src)170 pdf_data_source_TIFF_fill(PDF *p, PDF_data_source *src)
171 {
172     static const char *fn = "pdf_data_source_TIFF_fill";
173     pdf_image	*image;
174     int		col;
175     pdc_byte	*dest;
176     uint16	fillorder;
177     uint32	*s, *bc;
178 
179     image = (pdf_image *) src->private_data;
180 
181     PDC_TRY(p->pdc)
182     {
183         if (image->use_raw)
184         {
185             if (image->info.tiff.cur_line == image->strips)
186             {
187                 PDC_EXIT_TRY(p->pdc);
188                 return pdc_false;
189             }
190 
191             TIFFGetField(MYTIFF, TIFFTAG_STRIPBYTECOUNTS, &bc);
192 
193             if (bc[image->info.tiff.cur_line] > src->buffer_length)
194             {
195                 src->buffer_length = bc[image->info.tiff.cur_line];
196                 src->buffer_start = (pdc_byte *)
197                     pdc_realloc(p->pdc, src->buffer_start,
198                     src->buffer_length, fn);
199             }
200 
201             if (TIFFReadRawStrip(MYTIFF, (tstrip_t) image->info.tiff.cur_line,
202                             (tdata_t) src->buffer_start,
203                             (tsize_t) bc[image->info.tiff.cur_line]) == -1)
204             {
205                 pdc_error(p->pdc, PDF_E_IMAGE_CORRUPT, "TIFF",
206                           pdf_get_image_filename(p, image), 0, 0);
207             }
208 
209             src->next_byte = src->buffer_start;
210             src->bytes_available = bc[image->info.tiff.cur_line];
211 
212             /* special handling for uncompressed 16-bit images */
213             if (MYTIFF->tif_header.tiff_magic == TIFF_LITTLEENDIAN &&
214                 image->compression == pdf_comp_none && image->bpc == 16)
215             {
216                 TIFFSwabArrayOfShort((uint16 *) src->buffer_start,
217                         (unsigned long) src->bytes_available/2);
218             }
219 
220             if (TIFFGetField(MYTIFF, TIFFTAG_FILLORDER, &fillorder)
221                 && (fillorder == FILLORDER_LSB2MSB))
222             {
223                 TIFFReverseBits((unsigned char *) src->buffer_start,
224                     (unsigned long) src->bytes_available);
225             }
226 
227             /* The a and b values of (uncompressed) Lab must be adjusted */
228             if (p->colorspaces[image->colorspace].type == Lab)
229             {
230                 pdf_signed_to_unsigned(src->buffer_start, src->bytes_available);
231             }
232 
233             if (image->strips > 1)
234             {
235                 /* only a single strip of a multi-strip image */
236                 image->info.tiff.cur_line = image->strips;
237             }
238             else
239                 image->info.tiff.cur_line++;
240         }
241         else
242         {
243             {
244             if (image->info.tiff.cur_line++ == image->height)
245             {
246                 PDC_EXIT_TRY(p->pdc);
247                 return pdc_false;
248             }
249 
250             src->next_byte = src->buffer_start;
251             src->bytes_available = src->buffer_length;
252 
253             dest = src->buffer_start;
254             s = image->info.tiff.raster +
255                 ((int)image->height - image->info.tiff.cur_line) *
256                 (int) image->width;
257 
258             switch (image->components)
259             {
260                 case 1:
261                 if (image->bpc == 1)
262                 {
263                     unsigned char mask;
264 
265                     memset((void*) dest, 0, src->buffer_length);
266 
267                     for (mask=0x80, col = 0; col < image->width; col++)
268                     {
269                         if (TIFFGetR(*s++) != 0)
270                             *dest |= mask;
271 
272                         if ((mask>>=1) == 0)
273                         {
274                             mask = 0x80;
275                             ++dest;
276                         }
277                     }
278                 }
279                 else	/* bpc == 8 */
280                 {
281                     for (col = 0; col < image->width; col++, s++)
282                     {
283                         *dest++ = (pdc_byte) TIFFGetR(*s);
284                     }
285                 }
286                 break;
287 
288                 case 3:
289                 for (col = 0; col < image->width; col++, s++)
290                 {
291                     *dest++ = (pdc_byte) TIFFGetR(*s);
292                     *dest++ = (pdc_byte) TIFFGetG(*s);
293                     *dest++ = (pdc_byte) TIFFGetB(*s);
294                 }
295                 break;
296 
297                 case 4:
298                 for (col = 0; col < image->width; col++, s++)
299                 {
300                     unsigned char* t = (unsigned char*)&(*s);
301                     *dest++ = (pdc_byte) t[0];
302                     *dest++ = (pdc_byte) t[1];
303                     *dest++ = (pdc_byte) t[2];
304                     *dest++ = (pdc_byte) t[3];
305                 }
306                 break;
307 
308                 default:
309                 pdc_error(p->pdc, PDF_E_IMAGE_BADCOMP,
310                       pdc_errprintf(p->pdc, "%d", image->components),
311                       pdf_get_image_filename(p, image), 0, 0);
312                 }
313             }
314         }
315     }
316     PDC_CATCH(p->pdc)
317     {
318         image->corrupt = pdc_true;
319     }
320 
321     return !image->corrupt;
322 }
323 
324 static void
pdf_data_source_TIFF_terminate(PDF * p,PDF_data_source * src)325 pdf_data_source_TIFF_terminate(PDF *p, PDF_data_source *src)
326 {
327     pdc_free(p->pdc, (void *) src->buffer_start);
328 }
329 
330 static int
pdf_check_colormap(int n,uint16 * r,uint16 * g,uint16 * b)331 pdf_check_colormap(int n, uint16* r, uint16* g, uint16* b)
332 {
333     while (n-- > 0)
334 	if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256)
335 		return(16);
336     return(8);
337 }
338 
339 pdc_bool
pdf_is_TIFF_file(PDF * p,pdc_file * fp,pdf_tiff_info * tiff_info,pdc_bool check)340 pdf_is_TIFF_file(PDF *p, pdc_file *fp, pdf_tiff_info *tiff_info, pdc_bool check)
341 {
342     const char *filename;
343 
344     pdc_logg_cond(p->pdc, 1, trc_image, "\tChecking image type TIFF...\n");
345 
346     filename = pdc_file_name(fp);
347     tiff_info->tif = TIFFClientOpen(filename, "rc",
348             (void *)fp,
349             pdf_libtiff_read, NULL,
350             pdf_libtiff_seek, pdf_libtiff_close, pdf_libtiff_size,
351             NULL, NULL, (void *)p,
352             pdf_libtiff_malloc, pdf_libtiff_realloc, pdf_libtiff_free,
353             pdf_libtiff_error, pdf_libtiff_error);
354     if (tiff_info->tif == NULL)
355     {
356         pdc_fseek(fp, 0L, SEEK_SET);
357         return pdc_false;
358     }
359     if (check)
360         TIFFClose(tiff_info->tif);
361     return pdc_true;
362 }
363 
364 int
pdf_process_TIFF_data(PDF * p,int imageslot)365 pdf_process_TIFF_data(
366     PDF *p,
367     int imageslot)
368 {
369     static const char *fn = "pdf_process_TIFF_data";
370     uint32 width, height;
371     uint16 unit, bpc, compression, photometric, extra, *sinfo;
372     uint16 orientation, planarconfig;
373     uint16 *rmap, *gmap, *bmap;
374     tsample_t components;
375     pdf_image *image;
376     float res_x, res_y;  /* sic! */
377     pdf_colorspace cs;
378     int slot;
379     int errint = 0;
380     int errcode = 0;
381     pdc_bool isopen = pdc_false;
382     int strips;
383 
384     image = &p->images[imageslot];
385 
386     image->info.tiff.raster = (uint32 *) NULL;
387 
388     if (!pdf_is_TIFF_file(p, image->fp, &image->info.tiff, pdc_false))
389     {
390         errcode = PDF_E_IMAGE_CORRUPT;
391         goto PDF_TIFF_ERROR;
392     }
393 
394     MYTIFF->tif_fd = (FILE*) image->fp;
395     isopen = pdc_true;
396 
397     if (image->page != 1)
398     {
399         if (TIFFSetDirectory(MYTIFF, (tdir_t) (image->page - 1)) != 1 )
400 	{
401             errint = image->page;
402             errcode = PDF_E_IMAGE_NOPAGE;
403             goto PDF_TIFF_ERROR;
404 	}
405     }
406 
407     TIFFGetFieldDefaulted(MYTIFF, TIFFTAG_ORIENTATION, &orientation);
408     image->orientation = orientation;
409 
410     TIFFGetField(MYTIFF, TIFFTAG_COMPRESSION, &compression);
411 
412     TIFFGetField(MYTIFF, TIFFTAG_IMAGEWIDTH, &width);
413     image->width        = (pdc_scalar) width;
414 
415     TIFFGetField(MYTIFF, TIFFTAG_IMAGELENGTH, &height);
416     image->height       = (pdc_scalar) height;
417 
418     TIFFGetFieldDefaulted(MYTIFF, TIFFTAG_BITSPERSAMPLE, &bpc);
419     image->bpc		= bpc;
420 
421     TIFFGetFieldDefaulted(MYTIFF, TIFFTAG_SAMPLESPERPIXEL, &components);
422     image->components	= components;
423 
424     TIFFGetFieldDefaulted(MYTIFF, TIFFTAG_EXTRASAMPLES, &extra, &sinfo);
425 
426     TIFFGetFieldDefaulted(MYTIFF, TIFFTAG_PLANARCONFIG, &planarconfig);
427 
428     photometric = 255;	/* dummy value */
429     TIFFGetField(MYTIFF, TIFFTAG_PHOTOMETRIC, &photometric);
430 
431     /* fetch the resolution values if found in the file */
432     if (TIFFGetField(MYTIFF, TIFFTAG_XRESOLUTION, &res_x) &&
433 	TIFFGetField(MYTIFF, TIFFTAG_YRESOLUTION, &res_y) &&
434 	TIFFGetFieldDefaulted(MYTIFF, TIFFTAG_RESOLUTIONUNIT, &unit) &&
435 	res_x > 0 && res_y > 0) {
436 
437 	if (unit == RESUNIT_INCH) {
438 	    image->dpi_x = res_x;
439 	    image->dpi_y = res_y;
440 
441 	} else if (unit == RESUNIT_CENTIMETER) {
442 	    image->dpi_x = res_x * 2.54;
443 	    image->dpi_y = res_y * 2.54;
444 
445 	} else if (unit == RESUNIT_NONE) {
446 	    image->dpi_x = -res_x;
447 	    image->dpi_y = -res_y;
448 	}
449 
450 #define PDF_REALLY_BIG_DPI	10000
451 
452 	/* Guard against obviously wrong values */
453 	if (unit != RESUNIT_NONE &&
454 	    (image->dpi_x <= 1 ||
455 	    image->dpi_y <= 1 ||
456 	    image->dpi_x > PDF_REALLY_BIG_DPI ||
457 	    image->dpi_y > PDF_REALLY_BIG_DPI))
458 
459 	    image->dpi_x = image->dpi_y = 0;	/* unknown */
460     }
461 
462 
463 
464     /* ------------------------------------------------------------
465      * Reject unsupported flavors.
466      * ---------------------------------------------------------- */
467 
468     /* Catch some rare properties related to compression, photometric,
469      * and bpc which are definitely not supported (neither in pass-through
470      * mode nor libtiff) in order to provide a better error message than
471      * the generic "Error reading data".
472      */
473 
474     /* Unsupported compression types */
475     switch ((int) compression)
476     {
477 	case /* 34661 */ COMPRESSION_JBIG:
478 	case /* 34712 */ COMPRESSION_JP2000:
479 	case 9 		/* JBIG T85 */:
480 	case 10 	/* TIFF-FX JBIG (T.82) MRC (T.43) */:
481 	case 34715	/* TFX */:
482 	    errint = (int) compression;
483 	    errcode = PDF_E_TIFF_UNSUPP_COMPRESSION;
484 	    goto PDF_TIFF_ERROR;
485 	    break;
486 
487 	default:
488 	    break;
489     }
490 
491     /* Unsupported photometric values */
492     switch ((int) photometric)
493     {
494 	case PHOTOMETRIC_ICCLAB /*  9 */:
495 	case PHOTOMETRIC_ITULAB /* 10 */:
496 	    errint = (int) photometric;
497 	    errcode = PDF_E_TIFF_UNSUPP_COLORSPACE;
498 	    goto PDF_TIFF_ERROR;
499 	    break;
500 
501 	default:
502 	    break;
503     }
504 
505     /* 32-bit images are not supported */
506     if (image->bpc > 16)
507     {
508 	errcode = PDF_E_TIFF_16BIT_UNSUPP;
509 	goto PDF_TIFF_ERROR;
510     }
511 
512     /* We don't support 16-bit CMYK unless it's uncompressed */
513     if (image->bpc == 16 && components == 4 && compression != COMPRESSION_NONE)
514     {
515 	errcode = PDF_E_TIFF_16BITCMYK_UNSUPP;
516 	goto PDF_TIFF_ERROR;
517     }
518 
519 
520     /* ------------------------------------------------------------
521      * We assume pass-through mode in the beginning, and disable it
522      * for image types where it doesn't work.
523      * ---------------------------------------------------------- */
524 
525     image->use_raw = image->passthrough;
526 
527     /* Pass-through is not implemented for tiled images */
528     if (TIFFIsTiled(MYTIFF))
529 	image->use_raw = pdc_false;
530 
531 
532 
533     /* Can't handle these colorspaces in raw mode (except with OJPEG) */
534     if (compression != COMPRESSION_OJPEG &&
535 	(photometric == PHOTOMETRIC_YCBCR ||
536 	photometric == PHOTOMETRIC_CIELAB ||
537 	photometric == PHOTOMETRIC_MASK))
538     {
539 	    image->use_raw = pdc_false;
540     }
541 
542     /* Can't pass through extra bits or use multiple data sources in raw mode
543      * (except with OJPEG).
544      */
545     if (extra != 0 ||
546        (compression != COMPRESSION_OJPEG &&
547         planarconfig == PLANARCONFIG_SEPARATE && components > 1))
548     {
549 	image->components -= extra;	/* ignore the extra channels */
550 	image->use_raw = pdc_false;
551     }
552 
553     /* Can't pass through grayscale or RGB with additional alpha channel.
554      * Some TIFF images do not count the alpha channel as extra channel.
555      */
556     if (extra == 0 &&
557 	((photometric == PHOTOMETRIC_RGB && components == 4) ||
558 	 ((photometric == PHOTOMETRIC_MINISBLACK ||
559 	   photometric == PHOTOMETRIC_MINISWHITE) && components == 2)))
560     {
561 	image->components -= 1;	/* ignore the alpha channel */
562 	image->use_raw = pdc_false;
563     }
564 
565     /* PDF doesn't support other values of the color depth */
566     if (bpc != 1 && bpc != 2 && bpc != 4 && bpc != 8 && bpc != 16)
567 	image->use_raw = pdc_false;
568 
569     /* Disable pass-through for a large number of strips to avoid
570      * file size bloat (due to many small Image XObjects) and
571      * ugly display in Acrobat (because of banding artifacts).
572      * The threshold for the number of strips has been determined empirically
573      * as a good compromise between file size and performance.
574      *
575      * We must still maintain pass-through mode for those cases where it
576      * is functionally more advanced, and benefit from its better performance
577      * for small numbers of strips.
578      *
579      * Also, we maintain pass-through mode for very large images since
580      * pass-through mode - especially with pixel mode (RGBA retrieval) -
581      * may run out of memory.
582      */
583 
584 /* ca. 10K x 10K pixels (nopassthrough requires up to 4 times as many bytes!) */
585 #define PDF_TIFF_THRESHOLD  0x6000000
586 
587     strips = (int) TIFFNumberOfStrips(MYTIFF);
588 
589     if (strips > 25 &&
590 	compression != COMPRESSION_OJPEG && compression != COMPRESSION_JPEG &&
591 	photometric != PHOTOMETRIC_PALETTE &&
592 	image->width * image->height < PDF_TIFF_THRESHOLD)
593     {
594 	image->use_raw = pdc_false;
595     }
596 
597     if (image->bpc == 16)
598     {
599 	/* PDF < 1.5 doesn't support 16-bit images, so we cannot pass through */
600 	if (p->compatibility < PDC_1_5)
601 	{
602 	    image->use_raw = pdc_false;
603 	}
604 
605 	/*
606 	 * PDF requires big-endian 16-bit data. We therefore use passthrough
607 	 * mode only for big-endian input or uncompressed data.
608 	 *
609 	 * It's not nice to pull the endianness directly from the TIFF
610 	 * structure, but there doesn't seem to be a public interface for it.
611 	 */
612 	if (MYTIFF->tif_header.tiff_magic == TIFF_LITTLEENDIAN &&
613 	    (compression == COMPRESSION_DEFLATE ||
614 	    compression == COMPRESSION_ADOBE_DEFLATE))
615 	{
616 	    image->use_raw = pdc_false;
617 	}
618 
619 	/* We don't support 16-bit CMYK unless in passthrough mode.
620 	 * Compressed images have already been rejected earlier.
621 	 */
622 	if (components == 4 && image->use_raw == pdc_false)
623 	{
624 	    errcode = PDF_E_TIFF_16BITCMYK_UNSUPP;
625 	    goto PDF_TIFF_ERROR;
626 	}
627     }
628 
629     /*
630      * Disable pass-through for unknown compression schemes,
631      * and collect the necessary parameters for well-known schemes.
632      */
633 
634     if (image->use_raw == pdc_true)
635     {
636 	uint32 group3opts;
637 	uint16 predictor;
638 	toff_t jpegifoffset, jpegifbytecount;
639 
640         switch ((int) compression)
641         {
642             case COMPRESSION_CCITTRLE:
643             case COMPRESSION_CCITTRLEW:
644                 image->params = (char *) pdc_malloc(p->pdc, PDF_MAX_PARAMSTRING,
645                     fn);
646 
647                 strcpy(image->params, "/EndOfBlock false");
648                 strcat(image->params, "/EncodedByteAlign true");
649 
650                 if (photometric == PHOTOMETRIC_MINISBLACK)
651                     strcat(image->params, "/BlackIs1 true");
652 
653                 image->compression = pdf_comp_ccitt;
654                 break;
655 
656             case COMPRESSION_CCITTFAX3:
657                 image->params = (char*) pdc_malloc(p->pdc, PDF_MAX_PARAMSTRING,
658                     fn);
659 
660                 strcpy(image->params, "/EndOfBlock false");
661 
662                 /* The following contains disabled code segments.
663                  * Apparently, and contrary to my reading of the specs,
664                  * the following can not be deduced from the respective
665                  * TIFF entry or option:
666                  * - /EncodedByteAlign can not reliably be deduced from
667                  *   GROUP3OPT_FILLBITS;
668                  *
669                  * From practical experience, the respective lines are
670                  * disabled, but I don't have any clear explanation for this.
671                  * A few TIFF images still don't work with this setting,
672                  * unfortunately.
673                  */
674 
675                 /* SEE ABOVE!
676                 strcat(image->params, "/DamagedRowsBeforeError 1");
677                 */
678 
679                 if (TIFFGetField(MYTIFF, TIFFTAG_GROUP3OPTIONS, &group3opts))
680                 {
681                     /* /K = 0 (= G3,1D) is default */
682                     if (group3opts & GROUP3OPT_2DENCODING)
683                         strcat(image->params, "/K 1");
684 
685                     /* SEE ABOVE!
686                     if (group3opts & GROUP3OPT_FILLBITS)
687                         strcat(image->params, "/EncodedByteAlign true");
688                     */
689                 }
690 
691                 if (photometric == PHOTOMETRIC_MINISBLACK)
692                     strcat(image->params, "/BlackIs1 true");
693 
694                 image->compression = pdf_comp_ccitt;
695                 break;
696 
697             case COMPRESSION_CCITTFAX4:
698                 image->params = (char*) pdc_malloc(p->pdc, PDF_MAX_PARAMSTRING,
699                                                    fn);
700 
701                 strcpy(image->params, "/K -1");
702                 /* Required for bug #511 */
703                 strcat(image->params, "/EndOfBlock false");
704 
705                 if (photometric == PHOTOMETRIC_MINISBLACK)
706                     strcat(image->params, "/BlackIs1 true");
707 
708                 image->compression = pdf_comp_ccitt;
709                 break;
710 
711             case COMPRESSION_OJPEG:
712                 /*
713                  * Check whether a full-blown JPEG can be found inside the TIFF
714                  *
715                  * Heuristic:
716                  * If we find a positive JPEGIFOFFSET there should be valid
717                  * JFIF data; however, sometimes there isn't and we must not
718                  *call the JPEG module. Strangely enough, various creators which
719                  * do not emit valid JFIF do emit the JPEGIFBYTECOUNT tag.
720                  * Therefore we use the absence of JPEGIFBYTECOUNT as a hint
721                  * that JFIF processing might work.
722                  *
723                  * Known trouble-makers which include JPEGIFBYTECOUNT:
724                  * "Oi/GFS, writer v00.06.02"
725                  */
726                 if (TIFFGetField(MYTIFF, TIFFTAG_JPEGIFOFFSET, &jpegifoffset) &&
727                     jpegifoffset != 0 &&
728                    !TIFFGetField(MYTIFF, TIFFTAG_JPEGIFBYTECOUNT,
729                                  &jpegifbytecount))
730                 {
731                     /* stop TIFF processing */
732                     TIFFClose(MYTIFF);
733 
734                     /* store data offset for the JPEG module (after TIFFClose()
735                      * the image->info union is no longer used by the TIFF
736                      * module)
737                      */
738                     image->info.jpeg.jpegifoffset = jpegifoffset;
739 
740                     /* ...and process the data at the offset as JPEG */
741                     pdc_logg_cond(p->pdc, 1, trc_image,
742                         "\tTIFF with OJPEG: switching to JPEG processing...\n");
743                     return pdf_process_JPEG_data(p, imageslot);
744                 }
745                 else
746                 {
747                     /* We must repeat the check here since we omitted the OJPEG
748                      * case when we applied the test for the first time.
749                      */
750                     if (extra != 0 ||
751                       (planarconfig == PLANARCONFIG_SEPARATE && components > 1))
752                     {
753                         /* ignore the extra channels */
754                         image->components -= extra;
755                     }
756                     image->use_raw = pdc_false;
757                 }
758                 break;
759 
760             case COMPRESSION_NONE:
761                 if (photometric == PHOTOMETRIC_MINISWHITE)
762                     image->invert = !image->invert;
763 
764                 image->compression = pdf_comp_none;
765                 break;
766 
767             case COMPRESSION_LZW:
768                 if (TIFFGetField(MYTIFF, TIFFTAG_PREDICTOR, &predictor)) {
769                     if (predictor != pred_default && predictor != pred_tiff) {
770                         image->use_raw = pdc_false;
771                         break;
772                     } else
773                         image->predictor = (pdf_predictor) predictor;
774                 }
775 
776                 if (photometric == PHOTOMETRIC_MINISWHITE)
777                     image->invert = !image->invert;
778 
779                 image->compression = pdf_comp_lzw;
780                 break;
781 
782             case COMPRESSION_PACKBITS:
783                 if (photometric == PHOTOMETRIC_MINISWHITE)
784                     image->invert = !image->invert;
785 
786                 image->compression = pdf_comp_runlength;
787                 break;
788 
789             case COMPRESSION_DEFLATE:
790             case COMPRESSION_ADOBE_DEFLATE:
791                 if (TIFFGetField(MYTIFF, TIFFTAG_PREDICTOR, &predictor)) {
792                     if (predictor != pred_default && predictor != pred_tiff) {
793                         image->use_raw = pdc_false;
794                         break;
795                     } else
796                         image->predictor = (pdf_predictor) predictor;
797                 }
798 
799                 if (photometric == PHOTOMETRIC_MINISWHITE)
800                     image->invert = !image->invert;
801 
802                 image->compression = pdf_comp_flate;
803                 break;
804 
805             default:
806                 image->use_raw = pdc_false;
807         }
808     }
809 
810     if (image->use_raw)
811     {
812 	/* pass-through mode: directly copy chunks of strip data */
813 	image->strips = strips;
814 
815 	pdc_logg_cond(p->pdc, 1, trc_image, "\tpassthrough mode...\n");
816     }
817     else
818     {
819 	/* libtiff cannot handle JPEG-compressed TIFFs with separate image
820 	 * planes
821 	 */
822 	if (planarconfig == PLANARCONFIG_SEPARATE &&
823 	    (compression == COMPRESSION_OJPEG || compression==COMPRESSION_JPEG))
824 	{
825 	    errcode = PDF_E_TIFF_UNSUPP_SEPARATE;
826 	    goto PDF_TIFF_ERROR;
827 	}
828 
829 	/* Fallback: use TIFFlib to retrieve pixel data */
830 
831 	/* We have special handling for preserving bpc=1 if components=1,
832 	 * and therefore don't change bpc in this case.
833 	 */
834 	if (!(image->components == 1 && image->bpc == 1))
835 	{
836 	    /* Retrieve pixel data with libtiff, which converts to 8 bits. */
837 	    image->bpc = 8;
838 	}
839 
840 	image->strips = 1;
841         image->compression = pdf_comp_none;
842 
843 	/* Palette images are automatically converted to RGB by TIFFlib.
844 	 * Since there are actually 1-bit images (photometric=min-is-white)
845 	 * with a palette out there (which are invalid TIFF, and are not
846 	 * converted to RGB by TIFFlib) we must also check photometric.
847 	 */
848 	if (image->components == 1 && photometric == PHOTOMETRIC_PALETTE &&
849 	    TIFFGetField(MYTIFF, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap))
850 	{
851 	    image->components = 3;
852 	    image->bpc = 8;
853 	}
854 	pdc_logg_cond(p->pdc, 1, trc_image, "\tno passthrough mode...\n");
855     }
856 
857     if (image->imagemask)
858     {
859 	if (image->components != 1)
860         {
861 	    errcode = PDF_E_IMAGE_BADMASK;
862 	    goto PDF_TIFF_ERROR;
863 	}
864 
865 	if (p->compatibility == PDC_1_3)
866         {
867 	    if (image->components != 1 || image->bpc != 1)
868             {
869 		errcode = PDF_E_IMAGE_MASK1BIT13;
870 		goto PDF_TIFF_ERROR;
871 	    }
872 	}
873         else if (image->bpc > 1)
874         {
875 	    /* images with more than one bit will be written as /SMask,
876 	     * and don't require an /ImageMask entry.
877 	     */
878 	    image->imagemask = pdc_false;
879 	}
880     }
881 
882     if (image->mask != pdc_undef)
883     {
884         if (image->strips != 1)
885         {
886             errcode = PDF_E_TIFF_MASK_MULTISTRIP;
887             goto PDF_TIFF_ERROR;
888         }
889     }
890 
891     if (image->colorspace == pdc_undef)
892     {
893 	uint16 inkset;
894 
895         switch (image->components)
896         {
897             case 1:
898                 image->colorspace = DeviceGray;
899                 break;
900 
901             case 3:
902 		image->colorspace = DeviceRGB;
903                 break;
904 
905             case 4:
906                 if (photometric == PHOTOMETRIC_SEPARATED)
907                 {
908 		    /* Can't handle CMYK with mask */
909 		    if (extra != 0)
910 		    {
911 			errint = image->components;
912 			errcode = PDF_E_TIFF_CMYK_MASK;
913 			goto PDF_TIFF_ERROR;
914 		    }
915 
916                     TIFFGetFieldDefaulted(MYTIFF, TIFFTAG_INKSET, &inkset);
917                     if (inkset != INKSET_CMYK)
918                     {
919                         errint = inkset;
920                         errcode = PDF_E_TIFF_UNSUPP_SEP_NONCMYK;
921                         goto PDF_TIFF_ERROR;
922                     }
923                     image->colorspace = DeviceCMYK;
924                 }
925                 else
926                 {
927                     /* if it's not separated it must be RGB with alpha */
928                     image->components = 3;
929                     image->colorspace = DeviceRGB;
930                 }
931                 break;
932 
933             default:
934                 errint = image->components;
935                 errcode = PDF_E_IMAGE_BADCOMP;
936                 goto PDF_TIFF_ERROR;
937         }
938     }
939 
940 
941     image->src.private_data	= (void *) image;
942     image->src.init		= pdf_data_source_TIFF_init;
943     image->src.fill		= pdf_data_source_TIFF_fill;
944     image->src.terminate	= pdf_data_source_TIFF_terminate;
945     image->in_use = pdc_true;	/* mark slot as used */
946     image->src.next_byte        = NULL;
947 
948     if (image->use_raw) {
949 	uint32 row, rowsperstrip;
950 	int strip;
951 
952 	/* must handle colormap ourselves */
953 	if (photometric == PHOTOMETRIC_PALETTE)
954         {
955 	    int i;
956 	    pdf_colormap colormap;
957 
958 	    if (!TIFFGetField(MYTIFF, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap))
959             {
960                 errcode = PDF_E_IMAGE_COLORMAP;
961                 goto PDF_TIFF_ERROR;
962 	    }
963 
964 	    /* CCITT compression implicitly carries
965 	     * photometric==PHOTOMETRIC_MINISWHITE. Although the combination
966 	     * of CCITT compression and palette probably doesn't conform
967 	     * to the TIFF spec, we accept it, but must invert the color
968 	     * palette in order to match Acrobat's behavior.
969 	     * Note that most TIFF viewers either ignore the palette in
970 	     * this case or display the image with wrong colors.
971 	     */
972 	    if (compression == COMPRESSION_CCITTRLE ||
973 		compression == COMPRESSION_CCITTRLEW ||
974 		compression == COMPRESSION_CCITTFAX3 ||
975 		compression == COMPRESSION_CCITTFAX4)
976 	    {
977 		image->invert = !image->invert;
978 		pdc_logg_cond(p->pdc, 1, trc_image,
979 		    "\tinverting colors for CCITT-compressed "
980 		    "image with palette...\n");
981 	    }
982 
983 	    cs.type = Indexed;
984 	    cs.val.indexed.palette_size = 1 << bpc;
985 	    cs.val.indexed.colormap = &colormap;
986 	    cs.val.indexed.colormap_id = PDC_BAD_ID;
987 
988 	    cs.val.indexed.base = DeviceRGB;
989 
990 #define CVT(x) (uint16) ((x)>>8)
991 	    /* TODO: properly deal with 16-bit palette entries in PDF 1.5 */
992 	    if (pdf_check_colormap(cs.val.indexed.palette_size,
993 		rmap, gmap, bmap) == 16)
994 	    {
995                 /* convert colormap to 8 bit values  */
996 		for (i = 0; i < cs.val.indexed.palette_size; i++)
997                 {
998 		    rmap[i] = CVT(rmap[i]);
999 		    gmap[i] = CVT(gmap[i]);
1000 		    bmap[i] = CVT(bmap[i]);
1001 		}
1002 	    }
1003 #undef CVT
1004 
1005 	    for (i = 0; i < cs.val.indexed.palette_size; i++)
1006             {
1007 		colormap[i][0] = (pdc_byte) rmap[i];
1008 		colormap[i][1] = (pdc_byte) gmap[i];
1009 		colormap[i][2] = (pdc_byte) bmap[i];
1010 	    }
1011 
1012 	    image->components = 1;
1013 
1014 		slot = pdf_add_colorspace(p, &cs, pdc_false);
1015 		image->colorspace = slot;
1016 
1017 
1018 	}
1019 
1020 
1021 
1022 	if (image->strips > image->height)
1023 	    image->strips = (int) image->height;
1024 
1025 	if (TIFFGetFieldDefaulted(MYTIFF,
1026 	    TIFFTAG_ROWSPERSTRIP, &rowsperstrip) == 1 && (int)rowsperstrip!= -1)
1027 	    image->rowsperstrip = (int) rowsperstrip;
1028 	else
1029 	    image->rowsperstrip = (int) image->height;
1030 
1031 	/*
1032 	 * The first strip must be handled separately because it carries the
1033 	 * colormap for indexed images. Other strips reuse this colormap.
1034 	 */
1035 	image->info.tiff.cur_line = 0;
1036         image->height = (pdc_scalar)
1037 	    (image->rowsperstrip > (int) height ?
1038                                    (int) height : image->rowsperstrip);
1039 
1040 	/*
1041 	 * Images may also be written to the output before the first page
1042 	 * We do this ourselves (instead of in pdf_put_image() to avoid
1043 	 * many empty contents sections for multi-strip images.
1044 	 */
1045 	if (PDF_GET_STATE(p) == pdf_state_page)
1046 	    pdf_end_contents_section(p);
1047 
1048 	pdf_put_image(p, imageslot, pdc_true, pdc_false);
1049 
1050 	for (row = (uint32) image->rowsperstrip, strip = 1;
1051 		row < height; row += (uint32) image->rowsperstrip, strip++)
1052         {
1053             image->height = (pdc_scalar) (row+image->rowsperstrip > height ?
1054                                   (int) (height - row) : image->rowsperstrip);
1055 
1056 	    /*
1057 	     * tell pdf_data_source_TIFF_fill() to read only data of the
1058 	     * current strip
1059 	     */
1060 	    image->info.tiff.cur_line = strip;
1061 	    pdf_put_image(p, imageslot, pdc_false, pdc_false);
1062             /* Refresh, in case p->images reallocate */
1063             image = &p->images[imageslot];
1064 	}
1065 
1066         image->height = (pdc_scalar) height;
1067 	image->no -= (image->strips - 1);	/* number of first strip */
1068 
1069 	/* Special handling for multi-strip images (see comment above) */
1070 	if (PDF_GET_STATE(p) == pdf_state_page)
1071 	    pdf_begin_contents_section(p);
1072 
1073     }
1074     else /* !use_raw */
1075     {
1076 	size_t npixels;
1077 
1078 
1079 
1080 	/*
1081 	 * Retrieve full scan lines from TIFFlib for these color spaces,
1082 	 * and Gray, RGB, or CMYK pixel data otherwise.
1083 	 */
1084 	if (p->colorspaces[image->colorspace].type == DeviceCMYK ||
1085 	    (p->colorspaces[image->colorspace].type == ICCBased &&
1086 		image->components == 4))
1087 	{
1088 	    pdc_logg_cond(p->pdc, 1, trc_image,
1089 		"\tRetrieving full scan lines in native color space...\n");
1090 	    image->pixelmode = pdc_false;
1091 	}
1092 	else
1093 	{
1094 	    pdc_logg_cond(p->pdc, 1, trc_image,
1095 		"\tRetrieving converted pixel data (pixel mode)...\n");
1096 	    image->pixelmode = pdc_true;
1097 	}
1098 
1099         if (planarconfig == PLANARCONFIG_SEPARATE)
1100 	{
1101             errcode = PDF_E_TIFF_UNSUPP_SEPARATE;
1102             goto PDF_TIFF_ERROR;
1103         }
1104 	else if (image->pixelmode)
1105 	{
1106 	    npixels = (size_t) (width * height);
1107 
1108 	    image->info.tiff.raster = (uint32 *) pdc_malloc(p->pdc,
1109 		(size_t) (npixels * sizeof (uint32)), fn);
1110 
1111 	    if (!TIFFReadRGBAImageOriented(MYTIFF,
1112 		    width, height, image->info.tiff.raster, orientation, 1))
1113             {
1114                 errcode = PDC_E_IO_READ;
1115                 goto PDF_TIFF_ERROR;
1116 	    }
1117 	}
1118         else
1119         {
1120 	    int linecounter = 0, sclsize = TIFFScanlineSize(MYTIFF);
1121 
1122             npixels = (size_t) (sclsize * height);
1123 	    image->info.tiff.raster = (uint32 *)pdc_malloc(p->pdc, npixels, fn);
1124 
1125 	    while (linecounter < (int) height)
1126                 {
1127                     size_t ndots = (size_t)((height - linecounter - 1) * width);
1128 
1129                     if (npixels <= sizeof(uint32) * ndots)
1130                     {
1131                         errcode = PDF_E_IMAGE_CORRUPT;
1132                         goto PDF_TIFF_ERROR;
1133                     }
1134 
1135                     if (TIFFReadScanline(MYTIFF,
1136                         (tdata_t) (image->info.tiff.raster + ndots),
1137                         (uint32) linecounter, (tsample_t) 0) == -1)
1138                     {
1139                         errcode = PDC_E_IO_READ;
1140                         goto PDF_TIFF_ERROR;
1141                     }
1142                     linecounter++;
1143                 }
1144             }
1145 
1146 	pdf_put_image(p, imageslot, pdc_true, pdc_true);
1147 
1148         if (image->info.tiff.raster != NULL){
1149 	    pdc_free(p->pdc, (void *) image->info.tiff.raster);
1150             image->info.tiff.raster = NULL;
1151         }
1152 
1153     }
1154 
1155 
1156     if (!image->corrupt)
1157     {
1158         TIFFClose(MYTIFF);
1159         return imageslot;
1160     }
1161 
1162     PDF_TIFF_ERROR:
1163     {
1164         const char *stemp = NULL;
1165 
1166         if (errcode)
1167             stemp = pdf_get_image_filename(p, image);
1168 
1169         if (image->info.tiff.raster != NULL)
1170             pdc_free(p->pdc, (void *) image->info.tiff.raster);
1171 
1172         if (isopen)
1173             TIFFClose(MYTIFF);
1174 
1175         switch (errcode)
1176         {
1177             case PDC_E_IO_READ:
1178             case PDF_E_IMAGE_ICC:
1179             case PDF_E_IMAGE_ICC2:
1180             case PDF_E_IMAGE_MASK1BIT13:
1181             case PDF_E_IMAGE_COLORIZE:
1182             case PDF_E_TIFF_MASK_MULTISTRIP:
1183             case PDF_E_IMAGE_COLORMAP:
1184             case PDF_E_IMAGE_BADMASK:
1185             case PDF_E_TIFF_CMYK_MASK:
1186             case PDF_E_TIFF_UNSUPP_SEPARATE:
1187             case PDF_E_TIFF_16BITCMYK_UNSUPP:
1188             case PDF_E_TIFF_16BIT_UNSUPP:
1189 		pdc_set_errmsg(p->pdc, errcode, stemp, 0, 0, 0);
1190 		break;
1191 
1192             case PDF_E_IMAGE_CORRUPT:
1193 		pdc_set_errmsg(p->pdc, errcode, "TIFF", stemp, 0, 0);
1194 		break;
1195 
1196             case PDF_E_TIFF_UNSUPP_COLORSPACE:
1197             case PDF_E_TIFF_UNSUPP_COMPRESSION:
1198             case PDF_E_IMAGE_BADCOMP:
1199 		pdc_set_errmsg(p->pdc, errcode,
1200 		    pdc_errprintf(p->pdc, "%d", errint), stemp, 0, 0);
1201 		break;
1202 
1203             case PDF_E_IMAGE_NOPAGE:
1204 		pdc_set_errmsg(p->pdc, errcode,
1205 		    pdc_errprintf(p->pdc, "%d", errint), "TIFF", stemp, 0);
1206 		break;
1207 
1208             case PDF_E_TIFF_UNSUPP_SEP_NONCMYK:
1209 		pdc_set_errmsg(p->pdc, errcode,
1210 		    stemp, pdc_errprintf(p->pdc, "%d", errint), 0, 0);
1211 		break;
1212 
1213 	    case 0: 		/* error code and message already set */
1214 		break;
1215         }
1216     }
1217 
1218     return -1;
1219 }
1220 
1221 #undef MYTIFF
1222 #endif	/* HAVE_LIBTIFF */
1223