6 /* needed to implement our substitute TIFFIsCODECConfigured */
7 #if TIFFLIB_VERSION < 20031121
8 static int TIFFIsCODECConfigured(uint16 scheme);
14 tiff.c - implements reading and writing tiff files, uses io layer.
18 io_glue *ig = io_new_fd( fd );
19 i_img *im = i_readtiff_wiol(ig, -1); // no limit on how much is read
21 io_glue *ig = io_new_fd( fd );
22 return_code = i_writetiff_wiol(im, ig);
26 tiff.c implements the basic functions to read and write tiff files.
27 It uses the iolayer and needs either a seekable source or an entire
30 =head1 FUNCTION REFERENCE
32 Some of these functions are internal.
39 #define byteswap_macro(x) \
40 ((((x) & 0xff000000) >> 24) | (((x) & 0x00ff0000) >> 8) | \
41 (((x) & 0x0000ff00) << 8) | (((x) & 0x000000ff) << 24))
43 #define CLAMP8(x) ((x) < 0 ? 0 : (x) > 255 ? 255 : (x))
44 #define CLAMP16(x) ((x) < 0 ? 0 : (x) > 65535 ? 65535 : (x))
46 #define Sample16To8(num) ((num) / 257)
53 static i_img *read_one_rgb_tiled(TIFF *tif, i_img_dim width, i_img_dim height, int allow_incomplete);
54 static i_img *read_one_rgb_lines(TIFF *tif, i_img_dim width, i_img_dim height, int allow_incomplete);
56 static struct tag_name text_tag_names[] =
58 { "tiff_documentname", TIFFTAG_DOCUMENTNAME, },
59 { "tiff_imagedescription", TIFFTAG_IMAGEDESCRIPTION, },
60 { "tiff_make", TIFFTAG_MAKE, },
61 { "tiff_model", TIFFTAG_MODEL, },
62 { "tiff_pagename", TIFFTAG_PAGENAME, },
63 { "tiff_software", TIFFTAG_SOFTWARE, },
64 { "tiff_datetime", TIFFTAG_DATETIME, },
65 { "tiff_artist", TIFFTAG_ARTIST, },
66 { "tiff_hostcomputer", TIFFTAG_HOSTCOMPUTER, },
69 static struct tag_name
72 { "none", COMPRESSION_NONE },
73 { "ccittrle", COMPRESSION_CCITTRLE },
74 { "fax3", COMPRESSION_CCITTFAX3 },
75 { "t4", COMPRESSION_CCITTFAX3 },
76 { "fax4", COMPRESSION_CCITTFAX4 },
77 { "t6", COMPRESSION_CCITTFAX4 },
78 { "lzw", COMPRESSION_LZW },
79 { "jpeg", COMPRESSION_JPEG },
80 { "packbits", COMPRESSION_PACKBITS },
81 { "deflate", COMPRESSION_ADOBE_DEFLATE },
82 { "zip", COMPRESSION_ADOBE_DEFLATE },
83 { "oldzip", COMPRESSION_DEFLATE },
84 { "ccittrlew", COMPRESSION_CCITTRLEW },
87 static const int compress_value_count =
88 sizeof(compress_values) / sizeof(*compress_values);
91 myTIFFIsCODECConfigured(uint16 scheme);
93 typedef struct read_state_tag read_state_t;
94 /* the setup function creates the image object, allocates the line buffer */
95 typedef int (*read_setup_t)(read_state_t *state);
97 /* the putter writes the image data provided by the getter to the
98 image, x, y, width, height describe the target area of the image,
99 extras is the extra number of pixels stored for each scanline in
100 the raster buffer, (for tiles against the right side of the
103 typedef int (*read_putter_t)(read_state_t *state, i_img_dim x, i_img_dim y,
104 i_img_dim width, i_img_dim height, int extras);
106 /* reads from a tiled or strip image and calls the putter.
107 This may need a second type for handling non-contiguous images
109 typedef int (*read_getter_t)(read_state_t *state, read_putter_t putter);
111 struct read_state_tag {
115 i_img_dim pixels_read;
116 int allow_incomplete;
118 uint32 width, height;
119 uint16 bits_per_sample;
122 /* the total number of channels (samples per pixel) */
123 int samples_per_pixel;
125 /* if non-zero, which channel is the alpha channel, typically 3 for rgb */
128 /* whether or not to scale the color channels based on the alpha
129 channel. TIFF has 2 types of alpha channel, if the alpha channel
130 we use is EXTRASAMPLE_ASSOCALPHA then the color data will need to
131 be scaled to match Imager's conventions */
135 static int tile_contig_getter(read_state_t *state, read_putter_t putter);
136 static int strip_contig_getter(read_state_t *state, read_putter_t putter);
138 static int setup_paletted(read_state_t *state);
139 static int paletted_putter8(read_state_t *, i_img_dim, i_img_dim, i_img_dim, i_img_dim, int);
140 static int paletted_putter4(read_state_t *, i_img_dim, i_img_dim, i_img_dim, i_img_dim, int);
142 static int setup_16_rgb(read_state_t *state);
143 static int setup_16_grey(read_state_t *state);
144 static int putter_16(read_state_t *, i_img_dim, i_img_dim, i_img_dim, i_img_dim, int);
146 static int setup_8_rgb(read_state_t *state);
147 static int setup_8_grey(read_state_t *state);
148 static int putter_8(read_state_t *, i_img_dim, i_img_dim, i_img_dim, i_img_dim, int);
150 static int setup_32_rgb(read_state_t *state);
151 static int setup_32_grey(read_state_t *state);
152 static int putter_32(read_state_t *, i_img_dim, i_img_dim, i_img_dim, i_img_dim, int);
154 static int setup_bilevel(read_state_t *state);
155 static int putter_bilevel(read_state_t *, i_img_dim, i_img_dim, i_img_dim, i_img_dim, int);
157 static int setup_cmyk8(read_state_t *state);
158 static int putter_cmyk8(read_state_t *, i_img_dim, i_img_dim, i_img_dim, i_img_dim, int);
160 static int setup_cmyk16(read_state_t *state);
161 static int putter_cmyk16(read_state_t *, i_img_dim, i_img_dim, i_img_dim, i_img_dim, int);
163 rgb_channels(read_state_t *state, int *out_channels);
165 grey_channels(read_state_t *state, int *out_channels);
167 cmyk_channels(read_state_t *state, int *out_channels);
169 fallback_rgb_channels(TIFF *tif, i_img_dim width, i_img_dim height, int *channels, int *alpha_chan);
171 static const int text_tag_count =
172 sizeof(text_tag_names) / sizeof(*text_tag_names);
174 static void error_handler(char const *module, char const *fmt, va_list ap) {
175 mm_log((1, "tiff error fmt %s\n", fmt));
176 i_push_errorvf(0, fmt, ap);
179 #define WARN_BUFFER_LIMIT 10000
180 static char *warn_buffer = NULL;
181 static int warn_buffer_size = 0;
183 static void warn_handler(char const *module, char const *fmt, va_list ap) {
187 #ifdef IMAGER_VSNPRINTF
188 vsnprintf(buf, sizeof(buf), fmt, ap);
190 vsprintf(buf, fmt, ap);
192 mm_log((1, "tiff warning %s\n", buf));
194 if (!warn_buffer || strlen(warn_buffer)+strlen(buf)+2 > warn_buffer_size) {
195 int new_size = warn_buffer_size + strlen(buf) + 2;
196 char *old_buffer = warn_buffer;
197 if (new_size > WARN_BUFFER_LIMIT) {
198 new_size = WARN_BUFFER_LIMIT;
200 warn_buffer = myrealloc(warn_buffer, new_size);
201 if (!old_buffer) *warn_buffer = '\0';
202 warn_buffer_size = new_size;
204 if (strlen(warn_buffer)+strlen(buf)+2 <= warn_buffer_size) {
205 strcat(warn_buffer, buf);
206 strcat(warn_buffer, "\n");
210 static int save_tiff_tags(TIFF *tif, i_img *im);
213 pack_4bit_to(unsigned char *dest, const unsigned char *src, i_img_dim count);
216 static toff_t sizeproc(thandle_t x) {
222 =item comp_seek(h, o, w)
224 Compatability for 64 bit systems like latest freebsd (internal)
226 h - tiff handle, cast an io_glue object
235 comp_seek(thandle_t h, toff_t o, int w) {
236 io_glue *ig = (io_glue*)h;
237 return (toff_t) i_io_seek(ig, o, w);
241 =item comp_mmap(thandle_t, tdata_t*, toff_t*)
245 This shouldn't ever be called but newer tifflibs want it anyway.
252 comp_mmap(thandle_t h, tdata_t*p, toff_t*off) {
257 =item comp_munmap(thandle_t h, tdata_t p, toff_t off)
261 This shouldn't ever be called but newer tifflibs want it anyway.
267 comp_munmap(thandle_t h, tdata_t p, toff_t off) {
272 comp_read(thandle_t h, tdata_t p, tsize_t size) {
273 return i_io_read((io_glue *)h, p, size);
277 comp_write(thandle_t h, tdata_t p, tsize_t size) {
278 return i_io_write((io_glue *)h, p, size);
282 comp_close(thandle_t h) {
283 return i_io_close((io_glue *)h);
286 static i_img *read_one_tiff(TIFF *tif, int allow_incomplete) {
288 uint32 width, height;
289 uint16 samples_per_pixel;
293 int gotXres, gotYres;
295 uint16 bits_per_sample;
296 uint16 planar_config;
301 read_setup_t setupf = NULL;
302 read_getter_t getterf = NULL;
303 read_putter_t putterf = NULL;
304 int channels = MAXCHANNELS;
305 size_t sample_size = ~0; /* force failure if some code doesn't set it */
306 i_img_dim total_pixels;
310 TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width);
311 TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height);
312 TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &samples_per_pixel);
313 tiled = TIFFIsTiled(tif);
314 TIFFGetFieldDefaulted(tif, TIFFTAG_PHOTOMETRIC, &photometric);
315 TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE, &bits_per_sample);
316 TIFFGetFieldDefaulted(tif, TIFFTAG_PLANARCONFIG, &planar_config);
317 TIFFGetFieldDefaulted(tif, TIFFTAG_INKSET, &inkset);
319 mm_log((1, "i_readtiff_wiol: width=%d, height=%d, channels=%d\n", width, height, samples_per_pixel));
320 mm_log((1, "i_readtiff_wiol: %stiled\n", tiled?"":"not "));
321 mm_log((1, "i_readtiff_wiol: %sbyte swapped\n", TIFFIsByteSwapped(tif)?"":"not "));
323 total_pixels = width * height;
324 memset(&state, 0, sizeof(state));
326 state.allow_incomplete = allow_incomplete;
328 state.height = height;
329 state.bits_per_sample = bits_per_sample;
330 state.samples_per_pixel = samples_per_pixel;
331 state.photometric = photometric;
333 /* yes, this if() is horrible */
334 if (photometric == PHOTOMETRIC_PALETTE && bits_per_sample <= 8) {
335 setupf = setup_paletted;
336 if (bits_per_sample == 8)
337 putterf = paletted_putter8;
338 else if (bits_per_sample == 4)
339 putterf = paletted_putter4;
341 mm_log((1, "unsupported paletted bits_per_sample %d\n", bits_per_sample));
343 sample_size = sizeof(i_sample_t);
346 else if (bits_per_sample == 16
347 && photometric == PHOTOMETRIC_RGB
348 && samples_per_pixel >= 3) {
349 setupf = setup_16_rgb;
352 rgb_channels(&state, &channels);
354 else if (bits_per_sample == 16
355 && photometric == PHOTOMETRIC_MINISBLACK) {
356 setupf = setup_16_grey;
359 grey_channels(&state, &channels);
361 else if (bits_per_sample == 8
362 && photometric == PHOTOMETRIC_MINISBLACK) {
363 setupf = setup_8_grey;
366 grey_channels(&state, &channels);
368 else if (bits_per_sample == 8
369 && photometric == PHOTOMETRIC_RGB) {
370 setupf = setup_8_rgb;
373 rgb_channels(&state, &channels);
375 else if (bits_per_sample == 32
376 && photometric == PHOTOMETRIC_RGB
377 && samples_per_pixel >= 3) {
378 setupf = setup_32_rgb;
380 sample_size = sizeof(i_fsample_t);
381 rgb_channels(&state, &channels);
383 else if (bits_per_sample == 32
384 && photometric == PHOTOMETRIC_MINISBLACK) {
385 setupf = setup_32_grey;
387 sample_size = sizeof(i_fsample_t);
388 grey_channels(&state, &channels);
390 else if (bits_per_sample == 1
391 && (photometric == PHOTOMETRIC_MINISBLACK
392 || photometric == PHOTOMETRIC_MINISWHITE)
393 && samples_per_pixel == 1) {
394 setupf = setup_bilevel;
395 putterf = putter_bilevel;
396 sample_size = sizeof(i_palidx);
399 else if (bits_per_sample == 8
400 && photometric == PHOTOMETRIC_SEPARATED
401 && inkset == INKSET_CMYK
402 && samples_per_pixel >= 4) {
403 setupf = setup_cmyk8;
404 putterf = putter_cmyk8;
406 cmyk_channels(&state, &channels);
408 else if (bits_per_sample == 16
409 && photometric == PHOTOMETRIC_SEPARATED
410 && inkset == INKSET_CMYK
411 && samples_per_pixel >= 4) {
412 setupf = setup_cmyk16;
413 putterf = putter_cmyk16;
415 cmyk_channels(&state, &channels);
419 fallback_rgb_channels(tif, width, height, &channels, &alpha);
423 if (!i_int_check_image_file_limits(width, height, channels, sample_size)) {
428 if (planar_config == PLANARCONFIG_CONTIG)
429 getterf = tile_contig_getter;
432 if (planar_config == PLANARCONFIG_CONTIG)
433 getterf = strip_contig_getter;
435 if (setupf && getterf && putterf) {
439 if (!getterf(&state, putterf) || !state.pixels_read) {
441 i_img_destroy(state.img);
443 _TIFFfree(state.raster);
445 myfree(state.line_buf);
450 if (allow_incomplete && state.pixels_read < total_pixels) {
451 i_tags_setn(&(state.img->tags), "i_incomplete", 1);
452 i_tags_setn(&(state.img->tags), "i_lines_read",
453 state.pixels_read / width);
458 _TIFFfree(state.raster);
460 myfree(state.line_buf);
464 im = read_one_rgb_tiled(tif, width, height, allow_incomplete);
467 im = read_one_rgb_lines(tif, width, height, allow_incomplete);
474 /* general metadata */
475 i_tags_setn(&im->tags, "tiff_bitspersample", bits_per_sample);
476 i_tags_setn(&im->tags, "tiff_photometric", photometric);
477 TIFFGetFieldDefaulted(tif, TIFFTAG_COMPRESSION, &compress);
479 /* resolution tags */
480 TIFFGetFieldDefaulted(tif, TIFFTAG_RESOLUTIONUNIT, &resunit);
481 gotXres = TIFFGetField(tif, TIFFTAG_XRESOLUTION, &xres);
482 gotYres = TIFFGetField(tif, TIFFTAG_YRESOLUTION, &yres);
483 if (gotXres || gotYres) {
488 i_tags_setn(&im->tags, "tiff_resolutionunit", resunit);
489 if (resunit == RESUNIT_CENTIMETER) {
490 /* from dots per cm to dpi */
493 i_tags_set(&im->tags, "tiff_resolutionunit_name", "centimeter", -1);
495 else if (resunit == RESUNIT_NONE) {
496 i_tags_setn(&im->tags, "i_aspect_only", 1);
497 i_tags_set(&im->tags, "tiff_resolutionunit_name", "none", -1);
499 else if (resunit == RESUNIT_INCH) {
500 i_tags_set(&im->tags, "tiff_resolutionunit_name", "inch", -1);
503 i_tags_set(&im->tags, "tiff_resolutionunit_name", "unknown", -1);
505 /* tifflib doesn't seem to provide a way to get to the original rational
506 value of these, which would let me provide a more reasonable
507 precision. So make up a number. */
508 i_tags_set_float2(&im->tags, "i_xres", 0, xres, 6);
509 i_tags_set_float2(&im->tags, "i_yres", 0, yres, 6);
513 for (i = 0; i < text_tag_count; ++i) {
515 if (TIFFGetField(tif, text_tag_names[i].tag, &data)) {
516 mm_log((1, "i_readtiff_wiol: tag %d has value %s\n",
517 text_tag_names[i].tag, data));
518 i_tags_set(&im->tags, text_tag_names[i].name, data, -1);
522 i_tags_set(&im->tags, "i_format", "tiff", 4);
523 if (warn_buffer && *warn_buffer) {
524 i_tags_set(&im->tags, "i_warning", warn_buffer, -1);
528 for (i = 0; i < compress_value_count; ++i) {
529 if (compress_values[i].tag == compress) {
530 i_tags_set(&im->tags, "tiff_compression", compress_values[i].name, -1);
539 =item i_readtiff_wiol(im, ig)
544 i_readtiff_wiol(io_glue *ig, int allow_incomplete, int page) {
546 TIFFErrorHandler old_handler;
547 TIFFErrorHandler old_warn_handler;
552 old_handler = TIFFSetErrorHandler(error_handler);
553 old_warn_handler = TIFFSetWarningHandler(warn_handler);
557 /* Add code to get the filename info from the iolayer */
558 /* Also add code to check for mmapped code */
560 mm_log((1, "i_readtiff_wiol(ig %p, allow_incomplete %d, page %d)\n", ig, allow_incomplete, page));
562 tif = TIFFClientOpen("(Iolayer)",
574 mm_log((1, "i_readtiff_wiol: Unable to open tif file\n"));
575 i_push_error(0, "Error opening file");
576 TIFFSetErrorHandler(old_handler);
577 TIFFSetWarningHandler(old_warn_handler);
581 for (current_page = 0; current_page < page; ++current_page) {
582 if (!TIFFReadDirectory(tif)) {
583 mm_log((1, "i_readtiff_wiol: Unable to switch to directory %d\n", page));
584 i_push_errorf(0, "could not switch to page %d", page);
585 TIFFSetErrorHandler(old_handler);
586 TIFFSetWarningHandler(old_warn_handler);
592 im = read_one_tiff(tif, allow_incomplete);
594 if (TIFFLastDirectory(tif)) mm_log((1, "Last directory of tiff file\n"));
595 TIFFSetErrorHandler(old_handler);
596 TIFFSetWarningHandler(old_warn_handler);
602 =item i_readtiff_multi_wiol(ig, *count)
604 Reads multiple images from a TIFF.
609 i_readtiff_multi_wiol(io_glue *ig, int *count) {
611 TIFFErrorHandler old_handler;
612 TIFFErrorHandler old_warn_handler;
613 i_img **results = NULL;
614 int result_alloc = 0;
617 old_handler = TIFFSetErrorHandler(error_handler);
618 old_warn_handler = TIFFSetWarningHandler(warn_handler);
622 /* Add code to get the filename info from the iolayer */
623 /* Also add code to check for mmapped code */
625 mm_log((1, "i_readtiff_wiol(ig %p, length %d)\n", ig));
627 tif = TIFFClientOpen("(Iolayer)",
639 mm_log((1, "i_readtiff_wiol: Unable to open tif file\n"));
640 i_push_error(0, "Error opening file");
641 TIFFSetErrorHandler(old_handler);
642 TIFFSetWarningHandler(old_warn_handler);
648 i_img *im = read_one_tiff(tif, 0);
651 if (++*count > result_alloc) {
652 if (result_alloc == 0) {
654 results = mymalloc(result_alloc * sizeof(i_img *));
659 newresults = myrealloc(results, result_alloc * sizeof(i_img *));
661 i_img_destroy(im); /* don't leak it */
664 results = newresults;
667 results[*count-1] = im;
668 } while (TIFFReadDirectory(tif));
670 TIFFSetWarningHandler(old_warn_handler);
671 TIFFSetErrorHandler(old_handler);
677 i_writetiff_low_faxable(TIFF *tif, i_img *im, int fine) {
678 uint32 width, height;
679 unsigned char *linebuf = NULL;
684 float vres = fine ? 196 : 98;
690 if (width != im->xsize || height != im->ysize) {
691 i_push_error(0, "image too large for TIFF");
695 switch (im->channels) {
705 /* This means a colorspace we don't handle yet */
706 mm_log((1, "i_writetiff_wiol_faxable: don't handle %d channel images.\n", im->channels));
710 /* Add code to get the filename info from the iolayer */
711 /* Also add code to check for mmapped code */
714 mm_log((1, "i_writetiff_wiol_faxable: width=%d, height=%d, channels=%d\n", width, height, im->channels));
716 if (!TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width) )
717 { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField width=%d failed\n", width)); return 0; }
718 if (!TIFFSetField(tif, TIFFTAG_IMAGELENGTH, height) )
719 { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField length=%d failed\n", height)); return 0; }
720 if (!TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1))
721 { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField samplesperpixel=1 failed\n")); return 0; }
722 if (!TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT))
723 { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField Orientation=topleft\n")); return 0; }
724 if (!TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 1) )
725 { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField bitpersample=1\n")); return 0; }
726 if (!TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG))
727 { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField planarconfig\n")); return 0; }
728 if (!TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISWHITE))
729 { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField photometric=%d\n", PHOTOMETRIC_MINISBLACK)); return 0; }
730 if (!TIFFSetField(tif, TIFFTAG_COMPRESSION, 3))
731 { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField compression=3\n")); return 0; }
733 linebuf = (unsigned char *)_TIFFmalloc( TIFFScanlineSize(tif) );
735 if (!TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, TIFFDefaultStripSize(tif, -1))) {
736 mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField rowsperstrip=-1\n")); return 0; }
738 TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
739 TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rc);
741 mm_log((1, "i_writetiff_wiol_faxable: TIFFGetField rowsperstrip=%d\n", rowsperstrip));
742 mm_log((1, "i_writetiff_wiol_faxable: TIFFGetField scanlinesize=%d\n", TIFFScanlineSize(tif) ));
743 mm_log((1, "i_writetiff_wiol_faxable: TIFFGetField planarconfig=%d == %d\n", rc, PLANARCONFIG_CONTIG));
745 if (!TIFFSetField(tif, TIFFTAG_XRESOLUTION, (float)204))
746 { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField Xresolution=204\n")); return 0; }
747 if (!TIFFSetField(tif, TIFFTAG_YRESOLUTION, vres))
748 { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField Yresolution=196\n")); return 0; }
749 if (!TIFFSetField(tif, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH)) {
750 mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField ResolutionUnit=%d\n", RESUNIT_INCH)); return 0;
753 if (!save_tiff_tags(tif, im)) {
757 for (y=0; y<height; y++) {
759 for(x=0; x<width; x+=8) {
764 linebuf[linebufpos]=0;
765 bits = width-x; if(bits>8) bits=8;
766 i_gsamp(im, x, x+8, y, luma, &luma_chan, 1);
767 for(bitpos=0;bitpos<bits;bitpos++) {
768 linebuf[linebufpos] |= ((luma[bitpos] < 128) ? bitval : 0);
773 if (TIFFWriteScanline(tif, linebuf, y, 0) < 0) {
774 mm_log((1, "i_writetiff_wiol_faxable: TIFFWriteScanline failed.\n"));
778 if (linebuf) _TIFFfree(linebuf);
784 find_compression(char const *name, uint16 *compress) {
787 for (i = 0; i < compress_value_count; ++i) {
788 if (strcmp(compress_values[i].name, name) == 0) {
789 *compress = (uint16)compress_values[i].tag;
793 *compress = COMPRESSION_NONE;
799 get_compression(i_img *im, uint16 def_compress) {
803 if (i_tags_find(&im->tags, "tiff_compression", 0, &entry)
804 && im->tags.tags[entry].data) {
806 if (find_compression(im->tags.tags[entry].data, &compress)
807 && myTIFFIsCODECConfigured(compress))
810 if (i_tags_get_int(&im->tags, "tiff_compression", 0, &value)) {
811 if ((uint16)value == value
812 && myTIFFIsCODECConfigured((uint16)value))
813 return (uint16)value;
820 i_tiff_has_compression(const char *name) {
823 if (!find_compression(name, &compress))
826 return myTIFFIsCODECConfigured(compress);
830 set_base_tags(TIFF *tif, i_img *im, uint16 compress, uint16 photometric,
831 uint16 bits_per_sample, uint16 samples_per_pixel) {
834 int got_xres, got_yres;
837 if (!TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, im->xsize)) {
838 i_push_error(0, "write TIFF: setting width tag");
841 if (!TIFFSetField(tif, TIFFTAG_IMAGELENGTH, im->ysize)) {
842 i_push_error(0, "write TIFF: setting length tag");
845 if (!TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT)) {
846 i_push_error(0, "write TIFF: setting orientation tag");
849 if (!TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG)) {
850 i_push_error(0, "write TIFF: setting planar configuration tag");
853 if (!TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, photometric)) {
854 i_push_error(0, "write TIFF: setting photometric tag");
857 if (!TIFFSetField(tif, TIFFTAG_COMPRESSION, compress)) {
858 i_push_error(0, "write TIFF: setting compression tag");
861 if (!TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bits_per_sample)) {
862 i_push_error(0, "write TIFF: setting bits per sample tag");
865 if (!TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, samples_per_pixel)) {
866 i_push_error(0, "write TIFF: setting samples per pixel tag");
870 got_xres = i_tags_get_float(&im->tags, "i_xres", 0, &xres);
871 got_yres = i_tags_get_float(&im->tags, "i_yres", 0, &yres);
872 if (!i_tags_get_int(&im->tags, "i_aspect_only", 0,&aspect_only))
874 if (!i_tags_get_int(&im->tags, "tiff_resolutionunit", 0, &resunit))
875 resunit = RESUNIT_INCH;
876 if (got_xres || got_yres) {
882 resunit = RESUNIT_NONE;
885 if (resunit == RESUNIT_CENTIMETER) {
890 resunit = RESUNIT_INCH;
893 if (!TIFFSetField(tif, TIFFTAG_XRESOLUTION, (float)xres)) {
894 i_push_error(0, "write TIFF: setting xresolution tag");
897 if (!TIFFSetField(tif, TIFFTAG_YRESOLUTION, (float)yres)) {
898 i_push_error(0, "write TIFF: setting yresolution tag");
901 if (!TIFFSetField(tif, TIFFTAG_RESOLUTIONUNIT, (uint16)resunit)) {
902 i_push_error(0, "write TIFF: setting resolutionunit tag");
911 write_one_bilevel(TIFF *tif, i_img *im, int zero_is_white) {
912 uint16 compress = get_compression(im, COMPRESSION_PACKBITS);
914 unsigned char *in_row;
915 unsigned char *out_row;
920 mm_log((1, "tiff - write_one_bilevel(tif %p, im %p, zero_is_white %d)\n",
921 tif, im, zero_is_white));
923 /* ignore a silly choice */
924 if (compress == COMPRESSION_JPEG)
925 compress = COMPRESSION_PACKBITS;
928 case COMPRESSION_CCITTRLE:
929 case COMPRESSION_CCITTFAX3:
930 case COMPRESSION_CCITTFAX4:
931 /* natural fax photometric */
932 photometric = PHOTOMETRIC_MINISWHITE;
936 /* natural for most computer images */
937 photometric = PHOTOMETRIC_MINISBLACK;
941 if (!set_base_tags(tif, im, compress, photometric, 1, 1))
944 if (!TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, TIFFDefaultStripSize(tif, -1))) {
945 i_push_error(0, "write TIFF: setting rows per strip tag");
949 out_size = TIFFScanlineSize(tif);
950 out_row = (unsigned char *)_TIFFmalloc( out_size );
951 in_row = mymalloc(im->xsize);
953 invert = (photometric == PHOTOMETRIC_MINISWHITE) != (zero_is_white != 0);
955 for (y = 0; y < im->ysize; ++y) {
957 unsigned char *outp = out_row;
958 memset(out_row, 0, out_size);
959 i_gpal(im, 0, im->xsize, y, in_row);
960 for (x = 0; x < im->xsize; ++x) {
961 if (invert ? !in_row[x] : in_row[x]) {
970 if (TIFFWriteScanline(tif, out_row, y, 0) < 0) {
973 i_push_error(0, "write TIFF: write scan line failed");
985 set_palette(TIFF *tif, i_img *im, int size) {
992 colors = (uint16 *)_TIFFmalloc(sizeof(uint16) * 3 * size);
994 out[1] = colors + size;
995 out[2] = colors + 2 * size;
997 count = i_colorcount(im);
998 for (i = 0; i < count; ++i) {
999 i_getcolors(im, i, &c, 1);
1000 for (ch = 0; ch < 3; ++ch)
1001 out[ch][i] = c.channel[ch] * 257;
1003 for (; i < size; ++i) {
1004 for (ch = 0; ch < 3; ++ch)
1007 if (!TIFFSetField(tif, TIFFTAG_COLORMAP, out[0], out[1], out[2])) {
1009 i_push_error(0, "write TIFF: setting color map");
1018 write_one_paletted8(TIFF *tif, i_img *im) {
1019 uint16 compress = get_compression(im, COMPRESSION_PACKBITS);
1020 unsigned char *out_row;
1024 mm_log((1, "tiff - write_one_paletted8(tif %p, im %p)\n", tif, im));
1026 /* ignore a silly choice */
1027 if (compress == COMPRESSION_JPEG ||
1028 compress == COMPRESSION_CCITTRLE ||
1029 compress == COMPRESSION_CCITTFAX3 ||
1030 compress == COMPRESSION_CCITTFAX4)
1031 compress = COMPRESSION_PACKBITS;
1033 if (!TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, TIFFDefaultStripSize(tif, -1))) {
1034 i_push_error(0, "write TIFF: setting rows per strip tag");
1038 if (!set_base_tags(tif, im, compress, PHOTOMETRIC_PALETTE, 8, 1))
1041 if (!set_palette(tif, im, 256))
1044 out_size = TIFFScanlineSize(tif);
1045 out_row = (unsigned char *)_TIFFmalloc( out_size );
1047 for (y = 0; y < im->ysize; ++y) {
1048 i_gpal(im, 0, im->xsize, y, out_row);
1049 if (TIFFWriteScanline(tif, out_row, y, 0) < 0) {
1051 i_push_error(0, "write TIFF: write scan line failed");
1062 write_one_paletted4(TIFF *tif, i_img *im) {
1063 uint16 compress = get_compression(im, COMPRESSION_PACKBITS);
1064 unsigned char *in_row;
1065 unsigned char *out_row;
1069 mm_log((1, "tiff - write_one_paletted4(tif %p, im %p)\n", tif, im));
1071 /* ignore a silly choice */
1072 if (compress == COMPRESSION_JPEG ||
1073 compress == COMPRESSION_CCITTRLE ||
1074 compress == COMPRESSION_CCITTFAX3 ||
1075 compress == COMPRESSION_CCITTFAX4)
1076 compress = COMPRESSION_PACKBITS;
1078 if (!set_base_tags(tif, im, compress, PHOTOMETRIC_PALETTE, 4, 1))
1081 if (!set_palette(tif, im, 16))
1084 if (!TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, TIFFDefaultStripSize(tif, -1))) {
1085 i_push_error(0, "write TIFF: setting rows per strip tag");
1089 in_row = mymalloc(im->xsize);
1090 out_size = TIFFScanlineSize(tif);
1091 out_row = (unsigned char *)_TIFFmalloc( out_size );
1093 for (y = 0; y < im->ysize; ++y) {
1094 i_gpal(im, 0, im->xsize, y, in_row);
1095 memset(out_row, 0, out_size);
1096 pack_4bit_to(out_row, in_row, im->xsize);
1097 if (TIFFWriteScanline(tif, out_row, y, 0) < 0) {
1099 i_push_error(0, "write TIFF: write scan line failed");
1111 set_direct_tags(TIFF *tif, i_img *im, uint16 compress,
1112 uint16 bits_per_sample) {
1113 uint16 extras = EXTRASAMPLE_ASSOCALPHA;
1114 uint16 extra_count = im->channels == 2 || im->channels == 4;
1115 uint16 photometric = im->channels >= 3 ?
1116 PHOTOMETRIC_RGB : PHOTOMETRIC_MINISBLACK;
1118 if (!set_base_tags(tif, im, compress, photometric, bits_per_sample,
1124 if (!TIFFSetField(tif, TIFFTAG_EXTRASAMPLES, extra_count, &extras)) {
1125 i_push_error(0, "write TIFF: setting extra samples tag");
1130 if (compress == COMPRESSION_JPEG) {
1132 if (i_tags_get_int(&im->tags, "tiff_jpegquality", 0, &jpeg_quality)
1133 && jpeg_quality >= 0 && jpeg_quality <= 100) {
1134 if (!TIFFSetField(tif, TIFFTAG_JPEGQUALITY, jpeg_quality)) {
1135 i_push_error(0, "write TIFF: setting jpeg quality pseudo-tag");
1145 write_one_32(TIFF *tif, i_img *im) {
1146 uint16 compress = get_compression(im, COMPRESSION_PACKBITS);
1151 size_t sample_count = im->xsize * im->channels;
1152 size_t sample_index;
1154 mm_log((1, "tiff - write_one_32(tif %p, im %p)\n", tif, im));
1156 /* only 8 and 12 bit samples are supported by jpeg compression */
1157 if (compress == COMPRESSION_JPEG)
1158 compress = COMPRESSION_PACKBITS;
1160 if (!set_direct_tags(tif, im, compress, 32))
1163 in_row = mymalloc(sample_count * sizeof(unsigned));
1164 out_size = TIFFScanlineSize(tif);
1165 out_row = (uint32 *)_TIFFmalloc( out_size );
1167 for (y = 0; y < im->ysize; ++y) {
1168 if (i_gsamp_bits(im, 0, im->xsize, y, in_row, NULL, im->channels, 32) <= 0) {
1169 i_push_error(0, "Cannot read 32-bit samples");
1172 for (sample_index = 0; sample_index < sample_count; ++sample_index)
1173 out_row[sample_index] = in_row[sample_index];
1174 if (TIFFWriteScanline(tif, out_row, y, 0) < 0) {
1177 i_push_error(0, "write TIFF: write scan line failed");
1189 write_one_16(TIFF *tif, i_img *im) {
1190 uint16 compress = get_compression(im, COMPRESSION_PACKBITS);
1195 size_t sample_count = im->xsize * im->channels;
1196 size_t sample_index;
1198 mm_log((1, "tiff - write_one_16(tif %p, im %p)\n", tif, im));
1200 /* only 8 and 12 bit samples are supported by jpeg compression */
1201 if (compress == COMPRESSION_JPEG)
1202 compress = COMPRESSION_PACKBITS;
1204 if (!set_direct_tags(tif, im, compress, 16))
1207 in_row = mymalloc(sample_count * sizeof(unsigned));
1208 out_size = TIFFScanlineSize(tif);
1209 out_row = (uint16 *)_TIFFmalloc( out_size );
1211 for (y = 0; y < im->ysize; ++y) {
1212 if (i_gsamp_bits(im, 0, im->xsize, y, in_row, NULL, im->channels, 16) <= 0) {
1213 i_push_error(0, "Cannot read 16-bit samples");
1216 for (sample_index = 0; sample_index < sample_count; ++sample_index)
1217 out_row[sample_index] = in_row[sample_index];
1218 if (TIFFWriteScanline(tif, out_row, y, 0) < 0) {
1221 i_push_error(0, "write TIFF: write scan line failed");
1233 write_one_8(TIFF *tif, i_img *im) {
1234 uint16 compress = get_compression(im, COMPRESSION_PACKBITS);
1236 unsigned char *out_row;
1238 size_t sample_count = im->xsize * im->channels;
1240 mm_log((1, "tiff - write_one_8(tif %p, im %p)\n", tif, im));
1242 if (!set_direct_tags(tif, im, compress, 8))
1245 out_size = TIFFScanlineSize(tif);
1246 if (out_size < sample_count)
1247 out_size = sample_count;
1248 out_row = (unsigned char *)_TIFFmalloc( out_size );
1250 for (y = 0; y < im->ysize; ++y) {
1251 if (i_gsamp(im, 0, im->xsize, y, out_row, NULL, im->channels) <= 0) {
1252 i_push_error(0, "Cannot read 8-bit samples");
1255 if (TIFFWriteScanline(tif, out_row, y, 0) < 0) {
1257 i_push_error(0, "write TIFF: write scan line failed");
1267 i_writetiff_low(TIFF *tif, i_img *im) {
1268 uint32 width, height;
1274 channels = im->channels;
1276 if (width != im->xsize || height != im->ysize) {
1277 i_push_error(0, "image too large for TIFF");
1281 mm_log((1, "i_writetiff_low: width=%d, height=%d, channels=%d, bits=%d\n", width, height, channels, im->bits));
1282 if (im->type == i_palette_type) {
1283 mm_log((1, "i_writetiff_low: paletted, colors=%d\n", i_colorcount(im)));
1286 if (i_img_is_monochrome(im, &zero_is_white)) {
1287 if (!write_one_bilevel(tif, im, zero_is_white))
1290 else if (im->type == i_palette_type) {
1291 if (i_colorcount(im) <= 16) {
1292 if (!write_one_paletted4(tif, im))
1296 if (!write_one_paletted8(tif, im))
1300 else if (im->bits > 16) {
1301 if (!write_one_32(tif, im))
1304 else if (im->bits > 8) {
1305 if (!write_one_16(tif, im))
1309 if (!write_one_8(tif, im))
1313 if (!save_tiff_tags(tif, im))
1320 =item i_writetiff_multi_wiol(ig, imgs, count, fine_mode)
1322 Stores an image in the iolayer object.
1324 ig - io_object that defines source to write to
1325 imgs,count - the images to write
1331 i_writetiff_multi_wiol(io_glue *ig, i_img **imgs, int count) {
1333 TIFFErrorHandler old_handler;
1336 old_handler = TIFFSetErrorHandler(error_handler);
1339 mm_log((1, "i_writetiff_multi_wiol(ig %p, imgs %p, count %d)\n",
1342 /* FIXME: Enable the mmap interface */
1344 tif = TIFFClientOpen("No name",
1358 mm_log((1, "i_writetiff_multi_wiol: Unable to open tif file for writing\n"));
1359 i_push_error(0, "Could not create TIFF object");
1360 TIFFSetErrorHandler(old_handler);
1364 for (i = 0; i < count; ++i) {
1365 if (!i_writetiff_low(tif, imgs[i])) {
1367 TIFFSetErrorHandler(old_handler);
1371 if (!TIFFWriteDirectory(tif)) {
1372 i_push_error(0, "Cannot write TIFF directory");
1374 TIFFSetErrorHandler(old_handler);
1379 TIFFSetErrorHandler(old_handler);
1380 (void) TIFFClose(tif);
1389 =item i_writetiff_multi_wiol_faxable(ig, imgs, count, fine_mode)
1391 Stores an image in the iolayer object.
1393 ig - io_object that defines source to write to
1394 imgs,count - the images to write
1395 fine_mode - select fine or normal mode fax images
1402 i_writetiff_multi_wiol_faxable(io_glue *ig, i_img **imgs, int count, int fine) {
1405 TIFFErrorHandler old_handler;
1407 old_handler = TIFFSetErrorHandler(error_handler);
1410 mm_log((1, "i_writetiff_multi_wiol(ig %p, imgs %p, count %d)\n",
1413 /* FIXME: Enable the mmap interface */
1415 tif = TIFFClientOpen("No name",
1429 mm_log((1, "i_writetiff_mulit_wiol: Unable to open tif file for writing\n"));
1430 i_push_error(0, "Could not create TIFF object");
1431 TIFFSetErrorHandler(old_handler);
1435 for (i = 0; i < count; ++i) {
1436 if (!i_writetiff_low_faxable(tif, imgs[i], fine)) {
1438 TIFFSetErrorHandler(old_handler);
1442 if (!TIFFWriteDirectory(tif)) {
1443 i_push_error(0, "Cannot write TIFF directory");
1445 TIFFSetErrorHandler(old_handler);
1450 (void) TIFFClose(tif);
1451 TIFFSetErrorHandler(old_handler);
1460 =item i_writetiff_wiol(im, ig)
1462 Stores an image in the iolayer object.
1464 im - image object to write out
1465 ig - io_object that defines source to write to
1470 i_writetiff_wiol(i_img *img, io_glue *ig) {
1472 TIFFErrorHandler old_handler;
1474 old_handler = TIFFSetErrorHandler(error_handler);
1477 mm_log((1, "i_writetiff_wiol(img %p, ig %p)\n", img, ig));
1479 /* FIXME: Enable the mmap interface */
1481 tif = TIFFClientOpen("No name",
1495 mm_log((1, "i_writetiff_wiol: Unable to open tif file for writing\n"));
1496 i_push_error(0, "Could not create TIFF object");
1497 TIFFSetErrorHandler(old_handler);
1501 if (!i_writetiff_low(tif, img)) {
1503 TIFFSetErrorHandler(old_handler);
1507 (void) TIFFClose(tif);
1508 TIFFSetErrorHandler(old_handler);
1519 =item i_writetiff_wiol_faxable(i_img *, io_glue *)
1521 Stores an image in the iolayer object in faxable tiff format.
1523 im - image object to write out
1524 ig - io_object that defines source to write to
1526 Note, this may be rewritten to use to simply be a call to a
1527 lower-level function that gives more options for writing tiff at some
1534 i_writetiff_wiol_faxable(i_img *im, io_glue *ig, int fine) {
1536 TIFFErrorHandler old_handler;
1538 old_handler = TIFFSetErrorHandler(error_handler);
1541 mm_log((1, "i_writetiff_wiol(img %p, ig %p)\n", im, ig));
1543 /* FIXME: Enable the mmap interface */
1545 tif = TIFFClientOpen("No name",
1559 mm_log((1, "i_writetiff_wiol: Unable to open tif file for writing\n"));
1560 i_push_error(0, "Could not create TIFF object");
1561 TIFFSetErrorHandler(old_handler);
1565 if (!i_writetiff_low_faxable(tif, im, fine)) {
1567 TIFFSetErrorHandler(old_handler);
1571 (void) TIFFClose(tif);
1572 TIFFSetErrorHandler(old_handler);
1580 static int save_tiff_tags(TIFF *tif, i_img *im) {
1583 for (i = 0; i < text_tag_count; ++i) {
1585 if (i_tags_find(&im->tags, text_tag_names[i].name, 0, &entry)) {
1586 if (!TIFFSetField(tif, text_tag_names[i].tag,
1587 im->tags.tags[entry].data)) {
1588 i_push_errorf(0, "cannot save %s to TIFF", text_tag_names[i].name);
1599 unpack_4bit_to(unsigned char *dest, const unsigned char *src,
1600 size_t src_byte_count) {
1601 while (src_byte_count > 0) {
1602 *dest++ = *src >> 4;
1603 *dest++ = *src++ & 0xf;
1608 static void pack_4bit_to(unsigned char *dest, const unsigned char *src,
1609 i_img_dim pixel_count) {
1611 while (i < pixel_count) {
1613 *dest = *src++ << 4;
1623 =item fallback_rgb_channels
1625 Calculate the number of output channels when we fallback to the RGBA
1626 family of functions.
1632 fallback_rgb_channels(TIFF *tif, i_img_dim width, i_img_dim height, int *channels, int *alpha_chan) {
1638 TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &in_channels);
1639 TIFFGetFieldDefaulted(tif, TIFFTAG_PHOTOMETRIC, &photometric);
1641 switch (photometric) {
1642 case PHOTOMETRIC_SEPARATED:
1646 case PHOTOMETRIC_MINISWHITE:
1647 case PHOTOMETRIC_MINISBLACK:
1648 /* the TIFF RGBA functions expand single channel grey into RGB,
1649 so reduce it, we move the alpha channel into the right place
1658 /* TIFF images can have more than one alpha channel, but Imager can't
1659 this ignores the possibility of 2 channel images with 2 alpha,
1660 but there's not much I can do about that */
1662 if (TIFFGetField(tif, TIFFTAG_EXTRASAMPLES, &extra_count, &extras)
1664 *alpha_chan = (*channels)++;
1669 make_rgb(TIFF *tif, i_img_dim width, i_img_dim height, int *alpha_chan) {
1672 fallback_rgb_channels(tif, width, height, &channels, alpha_chan);
1674 return i_img_8_new(width, height, channels);
1678 read_one_rgb_lines(TIFF *tif, i_img_dim width, i_img_dim height, int allow_incomplete) {
1680 uint32* raster = NULL;
1681 uint32 rowsperstrip, row;
1686 im = make_rgb(tif, width, height, &alpha_chan);
1690 rc = TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
1691 mm_log((1, "i_readtiff_wiol: rowsperstrip=%d rc = %d\n", rowsperstrip, rc));
1693 if (rc != 1 || rowsperstrip==-1) {
1694 rowsperstrip = height;
1697 raster = (uint32*)_TIFFmalloc(width * rowsperstrip * sizeof (uint32));
1700 i_push_error(0, "No space for raster buffer");
1704 line_buf = mymalloc(sizeof(i_color) * width);
1706 for( row = 0; row < height; row += rowsperstrip ) {
1707 uint32 newrows, i_row;
1709 if (!TIFFReadRGBAStrip(tif, row, raster)) {
1710 if (allow_incomplete) {
1711 i_tags_setn(&im->tags, "i_lines_read", row);
1712 i_tags_setn(&im->tags, "i_incomplete", 1);
1716 i_push_error(0, "could not read TIFF image strip");
1723 newrows = (row+rowsperstrip > height) ? height-row : rowsperstrip;
1724 mm_log((1, "newrows=%d\n", newrows));
1726 for( i_row = 0; i_row < newrows; i_row++ ) {
1728 i_color *outp = line_buf;
1730 for(x = 0; x<width; x++) {
1731 uint32 temp = raster[x+width*(newrows-i_row-1)];
1732 outp->rgba.r = TIFFGetR(temp);
1733 outp->rgba.g = TIFFGetG(temp);
1734 outp->rgba.b = TIFFGetB(temp);
1737 /* the libtiff RGBA code expands greyscale into RGBA, so put the
1738 alpha in the right place and scale it */
1740 outp->channel[alpha_chan] = TIFFGetA(temp);
1741 if (outp->channel[alpha_chan]) {
1742 for (ch = 0; ch < alpha_chan; ++ch) {
1743 outp->channel[ch] = outp->channel[ch] * 255 / outp->channel[alpha_chan];
1750 i_plin(im, 0, width, i_row+row, line_buf);
1760 /* adapted from libtiff
1762 libtiff's TIFFReadRGBATile succeeds even when asked to read an
1763 invalid tile, which means we have no way of knowing whether the data
1764 we received from it is valid or not.
1766 So the caller here has set stoponerror to 1 so that
1767 TIFFRGBAImageGet() will fail.
1769 read_one_rgb_tiled() then takes that into account for i_incomplete
1773 myTIFFReadRGBATile(TIFFRGBAImage *img, uint32 col, uint32 row, uint32 * raster)
1777 uint32 tile_xsize, tile_ysize;
1778 uint32 read_xsize, read_ysize;
1782 * Verify that our request is legal - on a tile file, and on a
1786 TIFFGetFieldDefaulted(img->tif, TIFFTAG_TILEWIDTH, &tile_xsize);
1787 TIFFGetFieldDefaulted(img->tif, TIFFTAG_TILELENGTH, &tile_ysize);
1788 if( (col % tile_xsize) != 0 || (row % tile_ysize) != 0 )
1790 i_push_errorf(0, "Row/col passed to myTIFFReadRGBATile() must be top"
1791 "left corner of a tile.");
1796 * The TIFFRGBAImageGet() function doesn't allow us to get off the
1797 * edge of the image, even to fill an otherwise valid tile. So we
1798 * figure out how much we can read, and fix up the tile buffer to
1799 * a full tile configuration afterwards.
1802 if( row + tile_ysize > img->height )
1803 read_ysize = img->height - row;
1805 read_ysize = tile_ysize;
1807 if( col + tile_xsize > img->width )
1808 read_xsize = img->width - col;
1810 read_xsize = tile_xsize;
1813 * Read the chunk of imagery.
1816 img->row_offset = row;
1817 img->col_offset = col;
1819 ok = TIFFRGBAImageGet(img, raster, read_xsize, read_ysize );
1822 * If our read was incomplete we will need to fix up the tile by
1823 * shifting the data around as if a full tile of data is being returned.
1825 * This is all the more complicated because the image is organized in
1826 * bottom to top format.
1829 if( read_xsize == tile_xsize && read_ysize == tile_ysize )
1832 for( i_row = 0; i_row < read_ysize; i_row++ ) {
1833 memmove( raster + (tile_ysize - i_row - 1) * tile_xsize,
1834 raster + (read_ysize - i_row - 1) * read_xsize,
1835 read_xsize * sizeof(uint32) );
1836 _TIFFmemset( raster + (tile_ysize - i_row - 1) * tile_xsize+read_xsize,
1837 0, sizeof(uint32) * (tile_xsize - read_xsize) );
1840 for( i_row = read_ysize; i_row < tile_ysize; i_row++ ) {
1841 _TIFFmemset( raster + (tile_ysize - i_row - 1) * tile_xsize,
1842 0, sizeof(uint32) * tile_xsize );
1849 read_one_rgb_tiled(TIFF *tif, i_img_dim width, i_img_dim height, int allow_incomplete) {
1851 uint32* raster = NULL;
1854 uint32 tile_width, tile_height;
1855 unsigned long pixels = 0;
1856 char emsg[1024] = "";
1861 im = make_rgb(tif, width, height, &alpha_chan);
1865 if (!TIFFRGBAImageOK(tif, emsg)
1866 || !TIFFRGBAImageBegin(&img, tif, 1, emsg)) {
1867 i_push_error(0, emsg);
1872 TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tile_width);
1873 TIFFGetField(tif, TIFFTAG_TILELENGTH, &tile_height);
1874 mm_log((1, "i_readtiff_wiol: tile_width=%d, tile_height=%d\n", tile_width, tile_height));
1876 raster = (uint32*)_TIFFmalloc(tile_width * tile_height * sizeof (uint32));
1879 i_push_error(0, "No space for raster buffer");
1880 TIFFRGBAImageEnd(&img);
1883 line = mymalloc(tile_width * sizeof(i_color));
1885 for( row = 0; row < height; row += tile_height ) {
1886 for( col = 0; col < width; col += tile_width ) {
1888 /* Read the tile into an RGBA array */
1889 if (myTIFFReadRGBATile(&img, col, row, raster)) {
1891 uint32 newrows = (row+tile_height > height) ? height-row : tile_height;
1892 uint32 newcols = (col+tile_width > width ) ? width-col : tile_width;
1894 mm_log((1, "i_readtiff_wiol: tile(%d, %d) newcols=%d newrows=%d\n", col, row, newcols, newrows));
1895 for( i_row = 0; i_row < newrows; i_row++ ) {
1896 i_color *outp = line;
1897 for(x = 0; x < newcols; x++) {
1898 uint32 temp = raster[x+tile_width*(tile_height-i_row-1)];
1899 outp->rgba.r = TIFFGetR(temp);
1900 outp->rgba.g = TIFFGetG(temp);
1901 outp->rgba.b = TIFFGetB(temp);
1902 outp->rgba.a = TIFFGetA(temp);
1905 /* the libtiff RGBA code expands greyscale into RGBA, so put the
1906 alpha in the right place and scale it */
1908 outp->channel[alpha_chan] = TIFFGetA(temp);
1910 if (outp->channel[alpha_chan]) {
1911 for (ch = 0; ch < alpha_chan; ++ch) {
1912 outp->channel[ch] = outp->channel[ch] * 255 / outp->channel[alpha_chan];
1919 i_plin(im, col, col+newcols, row+i_row, line);
1921 pixels += newrows * newcols;
1924 if (allow_incomplete) {
1936 i_push_error(0, "TIFF: No image data could be read from the image");
1940 /* incomplete image */
1941 i_tags_setn(&im->tags, "i_incomplete", 1);
1942 i_tags_setn(&im->tags, "i_lines_read", pixels / width);
1946 TIFFRGBAImageEnd(&img);
1954 TIFFRGBAImageEnd(&img);
1960 i_tiff_libversion(void) {
1961 return TIFFGetVersion();
1965 setup_paletted(read_state_t *state) {
1968 int color_count = 1 << state->bits_per_sample;
1970 state->img = i_img_pal_new(state->width, state->height, 3, 256);
1974 /* setup the color map */
1975 if (!TIFFGetField(state->tif, TIFFTAG_COLORMAP, maps+0, maps+1, maps+2)) {
1976 i_push_error(0, "Cannot get colormap for paletted image");
1977 i_img_destroy(state->img);
1980 for (i = 0; i < color_count; ++i) {
1982 for (ch = 0; ch < 3; ++ch) {
1983 c.channel[ch] = Sample16To8(maps[ch][i]);
1985 i_addcolors(state->img, &c, 1);
1992 tile_contig_getter(read_state_t *state, read_putter_t putter) {
1993 uint32 tile_width, tile_height;
1994 uint32 this_tile_height, this_tile_width;
1995 uint32 rows_left, cols_left;
1998 state->raster = _TIFFmalloc(TIFFTileSize(state->tif));
1999 if (!state->raster) {
2000 i_push_error(0, "tiff: Out of memory allocating tile buffer");
2004 TIFFGetField(state->tif, TIFFTAG_TILEWIDTH, &tile_width);
2005 TIFFGetField(state->tif, TIFFTAG_TILELENGTH, &tile_height);
2006 rows_left = state->height;
2007 for (y = 0; y < state->height; y += this_tile_height) {
2008 this_tile_height = rows_left > tile_height ? tile_height : rows_left;
2010 cols_left = state->width;
2011 for (x = 0; x < state->width; x += this_tile_width) {
2012 this_tile_width = cols_left > tile_width ? tile_width : cols_left;
2014 if (TIFFReadTile(state->tif,
2017 if (!state->allow_incomplete) {
2022 putter(state, x, y, this_tile_width, this_tile_height, tile_width - this_tile_width);
2025 cols_left -= this_tile_width;
2028 rows_left -= this_tile_height;
2035 strip_contig_getter(read_state_t *state, read_putter_t putter) {
2036 uint32 rows_per_strip;
2037 tsize_t strip_size = TIFFStripSize(state->tif);
2038 uint32 y, strip_rows, rows_left;
2040 state->raster = _TIFFmalloc(strip_size);
2041 if (!state->raster) {
2042 i_push_error(0, "tiff: Out of memory allocating strip buffer");
2046 TIFFGetFieldDefaulted(state->tif, TIFFTAG_ROWSPERSTRIP, &rows_per_strip);
2047 rows_left = state->height;
2048 for (y = 0; y < state->height; y += strip_rows) {
2049 strip_rows = rows_left > rows_per_strip ? rows_per_strip : rows_left;
2050 if (TIFFReadEncodedStrip(state->tif,
2051 TIFFComputeStrip(state->tif, y, 0),
2054 if (!state->allow_incomplete)
2058 putter(state, 0, y, state->width, strip_rows, 0);
2060 rows_left -= strip_rows;
2067 paletted_putter8(read_state_t *state, i_img_dim x, i_img_dim y, i_img_dim width, i_img_dim height, int extras) {
2068 unsigned char *p = state->raster;
2070 state->pixels_read += width * height;
2071 while (height > 0) {
2072 i_ppal(state->img, x, x + width, y, p);
2073 p += width + extras;
2082 paletted_putter4(read_state_t *state, i_img_dim x, i_img_dim y, i_img_dim width, i_img_dim height, int extras) {
2083 uint32 img_line_size = (width + 1) / 2;
2084 uint32 skip_line_size = (width + extras + 1) / 2;
2085 unsigned char *p = state->raster;
2087 if (!state->line_buf)
2088 state->line_buf = mymalloc(state->width);
2090 state->pixels_read += width * height;
2091 while (height > 0) {
2092 unpack_4bit_to(state->line_buf, p, img_line_size);
2093 i_ppal(state->img, x, x + width, y, state->line_buf);
2094 p += skip_line_size;
2103 rgb_channels(read_state_t *state, int *out_channels) {
2109 state->alpha_chan = 0;
2110 state->scale_alpha = 0;
2113 if (state->samples_per_pixel == 3)
2116 if (!TIFFGetField(state->tif, TIFFTAG_EXTRASAMPLES, &extra_count, &extras)) {
2117 mm_log((1, "tiff: samples != 3 but no extra samples tag\n"));
2122 mm_log((1, "tiff: samples != 3 but no extra samples listed"));
2127 state->alpha_chan = 3;
2129 case EXTRASAMPLE_UNSPECIFIED:
2130 case EXTRASAMPLE_ASSOCALPHA:
2131 state->scale_alpha = 1;
2134 case EXTRASAMPLE_UNASSALPHA:
2135 state->scale_alpha = 0;
2139 mm_log((1, "tiff: unknown extra sample type %d, treating as assoc alpha\n",
2141 state->scale_alpha = 1;
2144 mm_log((1, "tiff alpha channel %d scale %d\n", state->alpha_chan, state->scale_alpha));
2148 grey_channels(read_state_t *state, int *out_channels) {
2154 state->alpha_chan = 0;
2155 state->scale_alpha = 0;
2158 if (state->samples_per_pixel == 1)
2161 if (!TIFFGetField(state->tif, TIFFTAG_EXTRASAMPLES, &extra_count, &extras)) {
2162 mm_log((1, "tiff: samples != 1 but no extra samples tag\n"));
2167 mm_log((1, "tiff: samples != 1 but no extra samples listed"));
2172 state->alpha_chan = 1;
2174 case EXTRASAMPLE_UNSPECIFIED:
2175 case EXTRASAMPLE_ASSOCALPHA:
2176 state->scale_alpha = 1;
2179 case EXTRASAMPLE_UNASSALPHA:
2180 state->scale_alpha = 0;
2184 mm_log((1, "tiff: unknown extra sample type %d, treating as assoc alpha\n",
2186 state->scale_alpha = 1;
2192 setup_16_rgb(read_state_t *state) {
2195 rgb_channels(state, &out_channels);
2197 state->img = i_img_16_new(state->width, state->height, out_channels);
2200 state->line_buf = mymalloc(sizeof(unsigned) * state->width * out_channels);
2206 setup_16_grey(read_state_t *state) {
2209 grey_channels(state, &out_channels);
2211 state->img = i_img_16_new(state->width, state->height, out_channels);
2214 state->line_buf = mymalloc(sizeof(unsigned) * state->width * out_channels);
2220 putter_16(read_state_t *state, i_img_dim x, i_img_dim y, i_img_dim width, i_img_dim height,
2222 uint16 *p = state->raster;
2223 int out_chan = state->img->channels;
2225 state->pixels_read += width * height;
2226 while (height > 0) {
2229 unsigned *outp = state->line_buf;
2231 for (i = 0; i < width; ++i) {
2232 for (ch = 0; ch < out_chan; ++ch) {
2235 if (state->alpha_chan && state->scale_alpha && outp[state->alpha_chan]) {
2236 for (ch = 0; ch < state->alpha_chan; ++ch) {
2237 int result = 0.5 + (outp[ch] * 65535.0 / outp[state->alpha_chan]);
2238 outp[ch] = CLAMP16(result);
2241 p += state->samples_per_pixel;
2245 i_psamp_bits(state->img, x, x + width, y, state->line_buf, NULL, out_chan, 16);
2247 p += row_extras * state->samples_per_pixel;
2256 setup_8_rgb(read_state_t *state) {
2259 rgb_channels(state, &out_channels);
2261 state->img = i_img_8_new(state->width, state->height, out_channels);
2264 state->line_buf = mymalloc(sizeof(unsigned) * state->width * out_channels);
2270 setup_8_grey(read_state_t *state) {
2273 grey_channels(state, &out_channels);
2275 state->img = i_img_8_new(state->width, state->height, out_channels);
2278 state->line_buf = mymalloc(sizeof(i_color) * state->width * out_channels);
2284 putter_8(read_state_t *state, i_img_dim x, i_img_dim y, i_img_dim width, i_img_dim height,
2286 unsigned char *p = state->raster;
2287 int out_chan = state->img->channels;
2289 state->pixels_read += width * height;
2290 while (height > 0) {
2293 i_color *outp = state->line_buf;
2295 for (i = 0; i < width; ++i) {
2296 for (ch = 0; ch < out_chan; ++ch) {
2297 outp->channel[ch] = p[ch];
2299 if (state->alpha_chan && state->scale_alpha
2300 && outp->channel[state->alpha_chan]) {
2301 for (ch = 0; ch < state->alpha_chan; ++ch) {
2302 int result = (outp->channel[ch] * 255 + 127) / outp->channel[state->alpha_chan];
2304 outp->channel[ch] = CLAMP8(result);
2307 p += state->samples_per_pixel;
2311 i_plin(state->img, x, x + width, y, state->line_buf);
2313 p += row_extras * state->samples_per_pixel;
2322 setup_32_rgb(read_state_t *state) {
2325 rgb_channels(state, &out_channels);
2327 state->img = i_img_double_new(state->width, state->height, out_channels);
2330 state->line_buf = mymalloc(sizeof(i_fcolor) * state->width);
2336 setup_32_grey(read_state_t *state) {
2339 grey_channels(state, &out_channels);
2341 state->img = i_img_double_new(state->width, state->height, out_channels);
2344 state->line_buf = mymalloc(sizeof(i_fcolor) * state->width);
2350 putter_32(read_state_t *state, i_img_dim x, i_img_dim y, i_img_dim width, i_img_dim height,
2352 uint32 *p = state->raster;
2353 int out_chan = state->img->channels;
2355 state->pixels_read += width * height;
2356 while (height > 0) {
2359 i_fcolor *outp = state->line_buf;
2361 for (i = 0; i < width; ++i) {
2362 for (ch = 0; ch < out_chan; ++ch) {
2363 outp->channel[ch] = p[ch] / 4294967295.0;
2365 if (state->alpha_chan && state->scale_alpha && outp->channel[state->alpha_chan]) {
2366 for (ch = 0; ch < state->alpha_chan; ++ch)
2367 outp->channel[ch] /= outp->channel[state->alpha_chan];
2369 p += state->samples_per_pixel;
2373 i_plinf(state->img, x, x + width, y, state->line_buf);
2375 p += row_extras * state->samples_per_pixel;
2384 setup_bilevel(read_state_t *state) {
2385 i_color black, white;
2386 state->img = i_img_pal_new(state->width, state->height, 1, 256);
2389 black.channel[0] = black.channel[1] = black.channel[2] =
2390 black.channel[3] = 0;
2391 white.channel[0] = white.channel[1] = white.channel[2] =
2392 white.channel[3] = 255;
2393 if (state->photometric == PHOTOMETRIC_MINISBLACK) {
2394 i_addcolors(state->img, &black, 1);
2395 i_addcolors(state->img, &white, 1);
2398 i_addcolors(state->img, &white, 1);
2399 i_addcolors(state->img, &black, 1);
2401 state->line_buf = mymalloc(state->width);
2407 putter_bilevel(read_state_t *state, i_img_dim x, i_img_dim y, i_img_dim width, i_img_dim height,
2409 unsigned char *line_in = state->raster;
2410 size_t line_size = (width + row_extras + 7) / 8;
2412 /* tifflib returns the bits in MSB2LSB order even when the file is
2413 in LSB2MSB, so we only need to handle MSB2LSB */
2414 state->pixels_read += width * height;
2415 while (height > 0) {
2417 unsigned char *outp = state->line_buf;
2418 unsigned char *inp = line_in;
2419 unsigned mask = 0x80;
2421 for (i = 0; i < width; ++i) {
2422 *outp++ = *inp & mask ? 1 : 0;
2430 i_ppal(state->img, x, x + width, y, state->line_buf);
2432 line_in += line_size;
2441 cmyk_channels(read_state_t *state, int *out_channels) {
2447 state->alpha_chan = 0;
2448 state->scale_alpha = 0;
2451 if (state->samples_per_pixel == 4)
2454 if (!TIFFGetField(state->tif, TIFFTAG_EXTRASAMPLES, &extra_count, &extras)) {
2455 mm_log((1, "tiff: CMYK samples != 4 but no extra samples tag\n"));
2460 mm_log((1, "tiff: CMYK samples != 4 but no extra samples listed"));
2465 state->alpha_chan = 4;
2467 case EXTRASAMPLE_UNSPECIFIED:
2468 case EXTRASAMPLE_ASSOCALPHA:
2469 state->scale_alpha = 1;
2472 case EXTRASAMPLE_UNASSALPHA:
2473 state->scale_alpha = 0;
2477 mm_log((1, "tiff: unknown extra sample type %d, treating as assoc alpha\n",
2479 state->scale_alpha = 1;
2485 setup_cmyk8(read_state_t *state) {
2488 cmyk_channels(state, &channels);
2489 state->img = i_img_8_new(state->width, state->height, channels);
2491 state->line_buf = mymalloc(sizeof(i_color) * state->width);
2497 putter_cmyk8(read_state_t *state, i_img_dim x, i_img_dim y, i_img_dim width, i_img_dim height,
2499 unsigned char *p = state->raster;
2501 state->pixels_read += width * height;
2502 while (height > 0) {
2505 i_color *outp = state->line_buf;
2507 for (i = 0; i < width; ++i) {
2508 unsigned char c, m, y, k;
2513 outp->rgba.r = (k * (255 - c)) / 255;
2514 outp->rgba.g = (k * (255 - m)) / 255;
2515 outp->rgba.b = (k * (255 - y)) / 255;
2516 if (state->alpha_chan) {
2517 outp->rgba.a = p[state->alpha_chan];
2518 if (state->scale_alpha
2520 for (ch = 0; ch < 3; ++ch) {
2521 int result = (outp->channel[ch] * 255 + 127) / outp->rgba.a;
2522 outp->channel[ch] = CLAMP8(result);
2526 p += state->samples_per_pixel;
2530 i_plin(state->img, x, x + width, y, state->line_buf);
2532 p += row_extras * state->samples_per_pixel;
2541 setup_cmyk16(read_state_t *state) {
2544 cmyk_channels(state, &channels);
2545 state->img = i_img_16_new(state->width, state->height, channels);
2547 state->line_buf = mymalloc(sizeof(unsigned) * state->width * channels);
2553 putter_cmyk16(read_state_t *state, i_img_dim x, i_img_dim y, i_img_dim width, i_img_dim height,
2555 uint16 *p = state->raster;
2556 int out_chan = state->img->channels;
2558 mm_log((4, "putter_cmyk16(%p, %d, %d, %d, %d, %d)\n", x, y, width, height, row_extras));
2560 state->pixels_read += width * height;
2561 while (height > 0) {
2564 unsigned *outp = state->line_buf;
2566 for (i = 0; i < width; ++i) {
2567 unsigned c, m, y, k;
2572 outp[0] = (k * (65535U - c)) / 65535U;
2573 outp[1] = (k * (65535U - m)) / 65535U;
2574 outp[2] = (k * (65535U - y)) / 65535U;
2575 if (state->alpha_chan) {
2576 outp[3] = p[state->alpha_chan];
2577 if (state->scale_alpha
2579 for (ch = 0; ch < 3; ++ch) {
2580 int result = (outp[ch] * 65535 + 32767) / outp[3];
2581 outp[3] = CLAMP16(result);
2585 p += state->samples_per_pixel;
2589 i_psamp_bits(state->img, x, x + width, y, state->line_buf, NULL, out_chan, 16);
2591 p += row_extras * state->samples_per_pixel;
2601 Older versions of tifflib we support don't define this, so define it
2604 If you want this detection to do anything useful, use a newer
2608 #if TIFFLIB_VERSION < 20031121
2611 TIFFIsCODECConfigured(uint16 scheme) {
2613 /* these schemes are all shipped with tifflib */
2614 case COMPRESSION_NONE:
2615 case COMPRESSION_PACKBITS:
2616 case COMPRESSION_CCITTRLE:
2617 case COMPRESSION_CCITTRLEW:
2618 case COMPRESSION_CCITTFAX3:
2619 case COMPRESSION_CCITTFAX4:
2622 /* these require external library support */
2624 case COMPRESSION_JPEG:
2625 case COMPRESSION_LZW:
2626 case COMPRESSION_DEFLATE:
2627 case COMPRESSION_ADOBE_DEFLATE:
2635 myTIFFIsCODECConfigured(uint16 scheme) {
2636 #if TIFFLIB_VERSION < 20040724
2637 if (scheme == COMPRESSION_LZW)
2641 return TIFFIsCODECConfigured(scheme);
2649 Arnar M. Hrafnkelsson <addi@umich.edu>, Tony Cook <tonyc@cpan.org>