]> Pileus Git - ~andy/gtk/blob - gdk-pixbuf/io-tiff.c
Changes to make gdk-pixbuf threadsafe (#157310, #157306, Colin Walters):
[~andy/gtk] / gdk-pixbuf / io-tiff.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */
2 /* GdkPixbuf library - TIFF image loader
3  *
4  * Copyright (C) 1999 Mark Crichton
5  * Copyright (C) 1999 The Free Software Foundation
6  *
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>
11  *
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.
16  *
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.
21  *
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.
26  */
27
28 /* Following code (almost) blatantly ripped from Imlib */
29
30 #include <config.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36 #include <tiffio.h>
37 #include <errno.h>
38 #include "gdk-pixbuf-private.h"
39 #include "gdk-pixbuf-io.h"
40
41 #ifdef G_OS_WIN32
42 #include <fcntl.h>
43 #include <io.h>
44 #define lseek(a,b,c) _lseek(a,b,c)
45 #define O_RDWR _O_RDWR
46 #endif
47 \f
48
49 typedef struct _TiffContext TiffContext;
50 struct _TiffContext
51 {
52         GdkPixbufModuleSizeFunc size_func;
53         GdkPixbufModulePreparedFunc prepare_func;
54         GdkPixbufModuleUpdatedFunc update_func;
55         gpointer user_data;
56         
57         guchar *buffer;
58         guint allocated;
59         guint used;
60         guint pos;
61 };
62
63 \f
64
65 static char *global_error = NULL;
66 static TIFFErrorHandler orig_error_handler = NULL;
67 static TIFFErrorHandler orig_warning_handler = NULL;
68
69 static void
70 tiff_warning_handler (const char *mod, const char *fmt, va_list ap)
71 {
72         /* Don't print anything; we should not be dumping junk to
73          * stderr, since that may be bad for some apps.
74          */
75
76         /* libTIFF seems to occasionally warn about things that
77          * are really errors, so maybe we should just call tiff_error_handler
78          * here.
79          */
80 }
81
82 static void
83 tiff_error_handler (const char *mod, const char *fmt, va_list ap)
84 {
85         if (global_error) {                
86                 /* Blah, loader called us twice */
87                 return;
88         }
89
90         global_error = g_strdup_vprintf (fmt, ap);
91 }
92
93 static void
94 tiff_push_handlers (void)
95 {
96         if (global_error)
97                 g_warning ("TIFF loader left crufty global_error around, FIXME");
98         
99         orig_error_handler = TIFFSetErrorHandler (tiff_error_handler);
100         orig_warning_handler = TIFFSetWarningHandler (tiff_warning_handler);
101 }
102
103 static void
104 tiff_pop_handlers (void)
105 {
106         if (global_error)
107                 g_warning ("TIFF loader left crufty global_error around, FIXME");
108         
109         TIFFSetErrorHandler (orig_error_handler);
110         TIFFSetWarningHandler (orig_warning_handler);
111 }
112
113 static void
114 tiff_set_error (GError    **error,
115                 int         error_code,
116                 const char *msg)
117 {
118         /* Take the error message from libtiff and merge it with
119          * some context we provide.
120          */
121         if (global_error) {
122                 g_set_error (error,
123                              GDK_PIXBUF_ERROR,
124                              error_code,
125                              "%s%s%s", msg, ": ", global_error);
126
127                 g_free (global_error);
128                 global_error = NULL;
129         }
130         else {
131                 g_set_error (error,
132                              GDK_PIXBUF_ERROR,
133                              error_code, msg);
134         }
135 }
136
137 \f
138
139 static void free_buffer (guchar *pixels, gpointer data)
140 {
141         g_free (pixels);
142 }
143
144 #if TIFFLIB_VERSION >= 20031226
145 static gboolean tifflibversion (int *major, int *minor, int *revision)
146 {
147         if (sscanf (TIFFGetVersion(), 
148                     "LIBTIFF, Version %d.%d.%d", 
149                     major, minor, revision) < 3)
150                 return FALSE;
151
152         return TRUE;
153 }
154 #endif
155
156 static GdkPixbuf *
157 tiff_image_parse (TIFF *tiff, TiffContext *context, GError **error)
158 {
159         guchar *pixels = NULL;
160         gint width, height, rowstride, bytes;
161         GdkPixbuf *pixbuf;
162 #if TIFFLIB_VERSION >= 20031226
163         gint major, minor, revision;
164 #endif
165
166         /* We're called with the lock held. */
167         
168         g_return_val_if_fail (global_error == NULL, NULL);
169
170         if (!TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width) || global_error) {
171                 tiff_set_error (error,
172                                 GDK_PIXBUF_ERROR_FAILED,
173                                 _("Could not get image width (bad TIFF file)"));
174                 return NULL;
175         }
176         
177         if (!TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height) || global_error) {
178                 tiff_set_error (error,
179                                 GDK_PIXBUF_ERROR_FAILED,
180                                 _("Could not get image height (bad TIFF file)"));
181                 return NULL;
182         }
183
184         if (width <= 0 || height <= 0) {
185                 g_set_error (error,
186                              GDK_PIXBUF_ERROR,
187                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
188                              _("Width or height of TIFF image is zero"));
189                 return NULL;                
190         }
191         
192         rowstride = width * 4;
193         if (rowstride / 4 != width) { /* overflow */
194                 g_set_error (error,
195                              GDK_PIXBUF_ERROR,
196                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
197                              _("Dimensions of TIFF image too large"));
198                 return NULL;                
199         }
200         
201         bytes = height * rowstride;
202         if (bytes / rowstride != height) { /* overflow */
203                 g_set_error (error,
204                              GDK_PIXBUF_ERROR,
205                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
206                              _("Dimensions of TIFF image too large"));
207                 return NULL;                
208         }
209
210         if (context && context->size_func) {
211                 gint w = width;
212                 gint h = height;
213                 (* context->size_func) (&w, &h, context->user_data);
214                 
215                 if (w == 0 || h == 0)
216                     return NULL;
217         }
218
219         pixels = g_try_malloc (bytes);
220
221         if (!pixels) {
222                 g_set_error (error,
223                              GDK_PIXBUF_ERROR,
224                              GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
225                              _("Insufficient memory to open TIFF file"));
226                 return NULL;
227         }
228
229         pixbuf = gdk_pixbuf_new_from_data (pixels, GDK_COLORSPACE_RGB, TRUE, 8, 
230                                            width, height, rowstride,
231                                            free_buffer, NULL);
232         if (!pixbuf) {
233                 g_free (pixels);
234                 g_set_error (error,
235                              GDK_PIXBUF_ERROR,
236                              GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
237                              _("Insufficient memory to open TIFF file"));
238                 return NULL;
239         }
240
241         if (context)
242                 (* context->prepare_func) (pixbuf, NULL, context->user_data);
243
244 #if TIFFLIB_VERSION >= 20031226
245         if (tifflibversion(&major, &minor, &revision) && major == 3 &&
246             (minor > 6 || (minor == 6 && revision > 0))) {                
247                 if (!TIFFReadRGBAImageOriented (tiff, width, height, (uint32 *)pixels, ORIENTATION_TOPLEFT, 1) || global_error) 
248                 {
249                         tiff_set_error (error,
250                                         GDK_PIXBUF_ERROR_FAILED,
251                                         _("Failed to load RGB data from TIFF file"));
252                         g_object_unref (pixbuf);
253                         return NULL;
254                 }
255
256 #if G_BYTE_ORDER == G_BIG_ENDIAN
257                 /* Turns out that the packing used by TIFFRGBAImage depends on 
258                  * the host byte order... 
259                  */ 
260                 while (pixels < pixbuf->pixels + bytes) {
261                         uint32 pixel = *(uint32 *)pixels;
262                         int r = TIFFGetR(pixel);
263                         int g = TIFFGetG(pixel);
264                         int b = TIFFGetB(pixel);
265                         int a = TIFFGetA(pixel);
266                         *pixels++ = r;
267                         *pixels++ = g;
268                         *pixels++ = b;
269                         *pixels++ = a;
270                 }
271 #endif
272         }
273         else 
274 #endif
275               {
276                 uint32 *rast, *tmp_rast;
277                 gint x, y;
278                 guchar *tmppix;
279
280                 /* Yes, it needs to be _TIFFMalloc... */
281                 rast = (uint32 *) _TIFFmalloc (width * height * sizeof (uint32));
282                 if (!rast) {
283                         g_set_error (error,
284                                      GDK_PIXBUF_ERROR,
285                                      GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
286                                      _("Insufficient memory to open TIFF file"));
287                         g_object_unref (pixbuf);
288                         
289                         return NULL;
290                 }
291                 if (!TIFFReadRGBAImage (tiff, width, height, rast, 1) || global_error) {
292                         tiff_set_error (error,
293                                         GDK_PIXBUF_ERROR_FAILED,
294                                         _("Failed to load RGB data from TIFF file"));
295                         g_object_unref (pixbuf);
296                         _TIFFfree (rast);
297                         
298                         return NULL;
299                 }
300                 
301                 pixels = gdk_pixbuf_get_pixels (pixbuf);
302                 
303                 g_assert (pixels);
304                 
305                 tmppix = pixels;
306                 
307                 for (y = 0; y < height; y++) {
308                         /* Unexplainable...are tiffs backwards? */
309                         /* Also looking at the GIMP plugin, this
310                          * whole reading thing can be a bit more
311                          * robust.
312                          */
313                         tmp_rast = rast + ((height - y - 1) * width);
314                         for (x = 0; x < width; x++) {
315                                 tmppix[0] = TIFFGetR (*tmp_rast);
316                                 tmppix[1] = TIFFGetG (*tmp_rast);
317                                 tmppix[2] = TIFFGetB (*tmp_rast);
318                                 tmppix[3] = TIFFGetA (*tmp_rast);
319                                 tmp_rast++;
320                                 tmppix += 4;
321                         }
322                 }
323                 
324                 _TIFFfree (rast);
325              }
326
327         if (context)
328                 (* context->update_func) (pixbuf, 0, 0, width, height, context->user_data);
329         
330         return pixbuf;
331 }
332
333 \f
334
335 /* Static loader */
336
337 static GdkPixbuf *
338 gdk_pixbuf__tiff_image_load (FILE *f, GError **error)
339 {
340         TIFF *tiff;
341         int fd;
342         GdkPixbuf *pixbuf;
343         
344         g_return_val_if_fail (f != NULL, NULL);
345
346         tiff_push_handlers ();
347         
348         fd = fileno (f);
349
350         /* On OSF, apparently fseek() works in some on-demand way, so
351          * the fseek gdk_pixbuf_new_from_file() doesn't work here
352          * since we are using the raw file descriptor. So, we call lseek() on the fd
353          * before using it. (#60840)
354          */
355         lseek (fd, 0, SEEK_SET);
356         tiff = TIFFFdOpen (fd, "libpixbuf-tiff", "r");
357         
358         if (!tiff || global_error) {
359                 tiff_set_error (error,
360                                 GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
361                                 _("Failed to open TIFF image"));
362                 tiff_pop_handlers ();
363
364                 return NULL;
365         }
366
367         pixbuf = tiff_image_parse (tiff, NULL, error);
368         
369         TIFFClose (tiff);
370         if (global_error) {
371                 tiff_set_error (error,
372                                 GDK_PIXBUF_ERROR_FAILED,
373                                 _("TIFFClose operation failed"));
374         }
375         
376         tiff_pop_handlers ();
377
378         return pixbuf;
379 }
380
381 \f
382
383 /* Progressive loader */
384
385 static gpointer
386 gdk_pixbuf__tiff_image_begin_load (GdkPixbufModuleSizeFunc size_func,
387                                    GdkPixbufModulePreparedFunc prepare_func,
388                                    GdkPixbufModuleUpdatedFunc update_func,
389                                    gpointer user_data,
390                                    GError **error)
391 {
392         TiffContext *context;
393         
394         context = g_new0 (TiffContext, 1);
395         context->size_func = size_func;
396         context->prepare_func = prepare_func;
397         context->update_func = update_func;
398         context->user_data = user_data;
399         context->buffer = NULL;
400         context->allocated = 0;
401         context->used = 0;
402         context->pos = 0;
403         
404         return context;
405 }
406
407 static tsize_t
408 tiff_read (thandle_t handle, tdata_t buf, tsize_t size)
409 {
410         TiffContext *context = (TiffContext *)handle;
411         
412         if (context->pos + size > context->used)
413                 return 0;
414         
415         memcpy (buf, context->buffer + context->pos, size);
416         context->pos += size;
417         return size;
418 }
419
420 static tsize_t
421 tiff_write (thandle_t handle, tdata_t buf, tsize_t size)
422 {
423         return -1;
424 }
425
426 static toff_t
427 tiff_seek (thandle_t handle, toff_t offset, int whence)
428 {
429         TiffContext *context = (TiffContext *)handle;
430         
431         switch (whence) {
432         case SEEK_SET:
433                 if (offset > context->used || offset < 0)
434                         return -1;
435                 context->pos = offset;
436                 break;
437         case SEEK_CUR:
438                 if (offset + context->pos >= context->used)
439                         return -1;
440                 context->pos += offset;
441                 break;
442         case SEEK_END:
443                 if (offset + context->used > context->used)
444                         return -1;
445                 context->pos = context->used + offset;
446                 break;
447         default:
448                 return -1;
449                 break;
450         }
451         return context->pos;
452 }
453
454 static int
455 tiff_close (thandle_t context)
456 {
457         return 0;
458 }
459
460 static toff_t
461 tiff_size (thandle_t handle)
462 {
463         TiffContext *context = (TiffContext *)handle;
464         
465         return context->used;
466 }
467
468 static int
469 tiff_map_file (thandle_t handle, tdata_t *buf, toff_t *size)
470 {
471         TiffContext *context = (TiffContext *)handle;
472         
473         *buf = context->buffer;
474         *size = context->used;
475         
476         return 0;
477 }
478
479 static void
480 tiff_unmap_file (thandle_t handle, tdata_t data, toff_t offset)
481 {
482 }
483
484 static gboolean
485 gdk_pixbuf__tiff_image_stop_load (gpointer data,
486                                   GError **error)
487 {
488         TiffContext *context = data;
489         TIFF *tiff;
490         gboolean retval;
491         
492         g_return_val_if_fail (data != NULL, FALSE);
493
494         tiff_push_handlers ();
495         
496         tiff = TIFFClientOpen ("libtiff-pixbuf", "r", data, 
497                                tiff_read, tiff_write, 
498                                tiff_seek, tiff_close, 
499                                tiff_size, 
500                                tiff_map_file, tiff_unmap_file);
501         if (!tiff || global_error) {
502                 tiff_set_error (error,
503                                 GDK_PIXBUF_ERROR_FAILED,
504                                 _("Failed to load TIFF image"));
505                 retval = FALSE;
506         } else {
507                 GdkPixbuf *pixbuf;
508                 
509                 pixbuf = tiff_image_parse (tiff, context, error);
510                 if (pixbuf)
511                         g_object_unref (pixbuf);
512                 retval = pixbuf != NULL;
513                 if (global_error)
514                         {
515                                 tiff_set_error (error,
516                                                 GDK_PIXBUF_ERROR_FAILED,
517                                                 _("Failed to load TIFF image"));
518                                 tiff_pop_handlers ();
519
520                                 retval = FALSE;
521                         }
522         }
523
524         if (tiff)
525                 TIFFClose (tiff);
526
527         g_assert (!global_error);
528         
529         g_free (context->buffer);
530         g_free (context);
531
532         tiff_pop_handlers ();
533
534         return retval;
535 }
536
537 static gboolean
538 make_available_at_least (TiffContext *context, guint needed)
539 {
540         guchar *new_buffer = NULL;
541         guint need_alloc;
542         
543         need_alloc = context->used + needed;
544         if (need_alloc > context->allocated) {
545                 guint new_size = 1;
546                 while (new_size < need_alloc)
547                         new_size *= 2;
548                 
549                 new_buffer = g_try_realloc (context->buffer, new_size);
550                 if (new_buffer) {
551                         context->buffer = new_buffer;
552                         context->allocated = new_size;
553                         return TRUE;
554                 }
555                 return FALSE;
556         }
557         return TRUE;
558 }
559
560 static gboolean
561 gdk_pixbuf__tiff_image_load_increment (gpointer data, const guchar *buf,
562                                        guint size, GError **error)
563 {
564         TiffContext *context = (TiffContext *) data;
565         
566         g_return_val_if_fail (data != NULL, FALSE);
567         
568         if (!make_available_at_least (context, size)) {
569                 g_set_error (error,
570                              GDK_PIXBUF_ERROR,
571                              GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
572                              _("Insufficient memory to open TIFF file"));
573                 return FALSE;
574         }
575         
576         memcpy (context->buffer + context->used, buf, size);
577         context->used += size;
578         return TRUE;
579 }
580
581 void
582 MODULE_ENTRY (tiff, fill_vtable) (GdkPixbufModule *module)
583 {
584         module->load = gdk_pixbuf__tiff_image_load;
585         module->begin_load = gdk_pixbuf__tiff_image_begin_load;
586         module->stop_load = gdk_pixbuf__tiff_image_stop_load;
587         module->load_increment = gdk_pixbuf__tiff_image_load_increment;
588 }
589
590 void
591 MODULE_ENTRY (tiff, fill_info) (GdkPixbufFormat *info)
592 {
593         static GdkPixbufModulePattern signature[] = {
594                 { "MM \x2a", "  z ", 100 },
595                 { "II\x2a ", "   z", 100 },
596                 { NULL, NULL, 0 }
597         };
598         static gchar * mime_types[] = {
599                 "image/tiff",
600                 NULL
601         };
602         static gchar * extensions[] = {
603                 "tiff",
604                 "tif",
605                 NULL
606         };
607
608         info->name = "tiff";
609         info->signature = signature;
610         info->description = N_("The TIFF image format");
611         info->mime_types = mime_types;
612         info->extensions = extensions;
613         /* not threadsafe, due the the error handler handling */
614         info->flags = 0;
615         info->license = "LGPL";
616 }