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) {
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) ig->seekcb(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) {
271 static i_img *read_one_tiff(TIFF *tif, int allow_incomplete) {
273 uint32 width, height;
274 uint16 samples_per_pixel;
278 int gotXres, gotYres;
280 uint16 bits_per_sample;
281 uint16 planar_config;
286 read_setup_t setupf = NULL;
287 read_getter_t getterf = NULL;
288 read_putter_t putterf = NULL;
289 int channels = MAXCHANNELS;
290 size_t sample_size = ~0; /* force failure if some code doesn't set it */
291 i_img_dim total_pixels;
295 TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width);
296 TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height);
297 TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &samples_per_pixel);
298 tiled = TIFFIsTiled(tif);
299 TIFFGetFieldDefaulted(tif, TIFFTAG_PHOTOMETRIC, &photometric);
300 TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE, &bits_per_sample);
301 TIFFGetFieldDefaulted(tif, TIFFTAG_PLANARCONFIG, &planar_config);
302 TIFFGetFieldDefaulted(tif, TIFFTAG_INKSET, &inkset);
304 mm_log((1, "i_readtiff_wiol: width=%d, height=%d, channels=%d\n", width, height, samples_per_pixel));
305 mm_log((1, "i_readtiff_wiol: %stiled\n", tiled?"":"not "));
306 mm_log((1, "i_readtiff_wiol: %sbyte swapped\n", TIFFIsByteSwapped(tif)?"":"not "));
308 total_pixels = width * height;
309 memset(&state, 0, sizeof(state));
311 state.allow_incomplete = allow_incomplete;
313 state.height = height;
314 state.bits_per_sample = bits_per_sample;
315 state.samples_per_pixel = samples_per_pixel;
316 state.photometric = photometric;
318 /* yes, this if() is horrible */
319 if (photometric == PHOTOMETRIC_PALETTE && bits_per_sample <= 8) {
320 setupf = setup_paletted;
321 if (bits_per_sample == 8)
322 putterf = paletted_putter8;
323 else if (bits_per_sample == 4)
324 putterf = paletted_putter4;
326 mm_log((1, "unsupported paletted bits_per_sample %d\n", bits_per_sample));
328 sample_size = sizeof(i_sample_t);
331 else if (bits_per_sample == 16
332 && photometric == PHOTOMETRIC_RGB
333 && samples_per_pixel >= 3) {
334 setupf = setup_16_rgb;
337 rgb_channels(&state, &channels);
339 else if (bits_per_sample == 16
340 && photometric == PHOTOMETRIC_MINISBLACK) {
341 setupf = setup_16_grey;
344 grey_channels(&state, &channels);
346 else if (bits_per_sample == 8
347 && photometric == PHOTOMETRIC_MINISBLACK) {
348 setupf = setup_8_grey;
351 grey_channels(&state, &channels);
353 else if (bits_per_sample == 8
354 && photometric == PHOTOMETRIC_RGB) {
355 setupf = setup_8_rgb;
358 rgb_channels(&state, &channels);
360 else if (bits_per_sample == 32
361 && photometric == PHOTOMETRIC_RGB
362 && samples_per_pixel >= 3) {
363 setupf = setup_32_rgb;
365 sample_size = sizeof(i_fsample_t);
366 rgb_channels(&state, &channels);
368 else if (bits_per_sample == 32
369 && photometric == PHOTOMETRIC_MINISBLACK) {
370 setupf = setup_32_grey;
372 sample_size = sizeof(i_fsample_t);
373 grey_channels(&state, &channels);
375 else if (bits_per_sample == 1
376 && (photometric == PHOTOMETRIC_MINISBLACK
377 || photometric == PHOTOMETRIC_MINISWHITE)
378 && samples_per_pixel == 1) {
379 setupf = setup_bilevel;
380 putterf = putter_bilevel;
381 sample_size = sizeof(i_palidx);
384 else if (bits_per_sample == 8
385 && photometric == PHOTOMETRIC_SEPARATED
386 && inkset == INKSET_CMYK
387 && samples_per_pixel >= 4) {
388 setupf = setup_cmyk8;
389 putterf = putter_cmyk8;
391 cmyk_channels(&state, &channels);
393 else if (bits_per_sample == 16
394 && photometric == PHOTOMETRIC_SEPARATED
395 && inkset == INKSET_CMYK
396 && samples_per_pixel >= 4) {
397 setupf = setup_cmyk16;
398 putterf = putter_cmyk16;
400 cmyk_channels(&state, &channels);
404 fallback_rgb_channels(tif, width, height, &channels, &alpha);
408 if (!i_int_check_image_file_limits(width, height, channels, sample_size)) {
413 if (planar_config == PLANARCONFIG_CONTIG)
414 getterf = tile_contig_getter;
417 if (planar_config == PLANARCONFIG_CONTIG)
418 getterf = strip_contig_getter;
420 if (setupf && getterf && putterf) {
424 if (!getterf(&state, putterf) || !state.pixels_read) {
426 i_img_destroy(state.img);
428 _TIFFfree(state.raster);
430 myfree(state.line_buf);
435 if (allow_incomplete && state.pixels_read < total_pixels) {
436 i_tags_setn(&(state.img->tags), "i_incomplete", 1);
437 i_tags_setn(&(state.img->tags), "i_lines_read",
438 state.pixels_read / width);
443 _TIFFfree(state.raster);
445 myfree(state.line_buf);
449 im = read_one_rgb_tiled(tif, width, height, allow_incomplete);
452 im = read_one_rgb_lines(tif, width, height, allow_incomplete);
459 /* general metadata */
460 i_tags_setn(&im->tags, "tiff_bitspersample", bits_per_sample);
461 i_tags_setn(&im->tags, "tiff_photometric", photometric);
462 TIFFGetFieldDefaulted(tif, TIFFTAG_COMPRESSION, &compress);
464 /* resolution tags */
465 TIFFGetFieldDefaulted(tif, TIFFTAG_RESOLUTIONUNIT, &resunit);
466 gotXres = TIFFGetField(tif, TIFFTAG_XRESOLUTION, &xres);
467 gotYres = TIFFGetField(tif, TIFFTAG_YRESOLUTION, &yres);
468 if (gotXres || gotYres) {
473 i_tags_setn(&im->tags, "tiff_resolutionunit", resunit);
474 if (resunit == RESUNIT_CENTIMETER) {
475 /* from dots per cm to dpi */
478 i_tags_set(&im->tags, "tiff_resolutionunit_name", "centimeter", -1);
480 else if (resunit == RESUNIT_NONE) {
481 i_tags_setn(&im->tags, "i_aspect_only", 1);
482 i_tags_set(&im->tags, "tiff_resolutionunit_name", "none", -1);
484 else if (resunit == RESUNIT_INCH) {
485 i_tags_set(&im->tags, "tiff_resolutionunit_name", "inch", -1);
488 i_tags_set(&im->tags, "tiff_resolutionunit_name", "unknown", -1);
490 /* tifflib doesn't seem to provide a way to get to the original rational
491 value of these, which would let me provide a more reasonable
492 precision. So make up a number. */
493 i_tags_set_float2(&im->tags, "i_xres", 0, xres, 6);
494 i_tags_set_float2(&im->tags, "i_yres", 0, yres, 6);
498 for (i = 0; i < text_tag_count; ++i) {
500 if (TIFFGetField(tif, text_tag_names[i].tag, &data)) {
501 mm_log((1, "i_readtiff_wiol: tag %d has value %s\n",
502 text_tag_names[i].tag, data));
503 i_tags_set(&im->tags, text_tag_names[i].name, data, -1);
507 i_tags_set(&im->tags, "i_format", "tiff", 4);
508 if (warn_buffer && *warn_buffer) {
509 i_tags_set(&im->tags, "i_warning", warn_buffer, -1);
513 for (i = 0; i < compress_value_count; ++i) {
514 if (compress_values[i].tag == compress) {
515 i_tags_set(&im->tags, "tiff_compression", compress_values[i].name, -1);
524 =item i_readtiff_wiol(im, ig)
529 i_readtiff_wiol(io_glue *ig, int allow_incomplete, int page) {
531 TIFFErrorHandler old_handler;
532 TIFFErrorHandler old_warn_handler;
536 old_handler = TIFFSetErrorHandler(error_handler);
537 old_warn_handler = TIFFSetWarningHandler(warn_handler);
541 /* Add code to get the filename info from the iolayer */
542 /* Also add code to check for mmapped code */
544 mm_log((1, "i_readtiff_wiol(ig %p, allow_incomplete %d, page %d)\n", ig, allow_incomplete, page));
546 tif = TIFFClientOpen("(Iolayer)",
549 (TIFFReadWriteProc) ig->readcb,
550 (TIFFReadWriteProc) ig->writecb,
551 (TIFFSeekProc) comp_seek,
552 (TIFFCloseProc) ig->closecb,
553 ig->sizecb ? (TIFFSizeProc) ig->sizecb : (TIFFSizeProc) sizeproc,
554 (TIFFMapFileProc) comp_mmap,
555 (TIFFUnmapFileProc) comp_munmap);
558 mm_log((1, "i_readtiff_wiol: Unable to open tif file\n"));
559 i_push_error(0, "Error opening file");
560 TIFFSetErrorHandler(old_handler);
561 TIFFSetWarningHandler(old_warn_handler);
566 if (!TIFFSetDirectory(tif, page)) {
567 mm_log((1, "i_readtiff_wiol: Unable to switch to directory %d\n", page));
568 i_push_errorf(0, "could not switch to page %d", page);
569 TIFFSetErrorHandler(old_handler);
570 TIFFSetWarningHandler(old_warn_handler);
576 im = read_one_tiff(tif, allow_incomplete);
578 if (TIFFLastDirectory(tif)) mm_log((1, "Last directory of tiff file\n"));
579 TIFFSetErrorHandler(old_handler);
580 TIFFSetWarningHandler(old_warn_handler);
586 =item i_readtiff_multi_wiol(ig, *count)
588 Reads multiple images from a TIFF.
593 i_readtiff_multi_wiol(io_glue *ig, int *count) {
595 TIFFErrorHandler old_handler;
596 TIFFErrorHandler old_warn_handler;
597 i_img **results = NULL;
598 int result_alloc = 0;
602 old_handler = TIFFSetErrorHandler(error_handler);
603 old_warn_handler = TIFFSetWarningHandler(warn_handler);
607 /* Add code to get the filename info from the iolayer */
608 /* Also add code to check for mmapped code */
610 mm_log((1, "i_readtiff_wiol(ig %p, length %d)\n", ig));
612 tif = TIFFClientOpen("(Iolayer)",
615 (TIFFReadWriteProc) ig->readcb,
616 (TIFFReadWriteProc) ig->writecb,
617 (TIFFSeekProc) comp_seek,
618 (TIFFCloseProc) ig->closecb,
619 ig->sizecb ? (TIFFSizeProc) ig->sizecb : (TIFFSizeProc) sizeproc,
620 (TIFFMapFileProc) comp_mmap,
621 (TIFFUnmapFileProc) comp_munmap);
624 mm_log((1, "i_readtiff_wiol: Unable to open tif file\n"));
625 i_push_error(0, "Error opening file");
626 TIFFSetErrorHandler(old_handler);
627 TIFFSetWarningHandler(old_warn_handler);
633 i_img *im = read_one_tiff(tif, 0);
636 if (++*count > result_alloc) {
637 if (result_alloc == 0) {
639 results = mymalloc(result_alloc * sizeof(i_img *));
644 newresults = myrealloc(results, result_alloc * sizeof(i_img *));
646 i_img_destroy(im); /* don't leak it */
649 results = newresults;
652 results[*count-1] = im;
653 } while (TIFFSetDirectory(tif, ++dirnum));
655 TIFFSetWarningHandler(old_warn_handler);
656 TIFFSetErrorHandler(old_handler);
662 i_writetiff_low_faxable(TIFF *tif, i_img *im, int fine) {
663 uint32 width, height;
664 unsigned char *linebuf = NULL;
669 float vres = fine ? 196 : 98;
675 if (width != im->xsize || height != im->ysize) {
676 i_push_error(0, "image too large for TIFF");
680 switch (im->channels) {
690 /* This means a colorspace we don't handle yet */
691 mm_log((1, "i_writetiff_wiol_faxable: don't handle %d channel images.\n", im->channels));
695 /* Add code to get the filename info from the iolayer */
696 /* Also add code to check for mmapped code */
699 mm_log((1, "i_writetiff_wiol_faxable: width=%d, height=%d, channels=%d\n", width, height, im->channels));
701 if (!TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width) )
702 { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField width=%d failed\n", width)); return 0; }
703 if (!TIFFSetField(tif, TIFFTAG_IMAGELENGTH, height) )
704 { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField length=%d failed\n", height)); return 0; }
705 if (!TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1))
706 { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField samplesperpixel=1 failed\n")); return 0; }
707 if (!TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT))
708 { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField Orientation=topleft\n")); return 0; }
709 if (!TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 1) )
710 { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField bitpersample=1\n")); return 0; }
711 if (!TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG))
712 { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField planarconfig\n")); return 0; }
713 if (!TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISWHITE))
714 { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField photometric=%d\n", PHOTOMETRIC_MINISBLACK)); return 0; }
715 if (!TIFFSetField(tif, TIFFTAG_COMPRESSION, 3))
716 { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField compression=3\n")); return 0; }
718 linebuf = (unsigned char *)_TIFFmalloc( TIFFScanlineSize(tif) );
720 if (!TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, TIFFDefaultStripSize(tif, -1))) {
721 mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField rowsperstrip=-1\n")); return 0; }
723 TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
724 TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rc);
726 mm_log((1, "i_writetiff_wiol_faxable: TIFFGetField rowsperstrip=%d\n", rowsperstrip));
727 mm_log((1, "i_writetiff_wiol_faxable: TIFFGetField scanlinesize=%d\n", TIFFScanlineSize(tif) ));
728 mm_log((1, "i_writetiff_wiol_faxable: TIFFGetField planarconfig=%d == %d\n", rc, PLANARCONFIG_CONTIG));
730 if (!TIFFSetField(tif, TIFFTAG_XRESOLUTION, (float)204))
731 { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField Xresolution=204\n")); return 0; }
732 if (!TIFFSetField(tif, TIFFTAG_YRESOLUTION, vres))
733 { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField Yresolution=196\n")); return 0; }
734 if (!TIFFSetField(tif, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH)) {
735 mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField ResolutionUnit=%d\n", RESUNIT_INCH)); return 0;
738 if (!save_tiff_tags(tif, im)) {
742 for (y=0; y<height; y++) {
744 for(x=0; x<width; x+=8) {
749 linebuf[linebufpos]=0;
750 bits = width-x; if(bits>8) bits=8;
751 i_gsamp(im, x, x+8, y, luma, &luma_chan, 1);
752 for(bitpos=0;bitpos<bits;bitpos++) {
753 linebuf[linebufpos] |= ((luma[bitpos] < 128) ? bitval : 0);
758 if (TIFFWriteScanline(tif, linebuf, y, 0) < 0) {
759 mm_log((1, "i_writetiff_wiol_faxable: TIFFWriteScanline failed.\n"));
763 if (linebuf) _TIFFfree(linebuf);
769 find_compression(char const *name, uint16 *compress) {
772 for (i = 0; i < compress_value_count; ++i) {
773 if (strcmp(compress_values[i].name, name) == 0) {
774 *compress = (uint16)compress_values[i].tag;
778 *compress = COMPRESSION_NONE;
784 get_compression(i_img *im, uint16 def_compress) {
788 if (i_tags_find(&im->tags, "tiff_compression", 0, &entry)
789 && im->tags.tags[entry].data) {
791 if (find_compression(im->tags.tags[entry].data, &compress)
792 && myTIFFIsCODECConfigured(compress))
795 if (i_tags_get_int(&im->tags, "tiff_compression", 0, &value)) {
796 if ((uint16)value == value
797 && myTIFFIsCODECConfigured((uint16)value))
798 return (uint16)value;
805 i_tiff_has_compression(const char *name) {
808 if (!find_compression(name, &compress))
811 return myTIFFIsCODECConfigured(compress);
815 set_base_tags(TIFF *tif, i_img *im, uint16 compress, uint16 photometric,
816 uint16 bits_per_sample, uint16 samples_per_pixel) {
819 int got_xres, got_yres;
822 if (!TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, im->xsize)) {
823 i_push_error(0, "write TIFF: setting width tag");
826 if (!TIFFSetField(tif, TIFFTAG_IMAGELENGTH, im->ysize)) {
827 i_push_error(0, "write TIFF: setting length tag");
830 if (!TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT)) {
831 i_push_error(0, "write TIFF: setting orientation tag");
834 if (!TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG)) {
835 i_push_error(0, "write TIFF: setting planar configuration tag");
838 if (!TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, photometric)) {
839 i_push_error(0, "write TIFF: setting photometric tag");
842 if (!TIFFSetField(tif, TIFFTAG_COMPRESSION, compress)) {
843 i_push_error(0, "write TIFF: setting compression tag");
846 if (!TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bits_per_sample)) {
847 i_push_error(0, "write TIFF: setting bits per sample tag");
850 if (!TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, samples_per_pixel)) {
851 i_push_error(0, "write TIFF: setting samples per pixel tag");
855 got_xres = i_tags_get_float(&im->tags, "i_xres", 0, &xres);
856 got_yres = i_tags_get_float(&im->tags, "i_yres", 0, &yres);
857 if (!i_tags_get_int(&im->tags, "i_aspect_only", 0,&aspect_only))
859 if (!i_tags_get_int(&im->tags, "tiff_resolutionunit", 0, &resunit))
860 resunit = RESUNIT_INCH;
861 if (got_xres || got_yres) {
867 resunit = RESUNIT_NONE;
870 if (resunit == RESUNIT_CENTIMETER) {
875 resunit = RESUNIT_INCH;
878 if (!TIFFSetField(tif, TIFFTAG_XRESOLUTION, (float)xres)) {
879 i_push_error(0, "write TIFF: setting xresolution tag");
882 if (!TIFFSetField(tif, TIFFTAG_YRESOLUTION, (float)yres)) {
883 i_push_error(0, "write TIFF: setting yresolution tag");
886 if (!TIFFSetField(tif, TIFFTAG_RESOLUTIONUNIT, (uint16)resunit)) {
887 i_push_error(0, "write TIFF: setting resolutionunit tag");
896 write_one_bilevel(TIFF *tif, i_img *im, int zero_is_white) {
897 uint16 compress = get_compression(im, COMPRESSION_PACKBITS);
899 unsigned char *in_row;
900 unsigned char *out_row;
905 mm_log((1, "tiff - write_one_bilevel(tif %p, im %p, zero_is_white %d)\n",
906 tif, im, zero_is_white));
908 /* ignore a silly choice */
909 if (compress == COMPRESSION_JPEG)
910 compress = COMPRESSION_PACKBITS;
913 case COMPRESSION_CCITTRLE:
914 case COMPRESSION_CCITTFAX3:
915 case COMPRESSION_CCITTFAX4:
916 /* natural fax photometric */
917 photometric = PHOTOMETRIC_MINISWHITE;
921 /* natural for most computer images */
922 photometric = PHOTOMETRIC_MINISBLACK;
926 if (!set_base_tags(tif, im, compress, photometric, 1, 1))
929 if (!TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, TIFFDefaultStripSize(tif, -1))) {
930 i_push_error(0, "write TIFF: setting rows per strip tag");
934 out_size = TIFFScanlineSize(tif);
935 out_row = (unsigned char *)_TIFFmalloc( out_size );
936 in_row = mymalloc(im->xsize);
938 invert = (photometric == PHOTOMETRIC_MINISWHITE) != (zero_is_white != 0);
940 for (y = 0; y < im->ysize; ++y) {
942 unsigned char *outp = out_row;
943 memset(out_row, 0, out_size);
944 i_gpal(im, 0, im->xsize, y, in_row);
945 for (x = 0; x < im->xsize; ++x) {
946 if (invert ? !in_row[x] : in_row[x]) {
955 if (TIFFWriteScanline(tif, out_row, y, 0) < 0) {
958 i_push_error(0, "write TIFF: write scan line failed");
970 set_palette(TIFF *tif, i_img *im, int size) {
977 colors = (uint16 *)_TIFFmalloc(sizeof(uint16) * 3 * size);
979 out[1] = colors + size;
980 out[2] = colors + 2 * size;
982 count = i_colorcount(im);
983 for (i = 0; i < count; ++i) {
984 i_getcolors(im, i, &c, 1);
985 for (ch = 0; ch < 3; ++ch)
986 out[ch][i] = c.channel[ch] * 257;
988 for (; i < size; ++i) {
989 for (ch = 0; ch < 3; ++ch)
992 if (!TIFFSetField(tif, TIFFTAG_COLORMAP, out[0], out[1], out[2])) {
994 i_push_error(0, "write TIFF: setting color map");
1003 write_one_paletted8(TIFF *tif, i_img *im) {
1004 uint16 compress = get_compression(im, COMPRESSION_PACKBITS);
1005 unsigned char *out_row;
1009 mm_log((1, "tiff - write_one_paletted8(tif %p, im %p)\n", tif, im));
1011 /* ignore a silly choice */
1012 if (compress == COMPRESSION_JPEG ||
1013 compress == COMPRESSION_CCITTRLE ||
1014 compress == COMPRESSION_CCITTFAX3 ||
1015 compress == COMPRESSION_CCITTFAX4)
1016 compress = COMPRESSION_PACKBITS;
1018 if (!TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, TIFFDefaultStripSize(tif, -1))) {
1019 i_push_error(0, "write TIFF: setting rows per strip tag");
1023 if (!set_base_tags(tif, im, compress, PHOTOMETRIC_PALETTE, 8, 1))
1026 if (!set_palette(tif, im, 256))
1029 out_size = TIFFScanlineSize(tif);
1030 out_row = (unsigned char *)_TIFFmalloc( out_size );
1032 for (y = 0; y < im->ysize; ++y) {
1033 i_gpal(im, 0, im->xsize, y, out_row);
1034 if (TIFFWriteScanline(tif, out_row, y, 0) < 0) {
1036 i_push_error(0, "write TIFF: write scan line failed");
1047 write_one_paletted4(TIFF *tif, i_img *im) {
1048 uint16 compress = get_compression(im, COMPRESSION_PACKBITS);
1049 unsigned char *in_row;
1050 unsigned char *out_row;
1054 mm_log((1, "tiff - write_one_paletted4(tif %p, im %p)\n", tif, im));
1056 /* ignore a silly choice */
1057 if (compress == COMPRESSION_JPEG ||
1058 compress == COMPRESSION_CCITTRLE ||
1059 compress == COMPRESSION_CCITTFAX3 ||
1060 compress == COMPRESSION_CCITTFAX4)
1061 compress = COMPRESSION_PACKBITS;
1063 if (!set_base_tags(tif, im, compress, PHOTOMETRIC_PALETTE, 4, 1))
1066 if (!set_palette(tif, im, 16))
1069 if (!TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, TIFFDefaultStripSize(tif, -1))) {
1070 i_push_error(0, "write TIFF: setting rows per strip tag");
1074 in_row = mymalloc(im->xsize);
1075 out_size = TIFFScanlineSize(tif);
1076 out_row = (unsigned char *)_TIFFmalloc( out_size );
1078 for (y = 0; y < im->ysize; ++y) {
1079 i_gpal(im, 0, im->xsize, y, in_row);
1080 memset(out_row, 0, out_size);
1081 pack_4bit_to(out_row, in_row, im->xsize);
1082 if (TIFFWriteScanline(tif, out_row, y, 0) < 0) {
1084 i_push_error(0, "write TIFF: write scan line failed");
1096 set_direct_tags(TIFF *tif, i_img *im, uint16 compress,
1097 uint16 bits_per_sample) {
1098 uint16 extras = EXTRASAMPLE_ASSOCALPHA;
1099 uint16 extra_count = im->channels == 2 || im->channels == 4;
1100 uint16 photometric = im->channels >= 3 ?
1101 PHOTOMETRIC_RGB : PHOTOMETRIC_MINISBLACK;
1103 if (!set_base_tags(tif, im, compress, photometric, bits_per_sample,
1109 if (!TIFFSetField(tif, TIFFTAG_EXTRASAMPLES, extra_count, &extras)) {
1110 i_push_error(0, "write TIFF: setting extra samples tag");
1115 if (compress == COMPRESSION_JPEG) {
1117 if (i_tags_get_int(&im->tags, "tiff_jpegquality", 0, &jpeg_quality)
1118 && jpeg_quality >= 0 && jpeg_quality <= 100) {
1119 if (!TIFFSetField(tif, TIFFTAG_JPEGQUALITY, jpeg_quality)) {
1120 i_push_error(0, "write TIFF: setting jpeg quality pseudo-tag");
1130 write_one_32(TIFF *tif, i_img *im) {
1131 uint16 compress = get_compression(im, COMPRESSION_PACKBITS);
1136 size_t sample_count = im->xsize * im->channels;
1137 size_t sample_index;
1139 mm_log((1, "tiff - write_one_32(tif %p, im %p)\n", tif, im));
1141 /* only 8 and 12 bit samples are supported by jpeg compression */
1142 if (compress == COMPRESSION_JPEG)
1143 compress = COMPRESSION_PACKBITS;
1145 if (!set_direct_tags(tif, im, compress, 32))
1148 in_row = mymalloc(sample_count * sizeof(unsigned));
1149 out_size = TIFFScanlineSize(tif);
1150 out_row = (uint32 *)_TIFFmalloc( out_size );
1152 for (y = 0; y < im->ysize; ++y) {
1153 if (i_gsamp_bits(im, 0, im->xsize, y, in_row, NULL, im->channels, 32) <= 0) {
1154 i_push_error(0, "Cannot read 32-bit samples");
1157 for (sample_index = 0; sample_index < sample_count; ++sample_index)
1158 out_row[sample_index] = in_row[sample_index];
1159 if (TIFFWriteScanline(tif, out_row, y, 0) < 0) {
1162 i_push_error(0, "write TIFF: write scan line failed");
1174 write_one_16(TIFF *tif, i_img *im) {
1175 uint16 compress = get_compression(im, COMPRESSION_PACKBITS);
1180 size_t sample_count = im->xsize * im->channels;
1181 size_t sample_index;
1183 mm_log((1, "tiff - write_one_16(tif %p, im %p)\n", tif, im));
1185 /* only 8 and 12 bit samples are supported by jpeg compression */
1186 if (compress == COMPRESSION_JPEG)
1187 compress = COMPRESSION_PACKBITS;
1189 if (!set_direct_tags(tif, im, compress, 16))
1192 in_row = mymalloc(sample_count * sizeof(unsigned));
1193 out_size = TIFFScanlineSize(tif);
1194 out_row = (uint16 *)_TIFFmalloc( out_size );
1196 for (y = 0; y < im->ysize; ++y) {
1197 if (i_gsamp_bits(im, 0, im->xsize, y, in_row, NULL, im->channels, 16) <= 0) {
1198 i_push_error(0, "Cannot read 16-bit samples");
1201 for (sample_index = 0; sample_index < sample_count; ++sample_index)
1202 out_row[sample_index] = in_row[sample_index];
1203 if (TIFFWriteScanline(tif, out_row, y, 0) < 0) {
1206 i_push_error(0, "write TIFF: write scan line failed");
1218 write_one_8(TIFF *tif, i_img *im) {
1219 uint16 compress = get_compression(im, COMPRESSION_PACKBITS);
1221 unsigned char *out_row;
1223 size_t sample_count = im->xsize * im->channels;
1225 mm_log((1, "tiff - write_one_8(tif %p, im %p)\n", tif, im));
1227 if (!set_direct_tags(tif, im, compress, 8))
1230 out_size = TIFFScanlineSize(tif);
1231 if (out_size < sample_count)
1232 out_size = sample_count;
1233 out_row = (unsigned char *)_TIFFmalloc( out_size );
1235 for (y = 0; y < im->ysize; ++y) {
1236 if (i_gsamp(im, 0, im->xsize, y, out_row, NULL, im->channels) <= 0) {
1237 i_push_error(0, "Cannot read 8-bit samples");
1240 if (TIFFWriteScanline(tif, out_row, y, 0) < 0) {
1242 i_push_error(0, "write TIFF: write scan line failed");
1252 i_writetiff_low(TIFF *tif, i_img *im) {
1253 uint32 width, height;
1259 channels = im->channels;
1261 if (width != im->xsize || height != im->ysize) {
1262 i_push_error(0, "image too large for TIFF");
1266 mm_log((1, "i_writetiff_low: width=%d, height=%d, channels=%d, bits=%d\n", width, height, channels, im->bits));
1267 if (im->type == i_palette_type) {
1268 mm_log((1, "i_writetiff_low: paletted, colors=%d\n", i_colorcount(im)));
1271 if (i_img_is_monochrome(im, &zero_is_white)) {
1272 if (!write_one_bilevel(tif, im, zero_is_white))
1275 else if (im->type == i_palette_type) {
1276 if (i_colorcount(im) <= 16) {
1277 if (!write_one_paletted4(tif, im))
1281 if (!write_one_paletted8(tif, im))
1285 else if (im->bits > 16) {
1286 if (!write_one_32(tif, im))
1289 else if (im->bits > 8) {
1290 if (!write_one_16(tif, im))
1294 if (!write_one_8(tif, im))
1298 if (!save_tiff_tags(tif, im))
1305 =item i_writetiff_multi_wiol(ig, imgs, count, fine_mode)
1307 Stores an image in the iolayer object.
1309 ig - io_object that defines source to write to
1310 imgs,count - the images to write
1316 i_writetiff_multi_wiol(io_glue *ig, i_img **imgs, int count) {
1318 TIFFErrorHandler old_handler;
1321 old_handler = TIFFSetErrorHandler(error_handler);
1324 mm_log((1, "i_writetiff_multi_wiol(ig %p, imgs %p, count %d)\n",
1327 /* FIXME: Enable the mmap interface */
1329 tif = TIFFClientOpen("No name",
1332 (TIFFReadWriteProc) ig->readcb,
1333 (TIFFReadWriteProc) ig->writecb,
1334 (TIFFSeekProc) comp_seek,
1335 (TIFFCloseProc) ig->closecb,
1336 ig->sizecb ? (TIFFSizeProc) ig->sizecb : (TIFFSizeProc) sizeproc,
1337 (TIFFMapFileProc) comp_mmap,
1338 (TIFFUnmapFileProc) comp_munmap);
1343 mm_log((1, "i_writetiff_multi_wiol: Unable to open tif file for writing\n"));
1344 i_push_error(0, "Could not create TIFF object");
1345 TIFFSetErrorHandler(old_handler);
1349 for (i = 0; i < count; ++i) {
1350 if (!i_writetiff_low(tif, imgs[i])) {
1352 TIFFSetErrorHandler(old_handler);
1356 if (!TIFFWriteDirectory(tif)) {
1357 i_push_error(0, "Cannot write TIFF directory");
1359 TIFFSetErrorHandler(old_handler);
1364 TIFFSetErrorHandler(old_handler);
1365 (void) TIFFClose(tif);
1371 =item i_writetiff_multi_wiol_faxable(ig, imgs, count, fine_mode)
1373 Stores an image in the iolayer object.
1375 ig - io_object that defines source to write to
1376 imgs,count - the images to write
1377 fine_mode - select fine or normal mode fax images
1384 i_writetiff_multi_wiol_faxable(io_glue *ig, i_img **imgs, int count, int fine) {
1387 TIFFErrorHandler old_handler;
1389 old_handler = TIFFSetErrorHandler(error_handler);
1392 mm_log((1, "i_writetiff_multi_wiol(ig %p, imgs %p, count %d)\n",
1395 /* FIXME: Enable the mmap interface */
1397 tif = TIFFClientOpen("No name",
1400 (TIFFReadWriteProc) ig->readcb,
1401 (TIFFReadWriteProc) ig->writecb,
1402 (TIFFSeekProc) comp_seek,
1403 (TIFFCloseProc) ig->closecb,
1404 ig->sizecb ? (TIFFSizeProc) ig->sizecb : (TIFFSizeProc) sizeproc,
1405 (TIFFMapFileProc) comp_mmap,
1406 (TIFFUnmapFileProc) comp_munmap);
1411 mm_log((1, "i_writetiff_mulit_wiol: Unable to open tif file for writing\n"));
1412 i_push_error(0, "Could not create TIFF object");
1413 TIFFSetErrorHandler(old_handler);
1417 for (i = 0; i < count; ++i) {
1418 if (!i_writetiff_low_faxable(tif, imgs[i], fine)) {
1420 TIFFSetErrorHandler(old_handler);
1424 if (!TIFFWriteDirectory(tif)) {
1425 i_push_error(0, "Cannot write TIFF directory");
1427 TIFFSetErrorHandler(old_handler);
1432 (void) TIFFClose(tif);
1433 TIFFSetErrorHandler(old_handler);
1439 =item i_writetiff_wiol(im, ig)
1441 Stores an image in the iolayer object.
1443 im - image object to write out
1444 ig - io_object that defines source to write to
1449 i_writetiff_wiol(i_img *img, io_glue *ig) {
1451 TIFFErrorHandler old_handler;
1453 old_handler = TIFFSetErrorHandler(error_handler);
1456 mm_log((1, "i_writetiff_wiol(img %p, ig %p)\n", img, ig));
1458 /* FIXME: Enable the mmap interface */
1460 tif = TIFFClientOpen("No name",
1463 (TIFFReadWriteProc) ig->readcb,
1464 (TIFFReadWriteProc) ig->writecb,
1465 (TIFFSeekProc) comp_seek,
1466 (TIFFCloseProc) ig->closecb,
1467 ig->sizecb ? (TIFFSizeProc) ig->sizecb : (TIFFSizeProc) sizeproc,
1468 (TIFFMapFileProc) comp_mmap,
1469 (TIFFUnmapFileProc) comp_munmap);
1474 mm_log((1, "i_writetiff_wiol: Unable to open tif file for writing\n"));
1475 i_push_error(0, "Could not create TIFF object");
1476 TIFFSetErrorHandler(old_handler);
1480 if (!i_writetiff_low(tif, img)) {
1482 TIFFSetErrorHandler(old_handler);
1486 (void) TIFFClose(tif);
1487 TIFFSetErrorHandler(old_handler);
1495 =item i_writetiff_wiol_faxable(i_img *, io_glue *)
1497 Stores an image in the iolayer object in faxable tiff format.
1499 im - image object to write out
1500 ig - io_object that defines source to write to
1502 Note, this may be rewritten to use to simply be a call to a
1503 lower-level function that gives more options for writing tiff at some
1510 i_writetiff_wiol_faxable(i_img *im, io_glue *ig, int fine) {
1512 TIFFErrorHandler old_handler;
1514 old_handler = TIFFSetErrorHandler(error_handler);
1517 mm_log((1, "i_writetiff_wiol(img %p, ig %p)\n", im, ig));
1519 /* FIXME: Enable the mmap interface */
1521 tif = TIFFClientOpen("No name",
1524 (TIFFReadWriteProc) ig->readcb,
1525 (TIFFReadWriteProc) ig->writecb,
1526 (TIFFSeekProc) comp_seek,
1527 (TIFFCloseProc) ig->closecb,
1528 ig->sizecb ? (TIFFSizeProc) ig->sizecb : (TIFFSizeProc) sizeproc,
1529 (TIFFMapFileProc) comp_mmap,
1530 (TIFFUnmapFileProc) comp_munmap);
1535 mm_log((1, "i_writetiff_wiol: Unable to open tif file for writing\n"));
1536 i_push_error(0, "Could not create TIFF object");
1537 TIFFSetErrorHandler(old_handler);
1541 if (!i_writetiff_low_faxable(tif, im, fine)) {
1543 TIFFSetErrorHandler(old_handler);
1547 (void) TIFFClose(tif);
1548 TIFFSetErrorHandler(old_handler);
1553 static int save_tiff_tags(TIFF *tif, i_img *im) {
1556 for (i = 0; i < text_tag_count; ++i) {
1558 if (i_tags_find(&im->tags, text_tag_names[i].name, 0, &entry)) {
1559 if (!TIFFSetField(tif, text_tag_names[i].tag,
1560 im->tags.tags[entry].data)) {
1561 i_push_errorf(0, "cannot save %s to TIFF", text_tag_names[i].name);
1572 unpack_4bit_to(unsigned char *dest, const unsigned char *src,
1573 size_t src_byte_count) {
1574 while (src_byte_count > 0) {
1575 *dest++ = *src >> 4;
1576 *dest++ = *src++ & 0xf;
1581 static void pack_4bit_to(unsigned char *dest, const unsigned char *src,
1582 i_img_dim pixel_count) {
1584 while (i < pixel_count) {
1586 *dest = *src++ << 4;
1596 =item fallback_rgb_channels
1598 Calculate the number of output channels when we fallback to the RGBA
1599 family of functions.
1605 fallback_rgb_channels(TIFF *tif, i_img_dim width, i_img_dim height, int *channels, int *alpha_chan) {
1611 TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &in_channels);
1612 TIFFGetFieldDefaulted(tif, TIFFTAG_PHOTOMETRIC, &photometric);
1614 switch (photometric) {
1615 case PHOTOMETRIC_SEPARATED:
1619 case PHOTOMETRIC_MINISWHITE:
1620 case PHOTOMETRIC_MINISBLACK:
1621 /* the TIFF RGBA functions expand single channel grey into RGB,
1622 so reduce it, we move the alpha channel into the right place
1631 /* TIFF images can have more than one alpha channel, but Imager can't
1632 this ignores the possibility of 2 channel images with 2 alpha,
1633 but there's not much I can do about that */
1635 if (TIFFGetField(tif, TIFFTAG_EXTRASAMPLES, &extra_count, &extras)
1637 *alpha_chan = (*channels)++;
1642 make_rgb(TIFF *tif, i_img_dim width, i_img_dim height, int *alpha_chan) {
1645 fallback_rgb_channels(tif, width, height, &channels, alpha_chan);
1647 return i_img_8_new(width, height, channels);
1651 read_one_rgb_lines(TIFF *tif, i_img_dim width, i_img_dim height, int allow_incomplete) {
1653 uint32* raster = NULL;
1654 uint32 rowsperstrip, row;
1659 im = make_rgb(tif, width, height, &alpha_chan);
1663 rc = TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
1664 mm_log((1, "i_readtiff_wiol: rowsperstrip=%d rc = %d\n", rowsperstrip, rc));
1666 if (rc != 1 || rowsperstrip==-1) {
1667 rowsperstrip = height;
1670 raster = (uint32*)_TIFFmalloc(width * rowsperstrip * sizeof (uint32));
1673 i_push_error(0, "No space for raster buffer");
1677 line_buf = mymalloc(sizeof(i_color) * width);
1679 for( row = 0; row < height; row += rowsperstrip ) {
1680 uint32 newrows, i_row;
1682 if (!TIFFReadRGBAStrip(tif, row, raster)) {
1683 if (allow_incomplete) {
1684 i_tags_setn(&im->tags, "i_lines_read", row);
1685 i_tags_setn(&im->tags, "i_incomplete", 1);
1689 i_push_error(0, "could not read TIFF image strip");
1696 newrows = (row+rowsperstrip > height) ? height-row : rowsperstrip;
1697 mm_log((1, "newrows=%d\n", newrows));
1699 for( i_row = 0; i_row < newrows; i_row++ ) {
1701 i_color *outp = line_buf;
1703 for(x = 0; x<width; x++) {
1704 uint32 temp = raster[x+width*(newrows-i_row-1)];
1705 outp->rgba.r = TIFFGetR(temp);
1706 outp->rgba.g = TIFFGetG(temp);
1707 outp->rgba.b = TIFFGetB(temp);
1710 /* the libtiff RGBA code expands greyscale into RGBA, so put the
1711 alpha in the right place and scale it */
1713 outp->channel[alpha_chan] = TIFFGetA(temp);
1714 if (outp->channel[alpha_chan]) {
1715 for (ch = 0; ch < alpha_chan; ++ch) {
1716 outp->channel[ch] = outp->channel[ch] * 255 / outp->channel[alpha_chan];
1723 i_plin(im, 0, width, i_row+row, line_buf);
1733 /* adapted from libtiff
1735 libtiff's TIFFReadRGBATile succeeds even when asked to read an
1736 invalid tile, which means we have no way of knowing whether the data
1737 we received from it is valid or not.
1739 So the caller here has set stoponerror to 1 so that
1740 TIFFRGBAImageGet() will fail.
1742 read_one_rgb_tiled() then takes that into account for i_incomplete
1746 myTIFFReadRGBATile(TIFFRGBAImage *img, uint32 col, uint32 row, uint32 * raster)
1750 uint32 tile_xsize, tile_ysize;
1751 uint32 read_xsize, read_ysize;
1755 * Verify that our request is legal - on a tile file, and on a
1759 TIFFGetFieldDefaulted(img->tif, TIFFTAG_TILEWIDTH, &tile_xsize);
1760 TIFFGetFieldDefaulted(img->tif, TIFFTAG_TILELENGTH, &tile_ysize);
1761 if( (col % tile_xsize) != 0 || (row % tile_ysize) != 0 )
1763 i_push_errorf(0, "Row/col passed to myTIFFReadRGBATile() must be top"
1764 "left corner of a tile.");
1769 * The TIFFRGBAImageGet() function doesn't allow us to get off the
1770 * edge of the image, even to fill an otherwise valid tile. So we
1771 * figure out how much we can read, and fix up the tile buffer to
1772 * a full tile configuration afterwards.
1775 if( row + tile_ysize > img->height )
1776 read_ysize = img->height - row;
1778 read_ysize = tile_ysize;
1780 if( col + tile_xsize > img->width )
1781 read_xsize = img->width - col;
1783 read_xsize = tile_xsize;
1786 * Read the chunk of imagery.
1789 img->row_offset = row;
1790 img->col_offset = col;
1792 ok = TIFFRGBAImageGet(img, raster, read_xsize, read_ysize );
1795 * If our read was incomplete we will need to fix up the tile by
1796 * shifting the data around as if a full tile of data is being returned.
1798 * This is all the more complicated because the image is organized in
1799 * bottom to top format.
1802 if( read_xsize == tile_xsize && read_ysize == tile_ysize )
1805 for( i_row = 0; i_row < read_ysize; i_row++ ) {
1806 memmove( raster + (tile_ysize - i_row - 1) * tile_xsize,
1807 raster + (read_ysize - i_row - 1) * read_xsize,
1808 read_xsize * sizeof(uint32) );
1809 _TIFFmemset( raster + (tile_ysize - i_row - 1) * tile_xsize+read_xsize,
1810 0, sizeof(uint32) * (tile_xsize - read_xsize) );
1813 for( i_row = read_ysize; i_row < tile_ysize; i_row++ ) {
1814 _TIFFmemset( raster + (tile_ysize - i_row - 1) * tile_xsize,
1815 0, sizeof(uint32) * tile_xsize );
1822 read_one_rgb_tiled(TIFF *tif, i_img_dim width, i_img_dim height, int allow_incomplete) {
1824 uint32* raster = NULL;
1827 uint32 tile_width, tile_height;
1828 unsigned long pixels = 0;
1829 char emsg[1024] = "";
1834 im = make_rgb(tif, width, height, &alpha_chan);
1838 if (!TIFFRGBAImageOK(tif, emsg)
1839 || !TIFFRGBAImageBegin(&img, tif, 1, emsg)) {
1840 i_push_error(0, emsg);
1845 TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tile_width);
1846 TIFFGetField(tif, TIFFTAG_TILELENGTH, &tile_height);
1847 mm_log((1, "i_readtiff_wiol: tile_width=%d, tile_height=%d\n", tile_width, tile_height));
1849 raster = (uint32*)_TIFFmalloc(tile_width * tile_height * sizeof (uint32));
1852 i_push_error(0, "No space for raster buffer");
1853 TIFFRGBAImageEnd(&img);
1856 line = mymalloc(tile_width * sizeof(i_color));
1858 for( row = 0; row < height; row += tile_height ) {
1859 for( col = 0; col < width; col += tile_width ) {
1861 /* Read the tile into an RGBA array */
1862 if (myTIFFReadRGBATile(&img, col, row, raster)) {
1864 uint32 newrows = (row+tile_height > height) ? height-row : tile_height;
1865 uint32 newcols = (col+tile_width > width ) ? width-col : tile_width;
1867 mm_log((1, "i_readtiff_wiol: tile(%d, %d) newcols=%d newrows=%d\n", col, row, newcols, newrows));
1868 for( i_row = 0; i_row < newrows; i_row++ ) {
1869 i_color *outp = line;
1870 for(x = 0; x < newcols; x++) {
1871 uint32 temp = raster[x+tile_width*(tile_height-i_row-1)];
1872 outp->rgba.r = TIFFGetR(temp);
1873 outp->rgba.g = TIFFGetG(temp);
1874 outp->rgba.b = TIFFGetB(temp);
1875 outp->rgba.a = TIFFGetA(temp);
1878 /* the libtiff RGBA code expands greyscale into RGBA, so put the
1879 alpha in the right place and scale it */
1881 outp->channel[alpha_chan] = TIFFGetA(temp);
1883 if (outp->channel[alpha_chan]) {
1884 for (ch = 0; ch < alpha_chan; ++ch) {
1885 outp->channel[ch] = outp->channel[ch] * 255 / outp->channel[alpha_chan];
1892 i_plin(im, col, col+newcols, row+i_row, line);
1894 pixels += newrows * newcols;
1897 if (allow_incomplete) {
1909 i_push_error(0, "TIFF: No image data could be read from the image");
1913 /* incomplete image */
1914 i_tags_setn(&im->tags, "i_incomplete", 1);
1915 i_tags_setn(&im->tags, "i_lines_read", pixels / width);
1919 TIFFRGBAImageEnd(&img);
1927 TIFFRGBAImageEnd(&img);
1933 i_tiff_libversion(void) {
1934 return TIFFGetVersion();
1938 setup_paletted(read_state_t *state) {
1941 int color_count = 1 << state->bits_per_sample;
1943 state->img = i_img_pal_new(state->width, state->height, 3, 256);
1947 /* setup the color map */
1948 if (!TIFFGetField(state->tif, TIFFTAG_COLORMAP, maps+0, maps+1, maps+2)) {
1949 i_push_error(0, "Cannot get colormap for paletted image");
1950 i_img_destroy(state->img);
1953 for (i = 0; i < color_count; ++i) {
1955 for (ch = 0; ch < 3; ++ch) {
1956 c.channel[ch] = Sample16To8(maps[ch][i]);
1958 i_addcolors(state->img, &c, 1);
1965 tile_contig_getter(read_state_t *state, read_putter_t putter) {
1966 uint32 tile_width, tile_height;
1967 uint32 this_tile_height, this_tile_width;
1968 uint32 rows_left, cols_left;
1971 state->raster = _TIFFmalloc(TIFFTileSize(state->tif));
1972 if (!state->raster) {
1973 i_push_error(0, "tiff: Out of memory allocating tile buffer");
1977 TIFFGetField(state->tif, TIFFTAG_TILEWIDTH, &tile_width);
1978 TIFFGetField(state->tif, TIFFTAG_TILELENGTH, &tile_height);
1979 rows_left = state->height;
1980 for (y = 0; y < state->height; y += this_tile_height) {
1981 this_tile_height = rows_left > tile_height ? tile_height : rows_left;
1983 cols_left = state->width;
1984 for (x = 0; x < state->width; x += this_tile_width) {
1985 this_tile_width = cols_left > tile_width ? tile_width : cols_left;
1987 if (TIFFReadTile(state->tif,
1990 if (!state->allow_incomplete) {
1995 putter(state, x, y, this_tile_width, this_tile_height, tile_width - this_tile_width);
1998 cols_left -= this_tile_width;
2001 rows_left -= this_tile_height;
2008 strip_contig_getter(read_state_t *state, read_putter_t putter) {
2009 uint32 rows_per_strip;
2010 tsize_t strip_size = TIFFStripSize(state->tif);
2011 uint32 y, strip_rows, rows_left;
2013 state->raster = _TIFFmalloc(strip_size);
2014 if (!state->raster) {
2015 i_push_error(0, "tiff: Out of memory allocating strip buffer");
2019 TIFFGetFieldDefaulted(state->tif, TIFFTAG_ROWSPERSTRIP, &rows_per_strip);
2020 rows_left = state->height;
2021 for (y = 0; y < state->height; y += strip_rows) {
2022 strip_rows = rows_left > rows_per_strip ? rows_per_strip : rows_left;
2023 if (TIFFReadEncodedStrip(state->tif,
2024 TIFFComputeStrip(state->tif, y, 0),
2027 if (!state->allow_incomplete)
2031 putter(state, 0, y, state->width, strip_rows, 0);
2033 rows_left -= strip_rows;
2040 paletted_putter8(read_state_t *state, i_img_dim x, i_img_dim y, i_img_dim width, i_img_dim height, int extras) {
2041 unsigned char *p = state->raster;
2043 state->pixels_read += width * height;
2044 while (height > 0) {
2045 i_ppal(state->img, x, x + width, y, p);
2046 p += width + extras;
2055 paletted_putter4(read_state_t *state, i_img_dim x, i_img_dim y, i_img_dim width, i_img_dim height, int extras) {
2056 uint32 img_line_size = (width + 1) / 2;
2057 uint32 skip_line_size = (width + extras + 1) / 2;
2058 unsigned char *p = state->raster;
2060 if (!state->line_buf)
2061 state->line_buf = mymalloc(state->width);
2063 state->pixels_read += width * height;
2064 while (height > 0) {
2065 unpack_4bit_to(state->line_buf, p, img_line_size);
2066 i_ppal(state->img, x, x + width, y, state->line_buf);
2067 p += skip_line_size;
2076 rgb_channels(read_state_t *state, int *out_channels) {
2082 state->alpha_chan = 0;
2083 state->scale_alpha = 0;
2086 if (state->samples_per_pixel == 3)
2089 if (!TIFFGetField(state->tif, TIFFTAG_EXTRASAMPLES, &extra_count, &extras)) {
2090 mm_log((1, "tiff: samples != 3 but no extra samples tag\n"));
2095 mm_log((1, "tiff: samples != 3 but no extra samples listed"));
2100 state->alpha_chan = 3;
2102 case EXTRASAMPLE_UNSPECIFIED:
2103 case EXTRASAMPLE_ASSOCALPHA:
2104 state->scale_alpha = 1;
2107 case EXTRASAMPLE_UNASSALPHA:
2108 state->scale_alpha = 0;
2112 mm_log((1, "tiff: unknown extra sample type %d, treating as assoc alpha\n",
2114 state->scale_alpha = 1;
2117 mm_log((1, "tiff alpha channel %d scale %d\n", state->alpha_chan, state->scale_alpha));
2121 grey_channels(read_state_t *state, int *out_channels) {
2127 state->alpha_chan = 0;
2128 state->scale_alpha = 0;
2131 if (state->samples_per_pixel == 1)
2134 if (!TIFFGetField(state->tif, TIFFTAG_EXTRASAMPLES, &extra_count, &extras)) {
2135 mm_log((1, "tiff: samples != 1 but no extra samples tag\n"));
2140 mm_log((1, "tiff: samples != 1 but no extra samples listed"));
2145 state->alpha_chan = 1;
2147 case EXTRASAMPLE_UNSPECIFIED:
2148 case EXTRASAMPLE_ASSOCALPHA:
2149 state->scale_alpha = 1;
2152 case EXTRASAMPLE_UNASSALPHA:
2153 state->scale_alpha = 0;
2157 mm_log((1, "tiff: unknown extra sample type %d, treating as assoc alpha\n",
2159 state->scale_alpha = 1;
2165 setup_16_rgb(read_state_t *state) {
2168 rgb_channels(state, &out_channels);
2170 state->img = i_img_16_new(state->width, state->height, out_channels);
2173 state->line_buf = mymalloc(sizeof(unsigned) * state->width * out_channels);
2179 setup_16_grey(read_state_t *state) {
2182 grey_channels(state, &out_channels);
2184 state->img = i_img_16_new(state->width, state->height, out_channels);
2187 state->line_buf = mymalloc(sizeof(unsigned) * state->width * out_channels);
2193 putter_16(read_state_t *state, i_img_dim x, i_img_dim y, i_img_dim width, i_img_dim height,
2195 uint16 *p = state->raster;
2196 int out_chan = state->img->channels;
2198 state->pixels_read += width * height;
2199 while (height > 0) {
2202 unsigned *outp = state->line_buf;
2204 for (i = 0; i < width; ++i) {
2205 for (ch = 0; ch < out_chan; ++ch) {
2208 if (state->alpha_chan && state->scale_alpha && outp[state->alpha_chan]) {
2209 for (ch = 0; ch < state->alpha_chan; ++ch) {
2210 int result = 0.5 + (outp[ch] * 65535.0 / outp[state->alpha_chan]);
2211 outp[ch] = CLAMP16(result);
2214 p += state->samples_per_pixel;
2218 i_psamp_bits(state->img, x, x + width, y, state->line_buf, NULL, out_chan, 16);
2220 p += row_extras * state->samples_per_pixel;
2229 setup_8_rgb(read_state_t *state) {
2232 rgb_channels(state, &out_channels);
2234 state->img = i_img_8_new(state->width, state->height, out_channels);
2237 state->line_buf = mymalloc(sizeof(unsigned) * state->width * out_channels);
2243 setup_8_grey(read_state_t *state) {
2246 grey_channels(state, &out_channels);
2248 state->img = i_img_8_new(state->width, state->height, out_channels);
2251 state->line_buf = mymalloc(sizeof(i_color) * state->width * out_channels);
2257 putter_8(read_state_t *state, i_img_dim x, i_img_dim y, i_img_dim width, i_img_dim height,
2259 unsigned char *p = state->raster;
2260 int out_chan = state->img->channels;
2262 state->pixels_read += width * height;
2263 while (height > 0) {
2266 i_color *outp = state->line_buf;
2268 for (i = 0; i < width; ++i) {
2269 for (ch = 0; ch < out_chan; ++ch) {
2270 outp->channel[ch] = p[ch];
2272 if (state->alpha_chan && state->scale_alpha
2273 && outp->channel[state->alpha_chan]) {
2274 for (ch = 0; ch < state->alpha_chan; ++ch) {
2275 int result = (outp->channel[ch] * 255 + 127) / outp->channel[state->alpha_chan];
2277 outp->channel[ch] = CLAMP8(result);
2280 p += state->samples_per_pixel;
2284 i_plin(state->img, x, x + width, y, state->line_buf);
2286 p += row_extras * state->samples_per_pixel;
2295 setup_32_rgb(read_state_t *state) {
2298 rgb_channels(state, &out_channels);
2300 state->img = i_img_double_new(state->width, state->height, out_channels);
2303 state->line_buf = mymalloc(sizeof(i_fcolor) * state->width);
2309 setup_32_grey(read_state_t *state) {
2312 grey_channels(state, &out_channels);
2314 state->img = i_img_double_new(state->width, state->height, out_channels);
2317 state->line_buf = mymalloc(sizeof(i_fcolor) * state->width);
2323 putter_32(read_state_t *state, i_img_dim x, i_img_dim y, i_img_dim width, i_img_dim height,
2325 uint32 *p = state->raster;
2326 int out_chan = state->img->channels;
2328 state->pixels_read += width * height;
2329 while (height > 0) {
2332 i_fcolor *outp = state->line_buf;
2334 for (i = 0; i < width; ++i) {
2335 for (ch = 0; ch < out_chan; ++ch) {
2336 outp->channel[ch] = p[ch] / 4294967295.0;
2338 if (state->alpha_chan && state->scale_alpha && outp->channel[state->alpha_chan]) {
2339 for (ch = 0; ch < state->alpha_chan; ++ch)
2340 outp->channel[ch] /= outp->channel[state->alpha_chan];
2342 p += state->samples_per_pixel;
2346 i_plinf(state->img, x, x + width, y, state->line_buf);
2348 p += row_extras * state->samples_per_pixel;
2357 setup_bilevel(read_state_t *state) {
2358 i_color black, white;
2359 state->img = i_img_pal_new(state->width, state->height, 1, 256);
2362 black.channel[0] = black.channel[1] = black.channel[2] =
2363 black.channel[3] = 0;
2364 white.channel[0] = white.channel[1] = white.channel[2] =
2365 white.channel[3] = 255;
2366 if (state->photometric == PHOTOMETRIC_MINISBLACK) {
2367 i_addcolors(state->img, &black, 1);
2368 i_addcolors(state->img, &white, 1);
2371 i_addcolors(state->img, &white, 1);
2372 i_addcolors(state->img, &black, 1);
2374 state->line_buf = mymalloc(state->width);
2380 putter_bilevel(read_state_t *state, i_img_dim x, i_img_dim y, i_img_dim width, i_img_dim height,
2382 unsigned char *line_in = state->raster;
2383 size_t line_size = (width + row_extras + 7) / 8;
2385 /* tifflib returns the bits in MSB2LSB order even when the file is
2386 in LSB2MSB, so we only need to handle MSB2LSB */
2387 state->pixels_read += width * height;
2388 while (height > 0) {
2390 unsigned char *outp = state->line_buf;
2391 unsigned char *inp = line_in;
2392 unsigned mask = 0x80;
2394 for (i = 0; i < width; ++i) {
2395 *outp++ = *inp & mask ? 1 : 0;
2403 i_ppal(state->img, x, x + width, y, state->line_buf);
2405 line_in += line_size;
2414 cmyk_channels(read_state_t *state, int *out_channels) {
2420 state->alpha_chan = 0;
2421 state->scale_alpha = 0;
2424 if (state->samples_per_pixel == 4)
2427 if (!TIFFGetField(state->tif, TIFFTAG_EXTRASAMPLES, &extra_count, &extras)) {
2428 mm_log((1, "tiff: CMYK samples != 4 but no extra samples tag\n"));
2433 mm_log((1, "tiff: CMYK samples != 4 but no extra samples listed"));
2438 state->alpha_chan = 4;
2440 case EXTRASAMPLE_UNSPECIFIED:
2441 case EXTRASAMPLE_ASSOCALPHA:
2442 state->scale_alpha = 1;
2445 case EXTRASAMPLE_UNASSALPHA:
2446 state->scale_alpha = 0;
2450 mm_log((1, "tiff: unknown extra sample type %d, treating as assoc alpha\n",
2452 state->scale_alpha = 1;
2458 setup_cmyk8(read_state_t *state) {
2461 cmyk_channels(state, &channels);
2462 state->img = i_img_8_new(state->width, state->height, channels);
2464 state->line_buf = mymalloc(sizeof(i_color) * state->width);
2470 putter_cmyk8(read_state_t *state, i_img_dim x, i_img_dim y, i_img_dim width, i_img_dim height,
2472 unsigned char *p = state->raster;
2474 state->pixels_read += width * height;
2475 while (height > 0) {
2478 i_color *outp = state->line_buf;
2480 for (i = 0; i < width; ++i) {
2481 unsigned char c, m, y, k;
2486 outp->rgba.r = (k * (255 - c)) / 255;
2487 outp->rgba.g = (k * (255 - m)) / 255;
2488 outp->rgba.b = (k * (255 - y)) / 255;
2489 if (state->alpha_chan) {
2490 outp->rgba.a = p[state->alpha_chan];
2491 if (state->scale_alpha
2493 for (ch = 0; ch < 3; ++ch) {
2494 int result = (outp->channel[ch] * 255 + 127) / outp->rgba.a;
2495 outp->channel[ch] = CLAMP8(result);
2499 p += state->samples_per_pixel;
2503 i_plin(state->img, x, x + width, y, state->line_buf);
2505 p += row_extras * state->samples_per_pixel;
2514 setup_cmyk16(read_state_t *state) {
2517 cmyk_channels(state, &channels);
2518 state->img = i_img_16_new(state->width, state->height, channels);
2520 state->line_buf = mymalloc(sizeof(unsigned) * state->width * channels);
2526 putter_cmyk16(read_state_t *state, i_img_dim x, i_img_dim y, i_img_dim width, i_img_dim height,
2528 uint16 *p = state->raster;
2529 int out_chan = state->img->channels;
2531 mm_log((4, "putter_cmyk16(%p, %d, %d, %d, %d, %d)\n", x, y, width, height, row_extras));
2533 state->pixels_read += width * height;
2534 while (height > 0) {
2537 unsigned *outp = state->line_buf;
2539 for (i = 0; i < width; ++i) {
2540 unsigned c, m, y, k;
2545 outp[0] = (k * (65535U - c)) / 65535U;
2546 outp[1] = (k * (65535U - m)) / 65535U;
2547 outp[2] = (k * (65535U - y)) / 65535U;
2548 if (state->alpha_chan) {
2549 outp[3] = p[state->alpha_chan];
2550 if (state->scale_alpha
2552 for (ch = 0; ch < 3; ++ch) {
2553 int result = (outp[ch] * 65535 + 32767) / outp[3];
2554 outp[3] = CLAMP16(result);
2558 p += state->samples_per_pixel;
2562 i_psamp_bits(state->img, x, x + width, y, state->line_buf, NULL, out_chan, 16);
2564 p += row_extras * state->samples_per_pixel;
2574 Older versions of tifflib we support don't define this, so define it
2577 If you want this detection to do anything useful, use a newer
2581 #if TIFFLIB_VERSION < 20031121
2584 TIFFIsCODECConfigured(uint16 scheme) {
2586 /* these schemes are all shipped with tifflib */
2587 case COMPRESSION_NONE:
2588 case COMPRESSION_PACKBITS:
2589 case COMPRESSION_CCITTRLE:
2590 case COMPRESSION_CCITTRLEW:
2591 case COMPRESSION_CCITTFAX3:
2592 case COMPRESSION_CCITTFAX4:
2595 /* these require external library support */
2597 case COMPRESSION_JPEG:
2598 case COMPRESSION_LZW:
2599 case COMPRESSION_DEFLATE:
2600 case COMPRESSION_ADOBE_DEFLATE:
2608 myTIFFIsCODECConfigured(uint16 scheme) {
2609 #if TIFFLIB_VERSION < 20040724
2610 if (scheme == COMPRESSION_LZW)
2614 return TIFFIsCODECConfigured(scheme);
2622 Arnar M. Hrafnkelsson <addi@umich.edu>, Tony Cook <tonyc@cpan.org>