1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */
2 /* GdkPixbuf library - TIFF image loader
4 * Copyright (C) 1999 Mark Crichton
5 * Copyright (C) 1999 The Free Software Foundation
7 * Authors: Mark Crichton <crichton@gimp.org>
8 * Federico Mena-Quintero <federico@gimp.org>
9 * Jonathan Blandford <jrb@redhat.com>
10 * S�ren Sandmann <sandmann@daimi.au.dk>
12 * This library is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public
14 * License as published by the Free Software Foundation; either
15 * version 2 of the License, or (at your option) any later version.
17 * This library is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with this library; if not, write to the
24 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 * Boston, MA 02111-1307, USA.
28 /* Following code (almost) blatantly ripped from Imlib */
38 #include "gdk-pixbuf-private.h"
39 #include "gdk-pixbuf-io.h"
44 #define lseek(a,b,c) _lseek(a,b,c)
45 #define O_RDWR _O_RDWR
49 typedef struct _TiffContext TiffContext;
52 GdkPixbufModuleSizeFunc size_func;
53 GdkPixbufModulePreparedFunc prepare_func;
54 GdkPixbufModuleUpdatedFunc update_func;
65 static char *global_error = NULL;
66 static TIFFErrorHandler orig_error_handler = NULL;
67 static TIFFErrorHandler orig_warning_handler = NULL;
70 tiff_warning_handler (const char *mod, const char *fmt, va_list ap)
72 /* Don't print anything; we should not be dumping junk to
73 * stderr, since that may be bad for some apps.
76 /* libTIFF seems to occasionally warn about things that
77 * are really errors, so maybe we should just call tiff_error_handler
83 tiff_error_handler (const char *mod, const char *fmt, va_list ap)
86 /* Blah, loader called us twice */
90 global_error = g_strdup_vprintf (fmt, ap);
94 tiff_push_handlers (void)
97 g_warning ("TIFF loader left crufty global_error around, FIXME");
99 orig_error_handler = TIFFSetErrorHandler (tiff_error_handler);
100 orig_warning_handler = TIFFSetWarningHandler (tiff_warning_handler);
104 tiff_pop_handlers (void)
107 g_warning ("TIFF loader left crufty global_error around, FIXME");
109 TIFFSetErrorHandler (orig_error_handler);
110 TIFFSetWarningHandler (orig_warning_handler);
114 tiff_set_error (GError **error,
118 /* Take the error message from libtiff and merge it with
119 * some context we provide.
125 "%s%s%s", msg, ": ", global_error);
127 g_free (global_error);
131 g_set_error_literal (error,
139 static void free_buffer (guchar *pixels, gpointer data)
145 tiff_image_parse (TIFF *tiff, TiffContext *context, GError **error)
147 guchar *pixels = NULL;
148 gint width, height, rowstride, bytes;
150 uint16 orientation = 0;
151 uint16 transform = 0;
153 gchar *icc_profile_base64;
154 const gchar *icc_profile;
155 guint icc_profile_size;
158 /* We're called with the lock held. */
160 g_return_val_if_fail (global_error == NULL, NULL);
162 if (!TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width) || global_error) {
163 tiff_set_error (error,
164 GDK_PIXBUF_ERROR_FAILED,
165 _("Could not get image width (bad TIFF file)"));
169 if (!TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height) || global_error) {
170 tiff_set_error (error,
171 GDK_PIXBUF_ERROR_FAILED,
172 _("Could not get image height (bad TIFF file)"));
176 if (width <= 0 || height <= 0) {
177 g_set_error_literal (error,
179 GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
180 _("Width or height of TIFF image is zero"));
184 rowstride = width * 4;
185 if (rowstride / 4 != width) { /* overflow */
186 g_set_error_literal (error,
188 GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
189 _("Dimensions of TIFF image too large"));
193 bytes = height * rowstride;
194 if (bytes / rowstride != height) { /* overflow */
195 g_set_error_literal (error,
197 GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
198 _("Dimensions of TIFF image too large"));
202 if (context && context->size_func) {
205 (* context->size_func) (&w, &h, context->user_data);
207 /* This is a signal that this function is being called
208 to support gdk_pixbuf_get_file_info, so we can stop
209 parsing the tiff file at this point. It is not an
212 if (w == 0 || h == 0)
216 pixels = g_try_malloc (bytes);
219 g_set_error_literal (error,
221 GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
222 _("Insufficient memory to open TIFF file"));
226 pixbuf = gdk_pixbuf_new_from_data (pixels, GDK_COLORSPACE_RGB, TRUE, 8,
227 width, height, rowstride,
231 g_set_error_literal (error,
233 GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
234 _("Insufficient memory to open TIFF file"));
238 /* Set the "orientation" key associated with this image. libtiff
239 orientation handling is odd, so further processing is required
240 by higher-level functions based on this tag. If the embedded
241 orientation tag is 1-4, libtiff flips/mirrors the image as
242 required, and no client processing is required - so we report
243 no orientation. Orientations 5-8 require rotations which would
244 swap the width and height of the image. libtiff does not do this.
245 Instead it interprets orientations 5-8 the same as 1-4.
246 See http://bugzilla.remotesensing.org/show_bug.cgi?id=1548.
247 To correct for this, the client must apply the transform normally
248 used for orientation 5 to both orientations 5 and 7, and apply
249 the transform normally used for orientation 7 for both
250 orientations 6 and 8. Then everythings works out OK! */
252 TIFFGetField (tiff, TIFFTAG_ORIENTATION, &orientation);
254 switch (orientation) {
268 if (transform > 0 ) {
270 g_snprintf (str, sizeof (str), "%d", transform);
271 gdk_pixbuf_set_option (pixbuf, "orientation", str);
274 TIFFGetField (tiff, TIFFTAG_COMPRESSION, &codec);
277 g_snprintf (str, sizeof (str), "%d", codec);
278 gdk_pixbuf_set_option (pixbuf, "compression", str);
281 /* Extract embedded ICC profile */
282 retval = TIFFGetField (tiff, TIFFTAG_ICCPROFILE, &icc_profile_size, &icc_profile);
284 icc_profile_base64 = g_base64_encode ((const guchar *) icc_profile, icc_profile_size);
285 gdk_pixbuf_set_option (pixbuf, "icc-profile", icc_profile_base64);
286 g_free (icc_profile_base64);
289 if (context && context->prepare_func)
290 (* context->prepare_func) (pixbuf, NULL, context->user_data);
292 if (!TIFFReadRGBAImageOriented (tiff, width, height, (uint32 *)pixels, ORIENTATION_TOPLEFT, 1) || global_error) {
293 tiff_set_error (error,
294 GDK_PIXBUF_ERROR_FAILED,
295 _("Failed to load RGB data from TIFF file"));
296 g_object_unref (pixbuf);
300 #if G_BYTE_ORDER == G_BIG_ENDIAN
301 /* Turns out that the packing used by TIFFRGBAImage depends on
302 * the host byte order...
304 while (pixels < pixbuf->pixels + bytes) {
305 uint32 pixel = *(uint32 *)pixels;
306 int r = TIFFGetR(pixel);
307 int g = TIFFGetG(pixel);
308 int b = TIFFGetB(pixel);
309 int a = TIFFGetA(pixel);
317 if (context && context->update_func)
318 (* context->update_func) (pixbuf, 0, 0, width, height, context->user_data);
328 gdk_pixbuf__tiff_image_load (FILE *f, GError **error)
334 g_return_val_if_fail (f != NULL, NULL);
336 tiff_push_handlers ();
340 /* On OSF, apparently fseek() works in some on-demand way, so
341 * the fseek gdk_pixbuf_new_from_file() doesn't work here
342 * since we are using the raw file descriptor. So, we call lseek() on the fd
343 * before using it. (#60840)
345 lseek (fd, 0, SEEK_SET);
346 tiff = TIFFFdOpen (fd, "libpixbuf-tiff", "r");
348 if (!tiff || global_error) {
349 tiff_set_error (error,
350 GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
351 _("Failed to open TIFF image"));
352 tiff_pop_handlers ();
357 pixbuf = tiff_image_parse (tiff, NULL, error);
361 tiff_set_error (error,
362 GDK_PIXBUF_ERROR_FAILED,
363 _("TIFFClose operation failed"));
366 tiff_pop_handlers ();
373 /* Progressive loader */
376 gdk_pixbuf__tiff_image_begin_load (GdkPixbufModuleSizeFunc size_func,
377 GdkPixbufModulePreparedFunc prepare_func,
378 GdkPixbufModuleUpdatedFunc update_func,
382 TiffContext *context;
384 context = g_new0 (TiffContext, 1);
385 context->size_func = size_func;
386 context->prepare_func = prepare_func;
387 context->update_func = update_func;
388 context->user_data = user_data;
389 context->buffer = NULL;
390 context->allocated = 0;
398 tiff_load_read (thandle_t handle, tdata_t buf, tsize_t size)
400 TiffContext *context = (TiffContext *)handle;
402 if (context->pos + size > context->used)
405 memcpy (buf, context->buffer + context->pos, size);
406 context->pos += size;
411 tiff_load_write (thandle_t handle, tdata_t buf, tsize_t size)
417 tiff_load_seek (thandle_t handle, toff_t offset, int whence)
419 TiffContext *context = (TiffContext *)handle;
423 if (offset > context->used)
425 context->pos = offset;
428 if (offset + context->pos >= context->used)
430 context->pos += offset;
433 if (offset + context->used > context->used)
435 context->pos = context->used + offset;
444 tiff_load_close (thandle_t context)
450 tiff_load_size (thandle_t handle)
452 TiffContext *context = (TiffContext *)handle;
454 return context->used;
458 tiff_load_map_file (thandle_t handle, tdata_t *buf, toff_t *size)
460 TiffContext *context = (TiffContext *)handle;
462 *buf = context->buffer;
463 *size = context->used;
469 tiff_load_unmap_file (thandle_t handle, tdata_t data, toff_t offset)
474 gdk_pixbuf__tiff_image_stop_load (gpointer data,
477 TiffContext *context = data;
481 g_return_val_if_fail (data != NULL, FALSE);
483 tiff_push_handlers ();
485 tiff = TIFFClientOpen ("libtiff-pixbuf", "r", data,
486 tiff_load_read, tiff_load_write,
487 tiff_load_seek, tiff_load_close,
489 tiff_load_map_file, tiff_load_unmap_file);
490 if (!tiff || global_error) {
491 tiff_set_error (error,
492 GDK_PIXBUF_ERROR_FAILED,
493 _("Failed to load TIFF image"));
498 pixbuf = tiff_image_parse (tiff, context, error);
500 g_object_unref (pixbuf);
501 retval = pixbuf != NULL;
504 tiff_set_error (error,
505 GDK_PIXBUF_ERROR_FAILED,
506 _("Failed to load TIFF image"));
507 tiff_pop_handlers ();
516 g_assert (!global_error);
518 g_free (context->buffer);
521 tiff_pop_handlers ();
527 make_available_at_least (TiffContext *context, guint needed)
529 guchar *new_buffer = NULL;
532 need_alloc = context->used + needed;
533 if (need_alloc > context->allocated) {
535 while (new_size < need_alloc)
538 new_buffer = g_try_realloc (context->buffer, new_size);
540 context->buffer = new_buffer;
541 context->allocated = new_size;
550 gdk_pixbuf__tiff_image_load_increment (gpointer data, const guchar *buf,
551 guint size, GError **error)
553 TiffContext *context = (TiffContext *) data;
555 g_return_val_if_fail (data != NULL, FALSE);
557 if (!make_available_at_least (context, size)) {
558 g_set_error_literal (error,
560 GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
561 _("Insufficient memory to open TIFF file"));
565 memcpy (context->buffer + context->used, buf, size);
566 context->used += size;
578 tiff_save_read (thandle_t handle, tdata_t buf, tsize_t size)
584 tiff_save_write (thandle_t handle, tdata_t buf, tsize_t size)
586 TiffSaveContext *context = (TiffSaveContext *)handle;
588 /* Modify buffer length */
589 if (context->pos + size > context->used)
590 context->used = context->pos + size;
593 if (context->used > context->allocated) {
594 context->buffer = g_realloc (context->buffer, context->pos + size);
595 context->allocated = context->used;
598 /* Now copy the data */
599 memcpy (context->buffer + context->pos, buf, size);
602 context->pos += size;
608 tiff_save_seek (thandle_t handle, toff_t offset, int whence)
610 TiffSaveContext *context = (TiffSaveContext *)handle;
614 context->pos = offset;
617 context->pos += offset;
620 context->pos = context->used + offset;
629 tiff_save_close (thandle_t context)
635 tiff_save_size (thandle_t handle)
640 static TiffSaveContext *
641 create_save_context (void)
643 TiffSaveContext *context;
645 context = g_new (TiffSaveContext, 1);
646 context->buffer = NULL;
647 context->allocated = 0;
655 free_save_context (TiffSaveContext *context)
657 g_free (context->buffer);
662 gdk_pixbuf__tiff_image_save_to_callback (GdkPixbufSaveFunc save_func,
670 gint width, height, rowstride;
673 gushort alpha_samples[1] = { EXTRASAMPLE_UNASSALPHA };
675 TiffSaveContext *context;
677 guchar *icc_profile = NULL;
678 gsize icc_profile_size = 0;
680 tiff_push_handlers ();
682 context = create_save_context ();
683 tiff = TIFFClientOpen ("libtiff-pixbuf", "w", context,
684 tiff_save_read, tiff_save_write,
685 tiff_save_seek, tiff_save_close,
689 if (!tiff || global_error) {
690 tiff_set_error (error,
691 GDK_PIXBUF_ERROR_FAILED,
692 _("Failed to save TIFF image"));
694 tiff_pop_handlers ();
696 free_save_context (context);
700 rowstride = gdk_pixbuf_get_rowstride (pixbuf);
701 pixels = gdk_pixbuf_get_pixels (pixbuf);
703 has_alpha = gdk_pixbuf_get_has_alpha (pixbuf);
705 height = gdk_pixbuf_get_height (pixbuf);
706 width = gdk_pixbuf_get_width (pixbuf);
708 TIFFSetField (tiff, TIFFTAG_IMAGEWIDTH, width);
709 TIFFSetField (tiff, TIFFTAG_IMAGELENGTH, height);
710 TIFFSetField (tiff, TIFFTAG_BITSPERSAMPLE, 8);
711 TIFFSetField (tiff, TIFFTAG_SAMPLESPERPIXEL, has_alpha ? 4 : 3);
712 TIFFSetField (tiff, TIFFTAG_ROWSPERSTRIP, height);
714 /* libtiff supports a number of 'codecs' such as:
715 1 None, 2 Huffman, 5 LZW, 7 JPEG, 8 Deflate, see tiff.h */
716 if (keys && *keys && values && *values) {
720 if (g_str_equal (keys[i], "compression")) {
721 guint16 codec = strtol (values[i], NULL, 0);
722 if (TIFFIsCODECConfigured (codec))
723 TIFFSetField (tiff, TIFFTAG_COMPRESSION, codec);
725 tiff_set_error (error,
726 GDK_PIXBUF_ERROR_FAILED,
727 _("TIFF compression doesn't refer to a valid codec."));
731 } else if (g_str_equal (keys[i], "icc-profile")) {
732 /* decode from base64 */
733 icc_profile = g_base64_decode (values[i], &icc_profile_size);
734 if (icc_profile_size < 127) {
737 GDK_PIXBUF_ERROR_BAD_OPTION,
738 _("Color profile has invalid length %d."),
739 (gint)icc_profile_size);
749 TIFFSetField (tiff, TIFFTAG_EXTRASAMPLES, 1, alpha_samples);
751 TIFFSetField (tiff, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
752 TIFFSetField (tiff, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB);
753 TIFFSetField (tiff, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
755 if (icc_profile != NULL)
756 TIFFSetField (tiff, TIFFTAG_ICCPROFILE, icc_profile_size, icc_profile);
758 for (y = 0; y < height; y++) {
759 if (TIFFWriteScanline (tiff, pixels + y * rowstride, y, 0) == -1 ||
765 tiff_set_error (error,
766 GDK_PIXBUF_ERROR_FAILED,
767 _("Failed to write TIFF data"));
776 tiff_set_error (error,
777 GDK_PIXBUF_ERROR_FAILED,
778 _("TIFFClose operation failed"));
784 /* Now call the callback */
785 retval = save_func (context->buffer, context->used, error, user_data);
788 g_free (icc_profile);
789 tiff_pop_handlers ();
790 free_save_context (context);
795 save_to_file_cb (const gchar *buf,
803 bytes = fwrite (buf, sizeof (gchar), count, (FILE *) data);
811 g_set_error_literal (error,
813 GDK_PIXBUF_ERROR_FAILED,
814 _("Couldn't write to TIFF file"));
822 gdk_pixbuf__tiff_image_save (FILE *f,
828 return gdk_pixbuf__tiff_image_save_to_callback (save_to_file_cb,
834 #define MODULE_ENTRY(function) G_MODULE_EXPORT void function
836 #define MODULE_ENTRY(function) void _gdk_pixbuf__tiff_ ## function
839 MODULE_ENTRY (fill_vtable) (GdkPixbufModule *module)
841 module->load = gdk_pixbuf__tiff_image_load;
842 module->begin_load = gdk_pixbuf__tiff_image_begin_load;
843 module->stop_load = gdk_pixbuf__tiff_image_stop_load;
844 module->load_increment = gdk_pixbuf__tiff_image_load_increment;
845 module->save = gdk_pixbuf__tiff_image_save;
846 module->save_to_callback = gdk_pixbuf__tiff_image_save_to_callback;
849 MODULE_ENTRY (fill_info) (GdkPixbufFormat *info)
851 static GdkPixbufModulePattern signature[] = {
852 { "MM \x2a", " z ", 100 },
853 { "II\x2a ", " z", 100 },
854 { "II* \020 CR\002 ", " z zzz z", 0 },
857 static gchar * mime_types[] = {
861 static gchar * extensions[] = {
868 info->signature = signature;
869 info->description = N_("The TIFF image format");
870 info->mime_types = mime_types;
871 info->extensions = extensions;
872 /* not threadsafe, due to the error handler handling */
873 info->flags = GDK_PIXBUF_FORMAT_WRITABLE;
874 info->license = "LGPL";