msi: Store action data for deferred rollback actions too.
[wine] / dlls / windowscodecs / ungif.c
1 /*
2  * Gif extracting routines - derived from libungif
3  *
4  * Portions Copyright 2006 Mike McCormack
5  *
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.
10  *
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.
15  *
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
19  */
20
21 /*
22  * Original copyright notice:
23  *
24  * The GIFLIB distribution is Copyright (c) 1997  Eric S. Raymond
25  *
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:
32  *
33  * The above copyright notice and this permission notice shall be included in
34  * all copies or substantial portions of the Software.
35  */
36
37
38 /******************************************************************************
39  *   "Gif-Lib" - Yet another gif library.
40  *
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  *****************************************************************************/
49
50 #include <stdlib.h>
51 #include <string.h>
52 #include "ungif.h"
53
54 #include <stdarg.h>
55 #include "windef.h"
56 #include "winbase.h"
57
58 static void *ungif_alloc( size_t sz )
59 {
60     return HeapAlloc( GetProcessHeap(), 0, sz );
61 }
62
63 static void *ungif_calloc( size_t num, size_t sz )
64 {
65     return HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, num*sz );
66 }
67
68 static void *ungif_realloc( void *ptr, size_t sz )
69 {
70     return HeapReAlloc( GetProcessHeap(), 0, ptr, sz );
71 }
72
73 static void ungif_free( void *ptr )
74 {
75     HeapFree( GetProcessHeap(), 0, ptr );
76 }
77
78 #define LZ_MAX_CODE         4095    /* Biggest code possible in 12 bits. */
79 #define LZ_BITS             12
80
81 #define NO_SUCH_CODE        4098    /* Impossible code, to signal empty. */
82
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;
102
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)
106
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);
114
115 static int DGifGetExtensionNext(GifFileType * GifFile, GifByteType ** GifExtension);
116 static int DGifGetCodeNext(GifFileType * GifFile, GifByteType ** GifCodeBlock);
117
118 /******************************************************************************
119  * Miscellaneous utility functions
120  *****************************************************************************/
121
122 /* return smallest bitfield size n will fit in */
123 static int
124 BitSize(int n) {
125
126     register int i;
127
128     for (i = 1; i <= 8; i++)
129         if ((1 << i) >= n)
130             break;
131     return (i);
132 }
133
134 /******************************************************************************
135  * Color map object functions
136  *****************************************************************************/
137
138 /*
139  * Allocate a color map of given size; initialize with contents of
140  * ColorMap if that pointer is non-NULL.
141  */
142 static ColorMapObject *
143 MakeMapObject(int ColorCount,
144               const GifColorType * ColorMap) {
145
146     ColorMapObject *Object;
147
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;
152     }
153
154     Object = ungif_alloc(sizeof(ColorMapObject));
155     if (Object == NULL) {
156         return NULL;
157     }
158
159     Object->Colors = ungif_calloc(ColorCount, sizeof(GifColorType));
160     if (Object->Colors == NULL) {
161         return NULL;
162     }
163
164     Object->ColorCount = ColorCount;
165     Object->BitsPerPixel = BitSize(ColorCount);
166
167     if (ColorMap) {
168         memcpy(Object->Colors, ColorMap, ColorCount * sizeof(GifColorType));
169     }
170
171     return (Object);
172 }
173
174 /*
175  * Free a color map object
176  */
177 static void
178 FreeMapObject(ColorMapObject * Object) {
179
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;
188          */
189     }
190 }
191
192 static int
193 AddExtensionBlock(SavedImage * New,
194                   int Len,
195                   const unsigned char ExtData[]) {
196
197     ExtensionBlock *ep;
198
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));
205
206     if (New->ExtensionBlocks == NULL)
207         return (GIF_ERROR);
208
209     ep = &New->ExtensionBlocks[New->ExtensionBlockCount++];
210
211     ep->ByteCount=Len;
212     ep->Bytes = ungif_alloc(ep->ByteCount);
213     if (ep->Bytes == NULL)
214         return (GIF_ERROR);
215
216     if (ExtData) {
217         memcpy(ep->Bytes, ExtData, Len);
218         ep->Function = New->Function;
219     }
220
221     return (GIF_OK);
222 }
223
224 static void
225 FreeExtension(SavedImage * Image)
226 {
227     ExtensionBlock *ep;
228
229     if ((Image == NULL) || (Image->ExtensionBlocks == NULL)) {
230         return;
231     }
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;
237 }
238
239 /******************************************************************************
240  * Image block allocation functions
241 ******************************************************************************/
242
243 static void
244 FreeSavedImages(GifFileType * GifFile) {
245
246     SavedImage *sp;
247
248     if ((GifFile == NULL) || (GifFile->SavedImages == NULL)) {
249         return;
250     }
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;
256         }
257
258         ungif_free(sp->RasterBits);
259
260         if (sp->ExtensionBlocks)
261             FreeExtension(sp);
262     }
263     ungif_free(GifFile->SavedImages);
264     GifFile->SavedImages=NULL;
265 }
266
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) {
273
274     int i, BitsPerPixel;
275     GifByteType Buf[3];
276
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;
281
282     if (READ(GifFile, Buf, 3) != 3) {
283         return GIF_ERROR;
284     }
285     GifFile->SColorResolution = (((Buf[0] & 0x70) + 1) >> 4) + 1;
286     BitsPerPixel = (Buf[0] & 0x07) + 1;
287     GifFile->SBackGroundColor = Buf[1];
288     GifFile->SAspectRatio = Buf[2];
289     if (Buf[0] & 0x80) {    /* Do we have global color map? */
290
291         GifFile->SColorMap = MakeMapObject(1 << BitsPerPixel, NULL);
292         if (GifFile->SColorMap == NULL) {
293             return GIF_ERROR;
294         }
295
296         /* Get the global color map: */
297         for (i = 0; i < GifFile->SColorMap->ColorCount; i++) {
298             if (READ(GifFile, Buf, 3) != 3) {
299                 FreeMapObject(GifFile->SColorMap);
300                 GifFile->SColorMap = NULL;
301                 return GIF_ERROR;
302             }
303             GifFile->SColorMap->Colors[i].Red = Buf[0];
304             GifFile->SColorMap->Colors[i].Green = Buf[1];
305             GifFile->SColorMap->Colors[i].Blue = Buf[2];
306         }
307     } else {
308         GifFile->SColorMap = NULL;
309     }
310
311     return GIF_OK;
312 }
313
314 /******************************************************************************
315  * This routine should be called before any attempt to read an image.
316  *****************************************************************************/
317 static int
318 DGifGetRecordType(GifFileType * GifFile,
319                   GifRecordType * Type) {
320
321     GifByteType Buf;
322
323     if (READ(GifFile, &Buf, 1) != 1) {
324         /* Wine-specific behavior: Native accepts broken GIF files that have no
325          * terminator, so we match this by treating EOF as a terminator. */
326         *Type = TERMINATE_RECORD_TYPE;
327         return GIF_OK;
328     }
329
330     switch (Buf) {
331       case ',':
332           *Type = IMAGE_DESC_RECORD_TYPE;
333           break;
334       case '!':
335           *Type = EXTENSION_RECORD_TYPE;
336           break;
337       case ';':
338           *Type = TERMINATE_RECORD_TYPE;
339           break;
340       default:
341           *Type = UNDEFINED_RECORD_TYPE;
342           return GIF_ERROR;
343     }
344
345     return GIF_OK;
346 }
347
348 /******************************************************************************
349  * This routine should be called before any attempt to read an image.
350  * Note it is assumed the Image desc. header (',') has been read.
351  *****************************************************************************/
352 static int
353 DGifGetImageDesc(GifFileType * GifFile) {
354
355     int i, BitsPerPixel;
356     GifByteType Buf[3];
357     GifFilePrivateType *Private = GifFile->Private;
358     SavedImage *sp;
359
360     if (DGifGetWord(GifFile, &GifFile->Image.Left) == GIF_ERROR ||
361         DGifGetWord(GifFile, &GifFile->Image.Top) == GIF_ERROR ||
362         DGifGetWord(GifFile, &GifFile->Image.Width) == GIF_ERROR ||
363         DGifGetWord(GifFile, &GifFile->Image.Height) == GIF_ERROR)
364         return GIF_ERROR;
365     if (READ(GifFile, Buf, 1) != 1) {
366         return GIF_ERROR;
367     }
368     BitsPerPixel = (Buf[0] & 0x07) + 1;
369     GifFile->Image.Interlace = (Buf[0] & 0x40);
370     if (Buf[0] & 0x80) {    /* Does this image have local color map? */
371
372         /*** FIXME: Why do we check both of these in order to do this?
373          * Why do we have both Image and SavedImages? */
374         if (GifFile->Image.ColorMap && GifFile->SavedImages == NULL)
375             FreeMapObject(GifFile->Image.ColorMap);
376
377         GifFile->Image.ColorMap = MakeMapObject(1 << BitsPerPixel, NULL);
378         if (GifFile->Image.ColorMap == NULL) {
379             return GIF_ERROR;
380         }
381
382         /* Get the image local color map: */
383         for (i = 0; i < GifFile->Image.ColorMap->ColorCount; i++) {
384             if (READ(GifFile, Buf, 3) != 3) {
385                 FreeMapObject(GifFile->Image.ColorMap);
386                 GifFile->Image.ColorMap = NULL;
387                 return GIF_ERROR;
388             }
389             GifFile->Image.ColorMap->Colors[i].Red = Buf[0];
390             GifFile->Image.ColorMap->Colors[i].Green = Buf[1];
391             GifFile->Image.ColorMap->Colors[i].Blue = Buf[2];
392         }
393     } else if (GifFile->Image.ColorMap) {
394         FreeMapObject(GifFile->Image.ColorMap);
395         GifFile->Image.ColorMap = NULL;
396     }
397
398     if (GifFile->SavedImages) {
399         if ((GifFile->SavedImages = ungif_realloc(GifFile->SavedImages,
400                                       sizeof(SavedImage) *
401                                       (GifFile->ImageCount + 1))) == NULL) {
402             return GIF_ERROR;
403         }
404     } else {
405         if ((GifFile->SavedImages = ungif_alloc(sizeof(SavedImage))) == NULL) {
406             return GIF_ERROR;
407         }
408     }
409
410     sp = &GifFile->SavedImages[GifFile->ImageCount];
411     sp->ImageDesc = GifFile->Image;
412     if (GifFile->Image.ColorMap != NULL) {
413         sp->ImageDesc.ColorMap = MakeMapObject(
414                                  GifFile->Image.ColorMap->ColorCount,
415                                  GifFile->Image.ColorMap->Colors);
416         if (sp->ImageDesc.ColorMap == NULL) {
417             return GIF_ERROR;
418         }
419     }
420     sp->RasterBits = NULL;
421     sp->ExtensionBlockCount = 0;
422     sp->ExtensionBlocks = NULL;
423
424     GifFile->ImageCount++;
425
426     Private->PixelCount = (long)GifFile->Image.Width *
427        (long)GifFile->Image.Height;
428
429     DGifSetupDecompress(GifFile);  /* Reset decompress algorithm parameters. */
430
431     return GIF_OK;
432 }
433
434 /******************************************************************************
435  * Get one full scanned line (Line) of length LineLen from GIF file.
436  *****************************************************************************/
437 static int
438 DGifGetLine(GifFileType * GifFile,
439             GifPixelType * Line,
440             int LineLen) {
441
442     GifByteType *Dummy;
443     GifFilePrivateType *Private = GifFile->Private;
444
445     if (!LineLen)
446         LineLen = GifFile->Image.Width;
447
448     if ((Private->PixelCount -= LineLen) > 0xffff0000UL) {
449         return GIF_ERROR;
450     }
451
452     if (DGifDecompressLine(GifFile, Line, LineLen) == GIF_OK) {
453         if (Private->PixelCount == 0) {
454             /* We probably would not be called any more, so lets clean
455              * everything before we return: need to flush out all rest of
456              * image until empty block (size 0) detected. We use GetCodeNext. */
457             do
458                 if (DGifGetCodeNext(GifFile, &Dummy) == GIF_ERROR)
459                     return GIF_ERROR;
460             while (Dummy != NULL) ;
461         }
462         return GIF_OK;
463     } else
464         return GIF_ERROR;
465 }
466
467 /******************************************************************************
468  * Get an extension block (see GIF manual) from gif file. This routine only
469  * returns the first data block, and DGifGetExtensionNext should be called
470  * after this one until NULL extension is returned.
471  * The Extension should NOT be freed by the user (not dynamically allocated).
472  * Note it is assumed the Extension desc. header ('!') has been read.
473  *****************************************************************************/
474 static int
475 DGifGetExtension(GifFileType * GifFile,
476                  int *ExtCode,
477                  GifByteType ** Extension) {
478
479     GifByteType Buf;
480
481     if (READ(GifFile, &Buf, 1) != 1) {
482         return GIF_ERROR;
483     }
484     *ExtCode = Buf;
485
486     return DGifGetExtensionNext(GifFile, Extension);
487 }
488
489 /******************************************************************************
490  * Get a following extension block (see GIF manual) from gif file. This
491  * routine should be called until NULL Extension is returned.
492  * The Extension should NOT be freed by the user (not dynamically allocated).
493  *****************************************************************************/
494 static int
495 DGifGetExtensionNext(GifFileType * GifFile,
496                      GifByteType ** Extension) {
497
498     GifByteType Buf;
499     GifFilePrivateType *Private = GifFile->Private;
500
501     if (READ(GifFile, &Buf, 1) != 1) {
502         return GIF_ERROR;
503     }
504     if (Buf > 0) {
505         *Extension = Private->Buf;    /* Use private unused buffer. */
506         (*Extension)[0] = Buf;  /* Pascal strings notation (pos. 0 is len.). */
507         if (READ(GifFile, &((*Extension)[1]), Buf) != Buf) {
508             return GIF_ERROR;
509         }
510     } else
511         *Extension = NULL;
512
513     return GIF_OK;
514 }
515
516 /******************************************************************************
517  * Get 2 bytes (word) from the given file:
518  *****************************************************************************/
519 static int
520 DGifGetWord(GifFileType * GifFile,
521             GifWord *Word) {
522
523     unsigned char c[2];
524
525     if (READ(GifFile, c, 2) != 2) {
526         return GIF_ERROR;
527     }
528
529     *Word = (((unsigned int)c[1]) << 8) + c[0];
530     return GIF_OK;
531 }
532
533 /******************************************************************************
534  * Continue to get the image code in compressed form. This routine should be
535  * called until NULL block is returned.
536  * The block should NOT be freed by the user (not dynamically allocated).
537  *****************************************************************************/
538 static int
539 DGifGetCodeNext(GifFileType * GifFile,
540                 GifByteType ** CodeBlock) {
541
542     GifByteType Buf;
543     GifFilePrivateType *Private = GifFile->Private;
544
545     if (READ(GifFile, &Buf, 1) != 1) {
546         return GIF_ERROR;
547     }
548
549     if (Buf > 0) {
550         *CodeBlock = Private->Buf;    /* Use private unused buffer. */
551         (*CodeBlock)[0] = Buf;  /* Pascal strings notation (pos. 0 is len.). */
552         if (READ(GifFile, &((*CodeBlock)[1]), Buf) != Buf) {
553             return GIF_ERROR;
554         }
555     } else {
556         *CodeBlock = NULL;
557         Private->Buf[0] = 0;    /* Make sure the buffer is empty! */
558         Private->PixelCount = 0;    /* And local info. indicate image read. */
559     }
560
561     return GIF_OK;
562 }
563
564 /******************************************************************************
565  * Setup the LZ decompression for this image:
566  *****************************************************************************/
567 static int
568 DGifSetupDecompress(GifFileType * GifFile) {
569
570     int i, BitsPerPixel;
571     GifByteType CodeSize;
572     GifPrefixType *Prefix;
573     GifFilePrivateType *Private = GifFile->Private;
574
575     READ(GifFile, &CodeSize, 1);    /* Read Code size from file. */
576     BitsPerPixel = CodeSize;
577
578     Private->Buf[0] = 0;    /* Input Buffer empty. */
579     Private->BitsPerPixel = BitsPerPixel;
580     Private->ClearCode = (1 << BitsPerPixel);
581     Private->EOFCode = Private->ClearCode + 1;
582     Private->RunningCode = Private->EOFCode + 1;
583     Private->RunningBits = BitsPerPixel + 1;    /* Number of bits per code. */
584     Private->MaxCode1 = 1 << Private->RunningBits;    /* Max. code + 1. */
585     Private->StackPtr = 0;    /* No pixels on the pixel stack. */
586     Private->LastCode = NO_SUCH_CODE;
587     Private->CrntShiftState = 0;    /* No information in CrntShiftDWord. */
588     Private->CrntShiftDWord = 0;
589
590     Prefix = Private->Prefix;
591     for (i = 0; i <= LZ_MAX_CODE; i++)
592         Prefix[i] = NO_SUCH_CODE;
593
594     return GIF_OK;
595 }
596
597 /******************************************************************************
598  * The LZ decompression routine:
599  * This version decompress the given gif file into Line of length LineLen.
600  * This routine can be called few times (one per scan line, for example), in
601  * order the complete the whole image.
602  *****************************************************************************/
603 static int
604 DGifDecompressLine(GifFileType * GifFile,
605                    GifPixelType * Line,
606                    int LineLen) {
607
608     int i = 0;
609     int j, CrntCode, EOFCode, ClearCode, CrntPrefix, LastCode, StackPtr;
610     GifByteType *Stack, *Suffix;
611     GifPrefixType *Prefix;
612     GifFilePrivateType *Private = GifFile->Private;
613
614     StackPtr = Private->StackPtr;
615     Prefix = Private->Prefix;
616     Suffix = Private->Suffix;
617     Stack = Private->Stack;
618     EOFCode = Private->EOFCode;
619     ClearCode = Private->ClearCode;
620     LastCode = Private->LastCode;
621
622     if (StackPtr != 0) {
623         /* Let pop the stack off before continuing to read the gif file: */
624         while (StackPtr != 0 && i < LineLen)
625             Line[i++] = Stack[--StackPtr];
626     }
627
628     while (i < LineLen) {    /* Decode LineLen items. */
629         if (DGifDecompressInput(GifFile, &CrntCode) == GIF_ERROR)
630             return GIF_ERROR;
631
632         if (CrntCode == EOFCode) {
633             /* Note, however, that usually we will not be here as we will stop
634              * decoding as soon as we got all the pixel, or EOF code will
635              * not be read at all, and DGifGetLine/Pixel clean everything.  */
636             if (i != LineLen - 1 || Private->PixelCount != 0) {
637                 return GIF_ERROR;
638             }
639             i++;
640         } else if (CrntCode == ClearCode) {
641             /* We need to start over again: */
642             for (j = 0; j <= LZ_MAX_CODE; j++)
643                 Prefix[j] = NO_SUCH_CODE;
644             Private->RunningCode = Private->EOFCode + 1;
645             Private->RunningBits = Private->BitsPerPixel + 1;
646             Private->MaxCode1 = 1 << Private->RunningBits;
647             LastCode = Private->LastCode = NO_SUCH_CODE;
648         } else {
649             /* It's a regular code - if in pixel range simply add it to output
650              * stream, otherwise trace to codes linked list until the prefix
651              * is in pixel range: */
652             if (CrntCode < ClearCode) {
653                 /* This is simple - its pixel scalar, so add it to output: */
654                 Line[i++] = CrntCode;
655             } else {
656                 /* It's a code to be traced: trace the linked list
657                  * until the prefix is a pixel, while pushing the suffix
658                  * pixels on our stack. If we done, pop the stack in reverse
659                  * order (that's what stack is good for!) for output.  */
660                 if (Prefix[CrntCode] == NO_SUCH_CODE) {
661                     /* Only allowed if CrntCode is exactly the running code:
662                      * In that case CrntCode = XXXCode, CrntCode or the
663                      * prefix code is last code and the suffix char is
664                      * exactly the prefix of last code! */
665                     if (CrntCode == Private->RunningCode - 2) {
666                         CrntPrefix = LastCode;
667                         Suffix[Private->RunningCode - 2] =
668                            Stack[StackPtr++] = DGifGetPrefixChar(Prefix,
669                                                                  LastCode,
670                                                                  ClearCode);
671                     } else {
672                         return GIF_ERROR;
673                     }
674                 } else
675                     CrntPrefix = CrntCode;
676
677                 /* Now (if image is O.K.) we should not get a NO_SUCH_CODE
678                  * during the trace. As we might loop forever, in case of
679                  * defective image, we count the number of loops we trace
680                  * and stop if we got LZ_MAX_CODE. Obviously we cannot
681                  * loop more than that.  */
682                 j = 0;
683                 while (j++ <= LZ_MAX_CODE &&
684                        CrntPrefix > ClearCode && CrntPrefix <= LZ_MAX_CODE) {
685                     Stack[StackPtr++] = Suffix[CrntPrefix];
686                     CrntPrefix = Prefix[CrntPrefix];
687                 }
688                 if (j >= LZ_MAX_CODE || CrntPrefix > LZ_MAX_CODE) {
689                     return GIF_ERROR;
690                 }
691                 /* Push the last character on stack: */
692                 Stack[StackPtr++] = CrntPrefix;
693
694                 /* Now lets pop all the stack into output: */
695                 while (StackPtr != 0 && i < LineLen)
696                     Line[i++] = Stack[--StackPtr];
697             }
698             if (LastCode != NO_SUCH_CODE) {
699                 Prefix[Private->RunningCode - 2] = LastCode;
700
701                 if (CrntCode == Private->RunningCode - 2) {
702                     /* Only allowed if CrntCode is exactly the running code:
703                      * In that case CrntCode = XXXCode, CrntCode or the
704                      * prefix code is last code and the suffix char is
705                      * exactly the prefix of last code! */
706                     Suffix[Private->RunningCode - 2] =
707                        DGifGetPrefixChar(Prefix, LastCode, ClearCode);
708                 } else {
709                     Suffix[Private->RunningCode - 2] =
710                        DGifGetPrefixChar(Prefix, CrntCode, ClearCode);
711                 }
712             }
713             LastCode = CrntCode;
714         }
715     }
716
717     Private->LastCode = LastCode;
718     Private->StackPtr = StackPtr;
719
720     return GIF_OK;
721 }
722
723 /******************************************************************************
724  * Routine to trace the Prefixes linked list until we get a prefix which is
725  * not code, but a pixel value (less than ClearCode). Returns that pixel value.
726  * If image is defective, we might loop here forever, so we limit the loops to
727  * the maximum possible if image O.k. - LZ_MAX_CODE times.
728  *****************************************************************************/
729 static int
730 DGifGetPrefixChar(const GifPrefixType *Prefix,
731                   int Code,
732                   int ClearCode) {
733
734     int i = 0;
735
736     while (Code > ClearCode && i++ <= LZ_MAX_CODE)
737         Code = Prefix[Code];
738     return Code;
739 }
740
741 /******************************************************************************
742  * The LZ decompression input routine:
743  * This routine is responsible for the decompression of the bit stream from
744  * 8 bits (bytes) packets, into the real codes.
745  * Returns GIF_OK if read successfully.
746  *****************************************************************************/
747 static int
748 DGifDecompressInput(GifFileType * GifFile,
749                     int *Code) {
750
751     GifFilePrivateType *Private = GifFile->Private;
752
753     GifByteType NextByte;
754     static const unsigned short CodeMasks[] = {
755         0x0000, 0x0001, 0x0003, 0x0007,
756         0x000f, 0x001f, 0x003f, 0x007f,
757         0x00ff, 0x01ff, 0x03ff, 0x07ff,
758         0x0fff
759     };
760     /* The image can't contain more than LZ_BITS per code. */
761     if (Private->RunningBits > LZ_BITS) {
762         return GIF_ERROR;
763     }
764
765     while (Private->CrntShiftState < Private->RunningBits) {
766         /* Needs to get more bytes from input stream for next code: */
767         if (DGifBufferedInput(GifFile, Private->Buf, &NextByte) == GIF_ERROR) {
768             return GIF_ERROR;
769         }
770         Private->CrntShiftDWord |=
771            ((unsigned long)NextByte) << Private->CrntShiftState;
772         Private->CrntShiftState += 8;
773     }
774     *Code = Private->CrntShiftDWord & CodeMasks[Private->RunningBits];
775
776     Private->CrntShiftDWord >>= Private->RunningBits;
777     Private->CrntShiftState -= Private->RunningBits;
778
779     /* If code cannot fit into RunningBits bits, must raise its size. Note
780      * however that codes above 4095 are used for special signaling.
781      * If we're using LZ_BITS bits already and we're at the max code, just
782      * keep using the table as it is, don't increment Private->RunningCode.
783      */
784     if (Private->RunningCode < LZ_MAX_CODE + 2 &&
785             ++Private->RunningCode > Private->MaxCode1 &&
786             Private->RunningBits < LZ_BITS) {
787         Private->MaxCode1 <<= 1;
788         Private->RunningBits++;
789     }
790     return GIF_OK;
791 }
792
793 /******************************************************************************
794  * This routines read one gif data block at a time and buffers it internally
795  * so that the decompression routine could access it.
796  * The routine returns the next byte from its internal buffer (or read next
797  * block in if buffer empty) and returns GIF_OK if successful.
798  *****************************************************************************/
799 static int
800 DGifBufferedInput(GifFileType * GifFile,
801                   GifByteType * Buf,
802                   GifByteType * NextByte) {
803
804     if (Buf[0] == 0) {
805         /* Needs to read the next buffer - this one is empty: */
806         if (READ(GifFile, Buf, 1) != 1) {
807             return GIF_ERROR;
808         }
809         /* There shouldn't be any empty data blocks here as the LZW spec
810          * says the LZW termination code should come first.  Therefore we
811          * shouldn't be inside this routine at that point.
812          */
813         if (Buf[0] == 0) {
814             return GIF_ERROR;
815         }
816         if (READ(GifFile, &Buf[1], Buf[0]) != Buf[0]) {
817             return GIF_ERROR;
818         }
819         *NextByte = Buf[1];
820         Buf[1] = 2;    /* We use now the second place as last char read! */
821         Buf[0]--;
822     } else {
823         *NextByte = Buf[Buf[1]++];
824         Buf[0]--;
825     }
826
827     return GIF_OK;
828 }
829
830 /******************************************************************************
831  * This routine reads an entire GIF into core, hanging all its state info off
832  * the GifFileType pointer.  Call DGifOpenFileName() or DGifOpenFileHandle()
833  * first to initialize I/O.  Its inverse is EGifSpew().
834  ******************************************************************************/
835 int
836 DGifSlurp(GifFileType * GifFile) {
837
838     int ImageSize;
839     GifRecordType RecordType;
840     SavedImage *sp;
841     GifByteType *ExtData;
842     SavedImage temp_save;
843
844     temp_save.ExtensionBlocks = NULL;
845     temp_save.ExtensionBlockCount = 0;
846
847     do {
848         if (DGifGetRecordType(GifFile, &RecordType) == GIF_ERROR)
849             return (GIF_ERROR);
850
851         switch (RecordType) {
852           case IMAGE_DESC_RECORD_TYPE:
853               if (DGifGetImageDesc(GifFile) == GIF_ERROR)
854                   return (GIF_ERROR);
855
856               sp = &GifFile->SavedImages[GifFile->ImageCount - 1];
857               ImageSize = sp->ImageDesc.Width * sp->ImageDesc.Height;
858
859               sp->RasterBits = ungif_alloc(ImageSize * sizeof(GifPixelType));
860               if (sp->RasterBits == NULL) {
861                   return GIF_ERROR;
862               }
863               if (DGifGetLine(GifFile, sp->RasterBits, ImageSize) ==
864                   GIF_ERROR)
865                   return (GIF_ERROR);
866               if (temp_save.ExtensionBlocks) {
867                   sp->ExtensionBlocks = temp_save.ExtensionBlocks;
868                   sp->ExtensionBlockCount = temp_save.ExtensionBlockCount;
869
870                   temp_save.ExtensionBlocks = NULL;
871                   temp_save.ExtensionBlockCount = 0;
872
873                   /* FIXME: The following is wrong.  It is left in only for
874                    * backwards compatibility.  Someday it should go away. Use
875                    * the sp->ExtensionBlocks->Function variable instead. */
876                   sp->Function = sp->ExtensionBlocks[0].Function;
877               }
878               break;
879
880           case EXTENSION_RECORD_TYPE:
881               if (DGifGetExtension(GifFile, &temp_save.Function, &ExtData) ==
882                   GIF_ERROR)
883                   return (GIF_ERROR);
884               while (ExtData != NULL) {
885
886                   /* Create an extension block with our data */
887                   if (AddExtensionBlock(&temp_save, ExtData[0], &ExtData[1])
888                       == GIF_ERROR)
889                       return (GIF_ERROR);
890
891                   if (DGifGetExtensionNext(GifFile, &ExtData) == GIF_ERROR)
892                       return (GIF_ERROR);
893                   temp_save.Function = 0;
894               }
895               break;
896
897           case TERMINATE_RECORD_TYPE:
898               break;
899
900           default:    /* Should be trapped by DGifGetRecordType */
901               break;
902         }
903     } while (RecordType != TERMINATE_RECORD_TYPE);
904
905     /* Just in case the Gif has an extension block without an associated
906      * image... (Should we save this into a savefile structure with no image
907      * instead? Have to check if the present writing code can handle that as
908      * well.... */
909     if (temp_save.ExtensionBlocks)
910         FreeExtension(&temp_save);
911
912     return (GIF_OK);
913 }
914
915 /******************************************************************************
916  * GifFileType constructor with user supplied input function (TVT)
917  *****************************************************************************/
918 GifFileType *
919 DGifOpen(void *userData,
920          InputFunc readFunc) {
921
922     unsigned char Buf[GIF_STAMP_LEN + 1];
923     GifFileType *GifFile;
924     GifFilePrivateType *Private;
925
926     GifFile = ungif_alloc(sizeof(GifFileType));
927     if (GifFile == NULL) {
928         return NULL;
929     }
930
931     memset(GifFile, '\0', sizeof(GifFileType));
932
933     Private = ungif_alloc(sizeof(GifFilePrivateType));
934     if (!Private) {
935         ungif_free(GifFile);
936         return NULL;
937     }
938
939     GifFile->Private = (void*)Private;
940
941     Private->Read = readFunc;    /* TVT */
942     GifFile->UserData = userData;    /* TVT */
943
944     /* Lets see if this is a GIF file: */
945     if (READ(GifFile, Buf, GIF_STAMP_LEN) != GIF_STAMP_LEN) {
946         ungif_free(Private);
947         ungif_free(GifFile);
948         return NULL;
949     }
950
951     /* The GIF Version number is ignored at this time. Maybe we should do
952      * something more useful with it. */
953     Buf[GIF_STAMP_LEN] = 0;
954     if (memcmp(GIF_STAMP, Buf, GIF_VERSION_POS) != 0) {
955         ungif_free(Private);
956         ungif_free(GifFile);
957         return NULL;
958     }
959
960     if (DGifGetScreenDesc(GifFile) == GIF_ERROR) {
961         ungif_free(Private);
962         ungif_free(GifFile);
963         return NULL;
964     }
965
966     return GifFile;
967 }
968
969 /******************************************************************************
970  * This routine should be called last, to close the GIF file.
971  *****************************************************************************/
972 int
973 DGifCloseFile(GifFileType * GifFile) {
974
975     GifFilePrivateType *Private;
976
977     if (GifFile == NULL)
978         return GIF_ERROR;
979
980     Private = GifFile->Private;
981
982     if (GifFile->Image.ColorMap) {
983         FreeMapObject(GifFile->Image.ColorMap);
984         GifFile->Image.ColorMap = NULL;
985     }
986
987     if (GifFile->SColorMap) {
988         FreeMapObject(GifFile->SColorMap);
989         GifFile->SColorMap = NULL;
990     }
991
992     ungif_free(Private);
993     Private = NULL;
994
995     if (GifFile->SavedImages) {
996         FreeSavedImages(GifFile);
997         GifFile->SavedImages = NULL;
998     }
999
1000     ungif_free(GifFile);
1001
1002     return GIF_OK;
1003 }