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