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;
537 old_handler = TIFFSetErrorHandler(error_handler);
538 old_warn_handler = TIFFSetWarningHandler(warn_handler);
542 /* Add code to get the filename info from the iolayer */
543 /* Also add code to check for mmapped code */
545 mm_log((1, "i_readtiff_wiol(ig %p, allow_incomplete %d, page %d)\n", ig, allow_incomplete, page));
547 tif = TIFFClientOpen("(Iolayer)",
550 (TIFFReadWriteProc) ig->readcb,
551 (TIFFReadWriteProc) ig->writecb,
552 (TIFFSeekProc) comp_seek,
553 (TIFFCloseProc) ig->closecb,
554 ig->sizecb ? (TIFFSizeProc) ig->sizecb : (TIFFSizeProc) sizeproc,
555 (TIFFMapFileProc) comp_mmap,
556 (TIFFUnmapFileProc) comp_munmap);
559 mm_log((1, "i_readtiff_wiol: Unable to open tif file\n"));
560 i_push_error(0, "Error opening file");
561 TIFFSetErrorHandler(old_handler);
562 TIFFSetWarningHandler(old_warn_handler);
566 for (current_page = 0; current_page < page; ++current_page) {
567 if (!TIFFReadDirectory(tif)) {
568 mm_log((1, "i_readtiff_wiol: Unable to switch to directory %d\n", page));
569 i_push_errorf(0, "could not switch to page %d", page);
570 TIFFSetErrorHandler(old_handler);
571 TIFFSetWarningHandler(old_warn_handler);
577 im = read_one_tiff(tif, allow_incomplete);
579 if (TIFFLastDirectory(tif)) mm_log((1, "Last directory of tiff file\n"));
580 TIFFSetErrorHandler(old_handler);
581 TIFFSetWarningHandler(old_warn_handler);
587 =item i_readtiff_multi_wiol(ig, *count)
589 Reads multiple images from a TIFF.
594 i_readtiff_multi_wiol(io_glue *ig, int *count) {
596 TIFFErrorHandler old_handler;
597 TIFFErrorHandler old_warn_handler;
598 i_img **results = NULL;
599 int result_alloc = 0;
603 old_handler = TIFFSetErrorHandler(error_handler);
604 old_warn_handler = TIFFSetWarningHandler(warn_handler);
608 /* Add code to get the filename info from the iolayer */
609 /* Also add code to check for mmapped code */
611 mm_log((1, "i_readtiff_wiol(ig %p, length %d)\n", ig));
613 tif = TIFFClientOpen("(Iolayer)",
616 (TIFFReadWriteProc) ig->readcb,
617 (TIFFReadWriteProc) ig->writecb,
618 (TIFFSeekProc) comp_seek,
619 (TIFFCloseProc) ig->closecb,
620 ig->sizecb ? (TIFFSizeProc) ig->sizecb : (TIFFSizeProc) sizeproc,
621 (TIFFMapFileProc) comp_mmap,
622 (TIFFUnmapFileProc) comp_munmap);
625 mm_log((1, "i_readtiff_wiol: Unable to open tif file\n"));
626 i_push_error(0, "Error opening file");
627 TIFFSetErrorHandler(old_handler);
628 TIFFSetWarningHandler(old_warn_handler);
634 i_img *im = read_one_tiff(tif, 0);
637 if (++*count > result_alloc) {
638 if (result_alloc == 0) {
640 results = mymalloc(result_alloc * sizeof(i_img *));
645 newresults = myrealloc(results, result_alloc * sizeof(i_img *));
647 i_img_destroy(im); /* don't leak it */
650 results = newresults;
653 results[*count-1] = im;
654 } while (TIFFReadDirectory(tif));
656 TIFFSetWarningHandler(old_warn_handler);
657 TIFFSetErrorHandler(old_handler);
663 i_writetiff_low_faxable(TIFF *tif, i_img *im, int fine) {
664 uint32 width, height;
665 unsigned char *linebuf = NULL;
670 float vres = fine ? 196 : 98;
676 if (width != im->xsize || height != im->ysize) {
677 i_push_error(0, "image too large for TIFF");
681 switch (im->channels) {
691 /* This means a colorspace we don't handle yet */
692 mm_log((1, "i_writetiff_wiol_faxable: don't handle %d channel images.\n", im->channels));
696 /* Add code to get the filename info from the iolayer */
697 /* Also add code to check for mmapped code */
700 mm_log((1, "i_writetiff_wiol_faxable: width=%d, height=%d, channels=%d\n", width, height, im->channels));
702 if (!TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width) )
703 { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField width=%d failed\n", width)); return 0; }
704 if (!TIFFSetField(tif, TIFFTAG_IMAGELENGTH, height) )
705 { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField length=%d failed\n", height)); return 0; }
706 if (!TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1))
707 { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField samplesperpixel=1 failed\n")); return 0; }
708 if (!TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT))
709 { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField Orientation=topleft\n")); return 0; }
710 if (!TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 1) )
711 { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField bitpersample=1\n")); return 0; }
712 if (!TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG))
713 { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField planarconfig\n")); return 0; }
714 if (!TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISWHITE))
715 { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField photometric=%d\n", PHOTOMETRIC_MINISBLACK)); return 0; }
716 if (!TIFFSetField(tif, TIFFTAG_COMPRESSION, 3))
717 { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField compression=3\n")); return 0; }
719 linebuf = (unsigned char *)_TIFFmalloc( TIFFScanlineSize(tif) );
721 if (!TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, TIFFDefaultStripSize(tif, -1))) {
722 mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField rowsperstrip=-1\n")); return 0; }
724 TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
725 TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rc);
727 mm_log((1, "i_writetiff_wiol_faxable: TIFFGetField rowsperstrip=%d\n", rowsperstrip));
728 mm_log((1, "i_writetiff_wiol_faxable: TIFFGetField scanlinesize=%d\n", TIFFScanlineSize(tif) ));
729 mm_log((1, "i_writetiff_wiol_faxable: TIFFGetField planarconfig=%d == %d\n", rc, PLANARCONFIG_CONTIG));
731 if (!TIFFSetField(tif, TIFFTAG_XRESOLUTION, (float)204))
732 { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField Xresolution=204\n")); return 0; }
733 if (!TIFFSetField(tif, TIFFTAG_YRESOLUTION, vres))
734 { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField Yresolution=196\n")); return 0; }
735 if (!TIFFSetField(tif, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH)) {
736 mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField ResolutionUnit=%d\n", RESUNIT_INCH)); return 0;
739 if (!save_tiff_tags(tif, im)) {
743 for (y=0; y<height; y++) {
745 for(x=0; x<width; x+=8) {
750 linebuf[linebufpos]=0;
751 bits = width-x; if(bits>8) bits=8;
752 i_gsamp(im, x, x+8, y, luma, &luma_chan, 1);
753 for(bitpos=0;bitpos<bits;bitpos++) {
754 linebuf[linebufpos] |= ((luma[bitpos] < 128) ? bitval : 0);
759 if (TIFFWriteScanline(tif, linebuf, y, 0) < 0) {
760 mm_log((1, "i_writetiff_wiol_faxable: TIFFWriteScanline failed.\n"));
764 if (linebuf) _TIFFfree(linebuf);
770 find_compression(char const *name, uint16 *compress) {
773 for (i = 0; i < compress_value_count; ++i) {
774 if (strcmp(compress_values[i].name, name) == 0) {
775 *compress = (uint16)compress_values[i].tag;
779 *compress = COMPRESSION_NONE;
785 get_compression(i_img *im, uint16 def_compress) {
789 if (i_tags_find(&im->tags, "tiff_compression", 0, &entry)
790 && im->tags.tags[entry].data) {
792 if (find_compression(im->tags.tags[entry].data, &compress)
793 && myTIFFIsCODECConfigured(compress))
796 if (i_tags_get_int(&im->tags, "tiff_compression", 0, &value)) {
797 if ((uint16)value == value
798 && myTIFFIsCODECConfigured((uint16)value))
799 return (uint16)value;
806 i_tiff_has_compression(const char *name) {
809 if (!find_compression(name, &compress))
812 return myTIFFIsCODECConfigured(compress);
816 set_base_tags(TIFF *tif, i_img *im, uint16 compress, uint16 photometric,
817 uint16 bits_per_sample, uint16 samples_per_pixel) {
820 int got_xres, got_yres;
823 if (!TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, im->xsize)) {
824 i_push_error(0, "write TIFF: setting width tag");
827 if (!TIFFSetField(tif, TIFFTAG_IMAGELENGTH, im->ysize)) {
828 i_push_error(0, "write TIFF: setting length tag");
831 if (!TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT)) {
832 i_push_error(0, "write TIFF: setting orientation tag");
835 if (!TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG)) {
836 i_push_error(0, "write TIFF: setting planar configuration tag");
839 if (!TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, photometric)) {
840 i_push_error(0, "write TIFF: setting photometric tag");
843 if (!TIFFSetField(tif, TIFFTAG_COMPRESSION, compress)) {
844 i_push_error(0, "write TIFF: setting compression tag");
847 if (!TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bits_per_sample)) {
848 i_push_error(0, "write TIFF: setting bits per sample tag");
851 if (!TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, samples_per_pixel)) {
852 i_push_error(0, "write TIFF: setting samples per pixel tag");
856 got_xres = i_tags_get_float(&im->tags, "i_xres", 0, &xres);
857 got_yres = i_tags_get_float(&im->tags, "i_yres", 0, &yres);
858 if (!i_tags_get_int(&im->tags, "i_aspect_only", 0,&aspect_only))
860 if (!i_tags_get_int(&im->tags, "tiff_resolutionunit", 0, &resunit))
861 resunit = RESUNIT_INCH;
862 if (got_xres || got_yres) {
868 resunit = RESUNIT_NONE;
871 if (resunit == RESUNIT_CENTIMETER) {
876 resunit = RESUNIT_INCH;
879 if (!TIFFSetField(tif, TIFFTAG_XRESOLUTION, (float)xres)) {
880 i_push_error(0, "write TIFF: setting xresolution tag");
883 if (!TIFFSetField(tif, TIFFTAG_YRESOLUTION, (float)yres)) {
884 i_push_error(0, "write TIFF: setting yresolution tag");
887 if (!TIFFSetField(tif, TIFFTAG_RESOLUTIONUNIT, (uint16)resunit)) {
888 i_push_error(0, "write TIFF: setting resolutionunit tag");
897 write_one_bilevel(TIFF *tif, i_img *im, int zero_is_white) {
898 uint16 compress = get_compression(im, COMPRESSION_PACKBITS);
900 unsigned char *in_row;
901 unsigned char *out_row;
906 mm_log((1, "tiff - write_one_bilevel(tif %p, im %p, zero_is_white %d)\n",
907 tif, im, zero_is_white));
909 /* ignore a silly choice */
910 if (compress == COMPRESSION_JPEG)
911 compress = COMPRESSION_PACKBITS;
914 case COMPRESSION_CCITTRLE:
915 case COMPRESSION_CCITTFAX3:
916 case COMPRESSION_CCITTFAX4:
917 /* natural fax photometric */
918 photometric = PHOTOMETRIC_MINISWHITE;
922 /* natural for most computer images */
923 photometric = PHOTOMETRIC_MINISBLACK;
927 if (!set_base_tags(tif, im, compress, photometric, 1, 1))
930 if (!TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, TIFFDefaultStripSize(tif, -1))) {
931 i_push_error(0, "write TIFF: setting rows per strip tag");
935 out_size = TIFFScanlineSize(tif);
936 out_row = (unsigned char *)_TIFFmalloc( out_size );
937 in_row = mymalloc(im->xsize);
939 invert = (photometric == PHOTOMETRIC_MINISWHITE) != (zero_is_white != 0);
941 for (y = 0; y < im->ysize; ++y) {
943 unsigned char *outp = out_row;
944 memset(out_row, 0, out_size);
945 i_gpal(im, 0, im->xsize, y, in_row);
946 for (x = 0; x < im->xsize; ++x) {
947 if (invert ? !in_row[x] : in_row[x]) {
956 if (TIFFWriteScanline(tif, out_row, y, 0) < 0) {
959 i_push_error(0, "write TIFF: write scan line failed");
971 set_palette(TIFF *tif, i_img *im, int size) {
978 colors = (uint16 *)_TIFFmalloc(sizeof(uint16) * 3 * size);
980 out[1] = colors + size;
981 out[2] = colors + 2 * size;
983 count = i_colorcount(im);
984 for (i = 0; i < count; ++i) {
985 i_getcolors(im, i, &c, 1);
986 for (ch = 0; ch < 3; ++ch)
987 out[ch][i] = c.channel[ch] * 257;
989 for (; i < size; ++i) {
990 for (ch = 0; ch < 3; ++ch)
993 if (!TIFFSetField(tif, TIFFTAG_COLORMAP, out[0], out[1], out[2])) {
995 i_push_error(0, "write TIFF: setting color map");
1004 write_one_paletted8(TIFF *tif, i_img *im) {
1005 uint16 compress = get_compression(im, COMPRESSION_PACKBITS);
1006 unsigned char *out_row;
1010 mm_log((1, "tiff - write_one_paletted8(tif %p, im %p)\n", tif, im));
1012 /* ignore a silly choice */
1013 if (compress == COMPRESSION_JPEG ||
1014 compress == COMPRESSION_CCITTRLE ||
1015 compress == COMPRESSION_CCITTFAX3 ||
1016 compress == COMPRESSION_CCITTFAX4)
1017 compress = COMPRESSION_PACKBITS;
1019 if (!TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, TIFFDefaultStripSize(tif, -1))) {
1020 i_push_error(0, "write TIFF: setting rows per strip tag");
1024 if (!set_base_tags(tif, im, compress, PHOTOMETRIC_PALETTE, 8, 1))
1027 if (!set_palette(tif, im, 256))
1030 out_size = TIFFScanlineSize(tif);
1031 out_row = (unsigned char *)_TIFFmalloc( out_size );
1033 for (y = 0; y < im->ysize; ++y) {
1034 i_gpal(im, 0, im->xsize, y, out_row);
1035 if (TIFFWriteScanline(tif, out_row, y, 0) < 0) {
1037 i_push_error(0, "write TIFF: write scan line failed");
1048 write_one_paletted4(TIFF *tif, i_img *im) {
1049 uint16 compress = get_compression(im, COMPRESSION_PACKBITS);
1050 unsigned char *in_row;
1051 unsigned char *out_row;
1055 mm_log((1, "tiff - write_one_paletted4(tif %p, im %p)\n", tif, im));
1057 /* ignore a silly choice */
1058 if (compress == COMPRESSION_JPEG ||
1059 compress == COMPRESSION_CCITTRLE ||
1060 compress == COMPRESSION_CCITTFAX3 ||
1061 compress == COMPRESSION_CCITTFAX4)
1062 compress = COMPRESSION_PACKBITS;
1064 if (!set_base_tags(tif, im, compress, PHOTOMETRIC_PALETTE, 4, 1))
1067 if (!set_palette(tif, im, 16))
1070 if (!TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, TIFFDefaultStripSize(tif, -1))) {
1071 i_push_error(0, "write TIFF: setting rows per strip tag");
1075 in_row = mymalloc(im->xsize);
1076 out_size = TIFFScanlineSize(tif);
1077 out_row = (unsigned char *)_TIFFmalloc( out_size );
1079 for (y = 0; y < im->ysize; ++y) {
1080 i_gpal(im, 0, im->xsize, y, in_row);
1081 memset(out_row, 0, out_size);
1082 pack_4bit_to(out_row, in_row, im->xsize);
1083 if (TIFFWriteScanline(tif, out_row, y, 0) < 0) {
1085 i_push_error(0, "write TIFF: write scan line failed");
1097 set_direct_tags(TIFF *tif, i_img *im, uint16 compress,
1098 uint16 bits_per_sample) {
1099 uint16 extras = EXTRASAMPLE_ASSOCALPHA;
1100 uint16 extra_count = im->channels == 2 || im->channels == 4;
1101 uint16 photometric = im->channels >= 3 ?
1102 PHOTOMETRIC_RGB : PHOTOMETRIC_MINISBLACK;
1104 if (!set_base_tags(tif, im, compress, photometric, bits_per_sample,
1110 if (!TIFFSetField(tif, TIFFTAG_EXTRASAMPLES, extra_count, &extras)) {
1111 i_push_error(0, "write TIFF: setting extra samples tag");
1116 if (compress == COMPRESSION_JPEG) {
1118 if (i_tags_get_int(&im->tags, "tiff_jpegquality", 0, &jpeg_quality)
1119 && jpeg_quality >= 0 && jpeg_quality <= 100) {
1120 if (!TIFFSetField(tif, TIFFTAG_JPEGQUALITY, jpeg_quality)) {
1121 i_push_error(0, "write TIFF: setting jpeg quality pseudo-tag");
1131 write_one_32(TIFF *tif, i_img *im) {
1132 uint16 compress = get_compression(im, COMPRESSION_PACKBITS);
1137 size_t sample_count = im->xsize * im->channels;
1138 size_t sample_index;
1140 mm_log((1, "tiff - write_one_32(tif %p, im %p)\n", tif, im));
1142 /* only 8 and 12 bit samples are supported by jpeg compression */
1143 if (compress == COMPRESSION_JPEG)
1144 compress = COMPRESSION_PACKBITS;
1146 if (!set_direct_tags(tif, im, compress, 32))
1149 in_row = mymalloc(sample_count * sizeof(unsigned));
1150 out_size = TIFFScanlineSize(tif);
1151 out_row = (uint32 *)_TIFFmalloc( out_size );
1153 for (y = 0; y < im->ysize; ++y) {
1154 if (i_gsamp_bits(im, 0, im->xsize, y, in_row, NULL, im->channels, 32) <= 0) {
1155 i_push_error(0, "Cannot read 32-bit samples");
1158 for (sample_index = 0; sample_index < sample_count; ++sample_index)
1159 out_row[sample_index] = in_row[sample_index];
1160 if (TIFFWriteScanline(tif, out_row, y, 0) < 0) {
1163 i_push_error(0, "write TIFF: write scan line failed");
1175 write_one_16(TIFF *tif, i_img *im) {
1176 uint16 compress = get_compression(im, COMPRESSION_PACKBITS);
1181 size_t sample_count = im->xsize * im->channels;
1182 size_t sample_index;
1184 mm_log((1, "tiff - write_one_16(tif %p, im %p)\n", tif, im));
1186 /* only 8 and 12 bit samples are supported by jpeg compression */
1187 if (compress == COMPRESSION_JPEG)
1188 compress = COMPRESSION_PACKBITS;
1190 if (!set_direct_tags(tif, im, compress, 16))
1193 in_row = mymalloc(sample_count * sizeof(unsigned));
1194 out_size = TIFFScanlineSize(tif);
1195 out_row = (uint16 *)_TIFFmalloc( out_size );
1197 for (y = 0; y < im->ysize; ++y) {
1198 if (i_gsamp_bits(im, 0, im->xsize, y, in_row, NULL, im->channels, 16) <= 0) {
1199 i_push_error(0, "Cannot read 16-bit samples");
1202 for (sample_index = 0; sample_index < sample_count; ++sample_index)
1203 out_row[sample_index] = in_row[sample_index];
1204 if (TIFFWriteScanline(tif, out_row, y, 0) < 0) {
1207 i_push_error(0, "write TIFF: write scan line failed");
1219 write_one_8(TIFF *tif, i_img *im) {
1220 uint16 compress = get_compression(im, COMPRESSION_PACKBITS);
1222 unsigned char *out_row;
1224 size_t sample_count = im->xsize * im->channels;
1226 mm_log((1, "tiff - write_one_8(tif %p, im %p)\n", tif, im));
1228 if (!set_direct_tags(tif, im, compress, 8))
1231 out_size = TIFFScanlineSize(tif);
1232 if (out_size < sample_count)
1233 out_size = sample_count;
1234 out_row = (unsigned char *)_TIFFmalloc( out_size );
1236 for (y = 0; y < im->ysize; ++y) {
1237 if (i_gsamp(im, 0, im->xsize, y, out_row, NULL, im->channels) <= 0) {
1238 i_push_error(0, "Cannot read 8-bit samples");
1241 if (TIFFWriteScanline(tif, out_row, y, 0) < 0) {
1243 i_push_error(0, "write TIFF: write scan line failed");
1253 i_writetiff_low(TIFF *tif, i_img *im) {
1254 uint32 width, height;
1260 channels = im->channels;
1262 if (width != im->xsize || height != im->ysize) {
1263 i_push_error(0, "image too large for TIFF");
1267 mm_log((1, "i_writetiff_low: width=%d, height=%d, channels=%d, bits=%d\n", width, height, channels, im->bits));
1268 if (im->type == i_palette_type) {
1269 mm_log((1, "i_writetiff_low: paletted, colors=%d\n", i_colorcount(im)));
1272 if (i_img_is_monochrome(im, &zero_is_white)) {
1273 if (!write_one_bilevel(tif, im, zero_is_white))
1276 else if (im->type == i_palette_type) {
1277 if (i_colorcount(im) <= 16) {
1278 if (!write_one_paletted4(tif, im))
1282 if (!write_one_paletted8(tif, im))
1286 else if (im->bits > 16) {
1287 if (!write_one_32(tif, im))
1290 else if (im->bits > 8) {
1291 if (!write_one_16(tif, im))
1295 if (!write_one_8(tif, im))
1299 if (!save_tiff_tags(tif, im))
1306 =item i_writetiff_multi_wiol(ig, imgs, count, fine_mode)
1308 Stores an image in the iolayer object.
1310 ig - io_object that defines source to write to
1311 imgs,count - the images to write
1317 i_writetiff_multi_wiol(io_glue *ig, i_img **imgs, int count) {
1319 TIFFErrorHandler old_handler;
1322 old_handler = TIFFSetErrorHandler(error_handler);
1325 mm_log((1, "i_writetiff_multi_wiol(ig %p, imgs %p, count %d)\n",
1328 /* FIXME: Enable the mmap interface */
1330 tif = TIFFClientOpen("No name",
1333 (TIFFReadWriteProc) ig->readcb,
1334 (TIFFReadWriteProc) ig->writecb,
1335 (TIFFSeekProc) comp_seek,
1336 (TIFFCloseProc) ig->closecb,
1337 ig->sizecb ? (TIFFSizeProc) ig->sizecb : (TIFFSizeProc) sizeproc,
1338 (TIFFMapFileProc) comp_mmap,
1339 (TIFFUnmapFileProc) comp_munmap);
1344 mm_log((1, "i_writetiff_multi_wiol: Unable to open tif file for writing\n"));
1345 i_push_error(0, "Could not create TIFF object");
1346 TIFFSetErrorHandler(old_handler);
1350 for (i = 0; i < count; ++i) {
1351 if (!i_writetiff_low(tif, imgs[i])) {
1353 TIFFSetErrorHandler(old_handler);
1357 if (!TIFFWriteDirectory(tif)) {
1358 i_push_error(0, "Cannot write TIFF directory");
1360 TIFFSetErrorHandler(old_handler);
1365 TIFFSetErrorHandler(old_handler);
1366 (void) TIFFClose(tif);
1372 =item i_writetiff_multi_wiol_faxable(ig, imgs, count, fine_mode)
1374 Stores an image in the iolayer object.
1376 ig - io_object that defines source to write to
1377 imgs,count - the images to write
1378 fine_mode - select fine or normal mode fax images
1385 i_writetiff_multi_wiol_faxable(io_glue *ig, i_img **imgs, int count, int fine) {
1388 TIFFErrorHandler old_handler;
1390 old_handler = TIFFSetErrorHandler(error_handler);
1393 mm_log((1, "i_writetiff_multi_wiol(ig %p, imgs %p, count %d)\n",
1396 /* FIXME: Enable the mmap interface */
1398 tif = TIFFClientOpen("No name",
1401 (TIFFReadWriteProc) ig->readcb,
1402 (TIFFReadWriteProc) ig->writecb,
1403 (TIFFSeekProc) comp_seek,
1404 (TIFFCloseProc) ig->closecb,
1405 ig->sizecb ? (TIFFSizeProc) ig->sizecb : (TIFFSizeProc) sizeproc,
1406 (TIFFMapFileProc) comp_mmap,
1407 (TIFFUnmapFileProc) comp_munmap);
1412 mm_log((1, "i_writetiff_mulit_wiol: Unable to open tif file for writing\n"));
1413 i_push_error(0, "Could not create TIFF object");
1414 TIFFSetErrorHandler(old_handler);
1418 for (i = 0; i < count; ++i) {
1419 if (!i_writetiff_low_faxable(tif, imgs[i], fine)) {
1421 TIFFSetErrorHandler(old_handler);
1425 if (!TIFFWriteDirectory(tif)) {
1426 i_push_error(0, "Cannot write TIFF directory");
1428 TIFFSetErrorHandler(old_handler);
1433 (void) TIFFClose(tif);
1434 TIFFSetErrorHandler(old_handler);
1440 =item i_writetiff_wiol(im, ig)
1442 Stores an image in the iolayer object.
1444 im - image object to write out
1445 ig - io_object that defines source to write to
1450 i_writetiff_wiol(i_img *img, io_glue *ig) {
1452 TIFFErrorHandler old_handler;
1454 old_handler = TIFFSetErrorHandler(error_handler);
1457 mm_log((1, "i_writetiff_wiol(img %p, ig %p)\n", img, ig));
1459 /* FIXME: Enable the mmap interface */
1461 tif = TIFFClientOpen("No name",
1464 (TIFFReadWriteProc) ig->readcb,
1465 (TIFFReadWriteProc) ig->writecb,
1466 (TIFFSeekProc) comp_seek,
1467 (TIFFCloseProc) ig->closecb,
1468 ig->sizecb ? (TIFFSizeProc) ig->sizecb : (TIFFSizeProc) sizeproc,
1469 (TIFFMapFileProc) comp_mmap,
1470 (TIFFUnmapFileProc) comp_munmap);
1475 mm_log((1, "i_writetiff_wiol: Unable to open tif file for writing\n"));
1476 i_push_error(0, "Could not create TIFF object");
1477 TIFFSetErrorHandler(old_handler);
1481 if (!i_writetiff_low(tif, img)) {
1483 TIFFSetErrorHandler(old_handler);
1487 (void) TIFFClose(tif);
1488 TIFFSetErrorHandler(old_handler);
1496 =item i_writetiff_wiol_faxable(i_img *, io_glue *)
1498 Stores an image in the iolayer object in faxable tiff format.
1500 im - image object to write out
1501 ig - io_object that defines source to write to
1503 Note, this may be rewritten to use to simply be a call to a
1504 lower-level function that gives more options for writing tiff at some
1511 i_writetiff_wiol_faxable(i_img *im, io_glue *ig, int fine) {
1513 TIFFErrorHandler old_handler;
1515 old_handler = TIFFSetErrorHandler(error_handler);
1518 mm_log((1, "i_writetiff_wiol(img %p, ig %p)\n", im, ig));
1520 /* FIXME: Enable the mmap interface */
1522 tif = TIFFClientOpen("No name",
1525 (TIFFReadWriteProc) ig->readcb,
1526 (TIFFReadWriteProc) ig->writecb,
1527 (TIFFSeekProc) comp_seek,
1528 (TIFFCloseProc) ig->closecb,
1529 ig->sizecb ? (TIFFSizeProc) ig->sizecb : (TIFFSizeProc) sizeproc,
1530 (TIFFMapFileProc) comp_mmap,
1531 (TIFFUnmapFileProc) comp_munmap);
1536 mm_log((1, "i_writetiff_wiol: Unable to open tif file for writing\n"));
1537 i_push_error(0, "Could not create TIFF object");
1538 TIFFSetErrorHandler(old_handler);
1542 if (!i_writetiff_low_faxable(tif, im, fine)) {
1544 TIFFSetErrorHandler(old_handler);
1548 (void) TIFFClose(tif);
1549 TIFFSetErrorHandler(old_handler);
1554 static int save_tiff_tags(TIFF *tif, i_img *im) {
1557 for (i = 0; i < text_tag_count; ++i) {
1559 if (i_tags_find(&im->tags, text_tag_names[i].name, 0, &entry)) {
1560 if (!TIFFSetField(tif, text_tag_names[i].tag,
1561 im->tags.tags[entry].data)) {
1562 i_push_errorf(0, "cannot save %s to TIFF", text_tag_names[i].name);
1573 unpack_4bit_to(unsigned char *dest, const unsigned char *src,
1574 size_t src_byte_count) {
1575 while (src_byte_count > 0) {
1576 *dest++ = *src >> 4;
1577 *dest++ = *src++ & 0xf;
1582 static void pack_4bit_to(unsigned char *dest, const unsigned char *src,
1583 i_img_dim pixel_count) {
1585 while (i < pixel_count) {
1587 *dest = *src++ << 4;
1597 =item fallback_rgb_channels
1599 Calculate the number of output channels when we fallback to the RGBA
1600 family of functions.
1606 fallback_rgb_channels(TIFF *tif, i_img_dim width, i_img_dim height, int *channels, int *alpha_chan) {
1612 TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &in_channels);
1613 TIFFGetFieldDefaulted(tif, TIFFTAG_PHOTOMETRIC, &photometric);
1615 switch (photometric) {
1616 case PHOTOMETRIC_SEPARATED:
1620 case PHOTOMETRIC_MINISWHITE:
1621 case PHOTOMETRIC_MINISBLACK:
1622 /* the TIFF RGBA functions expand single channel grey into RGB,
1623 so reduce it, we move the alpha channel into the right place
1632 /* TIFF images can have more than one alpha channel, but Imager can't
1633 this ignores the possibility of 2 channel images with 2 alpha,
1634 but there's not much I can do about that */
1636 if (TIFFGetField(tif, TIFFTAG_EXTRASAMPLES, &extra_count, &extras)
1638 *alpha_chan = (*channels)++;
1643 make_rgb(TIFF *tif, i_img_dim width, i_img_dim height, int *alpha_chan) {
1646 fallback_rgb_channels(tif, width, height, &channels, alpha_chan);
1648 return i_img_8_new(width, height, channels);
1652 read_one_rgb_lines(TIFF *tif, i_img_dim width, i_img_dim height, int allow_incomplete) {
1654 uint32* raster = NULL;
1655 uint32 rowsperstrip, row;
1660 im = make_rgb(tif, width, height, &alpha_chan);
1664 rc = TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
1665 mm_log((1, "i_readtiff_wiol: rowsperstrip=%d rc = %d\n", rowsperstrip, rc));
1667 if (rc != 1 || rowsperstrip==-1) {
1668 rowsperstrip = height;
1671 raster = (uint32*)_TIFFmalloc(width * rowsperstrip * sizeof (uint32));
1674 i_push_error(0, "No space for raster buffer");
1678 line_buf = mymalloc(sizeof(i_color) * width);
1680 for( row = 0; row < height; row += rowsperstrip ) {
1681 uint32 newrows, i_row;
1683 if (!TIFFReadRGBAStrip(tif, row, raster)) {
1684 if (allow_incomplete) {
1685 i_tags_setn(&im->tags, "i_lines_read", row);
1686 i_tags_setn(&im->tags, "i_incomplete", 1);
1690 i_push_error(0, "could not read TIFF image strip");
1697 newrows = (row+rowsperstrip > height) ? height-row : rowsperstrip;
1698 mm_log((1, "newrows=%d\n", newrows));
1700 for( i_row = 0; i_row < newrows; i_row++ ) {
1702 i_color *outp = line_buf;
1704 for(x = 0; x<width; x++) {
1705 uint32 temp = raster[x+width*(newrows-i_row-1)];
1706 outp->rgba.r = TIFFGetR(temp);
1707 outp->rgba.g = TIFFGetG(temp);
1708 outp->rgba.b = TIFFGetB(temp);
1711 /* the libtiff RGBA code expands greyscale into RGBA, so put the
1712 alpha in the right place and scale it */
1714 outp->channel[alpha_chan] = TIFFGetA(temp);
1715 if (outp->channel[alpha_chan]) {
1716 for (ch = 0; ch < alpha_chan; ++ch) {
1717 outp->channel[ch] = outp->channel[ch] * 255 / outp->channel[alpha_chan];
1724 i_plin(im, 0, width, i_row+row, line_buf);
1734 /* adapted from libtiff
1736 libtiff's TIFFReadRGBATile succeeds even when asked to read an
1737 invalid tile, which means we have no way of knowing whether the data
1738 we received from it is valid or not.
1740 So the caller here has set stoponerror to 1 so that
1741 TIFFRGBAImageGet() will fail.
1743 read_one_rgb_tiled() then takes that into account for i_incomplete
1747 myTIFFReadRGBATile(TIFFRGBAImage *img, uint32 col, uint32 row, uint32 * raster)
1751 uint32 tile_xsize, tile_ysize;
1752 uint32 read_xsize, read_ysize;
1756 * Verify that our request is legal - on a tile file, and on a
1760 TIFFGetFieldDefaulted(img->tif, TIFFTAG_TILEWIDTH, &tile_xsize);
1761 TIFFGetFieldDefaulted(img->tif, TIFFTAG_TILELENGTH, &tile_ysize);
1762 if( (col % tile_xsize) != 0 || (row % tile_ysize) != 0 )
1764 i_push_errorf(0, "Row/col passed to myTIFFReadRGBATile() must be top"
1765 "left corner of a tile.");
1770 * The TIFFRGBAImageGet() function doesn't allow us to get off the
1771 * edge of the image, even to fill an otherwise valid tile. So we
1772 * figure out how much we can read, and fix up the tile buffer to
1773 * a full tile configuration afterwards.
1776 if( row + tile_ysize > img->height )
1777 read_ysize = img->height - row;
1779 read_ysize = tile_ysize;
1781 if( col + tile_xsize > img->width )
1782 read_xsize = img->width - col;
1784 read_xsize = tile_xsize;
1787 * Read the chunk of imagery.
1790 img->row_offset = row;
1791 img->col_offset = col;
1793 ok = TIFFRGBAImageGet(img, raster, read_xsize, read_ysize );
1796 * If our read was incomplete we will need to fix up the tile by
1797 * shifting the data around as if a full tile of data is being returned.
1799 * This is all the more complicated because the image is organized in
1800 * bottom to top format.
1803 if( read_xsize == tile_xsize && read_ysize == tile_ysize )
1806 for( i_row = 0; i_row < read_ysize; i_row++ ) {
1807 memmove( raster + (tile_ysize - i_row - 1) * tile_xsize,
1808 raster + (read_ysize - i_row - 1) * read_xsize,
1809 read_xsize * sizeof(uint32) );
1810 _TIFFmemset( raster + (tile_ysize - i_row - 1) * tile_xsize+read_xsize,
1811 0, sizeof(uint32) * (tile_xsize - read_xsize) );
1814 for( i_row = read_ysize; i_row < tile_ysize; i_row++ ) {
1815 _TIFFmemset( raster + (tile_ysize - i_row - 1) * tile_xsize,
1816 0, sizeof(uint32) * tile_xsize );
1823 read_one_rgb_tiled(TIFF *tif, i_img_dim width, i_img_dim height, int allow_incomplete) {
1825 uint32* raster = NULL;
1828 uint32 tile_width, tile_height;
1829 unsigned long pixels = 0;
1830 char emsg[1024] = "";
1835 im = make_rgb(tif, width, height, &alpha_chan);
1839 if (!TIFFRGBAImageOK(tif, emsg)
1840 || !TIFFRGBAImageBegin(&img, tif, 1, emsg)) {
1841 i_push_error(0, emsg);
1846 TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tile_width);
1847 TIFFGetField(tif, TIFFTAG_TILELENGTH, &tile_height);
1848 mm_log((1, "i_readtiff_wiol: tile_width=%d, tile_height=%d\n", tile_width, tile_height));
1850 raster = (uint32*)_TIFFmalloc(tile_width * tile_height * sizeof (uint32));
1853 i_push_error(0, "No space for raster buffer");
1854 TIFFRGBAImageEnd(&img);
1857 line = mymalloc(tile_width * sizeof(i_color));
1859 for( row = 0; row < height; row += tile_height ) {
1860 for( col = 0; col < width; col += tile_width ) {
1862 /* Read the tile into an RGBA array */
1863 if (myTIFFReadRGBATile(&img, col, row, raster)) {
1865 uint32 newrows = (row+tile_height > height) ? height-row : tile_height;
1866 uint32 newcols = (col+tile_width > width ) ? width-col : tile_width;
1868 mm_log((1, "i_readtiff_wiol: tile(%d, %d) newcols=%d newrows=%d\n", col, row, newcols, newrows));
1869 for( i_row = 0; i_row < newrows; i_row++ ) {
1870 i_color *outp = line;
1871 for(x = 0; x < newcols; x++) {
1872 uint32 temp = raster[x+tile_width*(tile_height-i_row-1)];
1873 outp->rgba.r = TIFFGetR(temp);
1874 outp->rgba.g = TIFFGetG(temp);
1875 outp->rgba.b = TIFFGetB(temp);
1876 outp->rgba.a = TIFFGetA(temp);
1879 /* the libtiff RGBA code expands greyscale into RGBA, so put the
1880 alpha in the right place and scale it */
1882 outp->channel[alpha_chan] = TIFFGetA(temp);
1884 if (outp->channel[alpha_chan]) {
1885 for (ch = 0; ch < alpha_chan; ++ch) {
1886 outp->channel[ch] = outp->channel[ch] * 255 / outp->channel[alpha_chan];
1893 i_plin(im, col, col+newcols, row+i_row, line);
1895 pixels += newrows * newcols;
1898 if (allow_incomplete) {
1910 i_push_error(0, "TIFF: No image data could be read from the image");
1914 /* incomplete image */
1915 i_tags_setn(&im->tags, "i_incomplete", 1);
1916 i_tags_setn(&im->tags, "i_lines_read", pixels / width);
1920 TIFFRGBAImageEnd(&img);
1928 TIFFRGBAImageEnd(&img);
1934 i_tiff_libversion(void) {
1935 return TIFFGetVersion();
1939 setup_paletted(read_state_t *state) {
1942 int color_count = 1 << state->bits_per_sample;
1944 state->img = i_img_pal_new(state->width, state->height, 3, 256);
1948 /* setup the color map */
1949 if (!TIFFGetField(state->tif, TIFFTAG_COLORMAP, maps+0, maps+1, maps+2)) {
1950 i_push_error(0, "Cannot get colormap for paletted image");
1951 i_img_destroy(state->img);
1954 for (i = 0; i < color_count; ++i) {
1956 for (ch = 0; ch < 3; ++ch) {
1957 c.channel[ch] = Sample16To8(maps[ch][i]);
1959 i_addcolors(state->img, &c, 1);
1966 tile_contig_getter(read_state_t *state, read_putter_t putter) {
1967 uint32 tile_width, tile_height;
1968 uint32 this_tile_height, this_tile_width;
1969 uint32 rows_left, cols_left;
1972 state->raster = _TIFFmalloc(TIFFTileSize(state->tif));
1973 if (!state->raster) {
1974 i_push_error(0, "tiff: Out of memory allocating tile buffer");
1978 TIFFGetField(state->tif, TIFFTAG_TILEWIDTH, &tile_width);
1979 TIFFGetField(state->tif, TIFFTAG_TILELENGTH, &tile_height);
1980 rows_left = state->height;
1981 for (y = 0; y < state->height; y += this_tile_height) {
1982 this_tile_height = rows_left > tile_height ? tile_height : rows_left;
1984 cols_left = state->width;
1985 for (x = 0; x < state->width; x += this_tile_width) {
1986 this_tile_width = cols_left > tile_width ? tile_width : cols_left;
1988 if (TIFFReadTile(state->tif,
1991 if (!state->allow_incomplete) {
1996 putter(state, x, y, this_tile_width, this_tile_height, tile_width - this_tile_width);
1999 cols_left -= this_tile_width;
2002 rows_left -= this_tile_height;
2009 strip_contig_getter(read_state_t *state, read_putter_t putter) {
2010 uint32 rows_per_strip;
2011 tsize_t strip_size = TIFFStripSize(state->tif);
2012 uint32 y, strip_rows, rows_left;
2014 state->raster = _TIFFmalloc(strip_size);
2015 if (!state->raster) {
2016 i_push_error(0, "tiff: Out of memory allocating strip buffer");
2020 TIFFGetFieldDefaulted(state->tif, TIFFTAG_ROWSPERSTRIP, &rows_per_strip);
2021 rows_left = state->height;
2022 for (y = 0; y < state->height; y += strip_rows) {
2023 strip_rows = rows_left > rows_per_strip ? rows_per_strip : rows_left;
2024 if (TIFFReadEncodedStrip(state->tif,
2025 TIFFComputeStrip(state->tif, y, 0),
2028 if (!state->allow_incomplete)
2032 putter(state, 0, y, state->width, strip_rows, 0);
2034 rows_left -= strip_rows;
2041 paletted_putter8(read_state_t *state, i_img_dim x, i_img_dim y, i_img_dim width, i_img_dim height, int extras) {
2042 unsigned char *p = state->raster;
2044 state->pixels_read += width * height;
2045 while (height > 0) {
2046 i_ppal(state->img, x, x + width, y, p);
2047 p += width + extras;
2056 paletted_putter4(read_state_t *state, i_img_dim x, i_img_dim y, i_img_dim width, i_img_dim height, int extras) {
2057 uint32 img_line_size = (width + 1) / 2;
2058 uint32 skip_line_size = (width + extras + 1) / 2;
2059 unsigned char *p = state->raster;
2061 if (!state->line_buf)
2062 state->line_buf = mymalloc(state->width);
2064 state->pixels_read += width * height;
2065 while (height > 0) {
2066 unpack_4bit_to(state->line_buf, p, img_line_size);
2067 i_ppal(state->img, x, x + width, y, state->line_buf);
2068 p += skip_line_size;
2077 rgb_channels(read_state_t *state, int *out_channels) {
2083 state->alpha_chan = 0;
2084 state->scale_alpha = 0;
2087 if (state->samples_per_pixel == 3)
2090 if (!TIFFGetField(state->tif, TIFFTAG_EXTRASAMPLES, &extra_count, &extras)) {
2091 mm_log((1, "tiff: samples != 3 but no extra samples tag\n"));
2096 mm_log((1, "tiff: samples != 3 but no extra samples listed"));
2101 state->alpha_chan = 3;
2103 case EXTRASAMPLE_UNSPECIFIED:
2104 case EXTRASAMPLE_ASSOCALPHA:
2105 state->scale_alpha = 1;
2108 case EXTRASAMPLE_UNASSALPHA:
2109 state->scale_alpha = 0;
2113 mm_log((1, "tiff: unknown extra sample type %d, treating as assoc alpha\n",
2115 state->scale_alpha = 1;
2118 mm_log((1, "tiff alpha channel %d scale %d\n", state->alpha_chan, state->scale_alpha));
2122 grey_channels(read_state_t *state, int *out_channels) {
2128 state->alpha_chan = 0;
2129 state->scale_alpha = 0;
2132 if (state->samples_per_pixel == 1)
2135 if (!TIFFGetField(state->tif, TIFFTAG_EXTRASAMPLES, &extra_count, &extras)) {
2136 mm_log((1, "tiff: samples != 1 but no extra samples tag\n"));
2141 mm_log((1, "tiff: samples != 1 but no extra samples listed"));
2146 state->alpha_chan = 1;
2148 case EXTRASAMPLE_UNSPECIFIED:
2149 case EXTRASAMPLE_ASSOCALPHA:
2150 state->scale_alpha = 1;
2153 case EXTRASAMPLE_UNASSALPHA:
2154 state->scale_alpha = 0;
2158 mm_log((1, "tiff: unknown extra sample type %d, treating as assoc alpha\n",
2160 state->scale_alpha = 1;
2166 setup_16_rgb(read_state_t *state) {
2169 rgb_channels(state, &out_channels);
2171 state->img = i_img_16_new(state->width, state->height, out_channels);
2174 state->line_buf = mymalloc(sizeof(unsigned) * state->width * out_channels);
2180 setup_16_grey(read_state_t *state) {
2183 grey_channels(state, &out_channels);
2185 state->img = i_img_16_new(state->width, state->height, out_channels);
2188 state->line_buf = mymalloc(sizeof(unsigned) * state->width * out_channels);
2194 putter_16(read_state_t *state, i_img_dim x, i_img_dim y, i_img_dim width, i_img_dim height,
2196 uint16 *p = state->raster;
2197 int out_chan = state->img->channels;
2199 state->pixels_read += width * height;
2200 while (height > 0) {
2203 unsigned *outp = state->line_buf;
2205 for (i = 0; i < width; ++i) {
2206 for (ch = 0; ch < out_chan; ++ch) {
2209 if (state->alpha_chan && state->scale_alpha && outp[state->alpha_chan]) {
2210 for (ch = 0; ch < state->alpha_chan; ++ch) {
2211 int result = 0.5 + (outp[ch] * 65535.0 / outp[state->alpha_chan]);
2212 outp[ch] = CLAMP16(result);
2215 p += state->samples_per_pixel;
2219 i_psamp_bits(state->img, x, x + width, y, state->line_buf, NULL, out_chan, 16);
2221 p += row_extras * state->samples_per_pixel;
2230 setup_8_rgb(read_state_t *state) {
2233 rgb_channels(state, &out_channels);
2235 state->img = i_img_8_new(state->width, state->height, out_channels);
2238 state->line_buf = mymalloc(sizeof(unsigned) * state->width * out_channels);
2244 setup_8_grey(read_state_t *state) {
2247 grey_channels(state, &out_channels);
2249 state->img = i_img_8_new(state->width, state->height, out_channels);
2252 state->line_buf = mymalloc(sizeof(i_color) * state->width * out_channels);
2258 putter_8(read_state_t *state, i_img_dim x, i_img_dim y, i_img_dim width, i_img_dim height,
2260 unsigned char *p = state->raster;
2261 int out_chan = state->img->channels;
2263 state->pixels_read += width * height;
2264 while (height > 0) {
2267 i_color *outp = state->line_buf;
2269 for (i = 0; i < width; ++i) {
2270 for (ch = 0; ch < out_chan; ++ch) {
2271 outp->channel[ch] = p[ch];
2273 if (state->alpha_chan && state->scale_alpha
2274 && outp->channel[state->alpha_chan]) {
2275 for (ch = 0; ch < state->alpha_chan; ++ch) {
2276 int result = (outp->channel[ch] * 255 + 127) / outp->channel[state->alpha_chan];
2278 outp->channel[ch] = CLAMP8(result);
2281 p += state->samples_per_pixel;
2285 i_plin(state->img, x, x + width, y, state->line_buf);
2287 p += row_extras * state->samples_per_pixel;
2296 setup_32_rgb(read_state_t *state) {
2299 rgb_channels(state, &out_channels);
2301 state->img = i_img_double_new(state->width, state->height, out_channels);
2304 state->line_buf = mymalloc(sizeof(i_fcolor) * state->width);
2310 setup_32_grey(read_state_t *state) {
2313 grey_channels(state, &out_channels);
2315 state->img = i_img_double_new(state->width, state->height, out_channels);
2318 state->line_buf = mymalloc(sizeof(i_fcolor) * state->width);
2324 putter_32(read_state_t *state, i_img_dim x, i_img_dim y, i_img_dim width, i_img_dim height,
2326 uint32 *p = state->raster;
2327 int out_chan = state->img->channels;
2329 state->pixels_read += width * height;
2330 while (height > 0) {
2333 i_fcolor *outp = state->line_buf;
2335 for (i = 0; i < width; ++i) {
2336 for (ch = 0; ch < out_chan; ++ch) {
2337 outp->channel[ch] = p[ch] / 4294967295.0;
2339 if (state->alpha_chan && state->scale_alpha && outp->channel[state->alpha_chan]) {
2340 for (ch = 0; ch < state->alpha_chan; ++ch)
2341 outp->channel[ch] /= outp->channel[state->alpha_chan];
2343 p += state->samples_per_pixel;
2347 i_plinf(state->img, x, x + width, y, state->line_buf);
2349 p += row_extras * state->samples_per_pixel;
2358 setup_bilevel(read_state_t *state) {
2359 i_color black, white;
2360 state->img = i_img_pal_new(state->width, state->height, 1, 256);
2363 black.channel[0] = black.channel[1] = black.channel[2] =
2364 black.channel[3] = 0;
2365 white.channel[0] = white.channel[1] = white.channel[2] =
2366 white.channel[3] = 255;
2367 if (state->photometric == PHOTOMETRIC_MINISBLACK) {
2368 i_addcolors(state->img, &black, 1);
2369 i_addcolors(state->img, &white, 1);
2372 i_addcolors(state->img, &white, 1);
2373 i_addcolors(state->img, &black, 1);
2375 state->line_buf = mymalloc(state->width);
2381 putter_bilevel(read_state_t *state, i_img_dim x, i_img_dim y, i_img_dim width, i_img_dim height,
2383 unsigned char *line_in = state->raster;
2384 size_t line_size = (width + row_extras + 7) / 8;
2386 /* tifflib returns the bits in MSB2LSB order even when the file is
2387 in LSB2MSB, so we only need to handle MSB2LSB */
2388 state->pixels_read += width * height;
2389 while (height > 0) {
2391 unsigned char *outp = state->line_buf;
2392 unsigned char *inp = line_in;
2393 unsigned mask = 0x80;
2395 for (i = 0; i < width; ++i) {
2396 *outp++ = *inp & mask ? 1 : 0;
2404 i_ppal(state->img, x, x + width, y, state->line_buf);
2406 line_in += line_size;
2415 cmyk_channels(read_state_t *state, int *out_channels) {
2421 state->alpha_chan = 0;
2422 state->scale_alpha = 0;
2425 if (state->samples_per_pixel == 4)
2428 if (!TIFFGetField(state->tif, TIFFTAG_EXTRASAMPLES, &extra_count, &extras)) {
2429 mm_log((1, "tiff: CMYK samples != 4 but no extra samples tag\n"));
2434 mm_log((1, "tiff: CMYK samples != 4 but no extra samples listed"));
2439 state->alpha_chan = 4;
2441 case EXTRASAMPLE_UNSPECIFIED:
2442 case EXTRASAMPLE_ASSOCALPHA:
2443 state->scale_alpha = 1;
2446 case EXTRASAMPLE_UNASSALPHA:
2447 state->scale_alpha = 0;
2451 mm_log((1, "tiff: unknown extra sample type %d, treating as assoc alpha\n",
2453 state->scale_alpha = 1;
2459 setup_cmyk8(read_state_t *state) {
2462 cmyk_channels(state, &channels);
2463 state->img = i_img_8_new(state->width, state->height, channels);
2465 state->line_buf = mymalloc(sizeof(i_color) * state->width);
2471 putter_cmyk8(read_state_t *state, i_img_dim x, i_img_dim y, i_img_dim width, i_img_dim height,
2473 unsigned char *p = state->raster;
2475 state->pixels_read += width * height;
2476 while (height > 0) {
2479 i_color *outp = state->line_buf;
2481 for (i = 0; i < width; ++i) {
2482 unsigned char c, m, y, k;
2487 outp->rgba.r = (k * (255 - c)) / 255;
2488 outp->rgba.g = (k * (255 - m)) / 255;
2489 outp->rgba.b = (k * (255 - y)) / 255;
2490 if (state->alpha_chan) {
2491 outp->rgba.a = p[state->alpha_chan];
2492 if (state->scale_alpha
2494 for (ch = 0; ch < 3; ++ch) {
2495 int result = (outp->channel[ch] * 255 + 127) / outp->rgba.a;
2496 outp->channel[ch] = CLAMP8(result);
2500 p += state->samples_per_pixel;
2504 i_plin(state->img, x, x + width, y, state->line_buf);
2506 p += row_extras * state->samples_per_pixel;
2515 setup_cmyk16(read_state_t *state) {
2518 cmyk_channels(state, &channels);
2519 state->img = i_img_16_new(state->width, state->height, channels);
2521 state->line_buf = mymalloc(sizeof(unsigned) * state->width * channels);
2527 putter_cmyk16(read_state_t *state, i_img_dim x, i_img_dim y, i_img_dim width, i_img_dim height,
2529 uint16 *p = state->raster;
2530 int out_chan = state->img->channels;
2532 mm_log((4, "putter_cmyk16(%p, %d, %d, %d, %d, %d)\n", x, y, width, height, row_extras));
2534 state->pixels_read += width * height;
2535 while (height > 0) {
2538 unsigned *outp = state->line_buf;
2540 for (i = 0; i < width; ++i) {
2541 unsigned c, m, y, k;
2546 outp[0] = (k * (65535U - c)) / 65535U;
2547 outp[1] = (k * (65535U - m)) / 65535U;
2548 outp[2] = (k * (65535U - y)) / 65535U;
2549 if (state->alpha_chan) {
2550 outp[3] = p[state->alpha_chan];
2551 if (state->scale_alpha
2553 for (ch = 0; ch < 3; ++ch) {
2554 int result = (outp[ch] * 65535 + 32767) / outp[3];
2555 outp[3] = CLAMP16(result);
2559 p += state->samples_per_pixel;
2563 i_psamp_bits(state->img, x, x + width, y, state->line_buf, NULL, out_chan, 16);
2565 p += row_extras * state->samples_per_pixel;
2575 Older versions of tifflib we support don't define this, so define it
2578 If you want this detection to do anything useful, use a newer
2582 #if TIFFLIB_VERSION < 20031121
2585 TIFFIsCODECConfigured(uint16 scheme) {
2587 /* these schemes are all shipped with tifflib */
2588 case COMPRESSION_NONE:
2589 case COMPRESSION_PACKBITS:
2590 case COMPRESSION_CCITTRLE:
2591 case COMPRESSION_CCITTRLEW:
2592 case COMPRESSION_CCITTFAX3:
2593 case COMPRESSION_CCITTFAX4:
2596 /* these require external library support */
2598 case COMPRESSION_JPEG:
2599 case COMPRESSION_LZW:
2600 case COMPRESSION_DEFLATE:
2601 case COMPRESSION_ADOBE_DEFLATE:
2609 myTIFFIsCODECConfigured(uint16 scheme) {
2610 #if TIFFLIB_VERSION < 20040724
2611 if (scheme == COMPRESSION_LZW)
2615 return TIFFIsCODECConfigured(scheme);
2623 Arnar M. Hrafnkelsson <addi@umich.edu>, Tony Cook <tonyc@cpan.org>