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