]> git.imager.perl.org - imager.git/blob - TIFF/imtiff.c
bced21bf80213c2ace250ee2281e00e73bc7f44c
[imager.git] / TIFF / imtiff.c
1 #include <tiffio.h>
2 #include <string.h>
3 #include "imtiff.h"
4 #include "imext.h"
5
6 /* needed to implement our substitute TIFFIsCODECConfigured */
7 #if TIFFLIB_VERSION < 20031121
8 static int TIFFIsCODECConfigured(uint16 scheme);
9 #endif
10
11 /*
12 =head1 NAME
13
14 tiff.c - implements reading and writing tiff files, uses io layer.
15
16 =head1 SYNOPSIS
17
18    io_glue *ig = io_new_fd( fd );
19    i_img *im   = i_readtiff_wiol(ig, -1); // no limit on how much is read
20    // or 
21    io_glue *ig = io_new_fd( fd );
22    return_code = i_writetiff_wiol(im, ig); 
23
24 =head1 DESCRIPTION
25
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
28 memory mapped buffer.
29
30 =head1 FUNCTION REFERENCE
31
32 Some of these functions are internal.
33
34 =over
35
36 =cut
37 */
38
39 #define byteswap_macro(x) \
40      ((((x) & 0xff000000) >> 24) | (((x) & 0x00ff0000) >>  8) |     \
41       (((x) & 0x0000ff00) <<  8) | (((x) & 0x000000ff) << 24))
42
43 #define CLAMP8(x) ((x) < 0 ? 0 : (x) > 255 ? 255 : (x))
44 #define CLAMP16(x) ((x) < 0 ? 0 : (x) > 65535 ? 65535 : (x))
45
46 #define Sample16To8(num) ((num) / 257)
47
48 struct tag_name {
49   char *name;
50   uint32 tag;
51 };
52
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);
55
56 static struct tag_name text_tag_names[] =
57 {
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, },
67 };
68
69 static struct tag_name 
70 compress_values[] =
71   {
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 },
85   };
86
87 static const int compress_value_count = 
88   sizeof(compress_values) / sizeof(*compress_values);
89
90 static int 
91 myTIFFIsCODECConfigured(uint16 scheme);
92
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);
96
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
101    image) */
102
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);
105
106 /* reads from a tiled or strip image and calls the putter.
107    This may need a second type for handling non-contiguous images
108    at some point */
109 typedef int (*read_getter_t)(read_state_t *state, read_putter_t putter);
110
111 struct read_state_tag {
112   TIFF *tif;
113   i_img *img;
114   void *raster;
115   i_img_dim pixels_read;
116   int allow_incomplete;
117   void *line_buf;
118   uint32 width, height;
119   uint16 bits_per_sample;
120   uint16 photometric;
121
122   /* the total number of channels (samples per pixel) */
123   int samples_per_pixel;
124
125   /* if non-zero, which channel is the alpha channel, typically 3 for rgb */
126   int alpha_chan;
127
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 */
132   int scale_alpha;
133 };
134
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);
137
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);
141
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);
145
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);
149
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);
153
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);
156
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);
159
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);
162 static void
163 rgb_channels(read_state_t *state, int *out_channels);
164 static void
165 grey_channels(read_state_t *state, int *out_channels);
166 static void
167 cmyk_channels(read_state_t *state, int *out_channels);
168 static void
169 fallback_rgb_channels(TIFF *tif, i_img_dim width, i_img_dim height, int *channels, int *alpha_chan);
170
171 static const int text_tag_count = 
172   sizeof(text_tag_names) / sizeof(*text_tag_names);
173
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);
177 }
178
179 #define WARN_BUFFER_LIMIT 10000
180 static char *warn_buffer = NULL;
181 static int warn_buffer_size = 0;
182
183 static void warn_handler(char const *module, char const *fmt, va_list ap) {
184   char buf[1000];
185
186   buf[0] = '\0';
187 #ifdef HAVE_SNPRINTF
188   vsnprintf(buf, sizeof(buf), fmt, ap);
189 #else
190   vsprintf(buf, fmt, ap);
191 #endif
192   mm_log((1, "tiff warning %s\n", buf));
193
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;
199     }
200     warn_buffer = myrealloc(warn_buffer, new_size);
201     if (!old_buffer) *warn_buffer = '\0';
202     warn_buffer_size = new_size;
203   }
204   if (strlen(warn_buffer)+strlen(buf)+2 <= warn_buffer_size) {
205     strcat(warn_buffer, buf);
206     strcat(warn_buffer, "\n");
207   }
208 }
209
210 static int save_tiff_tags(TIFF *tif, i_img *im);
211
212 static void 
213 pack_4bit_to(unsigned char *dest, const unsigned char *src, i_img_dim count);
214
215
216 static toff_t sizeproc(thandle_t x) {
217         return 0;
218 }
219
220
221 /*
222 =item comp_seek(h, o, w)
223
224 Compatability for 64 bit systems like latest freebsd (internal)
225
226    h - tiff handle, cast an io_glue object
227    o - offset
228    w - whence
229
230 =cut
231 */
232
233 static
234 toff_t
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);
238 }
239
240 /*
241 =item comp_mmap(thandle_t, tdata_t*, toff_t*)
242
243 Dummy mmap stub.
244
245 This shouldn't ever be called but newer tifflibs want it anyway.
246
247 =cut
248 */
249
250 static 
251 int
252 comp_mmap(thandle_t h, tdata_t*p, toff_t*off) {
253   return -1;
254 }
255
256 /*
257 =item comp_munmap(thandle_t h, tdata_t p, toff_t off)
258
259 Dummy munmap stub.
260
261 This shouldn't ever be called but newer tifflibs want it anyway.
262
263 =cut
264 */
265
266 static void
267 comp_munmap(thandle_t h, tdata_t p, toff_t off) {
268   /* do nothing */
269 }
270
271 static i_img *read_one_tiff(TIFF *tif, int allow_incomplete) {
272   i_img *im;
273   uint32 width, height;
274   uint16 samples_per_pixel;
275   int tiled, error;
276   float xres, yres;
277   uint16 resunit;
278   int gotXres, gotYres;
279   uint16 photometric;
280   uint16 bits_per_sample;
281   uint16 planar_config;
282   uint16 inkset;
283   uint16 compress;
284   int i;
285   read_state_t state;
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;
292
293   error = 0;
294
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);
303
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 "));
307
308   total_pixels = width * height;
309   memset(&state, 0, sizeof(state));
310   state.tif = tif;
311   state.allow_incomplete = allow_incomplete;
312   state.width = width;
313   state.height = height;
314   state.bits_per_sample = bits_per_sample;
315   state.samples_per_pixel = samples_per_pixel;
316   state.photometric = photometric;
317
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;
325     else
326       mm_log((1, "unsupported paletted bits_per_sample %d\n", bits_per_sample));
327
328     sample_size = sizeof(i_sample_t);
329     channels = 1;
330   }
331   else if (bits_per_sample == 16 
332            && photometric == PHOTOMETRIC_RGB
333            && samples_per_pixel >= 3) {
334     setupf = setup_16_rgb;
335     putterf = putter_16;
336     sample_size = 2;
337     rgb_channels(&state, &channels);
338   }
339   else if (bits_per_sample == 16
340            && photometric == PHOTOMETRIC_MINISBLACK) {
341     setupf = setup_16_grey;
342     putterf = putter_16;
343     sample_size = 2;
344     grey_channels(&state, &channels);
345   }
346   else if (bits_per_sample == 8
347            && photometric == PHOTOMETRIC_MINISBLACK) {
348     setupf = setup_8_grey;
349     putterf = putter_8;
350     sample_size = 1;
351     grey_channels(&state, &channels);
352   }
353   else if (bits_per_sample == 8
354            && photometric == PHOTOMETRIC_RGB) {
355     setupf = setup_8_rgb;
356     putterf = putter_8;
357     sample_size = 1;
358     rgb_channels(&state, &channels);
359   }
360   else if (bits_per_sample == 32 
361            && photometric == PHOTOMETRIC_RGB
362            && samples_per_pixel >= 3) {
363     setupf = setup_32_rgb;
364     putterf = putter_32;
365     sample_size = sizeof(i_fsample_t);
366     rgb_channels(&state, &channels);
367   }
368   else if (bits_per_sample == 32
369            && photometric == PHOTOMETRIC_MINISBLACK) {
370     setupf = setup_32_grey;
371     putterf = putter_32;
372     sample_size = sizeof(i_fsample_t);
373     grey_channels(&state, &channels);
374   }
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);
382     channels = 1;
383   }
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;
390     sample_size = 1;
391     cmyk_channels(&state, &channels);
392   }
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;
399     sample_size = 2;
400     cmyk_channels(&state, &channels);
401   }
402   else {
403     int alpha;
404     fallback_rgb_channels(tif, width, height, &channels, &alpha);
405     sample_size = 1;
406   }
407
408   if (!i_int_check_image_file_limits(width, height, channels, sample_size)) {
409     return NULL;
410   }
411
412   if (tiled) {
413     if (planar_config == PLANARCONFIG_CONTIG)
414       getterf = tile_contig_getter;
415   }
416   else {
417     if (planar_config == PLANARCONFIG_CONTIG)
418       getterf = strip_contig_getter;
419   }
420   if (setupf && getterf && putterf) {
421
422     if (!setupf(&state))
423       return NULL;
424     if (!getterf(&state, putterf) || !state.pixels_read) {
425       if (state.img)
426         i_img_destroy(state.img);
427       if (state.raster)
428         _TIFFfree(state.raster);
429       if (state.line_buf)
430         myfree(state.line_buf);
431       
432       return NULL;
433     }
434
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);
439     }
440     im = state.img;
441     
442     if (state.raster)
443       _TIFFfree(state.raster);
444     if (state.line_buf)
445       myfree(state.line_buf);
446   }
447   else {
448     if (tiled) {
449       im = read_one_rgb_tiled(tif, width, height, allow_incomplete);
450     }
451     else {
452       im = read_one_rgb_lines(tif, width, height, allow_incomplete);
453     }
454   }
455
456   if (!im)
457     return NULL;
458
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);
463     
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) {
469     if (!gotXres)
470       xres = yres;
471     else if (!gotYres)
472       yres = xres;
473     i_tags_setn(&im->tags, "tiff_resolutionunit", resunit);
474     if (resunit == RESUNIT_CENTIMETER) {
475       /* from dots per cm to dpi */
476       xres *= 2.54;
477       yres *= 2.54;
478       i_tags_set(&im->tags, "tiff_resolutionunit_name", "centimeter", -1);
479     }
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);
483     }
484     else if (resunit == RESUNIT_INCH) {
485       i_tags_set(&im->tags, "tiff_resolutionunit_name", "inch", -1);
486     }
487     else {
488       i_tags_set(&im->tags, "tiff_resolutionunit_name", "unknown", -1);
489     }
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);
495   }
496
497   /* Text tags */
498   for (i = 0; i < text_tag_count; ++i) {
499     char *data;
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);
504     }
505   }
506
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);
510     *warn_buffer = '\0';
511   }
512
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);
516       break;
517     }
518   }
519   
520   return im;
521 }
522
523 /*
524 =item i_readtiff_wiol(im, ig)
525
526 =cut
527 */
528 i_img*
529 i_readtiff_wiol(io_glue *ig, int allow_incomplete, int page) {
530   TIFF* tif;
531   TIFFErrorHandler old_handler;
532   TIFFErrorHandler old_warn_handler;
533   i_img *im;
534
535   i_clear_error();
536   old_handler = TIFFSetErrorHandler(error_handler);
537   old_warn_handler = TIFFSetWarningHandler(warn_handler);
538   if (warn_buffer)
539     *warn_buffer = '\0';
540
541   /* Add code to get the filename info from the iolayer */
542   /* Also add code to check for mmapped code */
543
544   mm_log((1, "i_readtiff_wiol(ig %p, allow_incomplete %d, page %d)\n", ig, allow_incomplete, page));
545   
546   tif = TIFFClientOpen("(Iolayer)", 
547                        "rm", 
548                        (thandle_t) ig,
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);
556   
557   if (!tif) {
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);
562     return NULL;
563   }
564
565   if (page != 0) {
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);
571       TIFFClose(tif);
572       return NULL;
573     }
574   }
575
576   im = read_one_tiff(tif, allow_incomplete);
577
578   if (TIFFLastDirectory(tif)) mm_log((1, "Last directory of tiff file\n"));
579   TIFFSetErrorHandler(old_handler);
580   TIFFSetWarningHandler(old_warn_handler);
581   TIFFClose(tif);
582   return im;
583 }
584
585 /*
586 =item i_readtiff_multi_wiol(ig, *count)
587
588 Reads multiple images from a TIFF.
589
590 =cut
591 */
592 i_img**
593 i_readtiff_multi_wiol(io_glue *ig, int *count) {
594   TIFF* tif;
595   TIFFErrorHandler old_handler;
596   TIFFErrorHandler old_warn_handler;
597   i_img **results = NULL;
598   int result_alloc = 0;
599   int dirnum = 0;
600
601   i_clear_error();
602   old_handler = TIFFSetErrorHandler(error_handler);
603   old_warn_handler = TIFFSetWarningHandler(warn_handler);
604   if (warn_buffer)
605     *warn_buffer = '\0';
606
607   /* Add code to get the filename info from the iolayer */
608   /* Also add code to check for mmapped code */
609
610   mm_log((1, "i_readtiff_wiol(ig %p, length %d)\n", ig));
611   
612   tif = TIFFClientOpen("(Iolayer)", 
613                        "rm", 
614                        (thandle_t) ig,
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);
622   
623   if (!tif) {
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);
628     return NULL;
629   }
630
631   *count = 0;
632   do {
633     i_img *im = read_one_tiff(tif, 0);
634     if (!im)
635       break;
636     if (++*count > result_alloc) {
637       if (result_alloc == 0) {
638         result_alloc = 5;
639         results = mymalloc(result_alloc * sizeof(i_img *));
640       }
641       else {
642         i_img **newresults;
643         result_alloc *= 2;
644         newresults = myrealloc(results, result_alloc * sizeof(i_img *));
645         if (!newresults) {
646           i_img_destroy(im); /* don't leak it */
647           break;
648         }
649         results = newresults;
650       }
651     }
652     results[*count-1] = im;
653   } while (TIFFSetDirectory(tif, ++dirnum));
654
655   TIFFSetWarningHandler(old_warn_handler);
656   TIFFSetErrorHandler(old_handler);
657   TIFFClose(tif);
658   return results;
659 }
660
661 undef_int
662 i_writetiff_low_faxable(TIFF *tif, i_img *im, int fine) {
663   uint32 width, height;
664   unsigned char *linebuf = NULL;
665   uint32 y;
666   int rc;
667   uint32 x;
668   uint32 rowsperstrip;
669   float vres = fine ? 196 : 98;
670   int luma_chan;
671
672   width    = im->xsize;
673   height   = im->ysize;
674
675   if (width != im->xsize || height != im->ysize) {
676     i_push_error(0, "image too large for TIFF");
677     return 0;
678   }
679
680   switch (im->channels) {
681   case 1:
682   case 2:
683     luma_chan = 0;
684     break;
685   case 3:
686   case 4:
687     luma_chan = 1;
688     break;
689   default:
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));
692     return 0;
693   }
694
695   /* Add code to get the filename info from the iolayer */
696   /* Also add code to check for mmapped code */
697
698
699   mm_log((1, "i_writetiff_wiol_faxable: width=%d, height=%d, channels=%d\n", width, height, im->channels));
700   
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; }
717
718   linebuf = (unsigned char *)_TIFFmalloc( TIFFScanlineSize(tif) );
719   
720   if (!TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, TIFFDefaultStripSize(tif, -1))) {
721     mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField rowsperstrip=-1\n")); return 0; }
722
723   TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
724   TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rc);
725
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));
729
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; 
736   }
737
738   if (!save_tiff_tags(tif, im)) {
739     return 0;
740   }
741
742   for (y=0; y<height; y++) {
743     int linebufpos=0;
744     for(x=0; x<width; x+=8) { 
745       int bits;
746       int bitpos;
747       i_sample_t luma[8];
748       uint8 bitval = 128;
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);
754         bitval >>= 1;
755       }
756       linebufpos++;
757     }
758     if (TIFFWriteScanline(tif, linebuf, y, 0) < 0) {
759       mm_log((1, "i_writetiff_wiol_faxable: TIFFWriteScanline failed.\n"));
760       break;
761     }
762   }
763   if (linebuf) _TIFFfree(linebuf);
764
765   return 1;
766 }
767
768 static uint16
769 find_compression(char const *name, uint16 *compress) {
770   int i;
771
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;
775       return 1;
776     }
777   }
778   *compress = COMPRESSION_NONE;
779
780   return 0;
781 }
782
783 static uint16
784 get_compression(i_img *im, uint16 def_compress) {
785   int entry;
786   int value;
787
788   if (i_tags_find(&im->tags, "tiff_compression", 0, &entry)
789       && im->tags.tags[entry].data) {
790     uint16 compress;
791     if (find_compression(im->tags.tags[entry].data, &compress)
792         && myTIFFIsCODECConfigured(compress))
793       return compress;
794   }
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;
799   }
800
801   return def_compress;
802 }
803
804 int
805 i_tiff_has_compression(const char *name) {
806   uint16 compress;
807
808   if (!find_compression(name, &compress))
809     return 0;
810
811   return myTIFFIsCODECConfigured(compress);
812 }
813
814 static int
815 set_base_tags(TIFF *tif, i_img *im, uint16 compress, uint16 photometric, 
816               uint16 bits_per_sample, uint16 samples_per_pixel) {
817   double xres, yres;
818   int resunit;
819   int got_xres, got_yres;
820   int aspect_only;
821
822   if (!TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, im->xsize)) {
823     i_push_error(0, "write TIFF: setting width tag");
824     return 0;
825   }
826   if (!TIFFSetField(tif, TIFFTAG_IMAGELENGTH, im->ysize)) {
827     i_push_error(0, "write TIFF: setting length tag");
828     return 0;
829   }
830   if (!TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT)) {
831     i_push_error(0, "write TIFF: setting orientation tag");
832     return 0;
833   }
834   if (!TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG)) {
835     i_push_error(0, "write TIFF: setting planar configuration tag");
836     return 0;
837   }
838   if (!TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, photometric)) {
839     i_push_error(0, "write TIFF: setting photometric tag");
840     return 0;
841   }
842   if (!TIFFSetField(tif, TIFFTAG_COMPRESSION, compress)) {
843     i_push_error(0, "write TIFF: setting compression tag");
844     return 0;
845   }
846   if (!TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bits_per_sample)) {
847     i_push_error(0, "write TIFF: setting bits per sample tag");
848     return 0;
849   }
850   if (!TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, samples_per_pixel)) {
851     i_push_error(0, "write TIFF: setting samples per pixel tag");
852     return 0;
853   }
854
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))
858     aspect_only = 0;
859   if (!i_tags_get_int(&im->tags, "tiff_resolutionunit", 0, &resunit))
860     resunit = RESUNIT_INCH;
861   if (got_xres || got_yres) {
862     if (!got_xres)
863       xres = yres;
864     else if (!got_yres)
865       yres = xres;
866     if (aspect_only) {
867       resunit = RESUNIT_NONE;
868     }
869     else {
870       if (resunit == RESUNIT_CENTIMETER) {
871         xres /= 2.54;
872         yres /= 2.54;
873       }
874       else {
875         resunit  = RESUNIT_INCH;
876       }
877     }
878     if (!TIFFSetField(tif, TIFFTAG_XRESOLUTION, (float)xres)) {
879       i_push_error(0, "write TIFF: setting xresolution tag");
880       return 0;
881     }
882     if (!TIFFSetField(tif, TIFFTAG_YRESOLUTION, (float)yres)) {
883       i_push_error(0, "write TIFF: setting yresolution tag");
884       return 0;
885     }
886     if (!TIFFSetField(tif, TIFFTAG_RESOLUTIONUNIT, (uint16)resunit)) {
887       i_push_error(0, "write TIFF: setting resolutionunit tag");
888       return 0;
889     }
890   }
891
892   return 1;
893 }
894
895 static int 
896 write_one_bilevel(TIFF *tif, i_img *im, int zero_is_white) {
897   uint16 compress = get_compression(im, COMPRESSION_PACKBITS);
898   uint16 photometric;
899   unsigned char *in_row;
900   unsigned char *out_row;
901   unsigned out_size;
902   i_img_dim x, y;
903   int invert;
904
905   mm_log((1, "tiff - write_one_bilevel(tif %p, im %p, zero_is_white %d)\n", 
906           tif, im, zero_is_white));
907
908   /* ignore a silly choice */
909   if (compress == COMPRESSION_JPEG)
910     compress = COMPRESSION_PACKBITS;
911
912   switch (compress) {
913   case COMPRESSION_CCITTRLE:
914   case COMPRESSION_CCITTFAX3:
915   case COMPRESSION_CCITTFAX4:
916     /* natural fax photometric */
917     photometric = PHOTOMETRIC_MINISWHITE;
918     break;
919
920   default:
921     /* natural for most computer images */
922     photometric = PHOTOMETRIC_MINISBLACK;
923     break;
924   }
925
926   if (!set_base_tags(tif, im, compress, photometric, 1, 1))
927     return 0;
928
929   if (!TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, TIFFDefaultStripSize(tif, -1))) {
930     i_push_error(0, "write TIFF: setting rows per strip tag");
931     return 0; 
932   }
933
934   out_size = TIFFScanlineSize(tif);
935   out_row = (unsigned char *)_TIFFmalloc( out_size );
936   in_row = mymalloc(im->xsize);
937
938   invert = (photometric == PHOTOMETRIC_MINISWHITE) != (zero_is_white != 0);
939
940   for (y = 0; y < im->ysize; ++y) {
941     int mask = 0x80;
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]) {
947         *outp |= mask;
948       }
949       mask >>= 1;
950       if (!mask) {
951         ++outp;
952         mask = 0x80;
953       }
954     }
955     if (TIFFWriteScanline(tif, out_row, y, 0) < 0) {
956       _TIFFfree(out_row);
957       myfree(in_row);
958       i_push_error(0, "write TIFF: write scan line failed");
959       return 0;
960     }
961   }
962
963   _TIFFfree(out_row);
964   myfree(in_row);
965
966   return 1;
967 }
968
969 static int
970 set_palette(TIFF *tif, i_img *im, int size) {
971   int count;
972   uint16 *colors;
973   uint16 *out[3];
974   i_color c;
975   int i, ch;
976   
977   colors = (uint16 *)_TIFFmalloc(sizeof(uint16) * 3 * size);
978   out[0] = colors;
979   out[1] = colors + size;
980   out[2] = colors + 2 * size;
981     
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;
987   }
988   for (; i < size; ++i) {
989     for (ch = 0; ch < 3; ++ch)
990       out[ch][i] = 0;
991   }
992   if (!TIFFSetField(tif, TIFFTAG_COLORMAP, out[0], out[1], out[2])) {
993     _TIFFfree(colors);
994     i_push_error(0, "write TIFF: setting color map");
995     return 0;
996   }
997   _TIFFfree(colors);
998   
999   return 1;
1000 }
1001
1002 static int
1003 write_one_paletted8(TIFF *tif, i_img *im) {
1004   uint16 compress = get_compression(im, COMPRESSION_PACKBITS);
1005   unsigned char *out_row;
1006   unsigned out_size;
1007   i_img_dim y;
1008
1009   mm_log((1, "tiff - write_one_paletted8(tif %p, im %p)\n", tif, im));
1010
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;
1017
1018   if (!TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, TIFFDefaultStripSize(tif, -1))) {
1019     i_push_error(0, "write TIFF: setting rows per strip tag");
1020     return 0; 
1021   }
1022
1023   if (!set_base_tags(tif, im, compress, PHOTOMETRIC_PALETTE, 8, 1))
1024     return 0;
1025
1026   if (!set_palette(tif, im, 256))
1027     return 0;
1028
1029   out_size = TIFFScanlineSize(tif);
1030   out_row = (unsigned char *)_TIFFmalloc( out_size );
1031
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) {
1035       _TIFFfree(out_row);
1036       i_push_error(0, "write TIFF: write scan line failed");
1037       return 0;
1038     }
1039   }
1040
1041   _TIFFfree(out_row);
1042
1043   return 1;
1044 }
1045
1046 static int
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;
1051   size_t out_size;
1052   i_img_dim y;
1053
1054   mm_log((1, "tiff - write_one_paletted4(tif %p, im %p)\n", tif, im));
1055
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;
1062
1063   if (!set_base_tags(tif, im, compress, PHOTOMETRIC_PALETTE, 4, 1))
1064     return 0;
1065
1066   if (!set_palette(tif, im, 16))
1067     return 0;
1068
1069   if (!TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, TIFFDefaultStripSize(tif, -1))) {
1070     i_push_error(0, "write TIFF: setting rows per strip tag");
1071     return 0; 
1072   }
1073
1074   in_row = mymalloc(im->xsize);
1075   out_size = TIFFScanlineSize(tif);
1076   out_row = (unsigned char *)_TIFFmalloc( out_size );
1077
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) {
1083       _TIFFfree(out_row);
1084       i_push_error(0, "write TIFF: write scan line failed");
1085       return 0;
1086     }
1087   }
1088
1089   myfree(in_row);
1090   _TIFFfree(out_row);
1091
1092   return 1;
1093 }
1094
1095 static int
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;
1102
1103   if (!set_base_tags(tif, im, compress, photometric, bits_per_sample, 
1104                      im->channels)) {
1105     return 0;
1106   }
1107   
1108   if (extra_count) {
1109     if (!TIFFSetField(tif, TIFFTAG_EXTRASAMPLES, extra_count, &extras)) {
1110       i_push_error(0, "write TIFF: setting extra samples tag");
1111       return 0;
1112     }
1113   }
1114
1115   if (compress == COMPRESSION_JPEG) {
1116     int jpeg_quality;
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");
1121         return 0;
1122       }
1123     }
1124   }
1125
1126   return 1;
1127 }
1128
1129 static int 
1130 write_one_32(TIFF *tif, i_img *im) {
1131   uint16 compress = get_compression(im, COMPRESSION_PACKBITS);
1132   unsigned *in_row;
1133   size_t out_size;
1134   uint32 *out_row;
1135   i_img_dim y;
1136   size_t sample_count = im->xsize * im->channels;
1137   size_t sample_index;
1138     
1139   mm_log((1, "tiff - write_one_32(tif %p, im %p)\n", tif, im));
1140
1141   /* only 8 and 12 bit samples are supported by jpeg compression */
1142   if (compress == COMPRESSION_JPEG)
1143     compress = COMPRESSION_PACKBITS;
1144
1145   if (!set_direct_tags(tif, im, compress, 32))
1146     return 0;
1147
1148   in_row = mymalloc(sample_count * sizeof(unsigned));
1149   out_size = TIFFScanlineSize(tif);
1150   out_row = (uint32 *)_TIFFmalloc( out_size );
1151
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");
1155       return 0;
1156     }
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) {
1160       myfree(in_row);
1161       _TIFFfree(out_row);
1162       i_push_error(0, "write TIFF: write scan line failed");
1163       return 0;
1164     }
1165   }
1166
1167   myfree(in_row);
1168   _TIFFfree(out_row);
1169   
1170   return 1;
1171 }
1172
1173 static int 
1174 write_one_16(TIFF *tif, i_img *im) {
1175   uint16 compress = get_compression(im, COMPRESSION_PACKBITS);
1176   unsigned *in_row;
1177   size_t out_size;
1178   uint16 *out_row;
1179   i_img_dim y;
1180   size_t sample_count = im->xsize * im->channels;
1181   size_t sample_index;
1182     
1183   mm_log((1, "tiff - write_one_16(tif %p, im %p)\n", tif, im));
1184
1185   /* only 8 and 12 bit samples are supported by jpeg compression */
1186   if (compress == COMPRESSION_JPEG)
1187     compress = COMPRESSION_PACKBITS;
1188
1189   if (!set_direct_tags(tif, im, compress, 16))
1190     return 0;
1191
1192   in_row = mymalloc(sample_count * sizeof(unsigned));
1193   out_size = TIFFScanlineSize(tif);
1194   out_row = (uint16 *)_TIFFmalloc( out_size );
1195
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");
1199       return 0;
1200     }
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) {
1204       myfree(in_row);
1205       _TIFFfree(out_row);
1206       i_push_error(0, "write TIFF: write scan line failed");
1207       return 0;
1208     }
1209   }
1210
1211   myfree(in_row);
1212   _TIFFfree(out_row);
1213   
1214   return 1;
1215 }
1216
1217 static int 
1218 write_one_8(TIFF *tif, i_img *im) {
1219   uint16 compress = get_compression(im, COMPRESSION_PACKBITS);
1220   size_t out_size;
1221   unsigned char *out_row;
1222   i_img_dim y;
1223   size_t sample_count = im->xsize * im->channels;
1224     
1225   mm_log((1, "tiff - write_one_8(tif %p, im %p)\n", tif, im));
1226
1227   if (!set_direct_tags(tif, im, compress, 8))
1228     return 0;
1229
1230   out_size = TIFFScanlineSize(tif);
1231   if (out_size < sample_count)
1232     out_size = sample_count;
1233   out_row = (unsigned char *)_TIFFmalloc( out_size );
1234
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");
1238       return 0;
1239     }
1240     if (TIFFWriteScanline(tif, out_row, y, 0) < 0) {
1241       _TIFFfree(out_row);
1242       i_push_error(0, "write TIFF: write scan line failed");
1243       return 0;
1244     }
1245   }
1246   _TIFFfree(out_row);
1247   
1248   return 1;
1249 }
1250
1251 static int
1252 i_writetiff_low(TIFF *tif, i_img *im) {
1253   uint32 width, height;
1254   uint16 channels;
1255   int zero_is_white;
1256
1257   width    = im->xsize;
1258   height   = im->ysize;
1259   channels = im->channels;
1260
1261   if (width != im->xsize || height != im->ysize) {
1262     i_push_error(0, "image too large for TIFF");
1263     return 0;
1264   }
1265
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)));
1269   }
1270   
1271   if (i_img_is_monochrome(im, &zero_is_white)) {
1272     if (!write_one_bilevel(tif, im, zero_is_white))
1273       return 0;
1274   }
1275   else if (im->type == i_palette_type) {
1276     if (i_colorcount(im) <= 16) {
1277       if (!write_one_paletted4(tif, im))
1278         return 0;
1279     }
1280     else {
1281       if (!write_one_paletted8(tif, im))
1282         return 0;
1283     }
1284   }
1285   else if (im->bits > 16) {
1286     if (!write_one_32(tif, im))
1287       return 0;
1288   }
1289   else if (im->bits > 8) {
1290     if (!write_one_16(tif, im))
1291       return 0;
1292   }
1293   else {
1294     if (!write_one_8(tif, im))
1295       return 0;
1296   }
1297
1298   if (!save_tiff_tags(tif, im))
1299     return 0;
1300
1301   return 1;
1302 }
1303
1304 /*
1305 =item i_writetiff_multi_wiol(ig, imgs, count, fine_mode)
1306
1307 Stores an image in the iolayer object.
1308
1309    ig - io_object that defines source to write to 
1310    imgs,count - the images to write
1311
1312 =cut 
1313 */
1314
1315 undef_int
1316 i_writetiff_multi_wiol(io_glue *ig, i_img **imgs, int count) {
1317   TIFF* tif;
1318   TIFFErrorHandler old_handler;
1319   int i;
1320
1321   old_handler = TIFFSetErrorHandler(error_handler);
1322
1323   i_clear_error();
1324   mm_log((1, "i_writetiff_multi_wiol(ig %p, imgs %p, count %d)\n", 
1325           ig, imgs, count));
1326
1327   /* FIXME: Enable the mmap interface */
1328   
1329   tif = TIFFClientOpen("No name", 
1330                        "wm",
1331                        (thandle_t) ig, 
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);
1339   
1340
1341
1342   if (!tif) {
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);
1346     return 0;
1347   }
1348
1349   for (i = 0; i < count; ++i) {
1350     if (!i_writetiff_low(tif, imgs[i])) {
1351       TIFFClose(tif);
1352       TIFFSetErrorHandler(old_handler);
1353       return 0;
1354     }
1355
1356     if (!TIFFWriteDirectory(tif)) {
1357       i_push_error(0, "Cannot write TIFF directory");
1358       TIFFClose(tif);
1359       TIFFSetErrorHandler(old_handler);
1360       return 0;
1361     }
1362   }
1363
1364   TIFFSetErrorHandler(old_handler);
1365   (void) TIFFClose(tif);
1366
1367   return 1;
1368 }
1369
1370 /*
1371 =item i_writetiff_multi_wiol_faxable(ig, imgs, count, fine_mode)
1372
1373 Stores an image in the iolayer object.
1374
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
1378
1379 =cut 
1380 */
1381
1382
1383 undef_int
1384 i_writetiff_multi_wiol_faxable(io_glue *ig, i_img **imgs, int count, int fine) {
1385   TIFF* tif;
1386   int i;
1387   TIFFErrorHandler old_handler;
1388
1389   old_handler = TIFFSetErrorHandler(error_handler);
1390
1391   i_clear_error();
1392   mm_log((1, "i_writetiff_multi_wiol(ig %p, imgs %p, count %d)\n", 
1393           ig, imgs, count));
1394
1395   /* FIXME: Enable the mmap interface */
1396   
1397   tif = TIFFClientOpen("No name", 
1398                        "wm",
1399                        (thandle_t) ig, 
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);
1407   
1408
1409
1410   if (!tif) {
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);
1414     return 0;
1415   }
1416
1417   for (i = 0; i < count; ++i) {
1418     if (!i_writetiff_low_faxable(tif, imgs[i], fine)) {
1419       TIFFClose(tif);
1420       TIFFSetErrorHandler(old_handler);
1421       return 0;
1422     }
1423
1424     if (!TIFFWriteDirectory(tif)) {
1425       i_push_error(0, "Cannot write TIFF directory");
1426       TIFFClose(tif);
1427       TIFFSetErrorHandler(old_handler);
1428       return 0;
1429     }
1430   }
1431
1432   (void) TIFFClose(tif);
1433   TIFFSetErrorHandler(old_handler);
1434
1435   return 1;
1436 }
1437
1438 /*
1439 =item i_writetiff_wiol(im, ig)
1440
1441 Stores an image in the iolayer object.
1442
1443    im - image object to write out
1444    ig - io_object that defines source to write to 
1445
1446 =cut 
1447 */
1448 undef_int
1449 i_writetiff_wiol(i_img *img, io_glue *ig) {
1450   TIFF* tif;
1451   TIFFErrorHandler old_handler;
1452
1453   old_handler = TIFFSetErrorHandler(error_handler);
1454
1455   i_clear_error();
1456   mm_log((1, "i_writetiff_wiol(img %p, ig %p)\n", img, ig));
1457
1458   /* FIXME: Enable the mmap interface */
1459
1460   tif = TIFFClientOpen("No name", 
1461                        "wm",
1462                        (thandle_t) ig, 
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);
1470   
1471
1472
1473   if (!tif) {
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);
1477     return 0;
1478   }
1479
1480   if (!i_writetiff_low(tif, img)) {
1481     TIFFClose(tif);
1482     TIFFSetErrorHandler(old_handler);
1483     return 0;
1484   }
1485
1486   (void) TIFFClose(tif);
1487   TIFFSetErrorHandler(old_handler);
1488
1489   return 1;
1490 }
1491
1492
1493
1494 /*
1495 =item i_writetiff_wiol_faxable(i_img *, io_glue *)
1496
1497 Stores an image in the iolayer object in faxable tiff format.
1498
1499    im - image object to write out
1500    ig - io_object that defines source to write to 
1501
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
1504 point.
1505
1506 =cut
1507 */
1508
1509 undef_int
1510 i_writetiff_wiol_faxable(i_img *im, io_glue *ig, int fine) {
1511   TIFF* tif;
1512   TIFFErrorHandler old_handler;
1513
1514   old_handler = TIFFSetErrorHandler(error_handler);
1515
1516   i_clear_error();
1517   mm_log((1, "i_writetiff_wiol(img %p, ig %p)\n", im, ig));
1518
1519   /* FIXME: Enable the mmap interface */
1520   
1521   tif = TIFFClientOpen("No name", 
1522                        "wm",
1523                        (thandle_t) ig, 
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);
1531   
1532
1533
1534   if (!tif) {
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);
1538     return 0;
1539   }
1540
1541   if (!i_writetiff_low_faxable(tif, im, fine)) {
1542     TIFFClose(tif);
1543     TIFFSetErrorHandler(old_handler);
1544     return 0;
1545   }
1546
1547   (void) TIFFClose(tif);
1548   TIFFSetErrorHandler(old_handler);
1549
1550   return 1;
1551 }
1552
1553 static int save_tiff_tags(TIFF *tif, i_img *im) {
1554   int i;
1555  
1556   for (i = 0; i < text_tag_count; ++i) {
1557     int entry;
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);
1562        return 0;
1563       }
1564     }
1565   }
1566  
1567   return 1;
1568 }
1569
1570
1571 static void
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;
1577     --src_byte_count;
1578   }
1579 }
1580
1581 static void pack_4bit_to(unsigned char *dest, const unsigned char *src, 
1582                          i_img_dim pixel_count) {
1583   int i = 0;
1584   while (i < pixel_count) {
1585     if ((i & 1) == 0) {
1586       *dest = *src++ << 4;
1587     }
1588     else {
1589       *dest++ |= *src++;
1590     }
1591     ++i;
1592   }
1593 }
1594
1595 /*
1596 =item fallback_rgb_channels
1597
1598 Calculate the number of output channels when we fallback to the RGBA
1599 family of functions.
1600
1601 =cut
1602 */
1603
1604 static void
1605 fallback_rgb_channels(TIFF *tif, i_img_dim width, i_img_dim height, int *channels, int *alpha_chan) {
1606   uint16 photometric;
1607   uint16 in_channels;
1608   uint16 extra_count;
1609   uint16 *extras;
1610
1611   TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &in_channels);
1612   TIFFGetFieldDefaulted(tif, TIFFTAG_PHOTOMETRIC, &photometric);
1613
1614   switch (photometric) {
1615   case PHOTOMETRIC_SEPARATED:
1616     *channels = 3;
1617     break;
1618   
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 
1623        if needed */
1624     *channels = 1;
1625     break;
1626
1627   default:
1628     *channels = 3;
1629     break;
1630   }
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 */
1634   *alpha_chan = 0;
1635   if (TIFFGetField(tif, TIFFTAG_EXTRASAMPLES, &extra_count, &extras)
1636       && extra_count) {
1637     *alpha_chan = (*channels)++;
1638   }
1639 }
1640
1641 static i_img *
1642 make_rgb(TIFF *tif, i_img_dim width, i_img_dim height, int *alpha_chan) {
1643   int channels = 0;
1644
1645   fallback_rgb_channels(tif, width, height, &channels, alpha_chan);
1646
1647   return i_img_8_new(width, height, channels);
1648 }
1649
1650 static i_img *
1651 read_one_rgb_lines(TIFF *tif, i_img_dim width, i_img_dim height, int allow_incomplete) {
1652   i_img *im;
1653   uint32* raster = NULL;
1654   uint32 rowsperstrip, row;
1655   i_color *line_buf;
1656   int alpha_chan;
1657   int rc;
1658
1659   im = make_rgb(tif, width, height, &alpha_chan);
1660   if (!im)
1661     return NULL;
1662
1663   rc = TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
1664   mm_log((1, "i_readtiff_wiol: rowsperstrip=%d rc = %d\n", rowsperstrip, rc));
1665   
1666   if (rc != 1 || rowsperstrip==-1) {
1667     rowsperstrip = height;
1668   }
1669   
1670   raster = (uint32*)_TIFFmalloc(width * rowsperstrip * sizeof (uint32));
1671   if (!raster) {
1672     i_img_destroy(im);
1673     i_push_error(0, "No space for raster buffer");
1674     return NULL;
1675   }
1676
1677   line_buf = mymalloc(sizeof(i_color) * width);
1678   
1679   for( row = 0; row < height; row += rowsperstrip ) {
1680     uint32 newrows, i_row;
1681     
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);
1686         break;
1687       }
1688       else {
1689         i_push_error(0, "could not read TIFF image strip");
1690         _TIFFfree(raster);
1691         i_img_destroy(im);
1692         return NULL;
1693       }
1694     }
1695     
1696     newrows = (row+rowsperstrip > height) ? height-row : rowsperstrip;
1697     mm_log((1, "newrows=%d\n", newrows));
1698     
1699     for( i_row = 0; i_row < newrows; i_row++ ) { 
1700       uint32 x;
1701       i_color *outp = line_buf;
1702
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);
1708
1709         if (alpha_chan) {
1710           /* the libtiff RGBA code expands greyscale into RGBA, so put the
1711              alpha in the right place and scale it */
1712           int ch;
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];
1717             }
1718           }
1719         }
1720
1721         outp++;
1722       }
1723       i_plin(im, 0, width, i_row+row, line_buf);
1724     }
1725   }
1726
1727   myfree(line_buf);
1728   _TIFFfree(raster);
1729   
1730   return im;
1731 }
1732
1733 /* adapted from libtiff 
1734
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.
1738
1739   So the caller here has set stoponerror to 1 so that
1740   TIFFRGBAImageGet() will fail.
1741
1742   read_one_rgb_tiled() then takes that into account for i_incomplete
1743   or failure.
1744  */
1745 static int
1746 myTIFFReadRGBATile(TIFFRGBAImage *img, uint32 col, uint32 row, uint32 * raster)
1747
1748 {
1749     int         ok;
1750     uint32      tile_xsize, tile_ysize;
1751     uint32      read_xsize, read_ysize;
1752     uint32      i_row;
1753
1754     /*
1755      * Verify that our request is legal - on a tile file, and on a
1756      * tile boundary.
1757      */
1758     
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 )
1762     {
1763       i_push_errorf(0, "Row/col passed to myTIFFReadRGBATile() must be top"
1764                     "left corner of a tile.");
1765       return 0;
1766     }
1767
1768     /*
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.
1773      */
1774
1775     if( row + tile_ysize > img->height )
1776         read_ysize = img->height - row;
1777     else
1778         read_ysize = tile_ysize;
1779     
1780     if( col + tile_xsize > img->width )
1781         read_xsize = img->width - col;
1782     else
1783         read_xsize = tile_xsize;
1784
1785     /*
1786      * Read the chunk of imagery.
1787      */
1788     
1789     img->row_offset = row;
1790     img->col_offset = col;
1791
1792     ok = TIFFRGBAImageGet(img, raster, read_xsize, read_ysize );
1793         
1794     /*
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.
1797      *
1798      * This is all the more complicated because the image is organized in
1799      * bottom to top format. 
1800      */
1801
1802     if( read_xsize == tile_xsize && read_ysize == tile_ysize )
1803         return( ok );
1804
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) );
1811     }
1812
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 );
1816     }
1817
1818     return (ok);
1819 }
1820
1821 static i_img *
1822 read_one_rgb_tiled(TIFF *tif, i_img_dim width, i_img_dim height, int allow_incomplete) {
1823   i_img *im;
1824   uint32* raster = NULL;
1825   int ok = 1;
1826   uint32 row, col;
1827   uint32 tile_width, tile_height;
1828   unsigned long pixels = 0;
1829   char  emsg[1024] = "";
1830   TIFFRGBAImage img;
1831   i_color *line;
1832   int alpha_chan;
1833   
1834   im = make_rgb(tif, width, height, &alpha_chan);
1835   if (!im)
1836     return NULL;
1837   
1838   if (!TIFFRGBAImageOK(tif, emsg) 
1839       || !TIFFRGBAImageBegin(&img, tif, 1, emsg)) {
1840     i_push_error(0, emsg);
1841     i_img_destroy(im);
1842     return( 0 );
1843   }
1844
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));
1848   
1849   raster = (uint32*)_TIFFmalloc(tile_width * tile_height * sizeof (uint32));
1850   if (!raster) {
1851     i_img_destroy(im);
1852     i_push_error(0, "No space for raster buffer");
1853     TIFFRGBAImageEnd(&img);
1854     return NULL;
1855   }
1856   line = mymalloc(tile_width * sizeof(i_color));
1857   
1858   for( row = 0; row < height; row += tile_height ) {
1859     for( col = 0; col < width; col += tile_width ) {
1860       
1861       /* Read the tile into an RGBA array */
1862       if (myTIFFReadRGBATile(&img, col, row, raster)) {
1863         uint32 i_row, x;
1864         uint32 newrows = (row+tile_height > height) ? height-row : tile_height;
1865         uint32 newcols = (col+tile_width  > width ) ? width-col  : tile_width;
1866
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);
1876
1877             if (alpha_chan) {
1878               /* the libtiff RGBA code expands greyscale into RGBA, so put the
1879                  alpha in the right place and scale it */
1880               int ch;
1881               outp->channel[alpha_chan] = TIFFGetA(temp);
1882               
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];
1886                 }
1887               }
1888             }
1889
1890             ++outp;
1891           }
1892           i_plin(im, col, col+newcols, row+i_row, line);
1893         }
1894         pixels += newrows * newcols;
1895       }
1896       else {
1897         if (allow_incomplete) {
1898           ok = 0;
1899         }
1900         else {
1901           goto error;
1902         }
1903       }
1904     }
1905   }
1906
1907   if (!ok) {
1908     if (pixels == 0) {
1909       i_push_error(0, "TIFF: No image data could be read from the image");
1910       goto error;
1911     }
1912
1913     /* incomplete image */
1914     i_tags_setn(&im->tags, "i_incomplete", 1);
1915     i_tags_setn(&im->tags, "i_lines_read", pixels / width);
1916   }
1917
1918   myfree(line);
1919   TIFFRGBAImageEnd(&img);
1920   _TIFFfree(raster);
1921   
1922   return im;
1923
1924  error:
1925   myfree(line);
1926   _TIFFfree(raster);
1927   TIFFRGBAImageEnd(&img);
1928   i_img_destroy(im);
1929   return NULL;
1930 }
1931
1932 char const *
1933 i_tiff_libversion(void) {
1934   return TIFFGetVersion();
1935 }
1936
1937 static int 
1938 setup_paletted(read_state_t *state) {
1939   uint16 *maps[3];
1940   int i, ch;
1941   int color_count = 1 << state->bits_per_sample;
1942
1943   state->img = i_img_pal_new(state->width, state->height, 3, 256);
1944   if (!state->img)
1945     return 0;
1946
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);
1951     return 0;
1952   }
1953   for (i = 0; i < color_count; ++i) {
1954     i_color c;
1955     for (ch = 0; ch < 3; ++ch) {
1956       c.channel[ch] = Sample16To8(maps[ch][i]);
1957     }
1958     i_addcolors(state->img, &c, 1);
1959   }
1960
1961   return 1;
1962 }
1963
1964 static int 
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;
1969   uint32 x, y;
1970
1971   state->raster = _TIFFmalloc(TIFFTileSize(state->tif));
1972   if (!state->raster) {
1973     i_push_error(0, "tiff: Out of memory allocating tile buffer");
1974     return 0;
1975   }
1976
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;
1982
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;
1986
1987       if (TIFFReadTile(state->tif,
1988                        state->raster,
1989                        x, y, 0, 0) < 0) {
1990         if (!state->allow_incomplete) {
1991           return 0;
1992         }
1993       }
1994       else {
1995         putter(state, x, y, this_tile_width, this_tile_height, tile_width - this_tile_width);
1996       }
1997
1998       cols_left -= this_tile_width;
1999     }
2000
2001     rows_left -= this_tile_height;
2002   }
2003
2004   return 1;
2005 }
2006
2007 static int 
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;
2012
2013   state->raster = _TIFFmalloc(strip_size);
2014   if (!state->raster) {
2015     i_push_error(0, "tiff: Out of memory allocating strip buffer");
2016     return 0;
2017   }
2018   
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),
2025                              state->raster,
2026                              strip_size) < 0) {
2027       if (!state->allow_incomplete)
2028         return 0;
2029     }
2030     else {
2031       putter(state, 0, y, state->width, strip_rows, 0);
2032     }
2033     rows_left -= strip_rows;
2034   }
2035
2036   return 1;
2037 }
2038
2039 static int 
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;
2042
2043   state->pixels_read += width * height;
2044   while (height > 0) {
2045     i_ppal(state->img, x, x + width, y, p);
2046     p += width + extras;
2047     --height;
2048     ++y;
2049   }
2050
2051   return 1;
2052 }
2053
2054 static int 
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;
2059
2060   if (!state->line_buf)
2061     state->line_buf = mymalloc(state->width);
2062
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;
2068     --height;
2069     ++y;
2070   }
2071
2072   return 1;
2073 }
2074
2075 static void
2076 rgb_channels(read_state_t *state, int *out_channels) {
2077   uint16 extra_count;
2078   uint16 *extras;
2079   
2080   /* safe defaults */
2081   *out_channels = 3;
2082   state->alpha_chan = 0;
2083   state->scale_alpha = 0;
2084
2085   /* plain RGB */
2086   if (state->samples_per_pixel == 3)
2087     return;
2088  
2089   if (!TIFFGetField(state->tif, TIFFTAG_EXTRASAMPLES, &extra_count, &extras)) {
2090     mm_log((1, "tiff: samples != 3 but no extra samples tag\n"));
2091     return;
2092   }
2093
2094   if (!extra_count) {
2095     mm_log((1, "tiff: samples != 3 but no extra samples listed"));
2096     return;
2097   }
2098
2099   ++*out_channels;
2100   state->alpha_chan = 3;
2101   switch (*extras) {
2102   case EXTRASAMPLE_UNSPECIFIED:
2103   case EXTRASAMPLE_ASSOCALPHA:
2104     state->scale_alpha = 1;
2105     break;
2106
2107   case EXTRASAMPLE_UNASSALPHA:
2108     state->scale_alpha = 0;
2109     break;
2110
2111   default:
2112     mm_log((1, "tiff: unknown extra sample type %d, treating as assoc alpha\n",
2113             *extras));
2114     state->scale_alpha = 1;
2115     break;
2116   }
2117   mm_log((1, "tiff alpha channel %d scale %d\n", state->alpha_chan, state->scale_alpha));
2118 }
2119
2120 static void
2121 grey_channels(read_state_t *state, int *out_channels) {
2122   uint16 extra_count;
2123   uint16 *extras;
2124   
2125   /* safe defaults */
2126   *out_channels = 1;
2127   state->alpha_chan = 0;
2128   state->scale_alpha = 0;
2129
2130   /* plain grey */
2131   if (state->samples_per_pixel == 1)
2132     return;
2133  
2134   if (!TIFFGetField(state->tif, TIFFTAG_EXTRASAMPLES, &extra_count, &extras)) {
2135     mm_log((1, "tiff: samples != 1 but no extra samples tag\n"));
2136     return;
2137   }
2138
2139   if (!extra_count) {
2140     mm_log((1, "tiff: samples != 1 but no extra samples listed"));
2141     return;
2142   }
2143
2144   ++*out_channels;
2145   state->alpha_chan = 1;
2146   switch (*extras) {
2147   case EXTRASAMPLE_UNSPECIFIED:
2148   case EXTRASAMPLE_ASSOCALPHA:
2149     state->scale_alpha = 1;
2150     break;
2151
2152   case EXTRASAMPLE_UNASSALPHA:
2153     state->scale_alpha = 0;
2154     break;
2155
2156   default:
2157     mm_log((1, "tiff: unknown extra sample type %d, treating as assoc alpha\n",
2158             *extras));
2159     state->scale_alpha = 1;
2160     break;
2161   }
2162 }
2163
2164 static int
2165 setup_16_rgb(read_state_t *state) {
2166   int out_channels;
2167
2168   rgb_channels(state, &out_channels);
2169
2170   state->img = i_img_16_new(state->width, state->height, out_channels);
2171   if (!state->img)
2172     return 0;
2173   state->line_buf = mymalloc(sizeof(unsigned) * state->width * out_channels);
2174
2175   return 1;
2176 }
2177
2178 static int
2179 setup_16_grey(read_state_t *state) {
2180   int out_channels;
2181
2182   grey_channels(state, &out_channels);
2183
2184   state->img = i_img_16_new(state->width, state->height, out_channels);
2185   if (!state->img)
2186     return 0;
2187   state->line_buf = mymalloc(sizeof(unsigned) * state->width * out_channels);
2188
2189   return 1;
2190 }
2191
2192 static int 
2193 putter_16(read_state_t *state, i_img_dim x, i_img_dim y, i_img_dim width, i_img_dim height, 
2194           int row_extras) {
2195   uint16 *p = state->raster;
2196   int out_chan = state->img->channels;
2197
2198   state->pixels_read += width * height;
2199   while (height > 0) {
2200     i_img_dim i;
2201     int ch;
2202     unsigned *outp = state->line_buf;
2203
2204     for (i = 0; i < width; ++i) {
2205       for (ch = 0; ch < out_chan; ++ch) {
2206         outp[ch] = p[ch];
2207       }
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);
2212         }
2213       }
2214       p += state->samples_per_pixel;
2215       outp += out_chan;
2216     }
2217
2218     i_psamp_bits(state->img, x, x + width, y, state->line_buf, NULL, out_chan, 16);
2219
2220     p += row_extras * state->samples_per_pixel;
2221     --height;
2222     ++y;
2223   }
2224
2225   return 1;
2226 }
2227
2228 static int
2229 setup_8_rgb(read_state_t *state) {
2230   int out_channels;
2231
2232   rgb_channels(state, &out_channels);
2233
2234   state->img = i_img_8_new(state->width, state->height, out_channels);
2235   if (!state->img)
2236     return 0;
2237   state->line_buf = mymalloc(sizeof(unsigned) * state->width * out_channels);
2238
2239   return 1;
2240 }
2241
2242 static int
2243 setup_8_grey(read_state_t *state) {
2244   int out_channels;
2245
2246   grey_channels(state, &out_channels);
2247
2248   state->img = i_img_8_new(state->width, state->height, out_channels);
2249   if (!state->img)
2250     return 0;
2251   state->line_buf = mymalloc(sizeof(i_color) * state->width * out_channels);
2252
2253   return 1;
2254 }
2255
2256 static int 
2257 putter_8(read_state_t *state, i_img_dim x, i_img_dim y, i_img_dim width, i_img_dim height, 
2258           int row_extras) {
2259   unsigned char *p = state->raster;
2260   int out_chan = state->img->channels;
2261
2262   state->pixels_read += width * height;
2263   while (height > 0) {
2264     i_img_dim i;
2265     int ch;
2266     i_color *outp = state->line_buf;
2267
2268     for (i = 0; i < width; ++i) {
2269       for (ch = 0; ch < out_chan; ++ch) {
2270         outp->channel[ch] = p[ch];
2271       }
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];
2276         
2277           outp->channel[ch] = CLAMP8(result);
2278         }
2279       }
2280       p += state->samples_per_pixel;
2281       outp++;
2282     }
2283
2284     i_plin(state->img, x, x + width, y, state->line_buf);
2285
2286     p += row_extras * state->samples_per_pixel;
2287     --height;
2288     ++y;
2289   }
2290
2291   return 1;
2292 }
2293
2294 static int
2295 setup_32_rgb(read_state_t *state) {
2296   int out_channels;
2297
2298   rgb_channels(state, &out_channels);
2299
2300   state->img = i_img_double_new(state->width, state->height, out_channels);
2301   if (!state->img)
2302     return 0;
2303   state->line_buf = mymalloc(sizeof(i_fcolor) * state->width);
2304
2305   return 1;
2306 }
2307
2308 static int
2309 setup_32_grey(read_state_t *state) {
2310   int out_channels;
2311
2312   grey_channels(state, &out_channels);
2313
2314   state->img = i_img_double_new(state->width, state->height, out_channels);
2315   if (!state->img)
2316     return 0;
2317   state->line_buf = mymalloc(sizeof(i_fcolor) * state->width);
2318
2319   return 1;
2320 }
2321
2322 static int 
2323 putter_32(read_state_t *state, i_img_dim x, i_img_dim y, i_img_dim width, i_img_dim height, 
2324           int row_extras) {
2325   uint32 *p = state->raster;
2326   int out_chan = state->img->channels;
2327
2328   state->pixels_read += width * height;
2329   while (height > 0) {
2330     i_img_dim i;
2331     int ch;
2332     i_fcolor *outp = state->line_buf;
2333
2334     for (i = 0; i < width; ++i) {
2335       for (ch = 0; ch < out_chan; ++ch) {
2336         outp->channel[ch] = p[ch] / 4294967295.0;
2337       }
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];
2341       }
2342       p += state->samples_per_pixel;
2343       outp++;
2344     }
2345
2346     i_plinf(state->img, x, x + width, y, state->line_buf);
2347
2348     p += row_extras * state->samples_per_pixel;
2349     --height;
2350     ++y;
2351   }
2352
2353   return 1;
2354 }
2355
2356 static int
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);
2360   if (!state->img)
2361     return 0;
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);
2369   }
2370   else {
2371     i_addcolors(state->img, &white, 1);
2372     i_addcolors(state->img, &black, 1);
2373   }
2374   state->line_buf = mymalloc(state->width);
2375
2376   return 1;
2377 }
2378
2379 static int 
2380 putter_bilevel(read_state_t *state, i_img_dim x, i_img_dim y, i_img_dim width, i_img_dim height, 
2381                int row_extras) {
2382   unsigned char *line_in = state->raster;
2383   size_t line_size = (width + row_extras + 7) / 8;
2384   
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) {
2389     i_img_dim i;
2390     unsigned char *outp = state->line_buf;
2391     unsigned char *inp = line_in;
2392     unsigned mask = 0x80;
2393
2394     for (i = 0; i < width; ++i) {
2395       *outp++ = *inp & mask ? 1 : 0;
2396       mask >>= 1;
2397       if (!mask) {
2398         ++inp;
2399         mask = 0x80;
2400       }
2401     }
2402
2403     i_ppal(state->img, x, x + width, y, state->line_buf);
2404
2405     line_in += line_size;
2406     --height;
2407     ++y;
2408   }
2409
2410   return 1;
2411 }
2412
2413 static void
2414 cmyk_channels(read_state_t *state, int *out_channels) {
2415   uint16 extra_count;
2416   uint16 *extras;
2417   
2418   /* safe defaults */
2419   *out_channels = 3;
2420   state->alpha_chan = 0;
2421   state->scale_alpha = 0;
2422
2423   /* plain CMYK */
2424   if (state->samples_per_pixel == 4)
2425     return;
2426  
2427   if (!TIFFGetField(state->tif, TIFFTAG_EXTRASAMPLES, &extra_count, &extras)) {
2428     mm_log((1, "tiff: CMYK samples != 4 but no extra samples tag\n"));
2429     return;
2430   }
2431
2432   if (!extra_count) {
2433     mm_log((1, "tiff: CMYK samples != 4 but no extra samples listed"));
2434     return;
2435   }
2436
2437   ++*out_channels;
2438   state->alpha_chan = 4;
2439   switch (*extras) {
2440   case EXTRASAMPLE_UNSPECIFIED:
2441   case EXTRASAMPLE_ASSOCALPHA:
2442     state->scale_alpha = 1;
2443     break;
2444
2445   case EXTRASAMPLE_UNASSALPHA:
2446     state->scale_alpha = 0;
2447     break;
2448
2449   default:
2450     mm_log((1, "tiff: unknown extra sample type %d, treating as assoc alpha\n",
2451             *extras));
2452     state->scale_alpha = 1;
2453     break;
2454   }
2455 }
2456
2457 static int
2458 setup_cmyk8(read_state_t *state) {
2459   int channels;
2460
2461   cmyk_channels(state, &channels);
2462   state->img = i_img_8_new(state->width, state->height, channels);
2463
2464   state->line_buf = mymalloc(sizeof(i_color) * state->width);
2465
2466   return 1;
2467 }
2468
2469 static int 
2470 putter_cmyk8(read_state_t *state, i_img_dim x, i_img_dim y, i_img_dim width, i_img_dim height, 
2471                int row_extras) {
2472   unsigned char *p = state->raster;
2473
2474   state->pixels_read += width * height;
2475   while (height > 0) {
2476     i_img_dim i;
2477     int ch;
2478     i_color *outp = state->line_buf;
2479
2480     for (i = 0; i < width; ++i) {
2481       unsigned char c, m, y, k;
2482       c = p[0];
2483       m = p[1];
2484       y = p[2];
2485       k = 255 - p[3];
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 
2492             && outp->rgba.a) {
2493           for (ch = 0; ch < 3; ++ch) {
2494             int result = (outp->channel[ch] * 255 + 127) / outp->rgba.a;
2495             outp->channel[ch] = CLAMP8(result);
2496           }
2497         }
2498       }
2499       p += state->samples_per_pixel;
2500       outp++;
2501     }
2502
2503     i_plin(state->img, x, x + width, y, state->line_buf);
2504
2505     p += row_extras * state->samples_per_pixel;
2506     --height;
2507     ++y;
2508   }
2509
2510   return 1;
2511 }
2512
2513 static int
2514 setup_cmyk16(read_state_t *state) {
2515   int channels;
2516
2517   cmyk_channels(state, &channels);
2518   state->img = i_img_16_new(state->width, state->height, channels);
2519
2520   state->line_buf = mymalloc(sizeof(unsigned) * state->width * channels);
2521
2522   return 1;
2523 }
2524
2525 static int 
2526 putter_cmyk16(read_state_t *state, i_img_dim x, i_img_dim y, i_img_dim width, i_img_dim height, 
2527                int row_extras) {
2528   uint16 *p = state->raster;
2529   int out_chan = state->img->channels;
2530
2531   mm_log((4, "putter_cmyk16(%p, %d, %d, %d, %d, %d)\n", x, y, width, height, row_extras));
2532
2533   state->pixels_read += width * height;
2534   while (height > 0) {
2535     i_img_dim i;
2536     int ch;
2537     unsigned *outp = state->line_buf;
2538
2539     for (i = 0; i < width; ++i) {
2540       unsigned c, m, y, k;
2541       c = p[0];
2542       m = p[1];
2543       y = p[2];
2544       k = 65535 - p[3];
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 
2551             && outp[3]) {
2552           for (ch = 0; ch < 3; ++ch) {
2553             int result = (outp[ch] * 65535 + 32767) / outp[3];
2554             outp[3] = CLAMP16(result);
2555           }
2556         }
2557       }
2558       p += state->samples_per_pixel;
2559       outp += out_chan;
2560     }
2561
2562     i_psamp_bits(state->img, x, x + width, y, state->line_buf, NULL, out_chan, 16);
2563
2564     p += row_extras * state->samples_per_pixel;
2565     --height;
2566     ++y;
2567   }
2568
2569   return 1;
2570 }
2571
2572 /*
2573
2574   Older versions of tifflib we support don't define this, so define it
2575   ourselves.
2576
2577   If you want this detection to do anything useful, use a newer
2578   release of tifflib.
2579
2580  */
2581 #if TIFFLIB_VERSION < 20031121
2582
2583 int 
2584 TIFFIsCODECConfigured(uint16 scheme) {
2585   switch (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:
2593     return 1;
2594
2595     /* these require external library support */
2596   default:
2597  case COMPRESSION_JPEG:
2598  case COMPRESSION_LZW:
2599  case COMPRESSION_DEFLATE:
2600  case COMPRESSION_ADOBE_DEFLATE:
2601     return 0;
2602   }
2603 }
2604
2605 #endif
2606
2607 static int 
2608 myTIFFIsCODECConfigured(uint16 scheme) {
2609 #if TIFFLIB_VERSION < 20040724
2610   if (scheme == COMPRESSION_LZW)
2611     return 0;
2612 #endif
2613
2614   return TIFFIsCODECConfigured(scheme);
2615 }
2616
2617 /*
2618 =back
2619
2620 =head1 AUTHOR
2621
2622 Arnar M. Hrafnkelsson <addi@umich.edu>, Tony Cook <tonyc@cpan.org>
2623
2624 =head1 SEE ALSO
2625
2626 Imager(3)
2627
2628 =cut
2629 */