push 5b1efc32b5a8acb1d5b5e60584746392dd0c436e
[wine/hacks.git] / dlls / windowscodecs / ungif.c
blobcfc7613cd4d2202c616b1f1ec6d95cc7392d1403
1 /*
2 * Gif extracting routines - derived from libungif
4 * Portions Copyright 2006 Mike McCormack
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 * Original copyright notice:
24 * The GIFLIB distribution is Copyright (c) 1997 Eric S. Raymond
26 * Permission is hereby granted, free of charge, to any person obtaining a copy
27 * of this software and associated documentation files (the "Software"), to deal
28 * in the Software without restriction, including without limitation the rights
29 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
30 * copies of the Software, and to permit persons to whom the Software is
31 * furnished to do so, subject to the following conditions:
33 * The above copyright notice and this permission notice shall be included in
34 * all copies or substantial portions of the Software.
38 /******************************************************************************
39 * "Gif-Lib" - Yet another gif library.
41 * Written by: Gershon Elber IBM PC Ver 1.1, Aug. 1990
42 ******************************************************************************
43 * The kernel of the GIF Decoding process can be found here.
44 ******************************************************************************
45 * History:
46 * 16 Jun 89 - Version 1.0 by Gershon Elber.
47 * 3 Sep 90 - Version 1.1 by Gershon Elber (Support for Gif89, Unique names).
48 *****************************************************************************/
50 #include <stdlib.h>
51 #include <string.h>
52 #include "ungif.h"
54 #include <stdarg.h>
55 #include "windef.h"
56 #include "winbase.h"
58 static void *ungif_alloc( size_t sz )
60 return HeapAlloc( GetProcessHeap(), 0, sz );
63 static void *ungif_calloc( size_t num, size_t sz )
65 return HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, num*sz );
68 static void *ungif_realloc( void *ptr, size_t sz )
70 return HeapReAlloc( GetProcessHeap(), 0, ptr, sz );
73 static void ungif_free( void *ptr )
75 HeapFree( GetProcessHeap(), 0, ptr );
78 #define LZ_MAX_CODE 4095 /* Biggest code possible in 12 bits. */
79 #define LZ_BITS 12
81 #define NO_SUCH_CODE 4098 /* Impossible code, to signal empty. */
83 typedef struct GifFilePrivateType {
84 GifWord BitsPerPixel, /* Bits per pixel (Codes uses at least this + 1). */
85 ClearCode, /* The CLEAR LZ code. */
86 EOFCode, /* The EOF LZ code. */
87 RunningCode, /* The next code algorithm can generate. */
88 RunningBits, /* The number of bits required to represent RunningCode. */
89 MaxCode1, /* 1 bigger than max. possible code, in RunningBits bits. */
90 LastCode, /* The code before the current code. */
91 CrntCode, /* Current algorithm code. */
92 StackPtr, /* For character stack (see below). */
93 CrntShiftState; /* Number of bits in CrntShiftDWord. */
94 unsigned long CrntShiftDWord; /* For bytes decomposition into codes. */
95 unsigned long PixelCount; /* Number of pixels in image. */
96 InputFunc Read; /* function to read gif input (TVT) */
97 GifByteType Buf[256]; /* Compressed input is buffered here. */
98 GifByteType Stack[LZ_MAX_CODE]; /* Decoded pixels are stacked here. */
99 GifByteType Suffix[LZ_MAX_CODE + 1]; /* So we can trace the codes. */
100 GifPrefixType Prefix[LZ_MAX_CODE + 1];
101 } GifFilePrivateType;
103 /* avoid extra function call in case we use fread (TVT) */
104 #define READ(_gif,_buf,_len) \
105 ((GifFilePrivateType*)_gif->Private)->Read(_gif,_buf,_len)
107 static int DGifGetWord(GifFileType *GifFile, GifWord *Word);
108 static int DGifSetupDecompress(GifFileType *GifFile);
109 static int DGifDecompressLine(GifFileType *GifFile, GifPixelType *Line, int LineLen);
110 static int DGifGetPrefixChar(const GifPrefixType *Prefix, int Code, int ClearCode);
111 static int DGifDecompressInput(GifFileType *GifFile, int *Code);
112 static int DGifBufferedInput(GifFileType *GifFile, GifByteType *Buf,
113 GifByteType *NextByte);
115 static int DGifGetExtensionNext(GifFileType * GifFile, GifByteType ** GifExtension);
116 static int DGifGetCodeNext(GifFileType * GifFile, GifByteType ** GifCodeBlock);
118 /******************************************************************************
119 * Miscellaneous utility functions
120 *****************************************************************************/
122 /* return smallest bitfield size n will fit in */
123 static int
124 BitSize(int n) {
126 register int i;
128 for (i = 1; i <= 8; i++)
129 if ((1 << i) >= n)
130 break;
131 return (i);
134 /******************************************************************************
135 * Color map object functions
136 *****************************************************************************/
139 * Allocate a color map of given size; initialize with contents of
140 * ColorMap if that pointer is non-NULL.
142 static ColorMapObject *
143 MakeMapObject(int ColorCount,
144 const GifColorType * ColorMap) {
146 ColorMapObject *Object;
148 /*** FIXME: Our ColorCount has to be a power of two. Is it necessary to
149 * make the user know that or should we automatically round up instead? */
150 if (ColorCount != (1 << BitSize(ColorCount))) {
151 return NULL;
154 Object = ungif_alloc(sizeof(ColorMapObject));
155 if (Object == NULL) {
156 return NULL;
159 Object->Colors = ungif_calloc(ColorCount, sizeof(GifColorType));
160 if (Object->Colors == NULL) {
161 return NULL;
164 Object->ColorCount = ColorCount;
165 Object->BitsPerPixel = BitSize(ColorCount);
167 if (ColorMap) {
168 memcpy(Object->Colors, ColorMap, ColorCount * sizeof(GifColorType));
171 return (Object);
175 * Free a color map object
177 static void
178 FreeMapObject(ColorMapObject * Object) {
180 if (Object != NULL) {
181 ungif_free(Object->Colors);
182 ungif_free(Object);
183 /*** FIXME:
184 * When we are willing to break API we need to make this function
185 * FreeMapObject(ColorMapObject **Object)
186 * and do this assignment to NULL here:
187 * *Object = NULL;
192 static int
193 AddExtensionBlock(SavedImage * New,
194 int Len,
195 const unsigned char ExtData[]) {
197 ExtensionBlock *ep;
199 if (New->ExtensionBlocks == NULL)
200 New->ExtensionBlocks = ungif_alloc(sizeof(ExtensionBlock));
201 else
202 New->ExtensionBlocks = ungif_realloc(New->ExtensionBlocks,
203 sizeof(ExtensionBlock) *
204 (New->ExtensionBlockCount + 1));
206 if (New->ExtensionBlocks == NULL)
207 return (GIF_ERROR);
209 ep = &New->ExtensionBlocks[New->ExtensionBlockCount++];
211 ep->ByteCount=Len;
212 ep->Bytes = ungif_alloc(ep->ByteCount);
213 if (ep->Bytes == NULL)
214 return (GIF_ERROR);
216 if (ExtData) {
217 memcpy(ep->Bytes, ExtData, Len);
218 ep->Function = New->Function;
221 return (GIF_OK);
224 static void
225 FreeExtension(SavedImage * Image)
227 ExtensionBlock *ep;
229 if ((Image == NULL) || (Image->ExtensionBlocks == NULL)) {
230 return;
232 for (ep = Image->ExtensionBlocks;
233 ep < (Image->ExtensionBlocks + Image->ExtensionBlockCount); ep++)
234 ungif_free(ep->Bytes);
235 ungif_free(Image->ExtensionBlocks);
236 Image->ExtensionBlocks = NULL;
239 /******************************************************************************
240 * Image block allocation functions
241 ******************************************************************************/
243 static void
244 FreeSavedImages(GifFileType * GifFile) {
246 SavedImage *sp;
248 if ((GifFile == NULL) || (GifFile->SavedImages == NULL)) {
249 return;
251 for (sp = GifFile->SavedImages;
252 sp < GifFile->SavedImages + GifFile->ImageCount; sp++) {
253 if (sp->ImageDesc.ColorMap) {
254 FreeMapObject(sp->ImageDesc.ColorMap);
255 sp->ImageDesc.ColorMap = NULL;
258 ungif_free(sp->RasterBits);
260 if (sp->ExtensionBlocks)
261 FreeExtension(sp);
263 ungif_free(GifFile->SavedImages);
264 GifFile->SavedImages=NULL;
267 /******************************************************************************
268 * This routine should be called before any other DGif calls. Note that
269 * this routine is called automatically from DGif file open routines.
270 *****************************************************************************/
271 static int
272 DGifGetScreenDesc(GifFileType * GifFile) {
274 int i, BitsPerPixel;
275 GifByteType Buf[3];
277 /* Put the screen descriptor into the file: */
278 if (DGifGetWord(GifFile, &GifFile->SWidth) == GIF_ERROR ||
279 DGifGetWord(GifFile, &GifFile->SHeight) == GIF_ERROR)
280 return GIF_ERROR;
282 if (READ(GifFile, Buf, 3) != 3) {
283 return GIF_ERROR;
285 GifFile->SColorResolution = (((Buf[0] & 0x70) + 1) >> 4) + 1;
286 BitsPerPixel = (Buf[0] & 0x07) + 1;
287 GifFile->SBackGroundColor = Buf[1];
288 if (Buf[0] & 0x80) { /* Do we have global color map? */
290 GifFile->SColorMap = MakeMapObject(1 << BitsPerPixel, NULL);
291 if (GifFile->SColorMap == NULL) {
292 return GIF_ERROR;
295 /* Get the global color map: */
296 for (i = 0; i < GifFile->SColorMap->ColorCount; i++) {
297 if (READ(GifFile, Buf, 3) != 3) {
298 FreeMapObject(GifFile->SColorMap);
299 GifFile->SColorMap = NULL;
300 return GIF_ERROR;
302 GifFile->SColorMap->Colors[i].Red = Buf[0];
303 GifFile->SColorMap->Colors[i].Green = Buf[1];
304 GifFile->SColorMap->Colors[i].Blue = Buf[2];
306 } else {
307 GifFile->SColorMap = NULL;
310 return GIF_OK;
313 /******************************************************************************
314 * This routine should be called before any attempt to read an image.
315 *****************************************************************************/
316 static int
317 DGifGetRecordType(GifFileType * GifFile,
318 GifRecordType * Type) {
320 GifByteType Buf;
322 if (READ(GifFile, &Buf, 1) != 1) {
323 /* Wine-specific behavior: Native accepts broken GIF files that have no
324 * terminator, so we match this by treating EOF as a terminator. */
325 *Type = TERMINATE_RECORD_TYPE;
326 return GIF_OK;
329 switch (Buf) {
330 case ',':
331 *Type = IMAGE_DESC_RECORD_TYPE;
332 break;
333 case '!':
334 *Type = EXTENSION_RECORD_TYPE;
335 break;
336 case ';':
337 *Type = TERMINATE_RECORD_TYPE;
338 break;
339 default:
340 *Type = UNDEFINED_RECORD_TYPE;
341 return GIF_ERROR;
344 return GIF_OK;
347 /******************************************************************************
348 * This routine should be called before any attempt to read an image.
349 * Note it is assumed the Image desc. header (',') has been read.
350 *****************************************************************************/
351 static int
352 DGifGetImageDesc(GifFileType * GifFile) {
354 int i, BitsPerPixel;
355 GifByteType Buf[3];
356 GifFilePrivateType *Private = GifFile->Private;
357 SavedImage *sp;
359 if (DGifGetWord(GifFile, &GifFile->Image.Left) == GIF_ERROR ||
360 DGifGetWord(GifFile, &GifFile->Image.Top) == GIF_ERROR ||
361 DGifGetWord(GifFile, &GifFile->Image.Width) == GIF_ERROR ||
362 DGifGetWord(GifFile, &GifFile->Image.Height) == GIF_ERROR)
363 return GIF_ERROR;
364 if (READ(GifFile, Buf, 1) != 1) {
365 return GIF_ERROR;
367 BitsPerPixel = (Buf[0] & 0x07) + 1;
368 GifFile->Image.Interlace = (Buf[0] & 0x40);
369 if (Buf[0] & 0x80) { /* Does this image have local color map? */
371 /*** FIXME: Why do we check both of these in order to do this?
372 * Why do we have both Image and SavedImages? */
373 if (GifFile->Image.ColorMap && GifFile->SavedImages == NULL)
374 FreeMapObject(GifFile->Image.ColorMap);
376 GifFile->Image.ColorMap = MakeMapObject(1 << BitsPerPixel, NULL);
377 if (GifFile->Image.ColorMap == NULL) {
378 return GIF_ERROR;
381 /* Get the image local color map: */
382 for (i = 0; i < GifFile->Image.ColorMap->ColorCount; i++) {
383 if (READ(GifFile, Buf, 3) != 3) {
384 FreeMapObject(GifFile->Image.ColorMap);
385 GifFile->Image.ColorMap = NULL;
386 return GIF_ERROR;
388 GifFile->Image.ColorMap->Colors[i].Red = Buf[0];
389 GifFile->Image.ColorMap->Colors[i].Green = Buf[1];
390 GifFile->Image.ColorMap->Colors[i].Blue = Buf[2];
392 } else if (GifFile->Image.ColorMap) {
393 FreeMapObject(GifFile->Image.ColorMap);
394 GifFile->Image.ColorMap = NULL;
397 if (GifFile->SavedImages) {
398 if ((GifFile->SavedImages = ungif_realloc(GifFile->SavedImages,
399 sizeof(SavedImage) *
400 (GifFile->ImageCount + 1))) == NULL) {
401 return GIF_ERROR;
403 } else {
404 if ((GifFile->SavedImages = ungif_alloc(sizeof(SavedImage))) == NULL) {
405 return GIF_ERROR;
409 sp = &GifFile->SavedImages[GifFile->ImageCount];
410 sp->ImageDesc = GifFile->Image;
411 if (GifFile->Image.ColorMap != NULL) {
412 sp->ImageDesc.ColorMap = MakeMapObject(
413 GifFile->Image.ColorMap->ColorCount,
414 GifFile->Image.ColorMap->Colors);
415 if (sp->ImageDesc.ColorMap == NULL) {
416 return GIF_ERROR;
419 sp->RasterBits = NULL;
420 sp->ExtensionBlockCount = 0;
421 sp->ExtensionBlocks = NULL;
423 GifFile->ImageCount++;
425 Private->PixelCount = (long)GifFile->Image.Width *
426 (long)GifFile->Image.Height;
428 DGifSetupDecompress(GifFile); /* Reset decompress algorithm parameters. */
430 return GIF_OK;
433 /******************************************************************************
434 * Get one full scanned line (Line) of length LineLen from GIF file.
435 *****************************************************************************/
436 static int
437 DGifGetLine(GifFileType * GifFile,
438 GifPixelType * Line,
439 int LineLen) {
441 GifByteType *Dummy;
442 GifFilePrivateType *Private = GifFile->Private;
444 if (!LineLen)
445 LineLen = GifFile->Image.Width;
447 if ((Private->PixelCount -= LineLen) > 0xffff0000UL) {
448 return GIF_ERROR;
451 if (DGifDecompressLine(GifFile, Line, LineLen) == GIF_OK) {
452 if (Private->PixelCount == 0) {
453 /* We probably would not be called any more, so lets clean
454 * everything before we return: need to flush out all rest of
455 * image until empty block (size 0) detected. We use GetCodeNext. */
457 if (DGifGetCodeNext(GifFile, &Dummy) == GIF_ERROR)
458 return GIF_ERROR;
459 while (Dummy != NULL) ;
461 return GIF_OK;
462 } else
463 return GIF_ERROR;
466 /******************************************************************************
467 * Get an extension block (see GIF manual) from gif file. This routine only
468 * returns the first data block, and DGifGetExtensionNext should be called
469 * after this one until NULL extension is returned.
470 * The Extension should NOT be freed by the user (not dynamically allocated).
471 * Note it is assumed the Extension desc. header ('!') has been read.
472 *****************************************************************************/
473 static int
474 DGifGetExtension(GifFileType * GifFile,
475 int *ExtCode,
476 GifByteType ** Extension) {
478 GifByteType Buf;
480 if (READ(GifFile, &Buf, 1) != 1) {
481 return GIF_ERROR;
483 *ExtCode = Buf;
485 return DGifGetExtensionNext(GifFile, Extension);
488 /******************************************************************************
489 * Get a following extension block (see GIF manual) from gif file. This
490 * routine should be called until NULL Extension is returned.
491 * The Extension should NOT be freed by the user (not dynamically allocated).
492 *****************************************************************************/
493 static int
494 DGifGetExtensionNext(GifFileType * GifFile,
495 GifByteType ** Extension) {
497 GifByteType Buf;
498 GifFilePrivateType *Private = GifFile->Private;
500 if (READ(GifFile, &Buf, 1) != 1) {
501 return GIF_ERROR;
503 if (Buf > 0) {
504 *Extension = Private->Buf; /* Use private unused buffer. */
505 (*Extension)[0] = Buf; /* Pascal strings notation (pos. 0 is len.). */
506 if (READ(GifFile, &((*Extension)[1]), Buf) != Buf) {
507 return GIF_ERROR;
509 } else
510 *Extension = NULL;
512 return GIF_OK;
515 /******************************************************************************
516 * Get 2 bytes (word) from the given file:
517 *****************************************************************************/
518 static int
519 DGifGetWord(GifFileType * GifFile,
520 GifWord *Word) {
522 unsigned char c[2];
524 if (READ(GifFile, c, 2) != 2) {
525 return GIF_ERROR;
528 *Word = (((unsigned int)c[1]) << 8) + c[0];
529 return GIF_OK;
532 /******************************************************************************
533 * Continue to get the image code in compressed form. This routine should be
534 * called until NULL block is returned.
535 * The block should NOT be freed by the user (not dynamically allocated).
536 *****************************************************************************/
537 static int
538 DGifGetCodeNext(GifFileType * GifFile,
539 GifByteType ** CodeBlock) {
541 GifByteType Buf;
542 GifFilePrivateType *Private = GifFile->Private;
544 if (READ(GifFile, &Buf, 1) != 1) {
545 return GIF_ERROR;
548 if (Buf > 0) {
549 *CodeBlock = Private->Buf; /* Use private unused buffer. */
550 (*CodeBlock)[0] = Buf; /* Pascal strings notation (pos. 0 is len.). */
551 if (READ(GifFile, &((*CodeBlock)[1]), Buf) != Buf) {
552 return GIF_ERROR;
554 } else {
555 *CodeBlock = NULL;
556 Private->Buf[0] = 0; /* Make sure the buffer is empty! */
557 Private->PixelCount = 0; /* And local info. indicate image read. */
560 return GIF_OK;
563 /******************************************************************************
564 * Setup the LZ decompression for this image:
565 *****************************************************************************/
566 static int
567 DGifSetupDecompress(GifFileType * GifFile) {
569 int i, BitsPerPixel;
570 GifByteType CodeSize;
571 GifPrefixType *Prefix;
572 GifFilePrivateType *Private = GifFile->Private;
574 READ(GifFile, &CodeSize, 1); /* Read Code size from file. */
575 BitsPerPixel = CodeSize;
577 Private->Buf[0] = 0; /* Input Buffer empty. */
578 Private->BitsPerPixel = BitsPerPixel;
579 Private->ClearCode = (1 << BitsPerPixel);
580 Private->EOFCode = Private->ClearCode + 1;
581 Private->RunningCode = Private->EOFCode + 1;
582 Private->RunningBits = BitsPerPixel + 1; /* Number of bits per code. */
583 Private->MaxCode1 = 1 << Private->RunningBits; /* Max. code + 1. */
584 Private->StackPtr = 0; /* No pixels on the pixel stack. */
585 Private->LastCode = NO_SUCH_CODE;
586 Private->CrntShiftState = 0; /* No information in CrntShiftDWord. */
587 Private->CrntShiftDWord = 0;
589 Prefix = Private->Prefix;
590 for (i = 0; i <= LZ_MAX_CODE; i++)
591 Prefix[i] = NO_SUCH_CODE;
593 return GIF_OK;
596 /******************************************************************************
597 * The LZ decompression routine:
598 * This version decompress the given gif file into Line of length LineLen.
599 * This routine can be called few times (one per scan line, for example), in
600 * order the complete the whole image.
601 *****************************************************************************/
602 static int
603 DGifDecompressLine(GifFileType * GifFile,
604 GifPixelType * Line,
605 int LineLen) {
607 int i = 0;
608 int j, CrntCode, EOFCode, ClearCode, CrntPrefix, LastCode, StackPtr;
609 GifByteType *Stack, *Suffix;
610 GifPrefixType *Prefix;
611 GifFilePrivateType *Private = GifFile->Private;
613 StackPtr = Private->StackPtr;
614 Prefix = Private->Prefix;
615 Suffix = Private->Suffix;
616 Stack = Private->Stack;
617 EOFCode = Private->EOFCode;
618 ClearCode = Private->ClearCode;
619 LastCode = Private->LastCode;
621 if (StackPtr != 0) {
622 /* Let pop the stack off before continuing to read the gif file: */
623 while (StackPtr != 0 && i < LineLen)
624 Line[i++] = Stack[--StackPtr];
627 while (i < LineLen) { /* Decode LineLen items. */
628 if (DGifDecompressInput(GifFile, &CrntCode) == GIF_ERROR)
629 return GIF_ERROR;
631 if (CrntCode == EOFCode) {
632 /* Note, however, that usually we will not be here as we will stop
633 * decoding as soon as we got all the pixel, or EOF code will
634 * not be read at all, and DGifGetLine/Pixel clean everything. */
635 if (i != LineLen - 1 || Private->PixelCount != 0) {
636 return GIF_ERROR;
638 i++;
639 } else if (CrntCode == ClearCode) {
640 /* We need to start over again: */
641 for (j = 0; j <= LZ_MAX_CODE; j++)
642 Prefix[j] = NO_SUCH_CODE;
643 Private->RunningCode = Private->EOFCode + 1;
644 Private->RunningBits = Private->BitsPerPixel + 1;
645 Private->MaxCode1 = 1 << Private->RunningBits;
646 LastCode = Private->LastCode = NO_SUCH_CODE;
647 } else {
648 /* It's a regular code - if in pixel range simply add it to output
649 * stream, otherwise trace to codes linked list until the prefix
650 * is in pixel range: */
651 if (CrntCode < ClearCode) {
652 /* This is simple - its pixel scalar, so add it to output: */
653 Line[i++] = CrntCode;
654 } else {
655 /* It's a code to be traced: trace the linked list
656 * until the prefix is a pixel, while pushing the suffix
657 * pixels on our stack. If we done, pop the stack in reverse
658 * order (that's what stack is good for!) for output. */
659 if (Prefix[CrntCode] == NO_SUCH_CODE) {
660 /* Only allowed if CrntCode is exactly the running code:
661 * In that case CrntCode = XXXCode, CrntCode or the
662 * prefix code is last code and the suffix char is
663 * exactly the prefix of last code! */
664 if (CrntCode == Private->RunningCode - 2) {
665 CrntPrefix = LastCode;
666 Suffix[Private->RunningCode - 2] =
667 Stack[StackPtr++] = DGifGetPrefixChar(Prefix,
668 LastCode,
669 ClearCode);
670 } else {
671 return GIF_ERROR;
673 } else
674 CrntPrefix = CrntCode;
676 /* Now (if image is O.K.) we should not get a NO_SUCH_CODE
677 * during the trace. As we might loop forever, in case of
678 * defective image, we count the number of loops we trace
679 * and stop if we got LZ_MAX_CODE. Obviously we cannot
680 * loop more than that. */
681 j = 0;
682 while (j++ <= LZ_MAX_CODE &&
683 CrntPrefix > ClearCode && CrntPrefix <= LZ_MAX_CODE) {
684 Stack[StackPtr++] = Suffix[CrntPrefix];
685 CrntPrefix = Prefix[CrntPrefix];
687 if (j >= LZ_MAX_CODE || CrntPrefix > LZ_MAX_CODE) {
688 return GIF_ERROR;
690 /* Push the last character on stack: */
691 Stack[StackPtr++] = CrntPrefix;
693 /* Now lets pop all the stack into output: */
694 while (StackPtr != 0 && i < LineLen)
695 Line[i++] = Stack[--StackPtr];
697 if (LastCode != NO_SUCH_CODE) {
698 Prefix[Private->RunningCode - 2] = LastCode;
700 if (CrntCode == Private->RunningCode - 2) {
701 /* Only allowed if CrntCode is exactly the running code:
702 * In that case CrntCode = XXXCode, CrntCode or the
703 * prefix code is last code and the suffix char is
704 * exactly the prefix of last code! */
705 Suffix[Private->RunningCode - 2] =
706 DGifGetPrefixChar(Prefix, LastCode, ClearCode);
707 } else {
708 Suffix[Private->RunningCode - 2] =
709 DGifGetPrefixChar(Prefix, CrntCode, ClearCode);
712 LastCode = CrntCode;
716 Private->LastCode = LastCode;
717 Private->StackPtr = StackPtr;
719 return GIF_OK;
722 /******************************************************************************
723 * Routine to trace the Prefixes linked list until we get a prefix which is
724 * not code, but a pixel value (less than ClearCode). Returns that pixel value.
725 * If image is defective, we might loop here forever, so we limit the loops to
726 * the maximum possible if image O.k. - LZ_MAX_CODE times.
727 *****************************************************************************/
728 static int
729 DGifGetPrefixChar(const GifPrefixType *Prefix,
730 int Code,
731 int ClearCode) {
733 int i = 0;
735 while (Code > ClearCode && i++ <= LZ_MAX_CODE)
736 Code = Prefix[Code];
737 return Code;
740 /******************************************************************************
741 * The LZ decompression input routine:
742 * This routine is responsible for the decompression of the bit stream from
743 * 8 bits (bytes) packets, into the real codes.
744 * Returns GIF_OK if read successfully.
745 *****************************************************************************/
746 static int
747 DGifDecompressInput(GifFileType * GifFile,
748 int *Code) {
750 GifFilePrivateType *Private = GifFile->Private;
752 GifByteType NextByte;
753 static const unsigned short CodeMasks[] = {
754 0x0000, 0x0001, 0x0003, 0x0007,
755 0x000f, 0x001f, 0x003f, 0x007f,
756 0x00ff, 0x01ff, 0x03ff, 0x07ff,
757 0x0fff
759 /* The image can't contain more than LZ_BITS per code. */
760 if (Private->RunningBits > LZ_BITS) {
761 return GIF_ERROR;
764 while (Private->CrntShiftState < Private->RunningBits) {
765 /* Needs to get more bytes from input stream for next code: */
766 if (DGifBufferedInput(GifFile, Private->Buf, &NextByte) == GIF_ERROR) {
767 return GIF_ERROR;
769 Private->CrntShiftDWord |=
770 ((unsigned long)NextByte) << Private->CrntShiftState;
771 Private->CrntShiftState += 8;
773 *Code = Private->CrntShiftDWord & CodeMasks[Private->RunningBits];
775 Private->CrntShiftDWord >>= Private->RunningBits;
776 Private->CrntShiftState -= Private->RunningBits;
778 /* If code cannot fit into RunningBits bits, must raise its size. Note
779 * however that codes above 4095 are used for special signaling.
780 * If we're using LZ_BITS bits already and we're at the max code, just
781 * keep using the table as it is, don't increment Private->RunningCode.
783 if (Private->RunningCode < LZ_MAX_CODE + 2 &&
784 ++Private->RunningCode > Private->MaxCode1 &&
785 Private->RunningBits < LZ_BITS) {
786 Private->MaxCode1 <<= 1;
787 Private->RunningBits++;
789 return GIF_OK;
792 /******************************************************************************
793 * This routines read one gif data block at a time and buffers it internally
794 * so that the decompression routine could access it.
795 * The routine returns the next byte from its internal buffer (or read next
796 * block in if buffer empty) and returns GIF_OK if successful.
797 *****************************************************************************/
798 static int
799 DGifBufferedInput(GifFileType * GifFile,
800 GifByteType * Buf,
801 GifByteType * NextByte) {
803 if (Buf[0] == 0) {
804 /* Needs to read the next buffer - this one is empty: */
805 if (READ(GifFile, Buf, 1) != 1) {
806 return GIF_ERROR;
808 /* There shouldn't be any empty data blocks here as the LZW spec
809 * says the LZW termination code should come first. Therefore we
810 * shouldn't be inside this routine at that point.
812 if (Buf[0] == 0) {
813 return GIF_ERROR;
815 if (READ(GifFile, &Buf[1], Buf[0]) != Buf[0]) {
816 return GIF_ERROR;
818 *NextByte = Buf[1];
819 Buf[1] = 2; /* We use now the second place as last char read! */
820 Buf[0]--;
821 } else {
822 *NextByte = Buf[Buf[1]++];
823 Buf[0]--;
826 return GIF_OK;
829 /******************************************************************************
830 * This routine reads an entire GIF into core, hanging all its state info off
831 * the GifFileType pointer. Call DGifOpenFileName() or DGifOpenFileHandle()
832 * first to initialize I/O. Its inverse is EGifSpew().
833 ******************************************************************************/
835 DGifSlurp(GifFileType * GifFile) {
837 int ImageSize;
838 GifRecordType RecordType;
839 SavedImage *sp;
840 GifByteType *ExtData;
841 SavedImage temp_save;
843 temp_save.ExtensionBlocks = NULL;
844 temp_save.ExtensionBlockCount = 0;
846 do {
847 if (DGifGetRecordType(GifFile, &RecordType) == GIF_ERROR)
848 return (GIF_ERROR);
850 switch (RecordType) {
851 case IMAGE_DESC_RECORD_TYPE:
852 if (DGifGetImageDesc(GifFile) == GIF_ERROR)
853 return (GIF_ERROR);
855 sp = &GifFile->SavedImages[GifFile->ImageCount - 1];
856 ImageSize = sp->ImageDesc.Width * sp->ImageDesc.Height;
858 sp->RasterBits = ungif_alloc(ImageSize * sizeof(GifPixelType));
859 if (sp->RasterBits == NULL) {
860 return GIF_ERROR;
862 if (DGifGetLine(GifFile, sp->RasterBits, ImageSize) ==
863 GIF_ERROR)
864 return (GIF_ERROR);
865 if (temp_save.ExtensionBlocks) {
866 sp->ExtensionBlocks = temp_save.ExtensionBlocks;
867 sp->ExtensionBlockCount = temp_save.ExtensionBlockCount;
869 temp_save.ExtensionBlocks = NULL;
870 temp_save.ExtensionBlockCount = 0;
872 /* FIXME: The following is wrong. It is left in only for
873 * backwards compatibility. Someday it should go away. Use
874 * the sp->ExtensionBlocks->Function variable instead. */
875 sp->Function = sp->ExtensionBlocks[0].Function;
877 break;
879 case EXTENSION_RECORD_TYPE:
880 if (DGifGetExtension(GifFile, &temp_save.Function, &ExtData) ==
881 GIF_ERROR)
882 return (GIF_ERROR);
883 while (ExtData != NULL) {
885 /* Create an extension block with our data */
886 if (AddExtensionBlock(&temp_save, ExtData[0], &ExtData[1])
887 == GIF_ERROR)
888 return (GIF_ERROR);
890 if (DGifGetExtensionNext(GifFile, &ExtData) == GIF_ERROR)
891 return (GIF_ERROR);
892 temp_save.Function = 0;
894 break;
896 case TERMINATE_RECORD_TYPE:
897 break;
899 default: /* Should be trapped by DGifGetRecordType */
900 break;
902 } while (RecordType != TERMINATE_RECORD_TYPE);
904 /* Just in case the Gif has an extension block without an associated
905 * image... (Should we save this into a savefile structure with no image
906 * instead? Have to check if the present writing code can handle that as
907 * well.... */
908 if (temp_save.ExtensionBlocks)
909 FreeExtension(&temp_save);
911 return (GIF_OK);
914 /******************************************************************************
915 * GifFileType constructor with user supplied input function (TVT)
916 *****************************************************************************/
917 GifFileType *
918 DGifOpen(void *userData,
919 InputFunc readFunc) {
921 unsigned char Buf[GIF_STAMP_LEN + 1];
922 GifFileType *GifFile;
923 GifFilePrivateType *Private;
925 GifFile = ungif_alloc(sizeof(GifFileType));
926 if (GifFile == NULL) {
927 return NULL;
930 memset(GifFile, '\0', sizeof(GifFileType));
932 Private = ungif_alloc(sizeof(GifFilePrivateType));
933 if (!Private) {
934 ungif_free(GifFile);
935 return NULL;
938 GifFile->Private = (void*)Private;
940 Private->Read = readFunc; /* TVT */
941 GifFile->UserData = userData; /* TVT */
943 /* Lets see if this is a GIF file: */
944 if (READ(GifFile, Buf, GIF_STAMP_LEN) != GIF_STAMP_LEN) {
945 ungif_free(Private);
946 ungif_free(GifFile);
947 return NULL;
950 /* The GIF Version number is ignored at this time. Maybe we should do
951 * something more useful with it. */
952 Buf[GIF_STAMP_LEN] = 0;
953 if (memcmp(GIF_STAMP, Buf, GIF_VERSION_POS) != 0) {
954 ungif_free(Private);
955 ungif_free(GifFile);
956 return NULL;
959 if (DGifGetScreenDesc(GifFile) == GIF_ERROR) {
960 ungif_free(Private);
961 ungif_free(GifFile);
962 return NULL;
965 return GifFile;
968 /******************************************************************************
969 * This routine should be called last, to close the GIF file.
970 *****************************************************************************/
972 DGifCloseFile(GifFileType * GifFile) {
974 GifFilePrivateType *Private;
976 if (GifFile == NULL)
977 return GIF_ERROR;
979 Private = GifFile->Private;
981 if (GifFile->Image.ColorMap) {
982 FreeMapObject(GifFile->Image.ColorMap);
983 GifFile->Image.ColorMap = NULL;
986 if (GifFile->SColorMap) {
987 FreeMapObject(GifFile->SColorMap);
988 GifFile->SColorMap = NULL;
991 ungif_free(Private);
992 Private = NULL;
994 if (GifFile->SavedImages) {
995 FreeSavedImages(GifFile);
996 GifFile->SavedImages = NULL;
999 ungif_free(GifFile);
1001 return GIF_OK;