io-gif.c 43.5 KB
Newer Older
Havoc Pennington's avatar
Havoc Pennington committed
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 6
 * Copyright (C) 1999 The Free Software Foundation
 *
7 8
 * Authors: Jonathan Blandford <jrb@redhat.com>
 *          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 15 16 17 18 19
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * 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 24 25
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
26
 */
27

28 29 30 31 32 33 34 35 36 37 38 39 40 41
/* This loader is very hairy code.
 *
 * The main loop was not designed for incremental loading, so when it was hacked
 * in it got a bit messy.  Basicly, every function is written to expect a failed
 * read_gif, and lets you call it again assuming that the bytes are there.
 *
 * Return vals.
 * Unless otherwise specified, these are the return vals for most functions:
 *
 *  0 -> success
 * -1 -> more bytes needed.
 * -2 -> failure; abort the load
 * -3 -> control needs to be passed back to the main loop
 *        \_ (most of the time returning 0 will get this, but not always)
42
 *
43 44 45 46 47 48 49 50 51 52 53
 * >1 -> for functions that get a guchar, the char will be returned.
 *
 * -jrb (11/03/1999)
 */

/*
 * If you have any images that crash this code, please, please let me know and
 * send them to me.
 *                                            <jrb@redhat.com>
 */

54 55


56 57
#include <config.h>
#include <stdio.h>
58
#include <string.h>
Havoc Pennington's avatar
Havoc Pennington committed
59
#include <errno.h>
60
#include "gdk-pixbuf-private.h"
61
#include "gdk-pixbuf-io.h"
Havoc Pennington's avatar
Havoc Pennington committed
62
#include "io-gif-animation.h"
63

64

65

Havoc Pennington's avatar
Havoc Pennington committed
66 67
#undef DUMP_IMAGE_DETAILS

68
#define MAXCOLORMAPSIZE  256
Jonathan Blandford's avatar
Jonathan Blandford committed
69
#define MAX_LZW_BITS     12
70 71 72 73 74 75

#define INTERLACE          0x40
#define LOCALCOLORMAP      0x80
#define BitSet(byte, bit)  (((byte) & (bit)) == (bit))
#define LM_to_uint(a,b)         (((b)<<8)|(a))

76 77


78 79
typedef unsigned char CMap[3][MAXCOLORMAPSIZE];

80 81
/* Possible states we can be in. */
enum {
82
	GIF_START,
83 84 85 86 87 88 89
	GIF_GET_COLORMAP,
	GIF_GET_NEXT_STEP,
	GIF_GET_FRAME_INFO,
	GIF_GET_EXTENTION,
	GIF_GET_COLORMAP2,
	GIF_PREPARE_LZW,
	GIF_LZW_FILL_BUFFER,
90
	GIF_LZW_CLEAR_CODE,
91
	GIF_GET_LZW,
Havoc Pennington's avatar
Havoc Pennington committed
92
	GIF_DONE
93 94 95
};


96 97 98 99
typedef struct _Gif89 Gif89;
struct _Gif89
{
	int transparent;
Jonathan Blandford's avatar
Jonathan Blandford committed
100 101 102
	int delay_time;
	int input_flag;
	int disposal;
103 104 105 106
};

typedef struct _GifContext GifContext;
struct _GifContext
107
{
108
	int state; /* really only relevant for progressive loading */
109 110
	unsigned int width;
	unsigned int height;
Havoc Pennington's avatar
Havoc Pennington committed
111 112 113 114 115 116 117 118 119 120 121 122 123 124

        gboolean has_global_cmap;

        CMap global_color_map;
        gint global_colormap_size;
        unsigned int global_bit_pixel;
	unsigned int global_color_resolution;
        unsigned int background_index;

        gboolean frame_cmap_active;
        CMap frame_color_map;
        gint frame_colormap_size;
        unsigned int frame_bit_pixel;

125
	unsigned int aspect_ratio;
Havoc Pennington's avatar
Havoc Pennington committed
126
	GdkPixbufGifAnim *animation;
127
	GdkPixbufFrame *frame;
128
	Gif89 gif89;
129

Havoc Pennington's avatar
Havoc Pennington committed
130
	/* stuff per frame. */
131 132 133
	int frame_len;
	int frame_height;
	int frame_interlace;
134 135
	int x_offset;
	int y_offset;
136 137 138 139 140

	/* Static read only */
	FILE *file;

	/* progressive read, only. */
141 142
	ModulePreparedNotifyFunc prepare_func;
	ModuleUpdatedNotifyFunc update_func;
143
	gpointer user_data;
144
        guchar *buf;
145 146
	guint ptr;
	guint size;
147
	guint amount_needed;
148

149
	/* extension context */
150 151
	guchar extension_label;
	guchar extension_flag;
152

153 154
	/* get block context */
	guchar block_count;
155
	guchar block_buf[280];
156
	gint block_ptr;
157

158
	int old_state; /* used by lzw_fill buffer */
159 160 161 162 163
	/* get_code context */
	int code_curbit;
	int code_lastbit;
	int code_done;
	int code_last_byte;
164 165
	int lzw_code_pending;

Jonathan Blandford's avatar
Jonathan Blandford committed
166 167 168 169 170 171 172 173 174 175 176 177 178 179
	/* lzw context */
	gint lzw_fresh;
	gint lzw_code_size;
	guchar lzw_set_code_size;
	gint lzw_max_code;
	gint lzw_max_code_size;
	gint lzw_firstcode;
	gint lzw_oldcode;
	gint lzw_clear_code;
	gint lzw_end_code;
	gint *lzw_sp;

	gint lzw_table[2][(1 << MAX_LZW_BITS)];
	gint lzw_stack[(1 << (MAX_LZW_BITS)) * 2 + 1];
180

181 182 183 184
	/* painting context */
	gint draw_xpos;
	gint draw_ypos;
	gint draw_pass;
Havoc Pennington's avatar
Havoc Pennington committed
185 186 187

        /* error pointer */
        GError **error;
188
};
189

190
static int GetDataBlock (GifContext *, unsigned char *);
191

192 193


194
#ifdef IO_GIFDEBUG
195
static int count = 0;
196 197
#endif

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 205 206
#ifdef IO_GIFDEBUG
	gint i;
#endif
207 208
	if (context->file) {
#ifdef IO_GIFDEBUG
209
		count += len;
210 211
		g_print ("Fsize :%d\tcount :%d\t", len, count);
#endif
Havoc Pennington's avatar
Havoc Pennington committed
212 213 214 215 216 217 218 219
		retval = (fread(buffer, len, 1, context->file) != 0);

                if (!retval && ferror (context->file))
                        g_set_error (context->error,
                                     G_FILE_ERROR,
                                     g_file_error_from_errno (errno),
                                     _("Failure reading GIF: %s"), strerror (errno));
                
220 221 222 223 224 225 226
#ifdef IO_GIFDEBUG
		if (len < 100) {
			for (i = 0; i < len; i++)
				g_print ("%d ", buffer[i]);
		}
		g_print ("\n");
#endif
Havoc Pennington's avatar
Havoc Pennington committed
227
                
228 229 230
		return retval;
	} else {
#ifdef IO_GIFDEBUG
231
/*  		g_print ("\tlooking for %d bytes.  size == %d, ptr == %d\n", len, context->size, context->ptr); */
232 233
#endif
		if ((context->size - context->ptr) >= len) {
234
#ifdef IO_GIFDEBUG
235
			count += len;
236 237
#endif
			memcpy (buffer, context->buf + context->ptr, len);
238 239
			context->ptr += len;
			context->amount_needed = 0;
240 241 242 243 244 245 246 247 248
#ifdef IO_GIFDEBUG
			g_print ("Psize :%d\tcount :%d\t", len, count);
			if (len < 100) {
				for (i = 0; i < len; i++)
					g_print ("%d ", buffer[i]);
			}
			g_print ("\n");
#endif
			return TRUE;
249 250 251
		}
		context->amount_needed = len - (context->size - context->ptr);
	}
252
	return 0;
253 254
}

255 256 257
/* Changes the stage to be GIF_GET_COLORMAP */
static void
gif_set_get_colormap (GifContext *context)
258
{
Havoc Pennington's avatar
Havoc Pennington committed
259
	context->global_colormap_size = 0;
260 261
	context->state = GIF_GET_COLORMAP;
}
262

263 264 265
static void
gif_set_get_colormap2 (GifContext *context)
{
Havoc Pennington's avatar
Havoc Pennington committed
266
	context->frame_colormap_size = 0;
267 268 269 270 271 272 273
	context->state = GIF_GET_COLORMAP2;
}

static gint
gif_get_colormap (GifContext *context)
{
	unsigned char rgb[3];
274

Havoc Pennington's avatar
Havoc Pennington committed
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
	while (context->global_colormap_size < context->global_bit_pixel) {
		if (!gif_read (context, rgb, sizeof (rgb))) {
			return -1;
		}

		context->global_color_map[0][context->global_colormap_size] = rgb[0];
		context->global_color_map[1][context->global_colormap_size] = rgb[1];
		context->global_color_map[2][context->global_colormap_size] = rgb[2];

                if (context->global_colormap_size == context->background_index) {
                        context->animation->bg_red = rgb[0];
                        context->animation->bg_green = rgb[1];
                        context->animation->bg_blue = rgb[2];
                }

		context->global_colormap_size ++;
	}

	return 0;
}


static gint
gif_get_colormap2 (GifContext *context)
{
	unsigned char rgb[3];

	while (context->frame_colormap_size < context->frame_bit_pixel) {
303
		if (!gif_read (context, rgb, sizeof (rgb))) {
304
			return -1;
305 306
		}

Havoc Pennington's avatar
Havoc Pennington committed
307 308 309
		context->frame_color_map[0][context->frame_colormap_size] = rgb[0];
		context->frame_color_map[1][context->frame_colormap_size] = rgb[1];
		context->frame_color_map[2][context->frame_colormap_size] = rgb[2];
310

Havoc Pennington's avatar
Havoc Pennington committed
311
		context->frame_colormap_size ++;
312 313
	}

314
	return 0;
315
}
316

317 318 319 320 321 322 323 324
/*
 * in order for this function to work, we need to perform some black magic.
 * We want to return -1 to let the calling function know, as before, that it needs
 * more bytes.  If we return 0, we were able to successfully read all block->count bytes.
 * Problem is, we don't want to reread block_count every time, so we check to see if
 * context->block_count is 0 before we read in the function.
 *
 * 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 330 331
get_data_block (GifContext *context,
		unsigned char *buf,
		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 344
			return 0;
		}
345

346
	if (!gif_read (context, buf, context->block_count)) {
347 348 349 350 351 352 353 354 355 356 357
		return -1;
	}

	return 0;
}

static void
gif_set_get_extension (GifContext *context)
{
	context->state = GIF_GET_EXTENTION;
	context->extension_flag = TRUE;
358
	context->extension_label = 0;
359 360 361 362 363 364 365 366 367 368 369
	context->block_count = 0;
	context->block_ptr = 0;
}

static int
gif_get_extension (GifContext *context)
{
	gint retval;
	gint empty_block = FALSE;

	if (context->extension_flag) {
370 371 372
		if (context->extension_label == 0) {
			/* I guess bad things can happen if we have an extension of 0 )-: */
			/* I should look into this sometime */
373
			if (!gif_read (context, & context->extension_label , 1)) {
374 375 376 377 378 379 380 381 382
				return -1;
			}
		}

		switch (context->extension_label) {
		case 0xf9:			/* Graphic Control Extension */
			retval = get_data_block (context, (unsigned char *) context->block_buf, NULL);
			if (retval != 0)
				return retval;
Havoc Pennington's avatar
Havoc Pennington committed
383 384

			if (context->frame == NULL) {
385
				/* I only want to set the transparency if I haven't
Havoc Pennington's avatar
Havoc Pennington committed
386 387
				 * created the frame yet.
                                 */
388 389 390 391
				context->gif89.disposal = (context->block_buf[0] >> 2) & 0x7;
				context->gif89.input_flag = (context->block_buf[0] >> 1) & 0x1;
				context->gif89.delay_time = LM_to_uint (context->block_buf[1], context->block_buf[2]);
				
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 402 403 404 405 406
			context->extension_flag = FALSE;
		default:
			/* Unhandled extension */
			break;
		}
	}
407
	/* read all blocks, until I get an empty block, in case there was an extension I didn't know about. */
408 409 410 411
	do {
		retval = get_data_block (context, (unsigned char *) context->block_buf, &empty_block);
		if (retval != 0)
			return retval;
412
		context->block_count = 0;
413 414 415
	} while (!empty_block);

	return 0;
416 417
}

418
static int ZeroDataBlock = FALSE;
419 420

static int
421
GetDataBlock (GifContext *context,
422 423
	      unsigned char *buf)
{
424
/*  	unsigned char count; */
425

426
	if (!gif_read (context, &context->block_count, 1)) {
427 428 429 430
		/*g_message (_("GIF: error in getting DataBlock size\n"));*/
		return -1;
	}

431
	ZeroDataBlock = context->block_count == 0;
432

433
	if ((context->block_count != 0) && (!gif_read (context, buf, context->block_count))) {
434 435 436 437
		/*g_message (_("GIF: error in reading DataBlock\n"));*/
		return -1;
	}

438
	return context->block_count;
439 440
}

441 442 443 444 445

static void
gif_set_lzw_fill_buffer (GifContext *context)
{
	context->block_count = 0;
446
	context->old_state = context->state;
447 448
	context->state = GIF_LZW_FILL_BUFFER;
}
449 450

static int
451 452 453
gif_lzw_fill_buffer (GifContext *context)
{
	gint retval;
454

455 456
	if (context->code_done) {
		if (context->code_curbit >= context->code_lastbit) {
Havoc Pennington's avatar
Havoc Pennington committed
457 458 459 460 461
                        g_set_error (context->error,
                                     GDK_PIXBUF_ERROR,
                                     GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
                                     _("GIF file was missing some data (perhaps it was truncated somehow?)"));

462 463
			return -2;
		}
Havoc Pennington's avatar
Havoc Pennington committed
464 465 466 467 468 469 470 471
                /* Is this supposed to be an error or what? */
		/* g_message ("trying to read more data after we've done stuff\n"); */
                g_set_error (context->error,
                             GDK_PIXBUF_ERROR,
                             GDK_PIXBUF_ERROR_FAILED,
                             _("Internal error in the GIF loader (%s)"),
                             G_STRLOC);
                
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
		return -2;
	}

	context->block_buf[0] = context->block_buf[context->code_last_byte - 2];
	context->block_buf[1] = context->block_buf[context->code_last_byte - 1];

	retval = get_data_block (context, &context->block_buf[2], NULL);

	if (retval == -1)
		return -1;

	if (context->block_count == 0)
		context->code_done = TRUE;

	context->code_last_byte = 2 + context->block_count;
	context->code_curbit = (context->code_curbit - context->code_lastbit) + 16;
	context->code_lastbit = (2 + context->block_count) * 8;

490
	context->state = context->old_state;
491 492 493 494
	return 0;
}

static int
495 496
get_code (GifContext *context,
	  int   code_size)
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
{
	int i, j, ret;

	if ((context->code_curbit + code_size) >= context->code_lastbit){
		gif_set_lzw_fill_buffer (context);
		return -3;
	}

	ret = 0;
	for (i = context->code_curbit, j = 0; j < code_size; ++i, ++j)
		ret |= ((context->block_buf[i / 8] & (1 << (i % 8))) != 0) << j;

	context->code_curbit += code_size;

	return ret;
}

514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535

static void
set_gif_lzw_clear_code (GifContext *context)
{
	context->state = GIF_LZW_CLEAR_CODE;
	context->lzw_code_pending = -1;
}

static int
gif_lzw_clear_code (GifContext *context)
{
	gint code;

	code = get_code (context, context->lzw_code_size);
	if (code == -3)
		return -0;

	context->lzw_firstcode = context->lzw_oldcode = code;
	context->lzw_code_pending = code;
	context->state = GIF_GET_LZW;
	return 0;
}
536 537

static int
Jonathan Blandford's avatar
Jonathan Blandford committed
538
lzw_read_byte (GifContext *context)
539 540
{
	int code, incode;
541
	gint retval;
542
	gint my_retval;
543 544
	register int i;

545 546 547 548 549 550
	if (context->lzw_code_pending != -1) {
		retval = context->lzw_code_pending;
		context->lzw_code_pending = -1;
		return retval;
	}

Jonathan Blandford's avatar
Jonathan Blandford committed
551 552
	if (context->lzw_fresh) {
		context->lzw_fresh = FALSE;
553
		do {
554
			retval = get_code (context, context->lzw_code_size);
555 556 557
			if (retval < 0) {
				return retval;
			}
558

Jonathan Blandford's avatar
Jonathan Blandford committed
559 560 561
			context->lzw_firstcode = context->lzw_oldcode = retval;
		} while (context->lzw_firstcode == context->lzw_clear_code);
		return context->lzw_firstcode;
562 563
	}

564 565 566 567
	if (context->lzw_sp > context->lzw_stack) {
		my_retval = *--(context->lzw_sp);
		return my_retval;
	}
568

569
	while ((code = get_code (context, context->lzw_code_size)) >= 0) {
Jonathan Blandford's avatar
Jonathan Blandford committed
570 571 572 573
		if (code == context->lzw_clear_code) {
			for (i = 0; i < context->lzw_clear_code; ++i) {
				context->lzw_table[0][i] = 0;
				context->lzw_table[1][i] = i;
574
			}
Jonathan Blandford's avatar
Jonathan Blandford committed
575 576 577 578 579 580
			for (; i < (1 << MAX_LZW_BITS); ++i)
				context->lzw_table[0][i] = context->lzw_table[1][i] = 0;
			context->lzw_code_size = context->lzw_set_code_size + 1;
			context->lzw_max_code_size = 2 * context->lzw_clear_code;
			context->lzw_max_code = context->lzw_clear_code + 2;
			context->lzw_sp = context->lzw_stack;
581 582 583

			set_gif_lzw_clear_code (context);
			return -3;
Jonathan Blandford's avatar
Jonathan Blandford committed
584
		} else if (code == context->lzw_end_code) {
585 586 587
			int count;
			unsigned char buf[260];

588 589 590 591 592 593 594
                        /*  FIXME - we should handle this case */
                        g_set_error (context->error,
                                     GDK_PIXBUF_ERROR,
                                     GDK_PIXBUF_ERROR_FAILED,
                                     _("GIF image loader can't understand this image."));
                        return -2;
                        
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 605
				return -2;
			}
606 607 608 609
		}

		incode = code;

Jonathan Blandford's avatar
Jonathan Blandford committed
610 611 612
		if (code >= context->lzw_max_code) {
			*(context->lzw_sp)++ = context->lzw_firstcode;
			code = context->lzw_oldcode;
613
		}
614

Jonathan Blandford's avatar
Jonathan Blandford committed
615 616
		while (code >= context->lzw_clear_code) {
			*(context->lzw_sp)++ = context->lzw_table[1][code];
617

Jonathan Blandford's avatar
Jonathan Blandford committed
618
			if (code == context->lzw_table[0][code]) {
Havoc Pennington's avatar
Havoc Pennington committed
619 620 621 622
                                g_set_error (context->error,
                                             GDK_PIXBUF_ERROR,
                                             GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
                                             _("Circular table entry in GIF file"));
623
				return -2;
624
			}
Jonathan Blandford's avatar
Jonathan Blandford committed
625
			code = context->lzw_table[0][code];
626
		}
627

Jonathan Blandford's avatar
Jonathan Blandford committed
628
		*(context->lzw_sp)++ = context->lzw_firstcode = context->lzw_table[1][code];
629

Jonathan Blandford's avatar
Jonathan Blandford committed
630 631 632 633 634 635 636 637
		if ((code = context->lzw_max_code) < (1 << MAX_LZW_BITS)) {
			context->lzw_table[0][code] = context->lzw_oldcode;
			context->lzw_table[1][code] = context->lzw_firstcode;
			++context->lzw_max_code;
			if ((context->lzw_max_code >= context->lzw_max_code_size) &&
			    (context->lzw_max_code_size < (1 << MAX_LZW_BITS))) {
				context->lzw_max_code_size *= 2;
				++context->lzw_code_size;
638
			}
639
		}
640

Jonathan Blandford's avatar
Jonathan Blandford committed
641
		context->lzw_oldcode = incode;
642

643 644 645 646
		if (context->lzw_sp > context->lzw_stack) {
			my_retval = *--(context->lzw_sp);
			return my_retval;
		}
647 648 649 650
	}
	return code;
}

651
static void
652 653 654 655 656 657 658 659
gif_set_get_lzw (GifContext *context)
{
	context->state = GIF_GET_LZW;
	context->draw_xpos = 0;
	context->draw_ypos = 0;
	context->draw_pass = 0;
}

660 661 662 663
static void
gif_fill_in_pixels (GifContext *context, guchar *dest, gint offset, guchar v)
{
	guchar *pixel = NULL;
Havoc Pennington's avatar
Havoc Pennington committed
664
        guchar (*cmap)[MAXCOLORMAPSIZE];
665

Havoc Pennington's avatar
Havoc Pennington committed
666 667 668 669 670
        if (context->frame_cmap_active)
                cmap = context->frame_color_map;
        else
                cmap = context->global_color_map;
        
671
	if (context->gif89.transparent != -1) {
Havoc Pennington's avatar
Havoc Pennington committed
672 673 674 675 676
		pixel = dest + (context->draw_ypos + offset) * gdk_pixbuf_get_rowstride (context->frame->pixbuf) + context->draw_xpos * 4;
		*pixel = cmap [0][(guchar) v];
		*(pixel+1) = cmap [1][(guchar) v];
		*(pixel+2) = cmap [2][(guchar) v];
		*(pixel+3) = (guchar) ((v == context->gif89.transparent) ? 0 : 255);
677
	} else {
Havoc Pennington's avatar
Havoc Pennington committed
678 679 680 681
		pixel = dest + (context->draw_ypos + offset) * gdk_pixbuf_get_rowstride (context->frame->pixbuf) + context->draw_xpos * 3;
		*pixel = cmap [0][(guchar) v];
		*(pixel+1) = cmap [1][(guchar) v];
		*(pixel+2) = cmap [2][(guchar) v];
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
	}
}


/* only called if progressive and interlaced */
static void
gif_fill_in_lines (GifContext *context, guchar *dest, guchar v)
{
	switch (context->draw_pass) {
	case 0:
		if (context->draw_ypos > 4) {
			gif_fill_in_pixels (context, dest, -4, v);
			gif_fill_in_pixels (context, dest, -3, v);
		}
		if (context->draw_ypos < (context->frame_height - 4)) {
			gif_fill_in_pixels (context, dest, 3, v);
			gif_fill_in_pixels (context, dest, 4, v);
		}
700 701 702
		/* we don't need a break here.  We draw the outer pixels first, then the
		 * inner ones, then the innermost ones.  case 0 needs to draw all 3 bands.
		 * case 1, just the last two, and case 2 just draws the last one*/
703 704 705 706 707
	case 1:
		if (context->draw_ypos > 2)
			gif_fill_in_pixels (context, dest, -2, v);
		if (context->draw_ypos < (context->frame_height - 2))
			gif_fill_in_pixels (context, dest, 2, v);
708
		/* no break as above. */
709 710 711 712 713 714 715 716 717 718 719
	case 2:
		if (context->draw_ypos > 1)
			gif_fill_in_pixels (context, dest, -1, v);
		if (context->draw_ypos < (context->frame_height - 1))
			gif_fill_in_pixels (context, dest, 1, v);
	case 3:
	default:
		break;
	}
}

720
static int
721
gif_get_lzw (GifContext *context)
722 723
{
	guchar *dest, *temp;
724 725 726
	gint lower_bound, upper_bound; /* bounds for emitting the area_updated signal */
	gboolean bound_flag;
	gint first_pass; /* bounds for emitting the area_updated signal */
727 728
	gint v;

Havoc Pennington's avatar
Havoc Pennington committed
729 730 731 732 733 734 735 736 737 738 739 740
	if (context->frame == NULL) {
                context->frame = g_new (GdkPixbufFrame, 1);

                context->frame->composited = NULL;
                context->frame->revert = NULL;
                
                context->frame->pixbuf =
                        gdk_pixbuf_new (GDK_COLORSPACE_RGB,
                                        TRUE,
                                        8,
                                        context->frame_len,
                                        context->frame_height);
741 742 743 744 745 746 747 748 749
                if (!context->frame->pixbuf) {
                        g_free (context->frame);
                        g_set_error (context->error,
                                     GDK_PIXBUF_ERROR,
                                     GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
                                     _("Not enough memory to load GIF file"));
                        return -2;
                }

Havoc Pennington's avatar
Havoc Pennington committed
750 751 752 753 754 755
                context->frame->x_offset = context->x_offset;
                context->frame->y_offset = context->y_offset;
                context->frame->need_recomposite = TRUE;
                
                /* GIF delay is in hundredths, we want thousandths */
                context->frame->delay_time = context->gif89.delay_time * 10;
756 757 758 759 760 761 762 763 764

                /* Some GIFs apparently have delay time of 0,
                 * that crashes everything so set it to "fast".
                 * Also, timeouts less than 20 or so just lock up
                 * the app or make the animation choppy, so fix them.
                 */
                if (context->frame->delay_time < 20)
                        context->frame->delay_time = 20; /* 20 = "fast" */
                
Havoc Pennington's avatar
Havoc Pennington committed
765
                context->frame->elapsed = context->animation->total_time;
766
                context->animation->total_time += context->frame->delay_time;                
Havoc Pennington's avatar
Havoc Pennington committed
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
                
                switch (context->gif89.disposal) {
                case 0:
                case 1:
                        context->frame->action = GDK_PIXBUF_FRAME_RETAIN;
                        break;
                case 2:
                        context->frame->action = GDK_PIXBUF_FRAME_DISPOSE;
                        break;
                case 3:
                        context->frame->action = GDK_PIXBUF_FRAME_REVERT;
                        break;
                default:
                        context->frame->action = GDK_PIXBUF_FRAME_RETAIN;
                        break;
                }

                context->frame->bg_transparent = (context->gif89.transparent == context->background_index);
                
                {
                        /* Update animation size */
                        int w, h;
                        
                        context->animation->n_frames ++;
                        context->animation->frames = g_list_append (context->animation->frames, context->frame);

                        w = context->frame->x_offset +
                                gdk_pixbuf_get_width (context->frame->pixbuf);
                        h = context->frame->y_offset +
                                gdk_pixbuf_get_height (context->frame->pixbuf);
                        if (w > context->animation->width)
                                context->animation->width = w;
                        if (h > context->animation->height)
                                context->animation->height = h;
                }

                /* Only call prepare_func for the first frame */
		if (context->animation->frames->next == NULL) { 
                        if (context->prepare_func)
                                (* context->prepare_func) (context->frame->pixbuf,
                                                           GDK_PIXBUF_ANIMATION (context->animation),
                                                           context->user_data);
                } else {
                        /* Otherwise init frame with last frame */
                        GList *link;
                        GdkPixbufFrame *prev_frame;
                        
                        link = g_list_find (context->animation->frames, context->frame);

                        prev_frame = link->prev->data;

                        gdk_pixbuf_gif_anim_frame_composite (context->animation, prev_frame);

                        gdk_pixbuf_copy_area (prev_frame->composited,
                                              context->frame->x_offset,
                                              context->frame->y_offset,
                                              gdk_pixbuf_get_width (context->frame->pixbuf),
                                              gdk_pixbuf_get_height (context->frame->pixbuf),
                                              context->frame->pixbuf,
                                              0, 0);
                }
        }

	dest = gdk_pixbuf_get_pixels (context->frame->pixbuf);
831 832 833 834 835

	bound_flag = FALSE;
	lower_bound = upper_bound = context->draw_ypos;
	first_pass = context->draw_pass;

836
	while (TRUE) {
Havoc Pennington's avatar
Havoc Pennington committed
837 838 839 840 841 842 843
                guchar (*cmap)[MAXCOLORMAPSIZE];

                if (context->frame_cmap_active)
                        cmap = context->frame_color_map;
                else
                        cmap = context->global_color_map;
                
Jonathan Blandford's avatar
Jonathan Blandford committed
844
		v = lzw_read_byte (context);
845
		if (v < 0) {
846
			goto finished_data;
847
		}
848
		bound_flag = TRUE;
849

Havoc Pennington's avatar
Havoc Pennington committed
850 851 852 853 854 855 856
                g_assert (gdk_pixbuf_get_has_alpha (context->frame->pixbuf));
                
                temp = dest + context->draw_ypos * gdk_pixbuf_get_rowstride (context->frame->pixbuf) + context->draw_xpos * 4;
                *temp = cmap [0][(guchar) v];
                *(temp+1) = cmap [1][(guchar) v];
                *(temp+2) = cmap [2][(guchar) v];
                *(temp+3) = (guchar) ((v == context->gif89.transparent) ? 0 : 255);
857

858
		if (context->prepare_func && context->frame_interlace)
859
			gif_fill_in_lines (context, dest, v);
860

861
		context->draw_xpos++;
Havoc Pennington's avatar
Havoc Pennington committed
862
                
863 864
		if (context->draw_xpos == context->frame_len) {
			context->draw_xpos = 0;
865
			if (context->frame_interlace) {
866
				switch (context->draw_pass) {
867 868
				case 0:
				case 1:
869
					context->draw_ypos += 8;
870 871
					break;
				case 2:
872
					context->draw_ypos += 4;
873 874
					break;
				case 3:
875
					context->draw_ypos += 2;
876
					break;
877
				}
878

879 880 881
				if (context->draw_ypos >= context->frame_height) {
					context->draw_pass++;
					switch (context->draw_pass) {
882
					case 1:
883
						context->draw_ypos = 4;
884 885
						break;
					case 2:
886
						context->draw_ypos = 2;
887 888
						break;
					case 3:
889
						context->draw_ypos = 1;
890 891
						break;
					default:
892
						goto done;
893
					}
894
				}
895
			} else {
896
				context->draw_ypos++;
897
			}
898 899 900 901 902
			if (context->draw_pass != first_pass) {
				if (context->draw_ypos > lower_bound) {
					lower_bound = 0;
					upper_bound = context->frame_height;
				} else {
Havoc Pennington's avatar
Havoc Pennington committed
903
                                        
904 905 906
				}
			} else
				upper_bound = context->draw_ypos;
907
		}
908
		if (context->draw_ypos >= context->frame_height)
909 910
			break;
	}
Havoc Pennington's avatar
Havoc Pennington committed
911

912
 done:
Havoc Pennington's avatar
Havoc Pennington committed
913 914 915 916 917

        context->state = GIF_GET_NEXT_STEP;

        v = 0;

918
 finished_data:
Havoc Pennington's avatar
Havoc Pennington committed
919 920 921 922
        
        if (bound_flag)
                context->frame->need_recomposite = TRUE;
        
923 924 925
	if (bound_flag && context->update_func) {
		if (lower_bound <= upper_bound && first_pass == context->draw_pass) {
			(* context->update_func)
Havoc Pennington's avatar
Havoc Pennington committed
926
				(context->frame->pixbuf,
927
				 0, lower_bound,
Havoc Pennington's avatar
Havoc Pennington committed
928
				 gdk_pixbuf_get_width (context->frame->pixbuf),
929 930
				 upper_bound - lower_bound,
				 context->user_data);
931 932 933
		} else {
			if (lower_bound <= upper_bound) {
				(* context->update_func)
Havoc Pennington's avatar
Havoc Pennington committed
934 935 936 937 938
					(context->frame->pixbuf,
					 context->frame->x_offset,
                                         context->frame->y_offset,
					 gdk_pixbuf_get_width (context->frame->pixbuf),
					 gdk_pixbuf_get_height (context->frame->pixbuf),
939
					 context->user_data);
940 941
			} else {
				(* context->update_func)
Havoc Pennington's avatar
Havoc Pennington committed
942 943 944 945
					(context->frame->pixbuf,
					 context->frame->x_offset,
                                         context->frame->y_offset,
					 gdk_pixbuf_get_width (context->frame->pixbuf),
946 947
					 upper_bound,
					 context->user_data);
948
				(* context->update_func)
Havoc Pennington's avatar
Havoc Pennington committed
949 950 951 952 953
					(context->frame->pixbuf,
					 context->frame->x_offset,
                                         lower_bound + context->frame->y_offset,
					 gdk_pixbuf_get_width (context->frame->pixbuf),
					 gdk_pixbuf_get_height (context->frame->pixbuf),
954
					 context->user_data);
955 956 957 958
			}
		}
	}

Havoc Pennington's avatar
Havoc Pennington committed
959 960 961 962
	if (context->state == GIF_GET_NEXT_STEP) {
                /* Will be freed with context->animation, we are just
                 * marking that we're done with it (no current frame)
                 */
963
		context->frame = NULL;
Havoc Pennington's avatar
Havoc Pennington committed
964
                context->frame_cmap_active = FALSE;
965 966
	}
	
967
	return v;
968
}
969

970 971 972 973
static void
gif_set_prepare_lzw (GifContext *context)
{
	context->state = GIF_PREPARE_LZW;
974
	context->lzw_code_pending = -1;
975
}
976 977 978 979 980
static int
gif_prepare_lzw (GifContext *context)
{
	gint i;

981
	if (!gif_read (context, &(context->lzw_set_code_size), 1)) {
982 983 984
		/*g_message (_("GIF: EOF / read error on image data\n"));*/
		return -1;
	}
985 986 987 988 989 990 991 992
        
        if (context->lzw_set_code_size > MAX_LZW_BITS) {
                g_set_error (context->error,
                             GDK_PIXBUF_ERROR,
                             GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
                             _("GIF image is corrupt (incorrect LZW compression)"));
                return -2;
        }
993

Jonathan Blandford's avatar
Jonathan Blandford committed
994 995 996 997 998 999
	context->lzw_code_size = context->lzw_set_code_size + 1;
	context->lzw_clear_code = 1 << context->lzw_set_code_size;
	context->lzw_end_code = context->lzw_clear_code + 1;
	context->lzw_max_code_size = 2 * context->lzw_clear_code;
	context->lzw_max_code = context->lzw_clear_code + 2;
	context->lzw_fresh = TRUE;
1000 1001
	context->code_curbit = 0;
	context->code_lastbit = 0;
1002
	context->code_last_byte = 0;
1003
	context->code_done = FALSE;
1004