1 /*
2  * Copyright 2004 Richard Wilson <richard.wilson@netsurf-browser.org>
3  * Copyright 2008 Sean Fox <dyntryx@gmail.com>
4  *
5  * This file is part of NetSurf's libnsgif, http://www.netsurf-browser.org/
6  * Licenced under the MIT License,
7  *                http://www.opensource.org/licenses/mit-license.php
8  */
9 
10 #include <stdbool.h>
11 #include <stdio.h>
12 #include <string.h>
13 #include <stdlib.h>
14 #include <assert.h>
15 #include "libnsgif.h"
16 
17 /*	READING GIF FILES
18 	=================
19 
20 	The functions provided by this file allow for efficient progressive GIF
21 	decoding. Whilst the initialisation does not ensure that there is
22 	sufficient image data to complete the entire frame, it does ensure that
23 	the information provided is valid. Any subsequent attempts to decode an
24 	initialised GIF are guaranteed to succeed, and any bytes of the image
25 	not present are assumed to be totally transparent.
26 
27 	To begin decoding a GIF, the 'gif' structure must be initialised with
28 	the 'gif_data' and 'buffer_size' set to their initial values. The
29 	'buffer_position' should initially be 0, and will be internally updated
30 	as the decoding commences. The caller should then repeatedly call
31 	gif_initialise() with the structure until the function returns 1, or
32 	no more data is avaliable.
33 
34 	Once the initialisation has begun, the decoder completes the variables
35 	'frame_count' and 'frame_count_partial'. The former being the total
36 	number of frames that have been successfully initialised, and the
37 	latter being the number of frames that a partial amount of data is
38 	available for. This assists the caller in managing the animation whilst
39 	decoding is continuing.
40 
41 	To decode a frame, the caller must use gif_decode_frame() which updates
42 	the current 'frame_image' to reflect the desired frame. The required
43 	'disposal_method' is also updated to reflect how the frame should be
44 	plotted. The caller must not assume that the current 'frame_image' will
45 	be valid between calls if initialisation is still occuring, and should
46 	either always request that the frame is decoded (no processing will
47 	occur if the 'decoded_frame' has not been invalidated by initialisation)
48 	or perform the check itself.
49 
50 	It should be noted that gif_finalise() should always be called, even if
51 	no frames were initialised.  Additionally, it is the responsibility of
52 	the caller to free 'gif_data'.
53 
54 	[rjw] - Fri 2nd April 2004
55 */
56 
57 /*	TO-DO LIST
58 	=================
59 
60 	+ Plain text and comment extensions could be implemented if there is any
61 	interest in doing so.
62 */
63 
64 
65 
66 
67 /*	Maximum colour table size
68 */
69 #define GIF_MAX_COLOURS 256
70 
71 /*	Internal flag that the colour table needs to be processed
72 */
73 #define GIF_PROCESS_COLOURS 0xaa000000
74 
75 /*	Internal flag that a frame is invalid/unprocessed
76 */
77 #define GIF_INVALID_FRAME -1
78 
79 /*	Maximum LZW bits available
80 */
81 #define GIF_MAX_LZW 12
82 
83 /* Transparent colour
84 */
85 #define GIF_TRANSPARENT_COLOUR 0x00
86 
87 /*	GIF Flags
88 */
89 #define GIF_FRAME_COMBINE 1
90 #define GIF_FRAME_CLEAR 2
91 #define GIF_FRAME_RESTORE 3
92 #define GIF_FRAME_QUIRKS_RESTORE 4
93 #define GIF_IMAGE_SEPARATOR 0x2c
94 #define GIF_INTERLACE_MASK 0x40
95 #define GIF_COLOUR_TABLE_MASK 0x80
96 #define GIF_COLOUR_TABLE_SIZE_MASK 0x07
97 #define GIF_EXTENSION_INTRODUCER 0x21
98 #define GIF_EXTENSION_GRAPHIC_CONTROL 0xf9
99 #define GIF_DISPOSAL_MASK 0x1c
100 #define GIF_TRANSPARENCY_MASK 0x01
101 #define GIF_EXTENSION_COMMENT 0xfe
102 #define GIF_EXTENSION_PLAIN_TEXT 0x01
103 #define GIF_EXTENSION_APPLICATION 0xff
104 #define GIF_BLOCK_TERMINATOR 0x00
105 #define GIF_TRAILER 0x3b
106 
107 /*	Internal GIF routines
108 */
109 static gif_result gif_initialise_sprite(gif_animation *gif, unsigned int width, unsigned int height);
110 static gif_result gif_initialise_frame(gif_animation *gif);
111 static gif_result gif_initialise_frame_extensions(gif_animation *gif, const int frame);
112 static gif_result gif_skip_frame_extensions(gif_animation *gif);
113 static unsigned int gif_interlaced_line(int height, int y);
114 
115 
116 
117 /*	Internal LZW routines
118 */
119 static void gif_init_LZW(gif_animation *gif);
120 static bool gif_next_LZW(gif_animation *gif);
121 static int gif_next_code(gif_animation *gif, int code_size);
122 
123 /*	General LZW values. They are shared for all GIFs being decoded, and
124 	thus we can't handle progressive decoding efficiently without having
125 	the data for each image which would use an extra 10Kb or so per GIF.
126 */
127 static unsigned char buf[4];
128 static unsigned char *direct;
129 static int maskTbl[16] = {0x0000, 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f,
130 			  0x00ff, 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff};
131 static int table[2][(1 << GIF_MAX_LZW)];
132 static unsigned char stack[(1 << GIF_MAX_LZW) * 2];
133 static unsigned char *stack_pointer;
134 static int code_size, set_code_size;
135 static int max_code, max_code_size;
136 static int clear_code, end_code;
137 static int curbit, lastbit, last_byte;
138 static int firstcode, oldcode;
139 static bool zero_data_block = false;
140 static bool get_done;
141 
142 /*	Whether to clear the decoded image rather than plot
143 */
144 static bool clear_image = false;
145 
146 
147 
148 /**	Initialises necessary gif_animation members.
149 */
gif_create(gif_animation * gif,gif_bitmap_callback_vt * bitmap_callbacks)150 void gif_create(gif_animation *gif, gif_bitmap_callback_vt *bitmap_callbacks) {
151 	memset(gif, 0, sizeof(gif_animation));
152 	gif->bitmap_callbacks = *bitmap_callbacks;
153 	gif->decoded_frame = GIF_INVALID_FRAME;
154 }
155 
156 
157 /**	Initialises any workspace held by the animation and attempts to decode
158 	any information that hasn't already been decoded.
159 	If an error occurs, all previously decoded frames are retained.
160 
161 	@return GIF_FRAME_DATA_ERROR for GIF frame data error
162 		GIF_INSUFFICIENT_FRAME_DATA for insufficient data to process
163 		          any more frames
164 		GIF_INSUFFICIENT_MEMORY for memory error
165 		GIF_DATA_ERROR for GIF error
166 		GIF_INSUFFICIENT_DATA for insufficient data to do anything
167 		GIF_OK for successful decoding
168 		GIF_WORKING for successful decoding if more frames are expected
169 */
gif_initialise(gif_animation * gif,size_t size,unsigned char * data)170 gif_result gif_initialise(gif_animation *gif, size_t size, unsigned char *data) {
171 	unsigned char *gif_data;
172 	unsigned int index;
173 	gif_result return_value;
174 
175 	/* 	The GIF format is thoroughly documented; a full description
176 	 *	can be found at http://www.w3.org/Graphics/GIF/spec-gif89a.txt
177 	*/
178 
179 	/*	Initialize values
180 	*/
181 	gif->buffer_size = size;
182 	gif->gif_data = data;
183 
184 	/*	Check for sufficient data to be a GIF (6-byte header + 7-byte logical screen descriptor)
185 	*/
186 	if (gif->buffer_size < 13) return GIF_INSUFFICIENT_DATA;
187 
188 	/*	Get our current processing position
189 	*/
190 	gif_data = gif->gif_data + gif->buffer_position;
191 
192 	/*	See if we should initialise the GIF
193 	*/
194 	if (gif->buffer_position == 0) {
195 
196 		/*	We want everything to be NULL before we start so we've no chance
197 			of freeing bad pointers (paranoia)
198 		*/
199 		gif->frame_image = NULL;
200 		gif->frames = NULL;
201 		gif->local_colour_table = NULL;
202 		gif->global_colour_table = NULL;
203 
204 		/*	The caller may have been lazy and not reset any values
205 		*/
206 		gif->frame_count = 0;
207 		gif->frame_count_partial = 0;
208 		gif->decoded_frame = GIF_INVALID_FRAME;
209 
210 		/* 6-byte GIF file header is:
211 		 *
212 		 *	+0	3CHARS	Signature ('GIF')
213 		 *	+3	3CHARS	Version ('87a' or '89a')
214 		 */
215 		if (strncmp((const char *) gif_data, "GIF", 3) != 0)
216 			return GIF_DATA_ERROR;
217 		gif_data += 3;
218 
219 		/*	Ensure GIF reports version 87a or 89a
220 		*/
221 /*		if ((strncmp(gif_data, "87a", 3) != 0) &&
222 				(strncmp(gif_data, "89a", 3) != 0))
223 			LOG(("Unknown GIF format - proceeding anyway"));
224 */		gif_data += 3;
225 
226 		/* 7-byte Logical Screen Descriptor is:
227 		 *
228 		 *	+0	SHORT	Logical Screen Width
229 		 *	+2	SHORT	Logical Screen Height
230 		 *	+4	CHAR	__Packed Fields__
231 		 * 			1BIT	Global Colour Table Flag
232 		 * 			3BITS	Colour Resolution
233 		 * 			1BIT	Sort Flag
234 		 * 			3BITS	Size of Global Colour Table
235 		 *	+5	CHAR	Background Colour Index
236 		 *	+6	CHAR	Pixel Aspect Ratio
237 		 */
238 		gif->width = gif_data[0] | (gif_data[1] << 8);
239 		gif->height = gif_data[2] | (gif_data[3] << 8);
240 		gif->global_colours = (gif_data[4] & GIF_COLOUR_TABLE_MASK);
241 		gif->colour_table_size = (2 << (gif_data[4] & GIF_COLOUR_TABLE_SIZE_MASK));
242 		gif->background_index = gif_data[5];
243 		gif->aspect_ratio = gif_data[6];
244 		gif->loop_count = 1;
245 		gif_data += 7;
246 
247 		/*	Some broken GIFs report the size as the screen size they were created in. As
248 			such, we detect for the common cases and set the sizes as 0 if they are found
249 			which results in the GIF being the maximum size of the frames.
250 		*/
251 		if (((gif->width == 640) && (gif->height == 480)) ||
252 				((gif->width == 640) && (gif->height == 512)) ||
253 				((gif->width == 800) && (gif->height == 600)) ||
254 				((gif->width == 1024) && (gif->height == 768)) ||
255 				((gif->width == 1280) && (gif->height == 1024)) ||
256 				((gif->width == 1600) && (gif->height == 1200)) ||
257 				((gif->width == 0) || (gif->height == 0)) ||
258 				((gif->width > 2048) || (gif->height > 2048))) {
259 			gif->width = 1;
260 			gif->height = 1;
261 		}
262 
263 		/*	Allocate some data irrespective of whether we've got any colour tables. We
264 			always get the maximum size in case a GIF is lying to us. It's far better
265 			to give the wrong colours than to trample over some memory somewhere.
266 		*/
267 		gif->global_colour_table = calloc(GIF_MAX_COLOURS, sizeof(unsigned int));
268 		gif->local_colour_table = calloc(GIF_MAX_COLOURS, sizeof(unsigned int));
269 		if ((gif->global_colour_table == NULL) || (gif->local_colour_table == NULL)) {
270 			gif_finalise(gif);
271 			return GIF_INSUFFICIENT_MEMORY;
272 		}
273 
274 		/*	Set the first colour to a value that will never occur in reality so we
275 			know if we've processed it
276 		*/
277 		gif->global_colour_table[0] = GIF_PROCESS_COLOURS;
278 
279 		/*	Check if the GIF has no frame data (13-byte header + 1-byte termination block)
280 		 *	Although generally useless, the GIF specification does not expressly prohibit this
281 		 */
282 		if (gif->buffer_size == 14) {
283 			if (gif_data[0] == GIF_TRAILER)
284 				return GIF_OK;
285 			else
286 				return GIF_INSUFFICIENT_DATA;
287 		}
288 
289 		/*	Initialise enough workspace for 4 frames initially
290 		*/
291 		if ((gif->frames = (gif_frame *)malloc(sizeof(gif_frame))) == NULL) {
292 			gif_finalise(gif);
293 			return GIF_INSUFFICIENT_MEMORY;
294 		}
295 		gif->frame_holders = 1;
296 
297 		/*	Initialise the sprite header
298 		*/
299 		assert(gif->bitmap_callbacks.bitmap_create);
300 		if ((gif->frame_image = gif->bitmap_callbacks.bitmap_create(gif->width, gif->height)) == NULL) {
301 			gif_finalise(gif);
302 			return GIF_INSUFFICIENT_MEMORY;
303 		}
304 
305 		/*	Remember we've done this now
306 		*/
307 		gif->buffer_position = gif_data - gif->gif_data;
308 	}
309 
310 	/*	Do the colour map if we haven't already. As the top byte is always 0xff or 0x00
311 		depending on the transparency we know if it's been filled in.
312 	*/
313 	if (gif->global_colour_table[0] == GIF_PROCESS_COLOURS) {
314 		/*	Check for a global colour map signified by bit 7
315 		*/
316 		if (gif->global_colours) {
317 			if (gif->buffer_size < (gif->colour_table_size * 3 + 12)) {
318 				return GIF_INSUFFICIENT_DATA;
319 			}
320 			for (index = 0; index < gif->colour_table_size; index++) {
321 				/* Gif colour map contents are r,g,b.
322 				 *
323 				 * We want to pack them bytewise into the
324 				 * colour table, such that the red component
325 				 * is in byte 0 and the alpha component is in
326 				 * byte 3.
327 				 */
328 				unsigned char *entry = (unsigned char *) &gif->
329 						global_colour_table[index];
330 
331 				entry[0] = gif_data[0];	/* r */
332 				entry[1] = gif_data[1];	/* g */
333 				entry[2] = gif_data[2];	/* b */
334 				entry[3] = 0xff;	/* a */
335 
336 				gif_data += 3;
337 			}
338 			gif->buffer_position = (gif_data - gif->gif_data);
339 		} else {
340 			/*	Create a default colour table with the first two colours as black and white
341 			*/
342 			unsigned int *entry = gif->global_colour_table;
343 
344 			entry[0] = 0x00000000;
345 			/* Force Alpha channel to opaque */
346 			((unsigned char *) entry)[3] = 0xff;
347 
348 			entry[1] = 0xffffffff;
349 		}
350 	}
351 
352 	/*	Repeatedly try to initialise frames
353 	*/
354 	while ((return_value = gif_initialise_frame(gif)) == GIF_WORKING);
355 
356 	/*	If there was a memory error tell the caller
357 	*/
358 	if ((return_value == GIF_INSUFFICIENT_MEMORY) ||
359 			(return_value == GIF_DATA_ERROR))
360 		return return_value;
361 
362 	/*	If we didn't have some frames then a GIF_INSUFFICIENT_DATA becomes a
363 		GIF_INSUFFICIENT_FRAME_DATA
364 	*/
365 	if ((return_value == GIF_INSUFFICIENT_DATA) && (gif->frame_count_partial > 0))
366 		return GIF_INSUFFICIENT_FRAME_DATA;
367 
368 	/*	Return how many we got
369 	*/
370 	return return_value;
371 }
372 
373 
374 /**	Updates the sprite memory size
375 
376 	@return GIF_INSUFFICIENT_MEMORY for a memory error
377 		GIF_OK for success
378 */
gif_initialise_sprite(gif_animation * gif,unsigned int width,unsigned int height)379 static gif_result gif_initialise_sprite(gif_animation *gif, unsigned int width, unsigned int height) {
380 	unsigned int max_width;
381 	unsigned int max_height;
382 	struct bitmap *buffer;
383 
384 	/*	Check if we've changed
385 	*/
386 	if ((width <= gif->width) && (height <= gif->height))
387 		return GIF_OK;
388 
389 	/*	Get our maximum values
390 	*/
391 	max_width = (width > gif->width) ? width : gif->width;
392 	max_height = (height > gif->height) ? height : gif->height;
393 
394 	/*	Allocate some more memory
395 	*/
396 	assert(gif->bitmap_callbacks.bitmap_create);
397 	if ((buffer = gif->bitmap_callbacks.bitmap_create(max_width, max_height)) == NULL)
398 		return GIF_INSUFFICIENT_MEMORY;
399 	assert(gif->bitmap_callbacks.bitmap_destroy);
400 	gif->bitmap_callbacks.bitmap_destroy(gif->frame_image);
401 	gif->frame_image = buffer;
402 	gif->width = max_width;
403 	gif->height = max_height;
404 
405 	/*	Invalidate our currently decoded image
406 	*/
407 	gif->decoded_frame = GIF_INVALID_FRAME;
408 	return GIF_OK;
409 }
410 
411 
412 /**	Attempts to initialise the next frame
413 
414 	@return GIF_INSUFFICIENT_DATA for insufficient data to do anything
415 		GIF_FRAME_DATA_ERROR for GIF frame data error
416 		GIF_INSUFFICIENT_MEMORY for insufficient memory to process
417 		GIF_INSUFFICIENT_FRAME_DATA for insufficient data to complete the frame
418 		GIF_DATA_ERROR for GIF error (invalid frame header)
419 		GIF_OK for successful decoding
420 		GIF_WORKING for successful decoding if more frames are expected
421 */
gif_initialise_frame(gif_animation * gif)422 static gif_result gif_initialise_frame(gif_animation *gif) {
423 	int frame;
424 	gif_frame *temp_buf;
425 
426 	unsigned char *gif_data, *gif_end;
427 	int gif_bytes;
428 	unsigned int flags = 0;
429 	unsigned int width, height, offset_x, offset_y;
430 	unsigned int block_size, colour_table_size;
431 	bool first_image = true;
432 	gif_result return_value;
433 
434 	/*	Get the frame to decode and our data position
435 	*/
436 	frame = gif->frame_count;
437 
438 	/*	Get our buffer position etc.
439 	*/
440 	gif_data = (unsigned char *)(gif->gif_data + gif->buffer_position);
441 	gif_end = (unsigned char *)(gif->gif_data + gif->buffer_size);
442 	gif_bytes = (gif_end - gif_data);
443 
444 	/*	Check if we've finished
445 	*/
446 	if ((gif_bytes > 0) && (gif_data[0] == GIF_TRAILER)) return GIF_OK;
447 
448 	/*	Check if we have enough data
449 	 *	The shortest block of data is a 4-byte comment extension + 1-byte block terminator + 1-byte gif trailer
450 	*/
451 	if (gif_bytes < 6) return GIF_INSUFFICIENT_DATA;
452 
453 	/*	We could theoretically get some junk data that gives us millions of frames, so
454 		we ensure that we don't have a silly number
455 	*/
456 	if (frame > 4096) return GIF_FRAME_DATA_ERROR;
457 
458 	/*	Get some memory to store our pointers in etc.
459 	*/
460 	if ((int)gif->frame_holders <= frame) {
461 		/*	Allocate more memory
462 		*/
463 		if ((temp_buf = (gif_frame *)realloc(gif->frames,
464 					(frame + 1) * sizeof(gif_frame))) == NULL)
465 			return GIF_INSUFFICIENT_MEMORY;
466 		gif->frames = temp_buf;
467 		gif->frame_holders = frame + 1;
468 	}
469 
470 	/*	Store our frame pointer. We would do it when allocating except we
471 		start off with one frame allocated so we can always use realloc.
472 	*/
473 	gif->frames[frame].frame_pointer = gif->buffer_position;
474 	gif->frames[frame].display = false;
475 	gif->frames[frame].virgin = true;
476 	gif->frames[frame].disposal_method = 0;
477 	gif->frames[frame].transparency = false;
478 	gif->frames[frame].frame_delay = 100;
479 	gif->frames[frame].redraw_required = false;
480 
481 	/*	Invalidate any previous decoding we have of this frame
482 	*/
483 	if (gif->decoded_frame == frame)
484 		gif->decoded_frame = GIF_INVALID_FRAME;
485 
486 	/*	We pretend to initialise the frames, but really we just skip over all
487 		the data contained within. This is all basically a cut down version of
488 		gif_decode_frame that doesn't have any of the LZW bits in it.
489 	*/
490 
491 	/*	Initialise any extensions
492 	*/
493 	gif->buffer_position = gif_data - gif->gif_data;
494 	if ((return_value = gif_initialise_frame_extensions(gif, frame)) != GIF_OK)
495 		return return_value;
496 	gif_data = (gif->gif_data + gif->buffer_position);
497 	gif_bytes = (gif_end - gif_data);
498 
499 	/*	Check if we've finished
500 	*/
501 	if ((gif_bytes = (gif_end - gif_data)) < 1)
502 		return GIF_INSUFFICIENT_FRAME_DATA;
503 	else if (gif_data[0] == GIF_TRAILER) {
504 		gif->buffer_position = (gif_data - gif->gif_data);
505 		gif->frame_count = frame + 1;
506 		return GIF_OK;
507 	}
508 
509 	/*	If we're not done, there should be an image descriptor
510 	*/
511 	if (gif_data[0] != GIF_IMAGE_SEPARATOR) return GIF_FRAME_DATA_ERROR;
512 
513 	/*	Do some simple boundary checking
514 	*/
515 	offset_x = gif_data[1] | (gif_data[2] << 8);
516 	offset_y = gif_data[3] | (gif_data[4] << 8);
517 	width = gif_data[5] | (gif_data[6] << 8);
518 	height = gif_data[7] | (gif_data[8] << 8);
519 
520 	/*	Set up the redraw characteristics. We have to check for extending the area
521 		due to multi-image frames.
522 	*/
523 	if (!first_image) {
524 		if (gif->frames[frame].redraw_x > offset_x) {
525 			gif->frames[frame].redraw_width += (gif->frames[frame].redraw_x - offset_x);
526 			gif->frames[frame].redraw_x = offset_x;
527 		}
528 		if (gif->frames[frame].redraw_y > offset_y) {
529 			gif->frames[frame].redraw_height += (gif->frames[frame].redraw_y - offset_y);
530 			gif->frames[frame].redraw_y = offset_y;
531 		}
532 		if ((offset_x + width) > (gif->frames[frame].redraw_x + gif->frames[frame].redraw_width))
533 			gif->frames[frame].redraw_width = (offset_x + width) - gif->frames[frame].redraw_x;
534 		if ((offset_y + height) > (gif->frames[frame].redraw_y + gif->frames[frame].redraw_height))
535 			gif->frames[frame].redraw_height = (offset_y + height) - gif->frames[frame].redraw_y;
536 	} else {
537 		first_image = false;
538 		gif->frames[frame].redraw_x = offset_x;
539 		gif->frames[frame].redraw_y = offset_y;
540 		gif->frames[frame].redraw_width = width;
541 		gif->frames[frame].redraw_height = height;
542 	}
543 
544 	/*	if we are clearing the background then we need to redraw enough to cover the previous
545 		frame too
546 	*/
547 	gif->frames[frame].redraw_required = ((gif->frames[frame].disposal_method == GIF_FRAME_CLEAR) ||
548 						(gif->frames[frame].disposal_method == GIF_FRAME_RESTORE));
549 
550 	/*	Boundary checking - shouldn't ever happen except with junk data
551 	*/
552 	if (gif_initialise_sprite(gif, (offset_x + width), (offset_y + height)))
553 		return GIF_INSUFFICIENT_MEMORY;
554 
555 	/*	Decode the flags
556 	*/
557 	flags = gif_data[9];
558 	colour_table_size = 2 << (flags & GIF_COLOUR_TABLE_SIZE_MASK);
559 
560 	/*	Move our data onwards and remember we've got a bit of this frame
561 	*/
562 	gif_data += 10;
563 	gif_bytes = (gif_end - gif_data);
564 	gif->frame_count_partial = frame + 1;
565 
566 	/*	Skip the local colour table
567 	*/
568 	if (flags & GIF_COLOUR_TABLE_MASK) {
569 		gif_data += 3 * colour_table_size;
570 		if ((gif_bytes = (gif_end - gif_data)) < 0)
571 			return GIF_INSUFFICIENT_FRAME_DATA;
572 	}
573 
574 	/*	Ensure we have a correct code size
575 	*/
576 	if (gif_data[0] > GIF_MAX_LZW)
577 		return GIF_DATA_ERROR;
578 
579 	/*	Move our pointer to the actual image data
580 	*/
581 	gif_data++;
582 	if (--gif_bytes < 0)
583 		return GIF_INSUFFICIENT_FRAME_DATA;
584 
585 	/*	Repeatedly skip blocks until we get a zero block or run out of data
586 	 *	These blocks of image data are processed later by gif_decode_frame()
587 	*/
588 	block_size = 0;
589 	while (block_size != 1) {
590 		block_size = gif_data[0] + 1;
591 		/*	Check if the frame data runs off the end of the file
592 		*/
593 		if ((int)(gif_bytes - block_size) < 0) {
594 			/*	Try to recover by signaling the end of the gif.
595 			 *	Once we get garbage data, there is no logical
596 			 *	way to determine where the next frame is.
597 			 *	It's probably better to partially load the gif
598 			 *	than not at all.
599 			*/
600 			if (gif_bytes >= 2) {
601 				gif_data[0] = 0;
602 				gif_data[1] = GIF_TRAILER;
603 				gif_bytes = 1;
604 				++gif_data;
605 				break;
606 			} else
607 				return GIF_INSUFFICIENT_FRAME_DATA;
608 		} else {
609 			gif_bytes -= block_size;
610 			gif_data += block_size;
611 		}
612 	}
613 
614 	/*	Add the frame and set the display flag
615 	*/
616 	gif->buffer_position = gif_data - gif->gif_data;
617 	gif->frame_count = frame + 1;
618 	gif->frames[frame].display = true;
619 
620 	/*	Check if we've finished
621 	*/
622 	if (gif_bytes < 1)
623 		return GIF_INSUFFICIENT_FRAME_DATA;
624 	else
625 		if (gif_data[0] == GIF_TRAILER) return GIF_OK;
626 	return GIF_WORKING;
627 }
628 
629 /**	Attempts to initialise the frame's extensions
630 
631 	@return GIF_INSUFFICIENT_FRAME_DATA for insufficient data to complete the frame
632 		GIF_OK for successful initialisation
633 */
gif_initialise_frame_extensions(gif_animation * gif,const int frame)634 static gif_result gif_initialise_frame_extensions(gif_animation *gif, const int frame) {
635 	unsigned char *gif_data, *gif_end;
636 	int gif_bytes;
637 	unsigned int block_size;
638 
639 	/*	Get our buffer position etc.
640 	*/
641 	gif_data = (unsigned char *)(gif->gif_data + gif->buffer_position);
642 	gif_end = (unsigned char *)(gif->gif_data + gif->buffer_size);
643 
644 	/*	Initialise the extensions
645 	*/
646 	while (gif_data[0] == GIF_EXTENSION_INTRODUCER) {
647 		++gif_data;
648 		gif_bytes = (gif_end - gif_data);
649 
650 		/*	Switch on extension label
651 		*/
652 		switch(gif_data[0]) {
653 			/* 6-byte Graphic Control Extension is:
654 			 *
655 			 *	+0	CHAR	Graphic Control Label
656 			 *	+1	CHAR	Block Size
657 			 *	+2	CHAR	__Packed Fields__
658 			 *			3BITS	Reserved
659 			 *			3BITS	Disposal Method
660 			 *			1BIT	User Input Flag
661 			 *			1BIT	Transparent Color Flag
662 			 *	+3	SHORT	Delay Time
663 			 *	+5	CHAR	Transparent Color Index
664 			*/
665 			case GIF_EXTENSION_GRAPHIC_CONTROL:
666 				if (gif_bytes < 6) return GIF_INSUFFICIENT_FRAME_DATA;
667 				gif->frames[frame].frame_delay = gif_data[3] | (gif_data[4] << 8);
668 				if (gif_data[2] & GIF_TRANSPARENCY_MASK) {
669 					gif->frames[frame].transparency = true;
670 					gif->frames[frame].transparency_index = gif_data[5];
671 				}
672 				gif->frames[frame].disposal_method = ((gif_data[2] & GIF_DISPOSAL_MASK) >> 2);
673 				/*	I have encountered documentation and GIFs in the wild that use
674 				 *	0x04 to restore the previous frame, rather than the officially
675 				 *	documented 0x03.  I believe some (older?) software may even actually
676 				 *	export this way.  We handle this as a type of "quirks" mode.
677 				*/
678 				if (gif->frames[frame].disposal_method == GIF_FRAME_QUIRKS_RESTORE)
679 					gif->frames[frame].disposal_method = GIF_FRAME_RESTORE;
680 				gif_data += (2 + gif_data[1]);
681 				break;
682 
683 			/* 14-byte+ Application Extension is:
684 			 *
685 			 *	+0	CHAR	Application Extension Label
686 			 *	+1	CHAR	Block Size
687 			 *	+2	8CHARS	Application Identifier
688 			 *	+10	3CHARS	Appl. Authentication Code
689 			 *	+13	1-256	Application Data (Data sub-blocks)
690 			*/
691 			case GIF_EXTENSION_APPLICATION:
692 				if (gif_bytes < 17) return GIF_INSUFFICIENT_FRAME_DATA;
693 				if ((gif_data[1] == 0x0b) &&
694 					(strncmp((const char *) gif_data + 2,
695 						"NETSCAPE2.0", 11) == 0) &&
696 					(gif_data[13] == 0x03) &&
697 					(gif_data[14] == 0x01)) {
698 						gif->loop_count = gif_data[15] | (gif_data[16] << 8);
699 				}
700 				gif_data += (2 + gif_data[1]);
701 				break;
702 
703 			/*	Move the pointer to the first data sub-block
704 			 *	Skip 1 byte for the extension label
705 			*/
706 			case GIF_EXTENSION_COMMENT:
707 				++gif_data;
708 				break;
709 
710 			/*	Move the pointer to the first data sub-block
711 			 *	Skip 2 bytes for the extension label and size fields
712 			 *	Skip the extension size itself
713 			*/
714 			default:
715 				gif_data += (2 + gif_data[1]);
716 		}
717 
718 		/*	Repeatedly skip blocks until we get a zero block or run out of data
719 		 *	This data is ignored by this gif decoder
720 		*/
721 		gif_bytes = (gif_end - gif_data);
722 		block_size = 0;
723 		while (gif_data[0] != GIF_BLOCK_TERMINATOR) {
724 			block_size = gif_data[0] + 1;
725 			if ((gif_bytes -= block_size) < 0)
726 				return GIF_INSUFFICIENT_FRAME_DATA;
727 			gif_data += block_size;
728 		}
729 		++gif_data;
730 	}
731 
732 	/*	Set buffer position and return
733 	*/
734 	gif->buffer_position = (gif_data - gif->gif_data);
735 	return GIF_OK;
736 }
737 
738 
739 /**	Decodes a GIF frame.
740 
741 	@return GIF_FRAME_DATA_ERROR for GIF frame data error
742 		GIF_INSUFFICIENT_FRAME_DATA for insufficient data to complete the frame
743 		GIF_DATA_ERROR for GIF error (invalid frame header)
744 		GIF_INSUFFICIENT_DATA for insufficient data to do anything
745 		GIF_INSUFFICIENT_MEMORY for insufficient memory to process
746 		GIF_OK for successful decoding
747 		If a frame does not contain any image data, GIF_OK is returned and
748 			gif->current_error is set to GIF_FRAME_NO_DISPLAY
749 */
gif_decode_frame(gif_animation * gif,unsigned int frame)750 gif_result gif_decode_frame(gif_animation *gif, unsigned int frame) {
751 	unsigned int index = 0;
752 	unsigned char *gif_data, *gif_end;
753 	int gif_bytes;
754 	unsigned int width, height, offset_x, offset_y;
755 	unsigned int flags, colour_table_size, interlace;
756 	unsigned int *colour_table;
757 	unsigned int *frame_data = 0;	// Set to 0 for no warnings
758 	unsigned int *frame_scanline;
759 	unsigned int save_buffer_position;
760 	unsigned int return_value = 0;
761 	unsigned int x, y, decode_y, burst_bytes;
762 	int last_undisposed_frame = (frame - 1);
763 	register unsigned char colour;
764 
765 	/*	Ensure this frame is supposed to be decoded
766 	*/
767 	if (gif->frames[frame].display == false) {
768 		gif->current_error = GIF_FRAME_NO_DISPLAY;
769 		return GIF_OK;
770 	}
771 
772 	/*	Ensure we have a frame to decode
773 	*/
774 	if (frame > gif->frame_count_partial)
775 		return GIF_INSUFFICIENT_DATA;
776 	if ((!clear_image) && ((int)frame == gif->decoded_frame))
777 		return GIF_OK;
778 
779 	/*	Get the start of our frame data and the end of the GIF data
780 	*/
781 	gif_data = gif->gif_data + gif->frames[frame].frame_pointer;
782 	gif_end = gif->gif_data + gif->buffer_size;
783 	gif_bytes = (gif_end - gif_data);
784 
785 	/*	Check if we have enough data
786 	 *	The shortest block of data is a 10-byte image descriptor + 1-byte gif trailer
787 	*/
788 	if (gif_bytes < 12) return GIF_INSUFFICIENT_FRAME_DATA;
789 
790 	/*	Save the buffer position
791 	*/
792 	save_buffer_position = gif->buffer_position;
793 	gif->buffer_position = gif_data - gif->gif_data;
794 
795 	/*	Skip any extensions because we all ready processed them
796 	*/
797 	if ((return_value = gif_skip_frame_extensions(gif)) != GIF_OK)
798 		goto gif_decode_frame_exit;
799 	gif_data = (gif->gif_data + gif->buffer_position);
800 	gif_bytes = (gif_end - gif_data);
801 
802 	/*	Ensure we have enough data for the 10-byte image descriptor + 1-byte gif trailer
803 	*/
804 	if (gif_bytes < 12) {
805 		return_value = GIF_INSUFFICIENT_FRAME_DATA;
806 		goto gif_decode_frame_exit;
807 	}
808 
809 	/* 10-byte Image Descriptor is:
810 	 *
811 	 *	+0	CHAR	Image Separator (0x2c)
812 	 *	+1	SHORT	Image Left Position
813 	 *	+3	SHORT	Image Top Position
814 	 *	+5	SHORT	Width
815 	 *	+7	SHORT	Height
816 	 *	+9	CHAR	__Packed Fields__
817 	 *			1BIT	Local Colour Table Flag
818 	 *			1BIT	Interlace Flag
819 	 *			1BIT	Sort Flag
820 	 *			2BITS	Reserved
821 	 *			3BITS	Size of Local Colour Table
822 	*/
823 	if (gif_data[0] != GIF_IMAGE_SEPARATOR) {
824 		return_value = GIF_DATA_ERROR;
825 		goto gif_decode_frame_exit;
826 	}
827 	offset_x = gif_data[1] | (gif_data[2] << 8);
828 	offset_y = gif_data[3] | (gif_data[4] << 8);
829 	width = gif_data[5] | (gif_data[6] << 8);
830 	height = gif_data[7] | (gif_data[8] << 8);
831 
832 	/*	Boundary checking - shouldn't ever happen except unless the data has been
833 		modified since initialisation.
834 	*/
835 	if ((offset_x + width > gif->width) || (offset_y + height > gif->height)) {
836 		return_value = GIF_DATA_ERROR;
837 		goto gif_decode_frame_exit;
838 	}
839 
840 	/*	Decode the flags
841 	*/
842 	flags = gif_data[9];
843 	colour_table_size = 2 << (flags & GIF_COLOUR_TABLE_SIZE_MASK);
844 	interlace = flags & GIF_INTERLACE_MASK;
845 
846 	/*	Move our pointer to the colour table or image data (if no colour table is given)
847 	*/
848 	gif_data += 10;
849 	gif_bytes = (gif_end - gif_data);
850 
851 	/*	Set up the colour table
852 	*/
853 	if (flags & GIF_COLOUR_TABLE_MASK) {
854 		if (gif_bytes < (int)(3 * colour_table_size)) {
855 			return_value = GIF_INSUFFICIENT_FRAME_DATA;
856 			goto gif_decode_frame_exit;
857 		}
858 		colour_table = gif->local_colour_table;
859 		if (!clear_image) {
860 			for (index = 0; index < colour_table_size; index++) {
861 				/* Gif colour map contents are r,g,b.
862 				 *
863 				 * We want to pack them bytewise into the
864 				 * colour table, such that the red component
865 				 * is in byte 0 and the alpha component is in
866 				 * byte 3.
867 				 */
868 				unsigned char *entry =
869 					(unsigned char *) &colour_table[index];
870 
871 				entry[0] = gif_data[0];	/* r */
872 				entry[1] = gif_data[1];	/* g */
873 				entry[2] = gif_data[2];	/* b */
874 				entry[3] = 0xff;	/* a */
875 
876 				gif_data += 3;
877 			}
878 		} else {
879 			gif_data += 3 * colour_table_size;
880 		}
881 		gif_bytes = (gif_end - gif_data);
882 	} else {
883 		colour_table = gif->global_colour_table;
884 	}
885 
886 	/*	Check if we've finished
887 	*/
888 	if (gif_bytes < 1) {
889 		return_value = GIF_INSUFFICIENT_FRAME_DATA;
890 		goto gif_decode_frame_exit;
891 	} else if (gif_data[0] == GIF_TRAILER) {
892 		return_value = GIF_OK;
893 		goto gif_decode_frame_exit;
894 	}
895 
896 	/*	Get the frame data
897 	*/
898 	assert(gif->bitmap_callbacks.bitmap_get_buffer);
899 	frame_data = (void *)gif->bitmap_callbacks.bitmap_get_buffer(gif->frame_image);
900 	if (!frame_data)
901 		return GIF_INSUFFICIENT_MEMORY;
902 
903 	/*	If we are clearing the image we just clear, if not decode
904 	*/
905 	if (!clear_image) {
906 		/*	Ensure we have enough data for a 1-byte LZW code size + 1-byte gif trailer
907 		*/
908 		if (gif_bytes < 2) {
909 			return_value = GIF_INSUFFICIENT_FRAME_DATA;
910 			goto gif_decode_frame_exit;
911 		/*	If we only have a 1-byte LZW code size + 1-byte gif trailer, we're finished
912 		*/
913 		} else if ((gif_bytes == 2) && (gif_data[1] == GIF_TRAILER)) {
914 			return_value = GIF_OK;
915 			goto gif_decode_frame_exit;
916 		}
917 
918 		/*	If the previous frame's disposal method requires we restore the background
919 		 *	colour or this is the first frame, clear the frame data
920 		*/
921 		if ((frame == 0) || (gif->decoded_frame == GIF_INVALID_FRAME)) {
922 			memset((char*)frame_data, GIF_TRANSPARENT_COLOUR, gif->width * gif->height * sizeof(int));
923 			gif->decoded_frame = frame;
924 			/* The line below would fill the image with its background color, but because GIFs support
925 			 * transparency we likely wouldn't want to do that. */
926 			/* memset((char*)frame_data, colour_table[gif->background_index], gif->width * gif->height * sizeof(int)); */
927 		} else if ((frame != 0) && (gif->frames[frame - 1].disposal_method == GIF_FRAME_CLEAR)) {
928 			clear_image = true;
929 			if ((return_value = gif_decode_frame(gif, (frame - 1))) != GIF_OK)
930 				goto gif_decode_frame_exit;
931 			clear_image = false;
932 		/*	If the previous frame's disposal method requires we restore the previous
933 		 *	image, find the last image set to "do not dispose" and get that frame data
934 		*/
935 		} else if ((frame != 0) && (gif->frames[frame - 1].disposal_method == GIF_FRAME_RESTORE)) {
936 			while ((last_undisposed_frame != -1) && (gif->frames[--last_undisposed_frame].disposal_method == GIF_FRAME_RESTORE))
937 				;
938 
939 			/*	If we don't find one, clear the frame data
940 			 */
941 			if (last_undisposed_frame == -1) {
942 				/* see notes above on transparency vs. background color */
943 				memset((char*)frame_data, GIF_TRANSPARENT_COLOUR, gif->width * gif->height * sizeof(int));
944 			} else {
945 				if ((return_value = gif_decode_frame(gif, last_undisposed_frame)) != GIF_OK)
946 					goto gif_decode_frame_exit;
947 				/*	Get this frame's data
948 				*/
949 				assert(gif->bitmap_callbacks.bitmap_get_buffer);
950 				frame_data = (void *)gif->bitmap_callbacks.bitmap_get_buffer(gif->frame_image);
951 				if (!frame_data)
952 					return GIF_INSUFFICIENT_MEMORY;
953 			}
954 		}
955 		gif->decoded_frame = frame;
956 
957 		/*	Initialise the LZW decoding
958 		*/
959 		set_code_size = gif_data[0];
960 		gif->buffer_position = (gif_data - gif->gif_data) + 1;
961 
962 		/*	Set our code variables
963 		*/
964 		code_size = set_code_size + 1;
965 		clear_code = (1 << set_code_size);
966 		end_code = clear_code + 1;
967 		max_code_size = clear_code << 1;
968 		max_code = clear_code + 2;
969 		curbit = lastbit = 0;
970 		last_byte = 2;
971 		get_done = false;
972 		direct = buf;
973 		gif_init_LZW(gif);
974 
975 		/*	Decompress the data
976 		*/
977 		for (y = 0; y < height; y++) {
978 			if (interlace)
979 				decode_y = gif_interlaced_line(height, y) + offset_y;
980 			else
981 				decode_y = y + offset_y;
982 			frame_scanline = frame_data + offset_x + (decode_y * gif->width);
983 
984 			/*	Rather than decoding pixel by pixel, we try to burst out streams
985 				of data to remove the need for end-of data checks every pixel.
986 			*/
987 			x = width;
988 			while (x > 0) {
989 				burst_bytes = (stack_pointer - stack);
990 				if (burst_bytes > 0) {
991 					if (burst_bytes > x)
992 						burst_bytes = x;
993 					x -= burst_bytes;
994 					while (burst_bytes-- > 0) {
995 						colour = *--stack_pointer;
996 						if (((gif->frames[frame].transparency) &&
997 							(colour != gif->frames[frame].transparency_index)) ||
998 							(!gif->frames[frame].transparency))
999 								*frame_scanline = colour_table[colour];
1000 						frame_scanline++;
1001 					}
1002 				} else {
1003 					if (!gif_next_LZW(gif)) {
1004 						/*	Unexpected end of frame, try to recover
1005 						*/
1006 						if (gif->current_error == GIF_END_OF_FRAME)
1007 							return_value = GIF_OK;
1008 						else
1009 							return_value = gif->current_error;
1010 						goto gif_decode_frame_exit;
1011 					}
1012 				}
1013 			}
1014 		}
1015 	} else {
1016 		/*	Clear our frame
1017 		*/
1018 		if (gif->frames[frame].disposal_method == GIF_FRAME_CLEAR) {
1019 			for (y = 0; y < height; y++) {
1020 				frame_scanline = frame_data + offset_x + ((offset_y + y) * gif->width);
1021 				if (gif->frames[frame].transparency)
1022 					memset(frame_scanline, GIF_TRANSPARENT_COLOUR, width * 4);
1023 				else
1024 					memset(frame_scanline, colour_table[gif->background_index], width * 4);
1025 			}
1026 		}
1027 	}
1028 gif_decode_frame_exit:
1029 
1030 	/*	Check if we should test for optimisation
1031 	*/
1032 	if (gif->frames[frame].virgin) {
1033 		if (gif->bitmap_callbacks.bitmap_test_opaque)
1034 			gif->frames[frame].opaque = gif->bitmap_callbacks.bitmap_test_opaque(gif->frame_image);
1035 		else
1036 			gif->frames[frame].opaque = false;
1037 		gif->frames[frame].virgin = false;
1038 	}
1039 	if (gif->bitmap_callbacks.bitmap_set_opaque)
1040 		gif->bitmap_callbacks.bitmap_set_opaque(gif->frame_image, gif->frames[frame].opaque);
1041 	if (gif->bitmap_callbacks.bitmap_modified)
1042 		gif->bitmap_callbacks.bitmap_modified(gif->frame_image);
1043 
1044 	/*	Restore the buffer position
1045 	*/
1046 	gif->buffer_position = save_buffer_position;
1047 
1048 	/*	Success!
1049 	*/
1050 	return return_value;
1051 
1052 }
1053 
1054 /**	Skips the frame's extensions (which have been previously initialised)
1055 
1056 	@return GIF_INSUFFICIENT_FRAME_DATA for insufficient data to complete the frame
1057 		GIF_OK for successful decoding
1058 */
gif_skip_frame_extensions(gif_animation * gif)1059 static gif_result gif_skip_frame_extensions(gif_animation *gif) {
1060 	unsigned char *gif_data, *gif_end;
1061 	int gif_bytes;
1062 	unsigned int block_size;
1063 
1064 	/*	Get our buffer position etc.
1065 	*/
1066 	gif_data = (unsigned char *)(gif->gif_data + gif->buffer_position);
1067 	gif_end = (unsigned char *)(gif->gif_data + gif->buffer_size);
1068 	gif_bytes = (gif_end - gif_data);
1069 
1070 	/*	Skip the extensions
1071 	*/
1072 	while (gif_data[0] == GIF_EXTENSION_INTRODUCER) {
1073 		++gif_data;
1074 
1075 		/*	Switch on extension label
1076 		*/
1077 		switch(gif_data[0]) {
1078 			/*	Move the pointer to the first data sub-block
1079 			 *	1 byte for the extension label
1080 			*/
1081 			case GIF_EXTENSION_COMMENT:
1082 				++gif_data;
1083 				break;
1084 
1085 			/*	Move the pointer to the first data sub-block
1086 			 *	2 bytes for the extension label and size fields
1087 			 *	Skip the extension size itself
1088 			*/
1089 			default:
1090 				gif_data += (2 + gif_data[1]);
1091 		}
1092 
1093 		/*	Repeatedly skip blocks until we get a zero block or run out of data
1094 		 *	This data is ignored by this gif decoder
1095 		*/
1096 		gif_bytes = (gif_end - gif_data);
1097 		block_size = 0;
1098 		while (gif_data[0] != GIF_BLOCK_TERMINATOR) {
1099 			block_size = gif_data[0] + 1;
1100 			if ((gif_bytes -= block_size) < 0)
1101 				return GIF_INSUFFICIENT_FRAME_DATA;
1102 			gif_data += block_size;
1103 		}
1104 		++gif_data;
1105 	}
1106 
1107 	/*	Set buffer position and return
1108 	*/
1109 	gif->buffer_position = (gif_data - gif->gif_data);
1110 	return GIF_OK;
1111 }
1112 
gif_interlaced_line(int height,int y)1113 static unsigned int gif_interlaced_line(int height, int y) {
1114 	if ((y << 3) < height) return (y << 3);
1115 	y -= ((height + 7) >> 3);
1116 	if ((y << 3) < (height - 4)) return (y << 3) + 4;
1117 	y -= ((height + 3) >> 3);
1118 	if ((y << 2) < (height - 2)) return (y << 2) + 2;
1119 	y -= ((height + 1) >> 2);
1120 	return (y << 1) + 1;
1121 }
1122 
1123 /*	Releases any workspace held by the animation
1124 */
gif_finalise(gif_animation * gif)1125 void gif_finalise(gif_animation *gif) {
1126 	/*	Release all our memory blocks
1127 	*/
1128 	if (gif->frame_image) {
1129 		assert(gif->bitmap_callbacks.bitmap_destroy);
1130 		gif->bitmap_callbacks.bitmap_destroy(gif->frame_image);
1131 	}
1132 	gif->frame_image = NULL;
1133 	free(gif->frames);
1134 	gif->frames = NULL;
1135 	free(gif->local_colour_table);
1136 	gif->local_colour_table = NULL;
1137 	free(gif->global_colour_table);
1138 	gif->global_colour_table = NULL;
1139 }
1140 
1141 /**
1142  * Initialise LZW decoding
1143  */
gif_init_LZW(gif_animation * gif)1144 void gif_init_LZW(gif_animation *gif) {
1145 	int i;
1146 
1147 	gif->current_error = 0;
1148 	if (clear_code >= (1 << GIF_MAX_LZW)) {
1149 		stack_pointer = stack;
1150 		gif->current_error = GIF_FRAME_DATA_ERROR;
1151 		return;
1152 	}
1153 
1154 	/* initialise our table */
1155 	memset(table, 0x00, (1 << GIF_MAX_LZW) * 8);
1156 	for (i = 0; i < clear_code; ++i)
1157 		table[1][i] = i;
1158 
1159 	/* update our LZW parameters */
1160 	code_size = set_code_size + 1;
1161 	max_code_size = clear_code << 1;
1162 	max_code = clear_code + 2;
1163 	stack_pointer = stack;
1164 	do {
1165 		firstcode = oldcode = gif_next_code(gif, code_size);
1166 	} while (firstcode == clear_code);
1167 	*stack_pointer++ =firstcode;
1168 }
1169 
1170 
gif_next_LZW(gif_animation * gif)1171 static bool gif_next_LZW(gif_animation *gif) {
1172 	int code, incode;
1173 	int block_size;
1174 	int new_code;
1175 
1176 	code = gif_next_code(gif, code_size);
1177 	if (code < 0) {
1178 	  	gif->current_error = code;
1179 		return false;
1180 	} else if (code == clear_code) {
1181 		gif_init_LZW(gif);
1182 		return true;
1183 	} else if (code == end_code) {
1184 		/* skip to the end of our data so multi-image GIFs work */
1185 		if (zero_data_block) {
1186 			gif->current_error = GIF_FRAME_DATA_ERROR;
1187 			return false;
1188 		}
1189 		block_size = 0;
1190 		while (block_size != 1) {
1191 			block_size = gif->gif_data[gif->buffer_position] + 1;
1192 			gif->buffer_position += block_size;
1193 		}
1194 		gif->current_error = GIF_FRAME_DATA_ERROR;
1195 		return false;
1196 	}
1197 
1198 	incode = code;
1199 	if (code >= max_code) {
1200 		*stack_pointer++ = firstcode;
1201 		code = oldcode;
1202 	}
1203 
1204 	/* The following loop is the most important in the GIF decoding cycle as every
1205 	 * single pixel passes through it.
1206 	 *
1207 	 * Note: our stack is always big enough to hold a complete decompressed chunk. */
1208 	while (code >= clear_code) {
1209 		*stack_pointer++ = table[1][code];
1210 		new_code = table[0][code];
1211 		if (new_code < clear_code) {
1212 			code = new_code;
1213 			break;
1214 		}
1215 		*stack_pointer++ = table[1][new_code];
1216 		code = table[0][new_code];
1217 		if (code == new_code) {
1218 		  	gif->current_error = GIF_FRAME_DATA_ERROR;
1219 			return false;
1220 		}
1221 	}
1222 
1223 	*stack_pointer++ = firstcode = table[1][code];
1224 
1225 	if ((code = max_code) < (1 << GIF_MAX_LZW)) {
1226 		table[0][code] = oldcode;
1227 		table[1][code] = firstcode;
1228 		++max_code;
1229 		if ((max_code >= max_code_size) && (max_code_size < (1 << GIF_MAX_LZW))) {
1230 			max_code_size = max_code_size << 1;
1231 			++code_size;
1232 		}
1233 	}
1234 	oldcode = incode;
1235 	return true;
1236 }
1237 
gif_next_code(gif_animation * gif,int code_size)1238 static int gif_next_code(gif_animation *gif, int code_size) {
1239 	int i, j, end, count, ret;
1240 	unsigned char *b;
1241 
1242 	end = curbit + code_size;
1243 	if (end >= lastbit) {
1244 		if (get_done)
1245 			return GIF_END_OF_FRAME;
1246 		buf[0] = direct[last_byte - 2];
1247 		buf[1] = direct[last_byte - 1];
1248 
1249 		/* get the next block */
1250 		direct = gif->gif_data + gif->buffer_position;
1251 		zero_data_block = ((count = direct[0]) == 0);
1252 		if ((gif->buffer_position + count) >= gif->buffer_size)
1253 			return GIF_INSUFFICIENT_FRAME_DATA;
1254 		if (count == 0)
1255 			get_done = true;
1256 		else {
1257 			direct -= 1;
1258 			buf[2] = direct[2];
1259 			buf[3] = direct[3];
1260 		}
1261 		gif->buffer_position += count + 1;
1262 
1263 		/* update our variables */
1264 		last_byte = 2 + count;
1265 		curbit = (curbit - lastbit) + 16;
1266 		lastbit = (2 + count) << 3;
1267 		end = curbit + code_size;
1268 	}
1269 
1270 	i = curbit >> 3;
1271 	if (i < 2)
1272 		b = buf;
1273 	else
1274 		b = direct;
1275 
1276 	ret = b[i];
1277 	j = (end >> 3) - 1;
1278 	if (i <= j) {
1279 		ret |= (b[i + 1] << 8);
1280 		if (i < j)
1281 			ret |= (b[i + 2] << 16);
1282 	}
1283 	ret = (ret >> (curbit % 8)) & maskTbl[code_size];
1284 	curbit += code_size;
1285 	return ret;
1286 }
1287