]> Pileus Git - ~andy/gtk/blob - gdk-pixbuf/io-gif.c
Add a (#ifdef 0'ed) test provoking a segfault in TIFFReadDirectory().
[~andy/gtk] / gdk-pixbuf / io-gif.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */
2 /* GdkPixbuf library - GIF image loader
3  *
4  * Copyright (C) 1999 Mark Crichton
5  * Copyright (C) 1999 The Free Software Foundation
6  *
7  * Authors: Jonathan Blandford <jrb@redhat.com>
8  *          Adapted from the gimp gif filter written by Adam Moss <adam@gimp.org>
9  *          Gimp work based on earlier work.
10  *          Permission to relicense under the LGPL obtained.
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 /* This loader is very hairy code.
29  *
30  * The main loop was not designed for incremental loading, so when it was hacked
31  * in it got a bit messy.  Basicly, every function is written to expect a failed
32  * read_gif, and lets you call it again assuming that the bytes are there.
33  *
34  * Return vals.
35  * Unless otherwise specified, these are the return vals for most functions:
36  *
37  *  0 -> success
38  * -1 -> more bytes needed.
39  * -2 -> failure; abort the load
40  * -3 -> control needs to be passed back to the main loop
41  *        \_ (most of the time returning 0 will get this, but not always)
42  *
43  * >1 -> for functions that get a guchar, the char will be returned.
44  *
45  * -jrb (11/03/1999)
46  */
47
48 /*
49  * If you have any images that crash this code, please, please let me know and
50  * send them to me.
51  *                                            <jrb@redhat.com>
52  */
53
54 \f
55
56 #include <config.h>
57 #include <stdio.h>
58 #include <string.h>
59 #include <errno.h>
60 #include "gdk-pixbuf-private.h"
61 #include "gdk-pixbuf-io.h"
62 #include "io-gif-animation.h"
63
64 \f
65
66 #undef DUMP_IMAGE_DETAILS
67
68 #define MAXCOLORMAPSIZE  256
69 #define MAX_LZW_BITS     12
70
71 #define INTERLACE          0x40
72 #define LOCALCOLORMAP      0x80
73 #define BitSet(byte, bit)  (((byte) & (bit)) == (bit))
74 #define LM_to_uint(a,b)         (((b)<<8)|(a))
75
76 \f
77
78 typedef unsigned char CMap[3][MAXCOLORMAPSIZE];
79
80 /* Possible states we can be in. */
81 enum {
82         GIF_START,
83         GIF_GET_COLORMAP,
84         GIF_GET_NEXT_STEP,
85         GIF_GET_FRAME_INFO,
86         GIF_GET_EXTENTION,
87         GIF_GET_COLORMAP2,
88         GIF_PREPARE_LZW,
89         GIF_LZW_FILL_BUFFER,
90         GIF_LZW_CLEAR_CODE,
91         GIF_GET_LZW,
92         GIF_DONE
93 };
94
95
96 typedef struct _Gif89 Gif89;
97 struct _Gif89
98 {
99         int transparent;
100         int delay_time;
101         int input_flag;
102         int disposal;
103 };
104
105 typedef struct _GifContext GifContext;
106 struct _GifContext
107 {
108         int state; /* really only relevant for progressive loading */
109         unsigned int width;
110         unsigned int height;
111
112         gboolean has_global_cmap;
113
114         CMap global_color_map;
115         gint global_colormap_size;
116         unsigned int global_bit_pixel;
117         unsigned int global_color_resolution;
118         unsigned int background_index;
119
120         gboolean frame_cmap_active;
121         CMap frame_color_map;
122         gint frame_colormap_size;
123         unsigned int frame_bit_pixel;
124
125         unsigned int aspect_ratio;
126         GdkPixbufGifAnim *animation;
127         GdkPixbufFrame *frame;
128         Gif89 gif89;
129
130         /* stuff per frame. */
131         int frame_len;
132         int frame_height;
133         int frame_interlace;
134         int x_offset;
135         int y_offset;
136
137         /* Static read only */
138         FILE *file;
139
140         /* progressive read, only. */
141         ModulePreparedNotifyFunc prepare_func;
142         ModuleUpdatedNotifyFunc update_func;
143         gpointer user_data;
144         guchar *buf;
145         guint ptr;
146         guint size;
147         guint amount_needed;
148
149         /* extension context */
150         guchar extension_label;
151         guchar extension_flag;
152
153         /* get block context */
154         guchar block_count;
155         guchar block_buf[280];
156         gint block_ptr;
157
158         int old_state; /* used by lzw_fill buffer */
159         /* get_code context */
160         int code_curbit;
161         int code_lastbit;
162         int code_done;
163         int code_last_byte;
164         int lzw_code_pending;
165
166         /* lzw context */
167         gint lzw_fresh;
168         gint lzw_code_size;
169         guchar lzw_set_code_size;
170         gint lzw_max_code;
171         gint lzw_max_code_size;
172         gint lzw_firstcode;
173         gint lzw_oldcode;
174         gint lzw_clear_code;
175         gint lzw_end_code;
176         gint *lzw_sp;
177
178         gint lzw_table[2][(1 << MAX_LZW_BITS)];
179         gint lzw_stack[(1 << (MAX_LZW_BITS)) * 2 + 1];
180
181         /* painting context */
182         gint draw_xpos;
183         gint draw_ypos;
184         gint draw_pass;
185
186         /* error pointer */
187         GError **error;
188 };
189
190 static int GetDataBlock (GifContext *, unsigned char *);
191
192 \f
193
194 #ifdef IO_GIFDEBUG
195 static int count = 0;
196 #endif
197
198 /* Returns TRUE if read is OK,
199  * FALSE if more memory is needed. */
200 static gboolean
201 gif_read (GifContext *context, guchar *buffer, size_t len)
202 {
203         gboolean retval;
204 #ifdef IO_GIFDEBUG
205         gint i;
206 #endif
207         if (context->file) {
208 #ifdef IO_GIFDEBUG
209                 count += len;
210                 g_print ("Fsize :%d\tcount :%d\t", len, count);
211 #endif
212                 retval = (fread(buffer, len, 1, context->file) != 0);
213
214                 if (!retval && ferror (context->file))
215                         g_set_error (context->error,
216                                      G_FILE_ERROR,
217                                      g_file_error_from_errno (errno),
218                                      _("Failure reading GIF: %s"), strerror (errno));
219                 
220 #ifdef IO_GIFDEBUG
221                 if (len < 100) {
222                         for (i = 0; i < len; i++)
223                                 g_print ("%d ", buffer[i]);
224                 }
225                 g_print ("\n");
226 #endif
227                 
228                 return retval;
229         } else {
230 #ifdef IO_GIFDEBUG
231 /*              g_print ("\tlooking for %d bytes.  size == %d, ptr == %d\n", len, context->size, context->ptr); */
232 #endif
233                 if ((context->size - context->ptr) >= len) {
234 #ifdef IO_GIFDEBUG
235                         count += len;
236 #endif
237                         memcpy (buffer, context->buf + context->ptr, len);
238                         context->ptr += len;
239                         context->amount_needed = 0;
240 #ifdef IO_GIFDEBUG
241                         g_print ("Psize :%d\tcount :%d\t", len, count);
242                         if (len < 100) {
243                                 for (i = 0; i < len; i++)
244                                         g_print ("%d ", buffer[i]);
245                         }
246                         g_print ("\n");
247 #endif
248                         return TRUE;
249                 }
250                 context->amount_needed = len - (context->size - context->ptr);
251         }
252         return 0;
253 }
254
255 /* Changes the stage to be GIF_GET_COLORMAP */
256 static void
257 gif_set_get_colormap (GifContext *context)
258 {
259         context->global_colormap_size = 0;
260         context->state = GIF_GET_COLORMAP;
261 }
262
263 static void
264 gif_set_get_colormap2 (GifContext *context)
265 {
266         context->frame_colormap_size = 0;
267         context->state = GIF_GET_COLORMAP2;
268 }
269
270 static gint
271 gif_get_colormap (GifContext *context)
272 {
273         unsigned char rgb[3];
274
275         while (context->global_colormap_size < context->global_bit_pixel) {
276                 if (!gif_read (context, rgb, sizeof (rgb))) {
277                         return -1;
278                 }
279
280                 context->global_color_map[0][context->global_colormap_size] = rgb[0];
281                 context->global_color_map[1][context->global_colormap_size] = rgb[1];
282                 context->global_color_map[2][context->global_colormap_size] = rgb[2];
283
284                 if (context->global_colormap_size == context->background_index) {
285                         context->animation->bg_red = rgb[0];
286                         context->animation->bg_green = rgb[1];
287                         context->animation->bg_blue = rgb[2];
288                 }
289
290                 context->global_colormap_size ++;
291         }
292
293         return 0;
294 }
295
296
297 static gint
298 gif_get_colormap2 (GifContext *context)
299 {
300         unsigned char rgb[3];
301
302         while (context->frame_colormap_size < context->frame_bit_pixel) {
303                 if (!gif_read (context, rgb, sizeof (rgb))) {
304                         return -1;
305                 }
306
307                 context->frame_color_map[0][context->frame_colormap_size] = rgb[0];
308                 context->frame_color_map[1][context->frame_colormap_size] = rgb[1];
309                 context->frame_color_map[2][context->frame_colormap_size] = rgb[2];
310
311                 context->frame_colormap_size ++;
312         }
313
314         return 0;
315 }
316
317 /*
318  * in order for this function to work, we need to perform some black magic.
319  * We want to return -1 to let the calling function know, as before, that it needs
320  * more bytes.  If we return 0, we were able to successfully read all block->count bytes.
321  * Problem is, we don't want to reread block_count every time, so we check to see if
322  * context->block_count is 0 before we read in the function.
323  *
324  * As a result, context->block_count MUST be 0 the first time the get_data_block is called
325  * within a context, and cannot be 0 the second time it's called.
326  */
327
328 static int
329 get_data_block (GifContext *context,
330                 unsigned char *buf,
331                 gint *empty_block)
332 {
333
334         if (context->block_count == 0) {
335                 if (!gif_read (context, &context->block_count, 1)) {
336                         return -1;
337                 }
338         }
339
340         if (context->block_count == 0)
341                 if (empty_block) {
342                         *empty_block = TRUE;
343                         return 0;
344                 }
345
346         if (!gif_read (context, buf, context->block_count)) {
347                 return -1;
348         }
349
350         return 0;
351 }
352
353 static void
354 gif_set_get_extension (GifContext *context)
355 {
356         context->state = GIF_GET_EXTENTION;
357         context->extension_flag = TRUE;
358         context->extension_label = 0;
359         context->block_count = 0;
360         context->block_ptr = 0;
361 }
362
363 static int
364 gif_get_extension (GifContext *context)
365 {
366         gint retval;
367         gint empty_block = FALSE;
368
369         if (context->extension_flag) {
370                 if (context->extension_label == 0) {
371                         /* I guess bad things can happen if we have an extension of 0 )-: */
372                         /* I should look into this sometime */
373                         if (!gif_read (context, & context->extension_label , 1)) {
374                                 return -1;
375                         }
376                 }
377
378                 switch (context->extension_label) {
379                 case 0xf9:                      /* Graphic Control Extension */
380                         retval = get_data_block (context, (unsigned char *) context->block_buf, NULL);
381                         if (retval != 0)
382                                 return retval;
383
384                         if (context->frame == NULL) {
385                                 /* I only want to set the transparency if I haven't
386                                  * created the frame yet.
387                                  */
388                                 context->gif89.disposal = (context->block_buf[0] >> 2) & 0x7;
389                                 context->gif89.input_flag = (context->block_buf[0] >> 1) & 0x1;
390                                 context->gif89.delay_time = LM_to_uint (context->block_buf[1], context->block_buf[2]);
391                                 
392                                 if ((context->block_buf[0] & 0x1) != 0) {
393                                         context->gif89.transparent = context->block_buf[3];
394                                 } else {
395                                         context->gif89.transparent = -1;
396                                 }
397                         }
398
399                         /* Now we've successfully loaded this one, we continue on our way */
400                         context->block_count = 0;
401                         context->extension_flag = FALSE;
402                 default:
403                         /* Unhandled extension */
404                         break;
405                 }
406         }
407         /* read all blocks, until I get an empty block, in case there was an extension I didn't know about. */
408         do {
409                 retval = get_data_block (context, (unsigned char *) context->block_buf, &empty_block);
410                 if (retval != 0)
411                         return retval;
412                 context->block_count = 0;
413         } while (!empty_block);
414
415         return 0;
416 }
417
418 static int ZeroDataBlock = FALSE;
419
420 static int
421 GetDataBlock (GifContext *context,
422               unsigned char *buf)
423 {
424 /*      unsigned char count; */
425
426         if (!gif_read (context, &context->block_count, 1)) {
427                 /*g_message (_("GIF: error in getting DataBlock size\n"));*/
428                 return -1;
429         }
430
431         ZeroDataBlock = context->block_count == 0;
432
433         if ((context->block_count != 0) && (!gif_read (context, buf, context->block_count))) {
434                 /*g_message (_("GIF: error in reading DataBlock\n"));*/
435                 return -1;
436         }
437
438         return context->block_count;
439 }
440
441
442 static void
443 gif_set_lzw_fill_buffer (GifContext *context)
444 {
445         context->block_count = 0;
446         context->old_state = context->state;
447         context->state = GIF_LZW_FILL_BUFFER;
448 }
449
450 static int
451 gif_lzw_fill_buffer (GifContext *context)
452 {
453         gint retval;
454
455         if (context->code_done) {
456                 if (context->code_curbit >= context->code_lastbit) {
457                         g_set_error (context->error,
458                                      GDK_PIXBUF_ERROR,
459                                      GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
460                                      _("GIF file was missing some data (perhaps it was truncated somehow?)"));
461
462                         return -2;
463                 }
464                 /* Is this supposed to be an error or what? */
465                 /* g_message ("trying to read more data after we've done stuff\n"); */
466                 g_set_error (context->error,
467                              GDK_PIXBUF_ERROR,
468                              GDK_PIXBUF_ERROR_FAILED,
469                              _("Internal error in the GIF loader (%s)"),
470                              G_STRLOC);
471                 
472                 return -2;
473         }
474
475         context->block_buf[0] = context->block_buf[context->code_last_byte - 2];
476         context->block_buf[1] = context->block_buf[context->code_last_byte - 1];
477
478         retval = get_data_block (context, &context->block_buf[2], NULL);
479
480         if (retval == -1)
481                 return -1;
482
483         if (context->block_count == 0)
484                 context->code_done = TRUE;
485
486         context->code_last_byte = 2 + context->block_count;
487         context->code_curbit = (context->code_curbit - context->code_lastbit) + 16;
488         context->code_lastbit = (2 + context->block_count) * 8;
489
490         context->state = context->old_state;
491         return 0;
492 }
493
494 static int
495 get_code (GifContext *context,
496           int   code_size)
497 {
498         int i, j, ret;
499
500         if ((context->code_curbit + code_size) >= context->code_lastbit){
501                 gif_set_lzw_fill_buffer (context);
502                 return -3;
503         }
504
505         ret = 0;
506         for (i = context->code_curbit, j = 0; j < code_size; ++i, ++j)
507                 ret |= ((context->block_buf[i / 8] & (1 << (i % 8))) != 0) << j;
508
509         context->code_curbit += code_size;
510
511         return ret;
512 }
513
514
515 static void
516 set_gif_lzw_clear_code (GifContext *context)
517 {
518         context->state = GIF_LZW_CLEAR_CODE;
519         context->lzw_code_pending = -1;
520 }
521
522 static int
523 gif_lzw_clear_code (GifContext *context)
524 {
525         gint code;
526
527         code = get_code (context, context->lzw_code_size);
528         if (code == -3)
529                 return -0;
530
531         context->lzw_firstcode = context->lzw_oldcode = code;
532         context->lzw_code_pending = code;
533         context->state = GIF_GET_LZW;
534         return 0;
535 }
536
537 static int
538 lzw_read_byte (GifContext *context)
539 {
540         int code, incode;
541         gint retval;
542         gint my_retval;
543         register int i;
544
545         if (context->lzw_code_pending != -1) {
546                 retval = context->lzw_code_pending;
547                 context->lzw_code_pending = -1;
548                 return retval;
549         }
550
551         if (context->lzw_fresh) {
552                 context->lzw_fresh = FALSE;
553                 do {
554                         retval = get_code (context, context->lzw_code_size);
555                         if (retval < 0) {
556                                 return retval;
557                         }
558
559                         context->lzw_firstcode = context->lzw_oldcode = retval;
560                 } while (context->lzw_firstcode == context->lzw_clear_code);
561                 return context->lzw_firstcode;
562         }
563
564         if (context->lzw_sp > context->lzw_stack) {
565                 my_retval = *--(context->lzw_sp);
566                 return my_retval;
567         }
568
569         while ((code = get_code (context, context->lzw_code_size)) >= 0) {
570                 if (code == context->lzw_clear_code) {
571                         for (i = 0; i < context->lzw_clear_code; ++i) {
572                                 context->lzw_table[0][i] = 0;
573                                 context->lzw_table[1][i] = i;
574                         }
575                         for (; i < (1 << MAX_LZW_BITS); ++i)
576                                 context->lzw_table[0][i] = context->lzw_table[1][i] = 0;
577                         context->lzw_code_size = context->lzw_set_code_size + 1;
578                         context->lzw_max_code_size = 2 * context->lzw_clear_code;
579                         context->lzw_max_code = context->lzw_clear_code + 2;
580                         context->lzw_sp = context->lzw_stack;
581
582                         set_gif_lzw_clear_code (context);
583                         return -3;
584                 } else if (code == context->lzw_end_code) {
585                         int count;
586                         unsigned char buf[260];
587
588                         /*  FIXME - we should handle this case */
589                         g_set_error (context->error,
590                                      GDK_PIXBUF_ERROR,
591                                      GDK_PIXBUF_ERROR_FAILED,
592                                      _("GIF image loader can't understand this image."));
593                         return -2;
594                         
595                         if (ZeroDataBlock) {
596                                 return -2;
597                         }
598
599                         while ((count = GetDataBlock (context, buf)) > 0)
600                                 ;
601
602                         if (count != 0) {
603                                 /*g_print (_("GIF: missing EOD in data stream (common occurence)"));*/
604                                 return -2;
605                         }
606                 }
607
608                 incode = code;
609
610                 if (code >= context->lzw_max_code) {
611                         *(context->lzw_sp)++ = context->lzw_firstcode;
612                         code = context->lzw_oldcode;
613                 }
614
615                 while (code >= context->lzw_clear_code) {
616                         if ((code >= (1 << MAX_LZW_BITS)) 
617                             || (context->lzw_sp >= context->lzw_stack + ((1 << (MAX_LZW_BITS)) * 2 + 1))) {
618                                 g_set_error (context->error,
619                                              GDK_PIXBUF_ERROR,
620                                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
621                                              _("Bad code encountered"));
622                                 return -2;
623                         }
624                         *(context->lzw_sp)++ = context->lzw_table[1][code];
625
626                         if (code == context->lzw_table[0][code]) {
627                                 g_set_error (context->error,
628                                              GDK_PIXBUF_ERROR,
629                                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
630                                              _("Circular table entry in GIF file"));
631                                 return -2;
632                         }
633                         code = context->lzw_table[0][code];
634                 }
635
636                 *(context->lzw_sp)++ = context->lzw_firstcode = context->lzw_table[1][code];
637
638                 if ((code = context->lzw_max_code) < (1 << MAX_LZW_BITS)) {
639                         context->lzw_table[0][code] = context->lzw_oldcode;
640                         context->lzw_table[1][code] = context->lzw_firstcode;
641                         ++context->lzw_max_code;
642                         if ((context->lzw_max_code >= context->lzw_max_code_size) &&
643                             (context->lzw_max_code_size < (1 << MAX_LZW_BITS))) {
644                                 context->lzw_max_code_size *= 2;
645                                 ++context->lzw_code_size;
646                         }
647                 }
648
649                 context->lzw_oldcode = incode;
650
651                 if (context->lzw_sp > context->lzw_stack) {
652                         my_retval = *--(context->lzw_sp);
653                         return my_retval;
654                 }
655         }
656         return code;
657 }
658
659 static void
660 gif_set_get_lzw (GifContext *context)
661 {
662         context->state = GIF_GET_LZW;
663         context->draw_xpos = 0;
664         context->draw_ypos = 0;
665         context->draw_pass = 0;
666 }
667
668 static void
669 gif_fill_in_pixels (GifContext *context, guchar *dest, gint offset, guchar v)
670 {
671         guchar *pixel = NULL;
672         guchar (*cmap)[MAXCOLORMAPSIZE];
673
674         if (context->frame_cmap_active)
675                 cmap = context->frame_color_map;
676         else
677                 cmap = context->global_color_map;
678         
679         if (context->gif89.transparent != -1) {
680                 pixel = dest + (context->draw_ypos + offset) * gdk_pixbuf_get_rowstride (context->frame->pixbuf) + context->draw_xpos * 4;
681                 *pixel = cmap [0][(guchar) v];
682                 *(pixel+1) = cmap [1][(guchar) v];
683                 *(pixel+2) = cmap [2][(guchar) v];
684                 *(pixel+3) = (guchar) ((v == context->gif89.transparent) ? 0 : 255);
685         } else {
686                 pixel = dest + (context->draw_ypos + offset) * gdk_pixbuf_get_rowstride (context->frame->pixbuf) + context->draw_xpos * 3;
687                 *pixel = cmap [0][(guchar) v];
688                 *(pixel+1) = cmap [1][(guchar) v];
689                 *(pixel+2) = cmap [2][(guchar) v];
690         }
691 }
692
693
694 /* only called if progressive and interlaced */
695 static void
696 gif_fill_in_lines (GifContext *context, guchar *dest, guchar v)
697 {
698         switch (context->draw_pass) {
699         case 0:
700                 if (context->draw_ypos > 4) {
701                         gif_fill_in_pixels (context, dest, -4, v);
702                         gif_fill_in_pixels (context, dest, -3, v);
703                 }
704                 if (context->draw_ypos < (context->frame_height - 4)) {
705                         gif_fill_in_pixels (context, dest, 3, v);
706                         gif_fill_in_pixels (context, dest, 4, v);
707                 }
708                 /* we don't need a break here.  We draw the outer pixels first, then the
709                  * inner ones, then the innermost ones.  case 0 needs to draw all 3 bands.
710                  * case 1, just the last two, and case 2 just draws the last one*/
711         case 1:
712                 if (context->draw_ypos > 2)
713                         gif_fill_in_pixels (context, dest, -2, v);
714                 if (context->draw_ypos < (context->frame_height - 2))
715                         gif_fill_in_pixels (context, dest, 2, v);
716                 /* no break as above. */
717         case 2:
718                 if (context->draw_ypos > 1)
719                         gif_fill_in_pixels (context, dest, -1, v);
720                 if (context->draw_ypos < (context->frame_height - 1))
721                         gif_fill_in_pixels (context, dest, 1, v);
722         case 3:
723         default:
724                 break;
725         }
726 }
727
728 static void
729 set_need_recomposite (gpointer data, gpointer user_data)
730 {
731         GdkPixbufFrame *frame = (GdkPixbufFrame *)data;
732         frame->need_recomposite = TRUE;
733 }
734
735
736 static int
737 gif_get_lzw (GifContext *context)
738 {
739         guchar *dest, *temp;
740         gint lower_bound, upper_bound; /* bounds for emitting the area_updated signal */
741         gboolean bound_flag;
742         gint first_pass; /* bounds for emitting the area_updated signal */
743         gint v;
744
745         if (context->frame == NULL) {
746                 context->frame = g_new (GdkPixbufFrame, 1);
747
748                 context->frame->composited = NULL;
749                 context->frame->revert = NULL;
750                 
751                 context->frame->pixbuf =
752                         gdk_pixbuf_new (GDK_COLORSPACE_RGB,
753                                         TRUE,
754                                         8,
755                                         context->frame_len,
756                                         context->frame_height);
757                 if (!context->frame->pixbuf) {
758                         g_free (context->frame);
759                         g_set_error (context->error,
760                                      GDK_PIXBUF_ERROR,
761                                      GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
762                                      _("Not enough memory to load GIF file"));
763                         return -2;
764                 }
765
766                 context->frame->x_offset = context->x_offset;
767                 context->frame->y_offset = context->y_offset;
768                 context->frame->need_recomposite = TRUE;
769                 
770                 /* GIF delay is in hundredths, we want thousandths */
771                 context->frame->delay_time = context->gif89.delay_time * 10;
772
773                 /* Some GIFs apparently have delay time of 0,
774                  * that crashes everything so set it to "fast".
775                  * Also, timeouts less than 20 or so just lock up
776                  * the app or make the animation choppy, so fix them.
777                  */
778                 if (context->frame->delay_time < 20)
779                         context->frame->delay_time = 20; /* 20 = "fast" */
780                 
781                 context->frame->elapsed = context->animation->total_time;
782                 context->animation->total_time += context->frame->delay_time;                
783                 
784                 switch (context->gif89.disposal) {
785                 case 0:
786                 case 1:
787                         context->frame->action = GDK_PIXBUF_FRAME_RETAIN;
788                         break;
789                 case 2:
790                         context->frame->action = GDK_PIXBUF_FRAME_DISPOSE;
791                         break;
792                 case 3:
793                         context->frame->action = GDK_PIXBUF_FRAME_REVERT;
794                         break;
795                 default:
796                         context->frame->action = GDK_PIXBUF_FRAME_RETAIN;
797                         break;
798                 }
799
800                 context->frame->bg_transparent = (context->gif89.transparent == context->background_index);
801                 
802                 {
803                         /* Update animation size */
804                         int w, h;
805                         
806                         context->animation->n_frames ++;
807                         context->animation->frames = g_list_append (context->animation->frames, context->frame);
808
809                         w = context->frame->x_offset +
810                                 gdk_pixbuf_get_width (context->frame->pixbuf);
811                         h = context->frame->y_offset +
812                                 gdk_pixbuf_get_height (context->frame->pixbuf);
813                         if (w  > context->animation->width || h > context->animation->height) {
814                                 g_list_foreach (context->animation->frames, set_need_recomposite, NULL);
815                         }
816                         if (w > context->animation->width)
817                                 context->animation->width = w;
818                         if (h > context->animation->height)
819                                 context->animation->height = h;
820                 }
821
822                 /* Only call prepare_func for the first frame */
823                 if (context->animation->frames->next == NULL) { 
824                         if (context->prepare_func)
825                                 (* context->prepare_func) (context->frame->pixbuf,
826                                                            GDK_PIXBUF_ANIMATION (context->animation),
827                                                            context->user_data);
828                 } else {
829                         /* Otherwise init frame with last frame */
830                         GList *link;
831                         GdkPixbufFrame *prev_frame;
832                         
833                         link = g_list_find (context->animation->frames, context->frame);
834
835                         prev_frame = link->prev->data;
836
837                         gdk_pixbuf_gif_anim_frame_composite (context->animation, prev_frame);
838
839                         gdk_pixbuf_copy_area (prev_frame->composited,
840                                               context->frame->x_offset,
841                                               context->frame->y_offset,
842                                               gdk_pixbuf_get_width (context->frame->pixbuf),
843                                               gdk_pixbuf_get_height (context->frame->pixbuf),
844                                               context->frame->pixbuf,
845                                               0, 0);
846                 }
847         }
848
849         dest = gdk_pixbuf_get_pixels (context->frame->pixbuf);
850
851         bound_flag = FALSE;
852         lower_bound = upper_bound = context->draw_ypos;
853         first_pass = context->draw_pass;
854
855         while (TRUE) {
856                 guchar (*cmap)[MAXCOLORMAPSIZE];
857
858                 if (context->frame_cmap_active)
859                         cmap = context->frame_color_map;
860                 else
861                         cmap = context->global_color_map;
862                 
863                 v = lzw_read_byte (context);
864                 if (v < 0) {
865                         goto finished_data;
866                 }
867                 bound_flag = TRUE;
868
869                 g_assert (gdk_pixbuf_get_has_alpha (context->frame->pixbuf));
870                 
871                 temp = dest + context->draw_ypos * gdk_pixbuf_get_rowstride (context->frame->pixbuf) + context->draw_xpos * 4;
872                 *temp = cmap [0][(guchar) v];
873                 *(temp+1) = cmap [1][(guchar) v];
874                 *(temp+2) = cmap [2][(guchar) v];
875                 *(temp+3) = (guchar) ((v == context->gif89.transparent) ? 0 : 255);
876
877                 if (context->prepare_func && context->frame_interlace)
878                         gif_fill_in_lines (context, dest, v);
879
880                 context->draw_xpos++;
881                 
882                 if (context->draw_xpos == context->frame_len) {
883                         context->draw_xpos = 0;
884                         if (context->frame_interlace) {
885                                 switch (context->draw_pass) {
886                                 case 0:
887                                 case 1:
888                                         context->draw_ypos += 8;
889                                         break;
890                                 case 2:
891                                         context->draw_ypos += 4;
892                                         break;
893                                 case 3:
894                                         context->draw_ypos += 2;
895                                         break;
896                                 }
897
898                                 if (context->draw_ypos >= context->frame_height) {
899                                         context->draw_pass++;
900                                         switch (context->draw_pass) {
901                                         case 1:
902                                                 context->draw_ypos = 4;
903                                                 break;
904                                         case 2:
905                                                 context->draw_ypos = 2;
906                                                 break;
907                                         case 3:
908                                                 context->draw_ypos = 1;
909                                                 break;
910                                         default:
911                                                 goto done;
912                                         }
913                                 }
914                         } else {
915                                 context->draw_ypos++;
916                         }
917                         if (context->draw_pass != first_pass) {
918                                 if (context->draw_ypos > lower_bound) {
919                                         lower_bound = 0;
920                                         upper_bound = context->frame_height;
921                                 } else {
922                                         
923                                 }
924                         } else
925                                 upper_bound = context->draw_ypos;
926                 }
927                 if (context->draw_ypos >= context->frame_height)
928                         break;
929         }
930
931  done:
932
933         context->state = GIF_GET_NEXT_STEP;
934
935         v = 0;
936
937  finished_data:
938         
939         if (bound_flag)
940                 context->frame->need_recomposite = TRUE;
941         
942         if (bound_flag && context->update_func) {
943                 if (lower_bound <= upper_bound && first_pass == context->draw_pass) {
944                         (* context->update_func)
945                                 (context->frame->pixbuf,
946                                  0, lower_bound,
947                                  gdk_pixbuf_get_width (context->frame->pixbuf),
948                                  upper_bound - lower_bound,
949                                  context->user_data);
950                 } else {
951                         if (lower_bound <= upper_bound) {
952                                 (* context->update_func)
953                                         (context->frame->pixbuf,
954                                          context->frame->x_offset,
955                                          context->frame->y_offset,
956                                          gdk_pixbuf_get_width (context->frame->pixbuf),
957                                          gdk_pixbuf_get_height (context->frame->pixbuf),
958                                          context->user_data);
959                         } else {
960                                 (* context->update_func)
961                                         (context->frame->pixbuf,
962                                          context->frame->x_offset,
963                                          context->frame->y_offset,
964                                          gdk_pixbuf_get_width (context->frame->pixbuf),
965                                          upper_bound,
966                                          context->user_data);
967                                 (* context->update_func)
968                                         (context->frame->pixbuf,
969                                          context->frame->x_offset,
970                                          lower_bound + context->frame->y_offset,
971                                          gdk_pixbuf_get_width (context->frame->pixbuf),
972                                          gdk_pixbuf_get_height (context->frame->pixbuf),
973                                          context->user_data);
974                         }
975                 }
976         }
977
978         if (context->state == GIF_GET_NEXT_STEP) {
979                 /* Will be freed with context->animation, we are just
980                  * marking that we're done with it (no current frame)
981                  */
982                 context->frame = NULL;
983                 context->frame_cmap_active = FALSE;
984         }
985         
986         return v;
987 }
988
989 static void
990 gif_set_prepare_lzw (GifContext *context)
991 {
992         context->state = GIF_PREPARE_LZW;
993         context->lzw_code_pending = -1;
994 }
995 static int
996 gif_prepare_lzw (GifContext *context)
997 {
998         gint i;
999
1000         if (!gif_read (context, &(context->lzw_set_code_size), 1)) {
1001                 /*g_message (_("GIF: EOF / read error on image data\n"));*/
1002                 return -1;
1003         }
1004         
1005         if (context->lzw_set_code_size > MAX_LZW_BITS) {
1006                 g_set_error (context->error,
1007                              GDK_PIXBUF_ERROR,
1008                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
1009                              _("GIF image is corrupt (incorrect LZW compression)"));
1010                 return -2;
1011         }
1012
1013         context->lzw_code_size = context->lzw_set_code_size + 1;
1014         context->lzw_clear_code = 1 << context->lzw_set_code_size;
1015         context->lzw_end_code = context->lzw_clear_code + 1;
1016         context->lzw_max_code_size = 2 * context->lzw_clear_code;
1017         context->lzw_max_code = context->lzw_clear_code + 2;
1018         context->lzw_fresh = TRUE;
1019         context->code_curbit = 0;
1020         context->code_lastbit = 0;
1021         context->code_last_byte = 0;
1022         context->code_done = FALSE;
1023
1024         g_assert (context->lzw_clear_code <= 
1025                   G_N_ELEMENTS (context->lzw_table[0]));
1026
1027         for (i = 0; i < context->lzw_clear_code; ++i) {
1028                 context->lzw_table[0][i] = 0;
1029                 context->lzw_table[1][i] = i;
1030         }
1031         for (; i < (1 << MAX_LZW_BITS); ++i)
1032                 context->lzw_table[0][i] = context->lzw_table[1][0] = 0;
1033
1034         context->lzw_sp = context->lzw_stack;
1035         gif_set_get_lzw (context);
1036
1037         return 0;
1038 }
1039
1040 /* needs 13 bytes to proceed. */
1041 static gint
1042 gif_init (GifContext *context)
1043 {
1044         unsigned char buf[16];
1045         char version[4];
1046
1047         if (!gif_read (context, buf, 6)) {
1048                 /* Unable to read magic number,
1049                  * gif_read() should have set error
1050                  */
1051                 return -1;
1052         }
1053
1054         if (strncmp ((char *) buf, "GIF", 3) != 0) {
1055                 /* Not a GIF file */
1056                 g_set_error (context->error,
1057                              GDK_PIXBUF_ERROR,
1058                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
1059                              _("File does not appear to be a GIF file"));
1060                 return -2;
1061         }
1062
1063         strncpy (version, (char *) buf + 3, 3);
1064         version[3] = '\0';
1065
1066         if ((strcmp (version, "87a") != 0) && (strcmp (version, "89a") != 0)) {
1067                 /* bad version number, not '87a' or '89a' */
1068                 g_set_error (context->error,
1069                              GDK_PIXBUF_ERROR,
1070                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
1071                              _("Version %s of the GIF file format is not supported"),
1072                              version);
1073                 return -2;
1074         }
1075
1076         /* read the screen descriptor */
1077         if (!gif_read (context, buf, 7)) {
1078                 /* Failed to read screen descriptor, error set */
1079                 return -1;
1080         }
1081
1082         context->width = LM_to_uint (buf[0], buf[1]);
1083         context->height = LM_to_uint (buf[2], buf[3]);
1084         /* The 4th byte is
1085          * high bit: whether to use the background index
1086          * next 3:   color resolution
1087          * next:     whether colormap is sorted by priority of allocation
1088          * last 3:   size of colormap
1089          */
1090         context->global_bit_pixel = 2 << (buf[4] & 0x07);
1091         context->global_color_resolution = (((buf[4] & 0x70) >> 3) + 1);
1092         context->has_global_cmap = (buf[4] & 0x80) != 0;
1093         context->background_index = buf[5];
1094         context->aspect_ratio = buf[6];
1095
1096         /* Use background of transparent black as default, though if
1097          * one isn't set explicitly no one should ever use it.
1098          */
1099         context->animation->bg_red = 0;
1100         context->animation->bg_green = 0;
1101         context->animation->bg_blue = 0;
1102         
1103         if (context->has_global_cmap) {
1104                 gif_set_get_colormap (context);
1105         } else {
1106                 context->state = GIF_GET_NEXT_STEP;
1107         }
1108
1109 #ifdef DUMP_IMAGE_DETAILS
1110         g_print (">Image width: %d height: %d global_cmap: %d background: %d\n",
1111                  context->width, context->height, context->has_global_cmap, context->background_index);
1112 #endif
1113         
1114         return 0;
1115 }
1116
1117 static void
1118 gif_set_get_frame_info (GifContext *context)
1119 {
1120         context->state = GIF_GET_FRAME_INFO;
1121 }
1122
1123 static gint
1124 gif_get_frame_info (GifContext *context)
1125 {
1126         unsigned char buf[9];
1127         
1128         if (!gif_read (context, buf, 9)) {
1129                 return -1;
1130         }
1131         
1132         /* Okay, we got all the info we need.  Lets record it */
1133         context->frame_len = LM_to_uint (buf[4], buf[5]);
1134         context->frame_height = LM_to_uint (buf[6], buf[7]);
1135         context->x_offset = LM_to_uint (buf[0], buf[1]);
1136         context->y_offset = LM_to_uint (buf[2], buf[3]);
1137
1138         if (((context->frame_height + context->y_offset) > context->height) ||
1139             ((context->frame_len + context->x_offset) > context->width)) {
1140                 /* All frames must fit in the image bounds */
1141                 context->state = GIF_DONE;
1142
1143                 g_set_error (context->error,
1144                              GDK_PIXBUF_ERROR,
1145                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
1146                              _("GIF image contained a frame appearing outside the image bounds."));
1147                 
1148                 return -2;
1149         }
1150         
1151         if (context->animation->frames == NULL &&
1152             context->gif89.disposal == 3) {
1153                 /* First frame can't have "revert to previous" as its
1154                  * dispose mode.
1155                  */
1156                 
1157                 context->state = GIF_DONE;
1158
1159                 g_set_error (context->error,
1160                              GDK_PIXBUF_ERROR,
1161                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
1162                              _("First frame of GIF image had 'revert to previous' as its disposal mode."));
1163                 
1164                 return -2;
1165         }
1166
1167 #ifdef DUMP_IMAGE_DETAILS
1168         g_print (">width: %d height: %d xoffset: %d yoffset: %d disposal: %d delay: %d transparent: %d\n",
1169                  context->frame_len, context->frame_height, context->x_offset, context->y_offset,
1170                  context->gif89.disposal, context->gif89.delay_time, context->gif89.transparent);
1171 #endif
1172         
1173         context->frame_interlace = BitSet (buf[8], INTERLACE);
1174         if (BitSet (buf[8], LOCALCOLORMAP)) {
1175
1176 #ifdef DUMP_IMAGE_DETAILS
1177                 g_print (">has local colormap\n");
1178 #endif
1179                 
1180                 /* Does this frame have it's own colormap. */
1181                 /* really only relevant when looking at the first frame
1182                  * of an animated gif. */
1183                 /* if it does, we need to re-read in the colormap,
1184                  * the gray_scale, and the bit_pixel */
1185                 context->frame_cmap_active = TRUE;
1186                 context->frame_bit_pixel = 1 << ((buf[8] & 0x07) + 1);
1187                 gif_set_get_colormap2 (context);
1188                 return 0;
1189         }
1190
1191         if (!context->has_global_cmap) {
1192                 context->state = GIF_DONE;
1193                 
1194                 g_set_error (context->error,
1195                              GDK_PIXBUF_ERROR,
1196                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
1197                              _("GIF image has no global colormap, and a frame inside it has no local colormap."));
1198                 
1199                 return -2;
1200         }
1201
1202         gif_set_prepare_lzw (context);
1203         return 0;
1204
1205 }
1206
1207 static gint
1208 gif_get_next_step (GifContext *context)
1209 {
1210         unsigned char c;
1211         while (TRUE) {
1212                 if (!gif_read (context, &c, 1)) {
1213                         return -1;
1214                 }
1215                 if (c == ';') {
1216                         /* GIF terminator */
1217                         /* hmm.  Not 100% sure what to do about this.  Should
1218                          * i try to return a blank image instead? */
1219                         context->state = GIF_DONE;
1220                         return 0;
1221                 }
1222
1223                 if (c == '!') {
1224                         /* Check the extention */
1225                         gif_set_get_extension (context);
1226                         return 0;
1227                 }
1228
1229                 /* look for frame */
1230                 if (c != ',') {
1231                         /* Not a valid start character */
1232                         continue;
1233                 }
1234                 /* load the frame */
1235                 gif_set_get_frame_info (context);
1236                 return 0;
1237         }
1238 }
1239
1240
1241 #define LOG(x) /* g_print ("%d: %s\n", __LINE__, x); */
1242
1243 static gint
1244 gif_main_loop (GifContext *context)
1245 {
1246         gint retval = 0;
1247
1248         do {
1249                 switch (context->state) {
1250                 case GIF_START:
1251                         LOG("start\n");
1252                         retval = gif_init (context);
1253                         break;
1254
1255                 case GIF_GET_COLORMAP:
1256                         LOG("get_colormap\n");
1257                         retval = gif_get_colormap (context);
1258                         if (retval == 0)
1259                                 context->state = GIF_GET_NEXT_STEP;
1260                         break;
1261
1262                 case GIF_GET_NEXT_STEP:
1263                         LOG("next_step\n");
1264                         retval = gif_get_next_step (context);
1265                         break;
1266
1267                 case GIF_GET_FRAME_INFO:
1268                         LOG("frame_info\n");
1269                         retval = gif_get_frame_info (context);
1270                         break;
1271
1272                 case GIF_GET_EXTENTION:
1273                         LOG("get_extension\n");
1274                         retval = gif_get_extension (context);
1275                         if (retval == 0)
1276                                 context->state = GIF_GET_NEXT_STEP;
1277                         break;
1278
1279                 case GIF_GET_COLORMAP2:
1280                         LOG("get_colormap2\n");
1281                         retval = gif_get_colormap2 (context);
1282                         if (retval == 0)
1283                                 gif_set_prepare_lzw (context);
1284                         break;
1285
1286                 case GIF_PREPARE_LZW:
1287                         LOG("prepare_lzw\n");
1288                         retval = gif_prepare_lzw (context);
1289                         break;
1290
1291                 case GIF_LZW_FILL_BUFFER:
1292                         LOG("fill_buffer\n");
1293                         retval = gif_lzw_fill_buffer (context);
1294                         break;
1295
1296                 case GIF_LZW_CLEAR_CODE:
1297                         LOG("clear_code\n");
1298                         retval = gif_lzw_clear_code (context);
1299                         break;
1300
1301                 case GIF_GET_LZW:
1302                         LOG("get_lzw\n");
1303                         retval = gif_get_lzw (context);
1304                         break;
1305
1306                 case GIF_DONE:
1307                         LOG("done\n");
1308                 default:
1309                         retval = 0;
1310                         goto done;
1311                 };
1312         } while ((retval == 0) || (retval == -3));
1313  done:
1314         return retval;
1315 }
1316
1317 static GifContext *
1318 new_context (void)
1319 {
1320         GifContext *context;
1321
1322         context = g_try_malloc (sizeof (GifContext));
1323         if (context == NULL)
1324                 return NULL;
1325
1326         memset (context, 0, sizeof (GifContext));
1327         
1328         context->animation = g_object_new (GDK_TYPE_PIXBUF_GIF_ANIM, NULL);        
1329         context->frame = NULL;
1330         context->file = NULL;
1331         context->state = GIF_START;
1332         context->prepare_func = NULL;
1333         context->update_func = NULL;
1334         context->user_data = NULL;
1335         context->buf = NULL;
1336         context->amount_needed = 0;
1337         context->gif89.transparent = -1;
1338         context->gif89.delay_time = -1;
1339         context->gif89.input_flag = -1;
1340         context->gif89.disposal = -1;
1341
1342         return context;
1343 }
1344 /* Shared library entry point */
1345 static GdkPixbuf *
1346 gdk_pixbuf__gif_image_load (FILE *file, GError **error)
1347 {
1348         GifContext *context;
1349         GdkPixbuf *pixbuf;
1350
1351         g_return_val_if_fail (file != NULL, NULL);
1352
1353         context = new_context ();
1354
1355         if (context == NULL) {
1356                 g_set_error (error,
1357                              GDK_PIXBUF_ERROR,
1358                              GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
1359                              _("Not enough memory to load GIF file"));
1360                 return NULL;
1361         }
1362         
1363         context->file = file;
1364         context->error = error;
1365         
1366         if (gif_main_loop (context) == -1 || context->animation->frames == NULL) {
1367                 if (context->error && *(context->error) == NULL)
1368                         g_set_error (context->error,
1369                                      GDK_PIXBUF_ERROR,
1370                                      GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
1371                                      _("GIF file was missing some data (perhaps it was truncated somehow?)"));
1372         }
1373         
1374         pixbuf = gdk_pixbuf_animation_get_static_image (GDK_PIXBUF_ANIMATION (context->animation));
1375
1376         if (pixbuf)
1377                 g_object_ref (pixbuf);
1378
1379         g_object_unref (context->animation);
1380         
1381         g_free (context->buf);
1382         g_free (context);
1383  
1384         return pixbuf;
1385 }
1386
1387 static gpointer
1388 gdk_pixbuf__gif_image_begin_load (ModulePreparedNotifyFunc prepare_func,
1389                                   ModuleUpdatedNotifyFunc update_func,
1390                                   gpointer user_data,
1391                                   GError **error)
1392 {
1393         GifContext *context;
1394
1395 #ifdef IO_GIFDEBUG
1396         count = 0;
1397 #endif
1398         context = new_context ();
1399
1400         if (context == NULL) {
1401                 g_set_error (error,
1402                              GDK_PIXBUF_ERROR,
1403                              GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
1404                              _("Not enough memory to load GIF file"));
1405                 return NULL;
1406         }
1407         
1408         context->error = error;
1409         context->prepare_func = prepare_func;
1410         context->update_func = update_func;
1411         context->user_data = user_data;
1412
1413         return (gpointer) context;
1414 }
1415
1416 static gboolean
1417 gdk_pixbuf__gif_image_stop_load (gpointer data, GError **error)
1418 {
1419         GifContext *context = (GifContext *) data;
1420         gboolean retval = TRUE;
1421         
1422         if (context->state != GIF_DONE) {
1423                 g_set_error (error,
1424                              GDK_PIXBUF_ERROR,
1425                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
1426                              _("GIF image was truncated or incomplete."));
1427
1428                 retval = FALSE;
1429         }
1430         
1431         g_object_unref (context->animation);
1432
1433         g_free (context->buf);
1434         g_free (context);
1435
1436         return retval;
1437 }
1438
1439 static gboolean
1440 gdk_pixbuf__gif_image_load_increment (gpointer data,
1441                                       const guchar *buf, guint size,
1442                                       GError **error)
1443 {
1444         gint retval;
1445         GifContext *context = (GifContext *) data;
1446
1447         context->error = error;
1448         
1449         if (context->amount_needed == 0) {
1450                 /* we aren't looking for some bytes. */
1451                 /* we can use buf now, but we don't want to keep it around at all.
1452                  * it will be gone by the end of the call. */
1453                 context->buf = (guchar*) buf; /* very dubious const cast */
1454                 context->ptr = 0;
1455                 context->size = size;
1456         } else {
1457                 /* we need some bytes */
1458                 if (size < context->amount_needed) {
1459                         context->amount_needed -= size;
1460                         /* copy it over and return */
1461                         memcpy (context->buf + context->size, buf, size);
1462                         context->size += size;
1463                         return TRUE;
1464                 } else if (size == context->amount_needed) {
1465                         memcpy (context->buf + context->size, buf, size);
1466                         context->size += size;
1467                 } else {
1468                         context->buf = g_realloc (context->buf, context->size + size);
1469                         memcpy (context->buf + context->size, buf, size);
1470                         context->size += size;
1471                 }
1472         }
1473
1474         retval = gif_main_loop (context);
1475
1476         if (retval == -2) {
1477                 context->buf = NULL;
1478                 return FALSE;
1479         }
1480         if (retval == -1) {
1481                 /* we didn't have enough memory */
1482                 /* prepare for the next image_load_increment */
1483                 if (context->buf == buf) {
1484                         g_assert (context->size == size);
1485                         context->buf = (guchar *)g_new (guchar, context->amount_needed + (context->size - context->ptr));
1486                         memcpy (context->buf, buf + context->ptr, context->size - context->ptr);
1487                 } else {
1488                         /* copy the left overs to the begining of the buffer */
1489                         /* and realloc the memory */
1490                         memmove (context->buf, context->buf + context->ptr, context->size - context->ptr);
1491                         context->buf = g_realloc (context->buf, context->amount_needed + (context->size - context->ptr));
1492                 }
1493                 context->size = context->size - context->ptr;
1494                 context->ptr = 0;
1495         } else {
1496                 /* we are prolly all done */
1497                 if (context->buf == buf)
1498                         context->buf = NULL;
1499         }
1500         return TRUE;
1501 }
1502
1503 static GdkPixbufAnimation *
1504 gdk_pixbuf__gif_image_load_animation (FILE *file,
1505                                       GError **error)
1506 {
1507         GifContext *context;
1508         GdkPixbufAnimation *animation;
1509
1510         g_return_val_if_fail (file != NULL, NULL);
1511
1512         context = new_context ();
1513
1514         if (context == NULL) {
1515                 g_set_error (error,
1516                              GDK_PIXBUF_ERROR,
1517                              GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
1518                              _("Not enough memory to load GIF file"));
1519                 return NULL;
1520         }
1521         
1522         context->error = error;
1523         context->file = file;
1524
1525         if (gif_main_loop (context) == -1 || context->animation->frames == NULL) {
1526                 if (context->error && *(context->error) == NULL)
1527                         g_set_error (context->error,
1528                                      GDK_PIXBUF_ERROR,
1529                                      GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
1530                                      _("GIF file was missing some data (perhaps it was truncated somehow?)"));
1531
1532                 g_object_unref (context->animation);
1533                 context->animation = NULL;
1534         }
1535
1536         if (context->animation)
1537                 animation = GDK_PIXBUF_ANIMATION (context->animation);
1538         else
1539                 animation = NULL;
1540
1541         if (context->error && *(context->error))
1542                 g_print ("%s\n", (*(context->error))->message);
1543         
1544         g_free (context->buf);
1545         g_free (context);
1546         return animation;
1547 }
1548
1549 void
1550 gdk_pixbuf__gif_fill_vtable (GdkPixbufModule *module)
1551 {
1552   module->load = gdk_pixbuf__gif_image_load;
1553   module->begin_load = gdk_pixbuf__gif_image_begin_load;
1554   module->stop_load = gdk_pixbuf__gif_image_stop_load;
1555   module->load_increment = gdk_pixbuf__gif_image_load_increment;
1556   module->load_animation = gdk_pixbuf__gif_image_load_animation;
1557 }