]> Pileus Git - ~andy/gtk/blob - gdk-pixbuf/io-tiff.c
Load-at-size functionality for gdk-pixbuf.
[~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 #define O_RDWR _O_RDWR
44 #endif
45 \f
46
47 typedef struct _TiffContext TiffContext;
48 struct _TiffContext
49 {
50         ModulePreparedNotifyFunc prepare_func;
51         ModuleUpdatedNotifyFunc update_func;
52         gpointer user_data;
53         
54         guchar *buffer;
55         guint allocated;
56         guint used;
57         guint pos;
58 };
59
60 \f
61
62 /* There's no user data for the error handlers, so we just have to
63  * put a big-ass lock on the whole TIFF loader
64  */
65 G_LOCK_DEFINE_STATIC (tiff_loader);
66 static char *global_error = NULL;
67 static TIFFErrorHandler orig_error_handler = NULL;
68 static TIFFErrorHandler orig_warning_handler = NULL;
69
70 static void
71 tiff_warning_handler (const char *mod, const char *fmt, va_list ap)
72 {
73         /* Don't print anything; we should not be dumping junk to
74          * stderr, since that may be bad for some apps.
75          */
76
77         /* libTIFF seems to occasionally warn about things that
78          * are really errors, so maybe we should just call tiff_error_handler
79          * here.
80          */
81 }
82
83 static void
84 tiff_error_handler (const char *mod, const char *fmt, va_list ap)
85 {
86         if (global_error) {                
87                 /* Blah, loader called us twice */
88                 return;
89         }
90
91         global_error = g_strdup_vprintf (fmt, ap);
92 }
93
94 static void
95 tiff_push_handlers (void)
96 {
97         if (global_error)
98                 g_warning ("TIFF loader left crufty global_error around, FIXME");
99         
100         orig_error_handler = TIFFSetErrorHandler (tiff_error_handler);
101         orig_warning_handler = TIFFSetWarningHandler (tiff_warning_handler);
102 }
103
104 static void
105 tiff_pop_handlers (void)
106 {
107         if (global_error)
108                 g_warning ("TIFF loader left crufty global_error around, FIXME");
109         
110         TIFFSetErrorHandler (orig_error_handler);
111         TIFFSetWarningHandler (orig_warning_handler);
112 }
113
114 static void
115 tiff_set_error (GError    **error,
116                 int         error_code,
117                 const char *msg)
118 {
119         /* Take the error message from libtiff and merge it with
120          * some context we provide.
121          */
122         if (global_error) {
123                 g_set_error (error,
124                              GDK_PIXBUF_ERROR,
125                              error_code,
126                              "%s%s%s", msg, ": ", global_error);
127
128                 g_free (global_error);
129                 global_error = NULL;
130         }
131         else {
132                 g_set_error (error,
133                              GDK_PIXBUF_ERROR,
134                              error_code, msg);
135         }
136 }
137
138 \f
139
140 static void free_buffer (guchar *pixels, gpointer data)
141 {
142         g_free (pixels);
143 }
144
145 static tileContigRoutine tiff_put_contig;
146 static tileSeparateRoutine tiff_put_separate;
147
148 /* We're lucky that TIFFRGBAImage uses the same RGBA packing
149    as gdk-pixbuf, thus we can simple reuse the default libtiff
150    put routines, only adjusting the coordinate system.
151  */ 
152 static void
153 put_contig (TIFFRGBAImage *img, uint32 *raster,
154             uint32 x, uint32 y, uint32 w, uint32 h,
155             int32 fromskew, int32 toskew, unsigned char *cp) 
156 {
157         uint32 *data = raster - y * img->width - x;
158
159         tiff_put_contig (img, data + img->width * (img->height - 1 - y) + x, 
160                          x, y, w, h, fromskew, -toskew - 2*(int32)w, cp);
161 }
162
163 static void
164 put_separate (TIFFRGBAImage *img, uint32 *raster,
165               uint32 x, uint32 y, uint32 w, uint32 h,
166               int32 fromskew, int32 toskew, 
167               unsigned char* r, unsigned char* g, unsigned char* b, unsigned char* a)
168 {
169         uint32 *data = raster - y * img->width - x;
170
171         tiff_put_separate (img, data + img->width * (img->height - 1 - y) + x, 
172                            x, y, w, h, fromskew, -toskew - 2*w, r, g, b, a);
173 }
174
175 static GdkPixbuf *
176 tiff_image_parse (TIFF *tiff, TiffContext *context, GError **error)
177 {
178         guchar *pixels = NULL;
179         gint width, height, rowstride, bytes;
180         GdkPixbuf *pixbuf;
181         TIFFRGBAImage img;
182         gchar emsg[1024];
183
184         /* We're called with the lock held. */
185         
186         g_return_val_if_fail (global_error == NULL, NULL);
187
188         if (!TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width) || global_error) {
189                 tiff_set_error (error,
190                                 GDK_PIXBUF_ERROR_FAILED,
191                                 _("Could not get image width (bad TIFF file)"));
192                 return NULL;
193         }
194         
195         if (!TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height) || global_error) {
196                 tiff_set_error (error,
197                                 GDK_PIXBUF_ERROR_FAILED,
198                                 _("Could not get image height (bad TIFF file)"));
199                 return NULL;
200         }
201
202         if (width <= 0 || height <= 0) {
203                 g_set_error (error,
204                              GDK_PIXBUF_ERROR,
205                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
206                              _("Width or height of TIFF image is zero"));
207                 return NULL;                
208         }
209         
210         rowstride = width * 4;
211         if (rowstride / 4 != width) { /* overflow */
212                 g_set_error (error,
213                              GDK_PIXBUF_ERROR,
214                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
215                              _("Dimensions of TIFF image too large"));
216                 return NULL;                
217         }
218         
219         bytes = height * rowstride;
220         if (bytes / rowstride != height) { /* overflow */
221                 g_set_error (error,
222                              GDK_PIXBUF_ERROR,
223                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
224                              _("Dimensions of TIFF image too large"));
225                 return NULL;                
226         }
227
228         pixels = g_try_malloc (bytes);
229
230         if (!pixels) {
231                 g_set_error (error,
232                              GDK_PIXBUF_ERROR,
233                              GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
234                              _("Insufficient memory to open TIFF file"));
235                 return NULL;
236         }
237
238         pixbuf = gdk_pixbuf_new_from_data (pixels, GDK_COLORSPACE_RGB, TRUE, 8, 
239                                            width, height, rowstride,
240                                            free_buffer, NULL);
241         if (!pixbuf) {
242                 g_free (pixels);
243                 g_set_error (error,
244                              GDK_PIXBUF_ERROR,
245                              GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
246                              _("Insufficient memory to open TIFF file"));
247                 return NULL;
248         }
249
250         G_UNLOCK (tiff_loader);
251         if (context)
252                 (* context->prepare_func) (pixbuf, NULL, context->user_data);
253         G_LOCK (tiff_loader);
254                 
255         if (!TIFFRGBAImageBegin (&img, tiff, 1, emsg) || global_error) {
256                 tiff_set_error (error,
257                                 GDK_PIXBUF_ERROR_FAILED,
258                                 _("Failed to load RGB data from TIFF file"));
259                 g_object_unref (pixbuf);
260                 return NULL;
261         }
262
263         if (img.put.any == NULL) {
264                 tiff_set_error (error,
265                                 GDK_PIXBUF_ERROR_FAILED,
266                                 _("Unsupported TIFF variant"));
267                 g_object_unref (pixbuf);
268                 return NULL;                
269         }
270         
271         if (img.isContig) {
272                 tiff_put_contig = img.put.contig;
273                 img.put.contig = put_contig;
274         }
275         else {
276                 tiff_put_separate = img.put.separate;
277                 img.put.separate = put_separate;
278         }
279
280         TIFFRGBAImageGet (&img, (uint32 *)pixels, width, height);
281         TIFFRGBAImageEnd (&img);
282
283 #ifdef WORDS_BIGENDIAN
284 /* Turns out that the packing used by TIFFRGBAImage depends on the host byte order... */ 
285         while (pixels < pixbuf->pixels + bytes) {
286                 uint32 pixel = *(uint32 *)pixels;
287                 int r = TIFFGetR(pixel);
288                 int g = TIFFGetG(pixel);
289                 int b = TIFFGetB(pixel);
290                 int a = TIFFGetA(pixel);
291                 *pixels++ = r;
292                 *pixels++ = g;
293                 *pixels++ = b;
294                 *pixels++ = a;
295         }
296 #endif
297
298         G_UNLOCK (tiff_loader);
299         if (context)
300                 (* context->update_func) (pixbuf, 0, 0, width, height, context->user_data);
301         G_LOCK (tiff_loader);
302         
303         return pixbuf;
304 }
305
306 \f
307
308 /* Static loader */
309
310 static GdkPixbuf *
311 gdk_pixbuf__tiff_image_load (FILE *f, GError **error)
312 {
313         TIFF *tiff;
314         int fd;
315         GdkPixbuf *pixbuf;
316         
317         g_return_val_if_fail (f != NULL, NULL);
318
319         G_LOCK (tiff_loader);
320
321         tiff_push_handlers ();
322         
323         fd = fileno (f);
324
325         /* On OSF, apparently fseek() works in some on-demand way, so
326          * the fseek gdk_pixbuf_new_from_file() doesn't work here
327          * since we are using the raw file descriptor. So, we call lseek() on the fd
328          * before using it. (#60840)
329          */
330         lseek (fd, 0, SEEK_SET);
331         tiff = TIFFFdOpen (fd, "libpixbuf-tiff", "r");
332         
333         if (!tiff || global_error) {
334                 tiff_set_error (error,
335                                 GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
336                                 _("Failed to open TIFF image"));
337                 tiff_pop_handlers ();
338
339                 G_UNLOCK (tiff_loader);
340                 return NULL;
341         }
342
343         pixbuf = tiff_image_parse (tiff, NULL, error);
344         
345         TIFFClose (tiff);
346         if (global_error) {
347                 tiff_set_error (error,
348                                 GDK_PIXBUF_ERROR_FAILED,
349                                 _("TIFFClose operation failed"));
350         }
351         
352         tiff_pop_handlers ();
353
354         G_UNLOCK (tiff_loader);
355         
356         return pixbuf;
357 }
358
359 \f
360
361 /* Progressive loader */
362
363 static gpointer
364 gdk_pixbuf__tiff_image_begin_load (ModuleSizeFunc size_func,
365                                    ModulePreparedNotifyFunc prepare_func,
366                                    ModuleUpdatedNotifyFunc update_func,
367                                    gpointer user_data,
368                                    GError **error)
369 {
370         TiffContext *context;
371         
372         context = g_new0 (TiffContext, 1);
373         context->prepare_func = prepare_func;
374         context->update_func = update_func;
375         context->user_data = user_data;
376         context->buffer = NULL;
377         context->allocated = 0;
378         context->used = 0;
379         context->pos = 0;
380         
381         return context;
382 }
383
384 static tsize_t
385 tiff_read (thandle_t handle, tdata_t buf, tsize_t size)
386 {
387         TiffContext *context = (TiffContext *)handle;
388         
389         if (context->pos + size > context->used)
390                 return 0;
391         
392         memcpy (buf, context->buffer + context->pos, size);
393         context->pos += size;
394         return size;
395 }
396
397 static tsize_t
398 tiff_write (thandle_t handle, tdata_t buf, tsize_t size)
399 {
400         return -1;
401 }
402
403 static toff_t
404 tiff_seek (thandle_t handle, toff_t offset, int whence)
405 {
406         TiffContext *context = (TiffContext *)handle;
407         
408         switch (whence) {
409         case SEEK_SET:
410                 if (offset > context->used || offset < 0)
411                         return -1;
412                 context->pos = offset;
413                 break;
414         case SEEK_CUR:
415                 if (offset + context->pos >= context->used)
416                         return -1;
417                 context->pos += offset;
418                 break;
419         case SEEK_END:
420                 if (offset + context->used > context->used)
421                         return -1;
422                 context->pos = context->used + offset;
423                 break;
424         default:
425                 return -1;
426                 break;
427         }
428         return context->pos;
429 }
430
431 static int
432 tiff_close (thandle_t context)
433 {
434         return 0;
435 }
436
437 static toff_t
438 tiff_size (thandle_t handle)
439 {
440         TiffContext *context = (TiffContext *)handle;
441         
442         return context->used;
443 }
444
445 static int
446 tiff_map_file (thandle_t handle, tdata_t *buf, toff_t *size)
447 {
448         TiffContext *context = (TiffContext *)handle;
449         
450         *buf = context->buffer;
451         *size = context->used;
452         
453         return 0;
454 }
455
456 static void
457 tiff_unmap_file (thandle_t handle, tdata_t data, toff_t offset)
458 {
459 }
460
461 static gboolean
462 gdk_pixbuf__tiff_image_stop_load (gpointer data,
463                                   GError **error)
464 {
465         TiffContext *context = data;
466         TIFF *tiff;
467         gboolean retval;
468         
469         g_return_val_if_fail (data != NULL, FALSE);
470
471         G_LOCK (tiff_loader);
472         
473         tiff_push_handlers ();
474         
475         tiff = TIFFClientOpen ("libtiff-pixbuf", "r", data, 
476                                tiff_read, tiff_write, 
477                                tiff_seek, tiff_close, 
478                                tiff_size, 
479                                tiff_map_file, tiff_unmap_file);
480         if (!tiff || global_error) {
481                 tiff_set_error (error,
482                                 GDK_PIXBUF_ERROR_FAILED,
483                                 _("Failed to load TIFF image"));
484                 retval = FALSE;
485         } else {
486                 GdkPixbuf *pixbuf;
487                 
488                 pixbuf = tiff_image_parse (tiff, context, error);
489                 if (pixbuf)
490                         g_object_unref (pixbuf);
491                 retval = pixbuf != NULL;
492                 if (global_error)
493                         {
494                                 tiff_set_error (error,
495                                                 GDK_PIXBUF_ERROR_FAILED,
496                                                 _("Failed to load TIFF image"));
497                                 tiff_pop_handlers ();
498
499                                 retval = FALSE;
500                         }
501         }
502
503         if (tiff)
504                 TIFFClose (tiff);
505
506         g_assert (!global_error);
507         
508         g_free (context->buffer);
509         g_free (context);
510
511         tiff_pop_handlers ();
512
513         G_UNLOCK (tiff_loader);
514
515         return retval;
516 }
517
518 static gboolean
519 make_available_at_least (TiffContext *context, guint needed)
520 {
521         guchar *new_buffer = NULL;
522         guint need_alloc;
523         
524         need_alloc = context->used + needed;
525         if (need_alloc > context->allocated) {
526                 guint new_size = 1;
527                 while (new_size < need_alloc)
528                         new_size *= 2;
529                 
530                 new_buffer = g_try_realloc (context->buffer, new_size);
531                 if (new_buffer) {
532                         context->buffer = new_buffer;
533                         context->allocated = new_size;
534                         return TRUE;
535                 }
536                 return FALSE;
537         }
538         return TRUE;
539 }
540
541 static gboolean
542 gdk_pixbuf__tiff_image_load_increment (gpointer data, const guchar *buf,
543                                        guint size, GError **error)
544 {
545         TiffContext *context = (TiffContext *) data;
546         
547         g_return_val_if_fail (data != NULL, FALSE);
548         
549         if (!make_available_at_least (context, size)) {
550                 g_set_error (error,
551                              GDK_PIXBUF_ERROR,
552                              GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
553                              _("Insufficient memory to open TIFF file"));
554                 return FALSE;
555         }
556         
557         memcpy (context->buffer + context->used, buf, size);
558         context->used += size;
559         return TRUE;
560 }
561
562 void
563 gdk_pixbuf__tiff_fill_vtable (GdkPixbufModule *module)
564 {
565         module->load = gdk_pixbuf__tiff_image_load;
566         module->begin_load = gdk_pixbuf__tiff_image_begin_load;
567         module->stop_load = gdk_pixbuf__tiff_image_stop_load;
568         module->load_increment = gdk_pixbuf__tiff_image_load_increment;
569 }