oleaut32/tests: Fix compilation on systems that don't support nameless unions.
[wine] / dlls / oleaut32 / 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 ((ColorMapObject *) NULL);
152     }
153
154     Object = ungif_alloc(sizeof(ColorMapObject));
155     if (Object == (ColorMapObject *) NULL) {
156         return ((ColorMapObject *) NULL);
157     }
158
159     Object->Colors = ungif_calloc(ColorCount, sizeof(GifColorType));
160     if (Object->Colors == (GifColorType *) 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     if (Buf[0] & 0x80) {    /* Do we have global color map? */
289
290         GifFile->SColorMap = MakeMapObject(1 << BitsPerPixel, NULL);
291         if (GifFile->SColorMap == NULL) {
292             return GIF_ERROR;
293         }
294
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;
301             }
302             GifFile->SColorMap->Colors[i].Red = Buf[0];
303             GifFile->SColorMap->Colors[i].Green = Buf[1];
304             GifFile->SColorMap->Colors[i].Blue = Buf[2];
305         }
306     } else {
307         GifFile->SColorMap = NULL;
308     }
309
310     return GIF_OK;
311 }
312
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) {
319
320     GifByteType Buf;
321
322     if (READ(GifFile, &Buf, 1) != 1) {
323         return GIF_ERROR;
324     }
325
326     switch (Buf) {
327       case ',':
328           *Type = IMAGE_DESC_RECORD_TYPE;
329           break;
330       case '!':
331           *Type = EXTENSION_RECORD_TYPE;
332           break;
333       case ';':
334           *Type = TERMINATE_RECORD_TYPE;
335           break;
336       default:
337           *Type = UNDEFINED_RECORD_TYPE;
338           return GIF_ERROR;
339     }
340
341     return GIF_OK;
342 }
343
344 /******************************************************************************
345  * This routine should be called before any attempt to read an image.
346  * Note it is assumed the Image desc. header (',') has been read.
347  *****************************************************************************/
348 static int
349 DGifGetImageDesc(GifFileType * GifFile) {
350
351     int i, BitsPerPixel;
352     GifByteType Buf[3];
353     GifFilePrivateType *Private = (GifFilePrivateType *)GifFile->Private;
354     SavedImage *sp;
355
356     if (DGifGetWord(GifFile, &GifFile->Image.Left) == GIF_ERROR ||
357         DGifGetWord(GifFile, &GifFile->Image.Top) == GIF_ERROR ||
358         DGifGetWord(GifFile, &GifFile->Image.Width) == GIF_ERROR ||
359         DGifGetWord(GifFile, &GifFile->Image.Height) == GIF_ERROR)
360         return GIF_ERROR;
361     if (READ(GifFile, Buf, 1) != 1) {
362         return GIF_ERROR;
363     }
364     BitsPerPixel = (Buf[0] & 0x07) + 1;
365     GifFile->Image.Interlace = (Buf[0] & 0x40);
366     if (Buf[0] & 0x80) {    /* Does this image have local color map? */
367
368         /*** FIXME: Why do we check both of these in order to do this?
369          * Why do we have both Image and SavedImages? */
370         if (GifFile->Image.ColorMap && GifFile->SavedImages == NULL)
371             FreeMapObject(GifFile->Image.ColorMap);
372
373         GifFile->Image.ColorMap = MakeMapObject(1 << BitsPerPixel, NULL);
374         if (GifFile->Image.ColorMap == NULL) {
375             return GIF_ERROR;
376         }
377
378         /* Get the image local color map: */
379         for (i = 0; i < GifFile->Image.ColorMap->ColorCount; i++) {
380             if (READ(GifFile, Buf, 3) != 3) {
381                 FreeMapObject(GifFile->Image.ColorMap);
382                 GifFile->Image.ColorMap = NULL;
383                 return GIF_ERROR;
384             }
385             GifFile->Image.ColorMap->Colors[i].Red = Buf[0];
386             GifFile->Image.ColorMap->Colors[i].Green = Buf[1];
387             GifFile->Image.ColorMap->Colors[i].Blue = Buf[2];
388         }
389     } else if (GifFile->Image.ColorMap) {
390         FreeMapObject(GifFile->Image.ColorMap);
391         GifFile->Image.ColorMap = NULL;
392     }
393
394     if (GifFile->SavedImages) {
395         if ((GifFile->SavedImages = ungif_realloc(GifFile->SavedImages,
396                                       sizeof(SavedImage) *
397                                       (GifFile->ImageCount + 1))) == NULL) {
398             return GIF_ERROR;
399         }
400     } else {
401         if ((GifFile->SavedImages = ungif_alloc(sizeof(SavedImage))) == NULL) {
402             return GIF_ERROR;
403         }
404     }
405
406     sp = &GifFile->SavedImages[GifFile->ImageCount];
407     memcpy(&sp->ImageDesc, &GifFile->Image, sizeof(GifImageDesc));
408     if (GifFile->Image.ColorMap != NULL) {
409         sp->ImageDesc.ColorMap = MakeMapObject(
410                                  GifFile->Image.ColorMap->ColorCount,
411                                  GifFile->Image.ColorMap->Colors);
412         if (sp->ImageDesc.ColorMap == NULL) {
413             return GIF_ERROR;
414         }
415     }
416     sp->RasterBits = (unsigned char *)NULL;
417     sp->ExtensionBlockCount = 0;
418     sp->ExtensionBlocks = (ExtensionBlock *) NULL;
419
420     GifFile->ImageCount++;
421
422     Private->PixelCount = (long)GifFile->Image.Width *
423        (long)GifFile->Image.Height;
424
425     DGifSetupDecompress(GifFile);  /* Reset decompress algorithm parameters. */
426
427     return GIF_OK;
428 }
429
430 /******************************************************************************
431  * Get one full scanned line (Line) of length LineLen from GIF file.
432  *****************************************************************************/
433 static int
434 DGifGetLine(GifFileType * GifFile,
435             GifPixelType * Line,
436             int LineLen) {
437
438     GifByteType *Dummy;
439     GifFilePrivateType *Private = (GifFilePrivateType *) GifFile->Private;
440
441     if (!LineLen)
442         LineLen = GifFile->Image.Width;
443
444     if ((Private->PixelCount -= LineLen) > 0xffff0000UL) {
445         return GIF_ERROR;
446     }
447
448     if (DGifDecompressLine(GifFile, Line, LineLen) == GIF_OK) {
449         if (Private->PixelCount == 0) {
450             /* We probably would not be called any more, so lets clean
451              * everything before we return: need to flush out all rest of
452              * image until empty block (size 0) detected. We use GetCodeNext. */
453             do
454                 if (DGifGetCodeNext(GifFile, &Dummy) == GIF_ERROR)
455                     return GIF_ERROR;
456             while (Dummy != NULL) ;
457         }
458         return GIF_OK;
459     } else
460         return GIF_ERROR;
461 }
462
463 /******************************************************************************
464  * Get an extension block (see GIF manual) from gif file. This routine only
465  * returns the first data block, and DGifGetExtensionNext should be called
466  * after this one until NULL extension is returned.
467  * The Extension should NOT be freed by the user (not dynamically allocated).
468  * Note it is assumed the Extension desc. header ('!') has been read.
469  *****************************************************************************/
470 static int
471 DGifGetExtension(GifFileType * GifFile,
472                  int *ExtCode,
473                  GifByteType ** Extension) {
474
475     GifByteType Buf;
476
477     if (READ(GifFile, &Buf, 1) != 1) {
478         return GIF_ERROR;
479     }
480     *ExtCode = Buf;
481
482     return DGifGetExtensionNext(GifFile, Extension);
483 }
484
485 /******************************************************************************
486  * Get a following extension block (see GIF manual) from gif file. This
487  * routine should be called until NULL Extension is returned.
488  * The Extension should NOT be freed by the user (not dynamically allocated).
489  *****************************************************************************/
490 static int
491 DGifGetExtensionNext(GifFileType * GifFile,
492                      GifByteType ** Extension) {
493
494     GifByteType Buf;
495     GifFilePrivateType *Private = (GifFilePrivateType *)GifFile->Private;
496
497     if (READ(GifFile, &Buf, 1) != 1) {
498         return GIF_ERROR;
499     }
500     if (Buf > 0) {
501         *Extension = Private->Buf;    /* Use private unused buffer. */
502         (*Extension)[0] = Buf;  /* Pascal strings notation (pos. 0 is len.). */
503         if (READ(GifFile, &((*Extension)[1]), Buf) != Buf) {
504             return GIF_ERROR;
505         }
506     } else
507         *Extension = NULL;
508
509     return GIF_OK;
510 }
511
512 /******************************************************************************
513  * Get 2 bytes (word) from the given file:
514  *****************************************************************************/
515 static int
516 DGifGetWord(GifFileType * GifFile,
517             GifWord *Word) {
518
519     unsigned char c[2];
520
521     if (READ(GifFile, c, 2) != 2) {
522         return GIF_ERROR;
523     }
524
525     *Word = (((unsigned int)c[1]) << 8) + c[0];
526     return GIF_OK;
527 }
528
529 /******************************************************************************
530  * Continue to get the image code in compressed form. This routine should be
531  * called until NULL block is returned.
532  * The block should NOT be freed by the user (not dynamically allocated).
533  *****************************************************************************/
534 static int
535 DGifGetCodeNext(GifFileType * GifFile,
536                 GifByteType ** CodeBlock) {
537
538     GifByteType Buf;
539     GifFilePrivateType *Private = (GifFilePrivateType *)GifFile->Private;
540
541     if (READ(GifFile, &Buf, 1) != 1) {
542         return GIF_ERROR;
543     }
544
545     if (Buf > 0) {
546         *CodeBlock = Private->Buf;    /* Use private unused buffer. */
547         (*CodeBlock)[0] = Buf;  /* Pascal strings notation (pos. 0 is len.). */
548         if (READ(GifFile, &((*CodeBlock)[1]), Buf) != Buf) {
549             return GIF_ERROR;
550         }
551     } else {
552         *CodeBlock = NULL;
553         Private->Buf[0] = 0;    /* Make sure the buffer is empty! */
554         Private->PixelCount = 0;    /* And local info. indicate image read. */
555     }
556
557     return GIF_OK;
558 }
559
560 /******************************************************************************
561  * Setup the LZ decompression for this image:
562  *****************************************************************************/
563 static int
564 DGifSetupDecompress(GifFileType * GifFile) {
565
566     int i, BitsPerPixel;
567     GifByteType CodeSize;
568     GifPrefixType *Prefix;
569     GifFilePrivateType *Private = (GifFilePrivateType *)GifFile->Private;
570
571     READ(GifFile, &CodeSize, 1);    /* Read Code size from file. */
572     BitsPerPixel = CodeSize;
573
574     Private->Buf[0] = 0;    /* Input Buffer empty. */
575     Private->BitsPerPixel = BitsPerPixel;
576     Private->ClearCode = (1 << BitsPerPixel);
577     Private->EOFCode = Private->ClearCode + 1;
578     Private->RunningCode = Private->EOFCode + 1;
579     Private->RunningBits = BitsPerPixel + 1;    /* Number of bits per code. */
580     Private->MaxCode1 = 1 << Private->RunningBits;    /* Max. code + 1. */
581     Private->StackPtr = 0;    /* No pixels on the pixel stack. */
582     Private->LastCode = NO_SUCH_CODE;
583     Private->CrntShiftState = 0;    /* No information in CrntShiftDWord. */
584     Private->CrntShiftDWord = 0;
585
586     Prefix = Private->Prefix;
587     for (i = 0; i <= LZ_MAX_CODE; i++)
588         Prefix[i] = NO_SUCH_CODE;
589
590     return GIF_OK;
591 }
592
593 /******************************************************************************
594  * The LZ decompression routine:
595  * This version decompress the given gif file into Line of length LineLen.
596  * This routine can be called few times (one per scan line, for example), in
597  * order the complete the whole image.
598  *****************************************************************************/
599 static int
600 DGifDecompressLine(GifFileType * GifFile,
601                    GifPixelType * Line,
602                    int LineLen) {
603
604     int i = 0;
605     int j, CrntCode, EOFCode, ClearCode, CrntPrefix, LastCode, StackPtr;
606     GifByteType *Stack, *Suffix;
607     GifPrefixType *Prefix;
608     GifFilePrivateType *Private = (GifFilePrivateType *) GifFile->Private;
609
610     StackPtr = Private->StackPtr;
611     Prefix = Private->Prefix;
612     Suffix = Private->Suffix;
613     Stack = Private->Stack;
614     EOFCode = Private->EOFCode;
615     ClearCode = Private->ClearCode;
616     LastCode = Private->LastCode;
617
618     if (StackPtr != 0) {
619         /* Let pop the stack off before continueing to read the gif file: */
620         while (StackPtr != 0 && i < LineLen)
621             Line[i++] = Stack[--StackPtr];
622     }
623
624     while (i < LineLen) {    /* Decode LineLen items. */
625         if (DGifDecompressInput(GifFile, &CrntCode) == GIF_ERROR)
626             return GIF_ERROR;
627
628         if (CrntCode == EOFCode) {
629             /* Note however that usually we will not be here as we will stop
630              * decoding as soon as we got all the pixel, or EOF code will
631              * not be read at all, and DGifGetLine/Pixel clean everything.  */
632             if (i != LineLen - 1 || Private->PixelCount != 0) {
633                 return GIF_ERROR;
634             }
635             i++;
636         } else if (CrntCode == ClearCode) {
637             /* We need to start over again: */
638             for (j = 0; j <= LZ_MAX_CODE; j++)
639                 Prefix[j] = NO_SUCH_CODE;
640             Private->RunningCode = Private->EOFCode + 1;
641             Private->RunningBits = Private->BitsPerPixel + 1;
642             Private->MaxCode1 = 1 << Private->RunningBits;
643             LastCode = Private->LastCode = NO_SUCH_CODE;
644         } else {
645             /* It's a regular code - if in pixel range simply add it to output
646              * stream, otherwise trace to codes linked list until the prefix
647              * is in pixel range: */
648             if (CrntCode < ClearCode) {
649                 /* This is simple - its pixel scalar, so add it to output: */
650                 Line[i++] = CrntCode;
651             } else {
652                 /* It's a code to be traced: trace the linked list
653                  * until the prefix is a pixel, while pushing the suffix
654                  * pixels on our stack. If we done, pop the stack in reverse
655                  * order (that's what stack is good for!) for output.  */
656                 if (Prefix[CrntCode] == NO_SUCH_CODE) {
657                     /* Only allowed if CrntCode is exactly the running code:
658                      * In that case CrntCode = XXXCode, CrntCode or the
659                      * prefix code is last code and the suffix char is
660                      * exactly the prefix of last code! */
661                     if (CrntCode == Private->RunningCode - 2) {
662                         CrntPrefix = LastCode;
663                         Suffix[Private->RunningCode - 2] =
664                            Stack[StackPtr++] = DGifGetPrefixChar(Prefix,
665                                                                  LastCode,
666                                                                  ClearCode);
667                     } else {
668                         return GIF_ERROR;
669                     }
670                 } else
671                     CrntPrefix = CrntCode;
672
673                 /* Now (if image is O.K.) we should not get a NO_SUCH_CODE
674                  * during the trace. As we might loop forever, in case of
675                  * defective image, we count the number of loops we trace
676                  * and stop if we got LZ_MAX_CODE. Obviously we cannot
677                  * loop more than that.  */
678                 j = 0;
679                 while (j++ <= LZ_MAX_CODE &&
680                        CrntPrefix > ClearCode && CrntPrefix <= LZ_MAX_CODE) {
681                     Stack[StackPtr++] = Suffix[CrntPrefix];
682                     CrntPrefix = Prefix[CrntPrefix];
683                 }
684                 if (j >= LZ_MAX_CODE || CrntPrefix > LZ_MAX_CODE) {
685                     return GIF_ERROR;
686                 }
687                 /* Push the last character on stack: */
688                 Stack[StackPtr++] = CrntPrefix;
689
690                 /* Now lets pop all the stack into output: */
691                 while (StackPtr != 0 && i < LineLen)
692                     Line[i++] = Stack[--StackPtr];
693             }
694             if (LastCode != NO_SUCH_CODE) {
695                 Prefix[Private->RunningCode - 2] = LastCode;
696
697                 if (CrntCode == Private->RunningCode - 2) {
698                     /* Only allowed if CrntCode is exactly the running code:
699                      * In that case CrntCode = XXXCode, CrntCode or the
700                      * prefix code is last code and the suffix char is
701                      * exactly the prefix of last code! */
702                     Suffix[Private->RunningCode - 2] =
703                        DGifGetPrefixChar(Prefix, LastCode, ClearCode);
704                 } else {
705                     Suffix[Private->RunningCode - 2] =
706                        DGifGetPrefixChar(Prefix, CrntCode, ClearCode);
707                 }
708             }
709             LastCode = CrntCode;
710         }
711     }
712
713     Private->LastCode = LastCode;
714     Private->StackPtr = StackPtr;
715
716     return GIF_OK;
717 }
718
719 /******************************************************************************
720  * Routine to trace the Prefixes linked list until we get a prefix which is
721  * not code, but a pixel value (less than ClearCode). Returns that pixel value.
722  * If image is defective, we might loop here forever, so we limit the loops to
723  * the maximum possible if image O.k. - LZ_MAX_CODE times.
724  *****************************************************************************/
725 static int
726 DGifGetPrefixChar(const GifPrefixType *Prefix,
727                   int Code,
728                   int ClearCode) {
729
730     int i = 0;
731
732     while (Code > ClearCode && i++ <= LZ_MAX_CODE)
733         Code = Prefix[Code];
734     return Code;
735 }
736
737 /******************************************************************************
738  * The LZ decompression input routine:
739  * This routine is responsible for the decompression of the bit stream from
740  * 8 bits (bytes) packets, into the real codes.
741  * Returns GIF_OK if read successfully.
742  *****************************************************************************/
743 static int
744 DGifDecompressInput(GifFileType * GifFile,
745                     int *Code) {
746
747     GifFilePrivateType *Private = (GifFilePrivateType *)GifFile->Private;
748
749     GifByteType NextByte;
750     static const unsigned short CodeMasks[] = {
751         0x0000, 0x0001, 0x0003, 0x0007,
752         0x000f, 0x001f, 0x003f, 0x007f,
753         0x00ff, 0x01ff, 0x03ff, 0x07ff,
754         0x0fff
755     };
756     /* The image can't contain more than LZ_BITS per code. */
757     if (Private->RunningBits > LZ_BITS) {
758         return GIF_ERROR;
759     }
760
761     while (Private->CrntShiftState < Private->RunningBits) {
762         /* Needs to get more bytes from input stream for next code: */
763         if (DGifBufferedInput(GifFile, Private->Buf, &NextByte) == GIF_ERROR) {
764             return GIF_ERROR;
765         }
766         Private->CrntShiftDWord |=
767            ((unsigned long)NextByte) << Private->CrntShiftState;
768         Private->CrntShiftState += 8;
769     }
770     *Code = Private->CrntShiftDWord & CodeMasks[Private->RunningBits];
771
772     Private->CrntShiftDWord >>= Private->RunningBits;
773     Private->CrntShiftState -= Private->RunningBits;
774
775     /* If code cannot fit into RunningBits bits, must raise its size. Note
776      * however that codes above 4095 are used for special signaling.
777      * If we're using LZ_BITS bits already and we're at the max code, just
778      * keep using the table as it is, don't increment Private->RunningCode.
779      */
780     if (Private->RunningCode < LZ_MAX_CODE + 2 &&
781             ++Private->RunningCode > Private->MaxCode1 &&
782             Private->RunningBits < LZ_BITS) {
783         Private->MaxCode1 <<= 1;
784         Private->RunningBits++;
785     }
786     return GIF_OK;
787 }
788
789 /******************************************************************************
790  * This routines read one gif data block at a time and buffers it internally
791  * so that the decompression routine could access it.
792  * The routine returns the next byte from its internal buffer (or read next
793  * block in if buffer empty) and returns GIF_OK if successful.
794  *****************************************************************************/
795 static int
796 DGifBufferedInput(GifFileType * GifFile,
797                   GifByteType * Buf,
798                   GifByteType * NextByte) {
799
800     if (Buf[0] == 0) {
801         /* Needs to read the next buffer - this one is empty: */
802         if (READ(GifFile, Buf, 1) != 1) {
803             return GIF_ERROR;
804         }
805         /* There shouldn't be any empty data blocks here as the LZW spec
806          * says the LZW termination code should come first.  Therefore we
807          * shouldn't be inside this routine at that point.
808          */
809         if (Buf[0] == 0) {
810             return GIF_ERROR;
811         }
812         if (READ(GifFile, &Buf[1], Buf[0]) != Buf[0]) {
813             return GIF_ERROR;
814         }
815         *NextByte = Buf[1];
816         Buf[1] = 2;    /* We use now the second place as last char read! */
817         Buf[0]--;
818     } else {
819         *NextByte = Buf[Buf[1]++];
820         Buf[0]--;
821     }
822
823     return GIF_OK;
824 }
825
826 /******************************************************************************
827  * This routine reads an entire GIF into core, hanging all its state info off
828  * the GifFileType pointer.  Call DGifOpenFileName() or DGifOpenFileHandle()
829  * first to initialize I/O.  Its inverse is EGifSpew().
830  ******************************************************************************/
831 int
832 DGifSlurp(GifFileType * GifFile) {
833
834     int ImageSize;
835     GifRecordType RecordType;
836     SavedImage *sp;
837     GifByteType *ExtData;
838     SavedImage temp_save;
839
840     temp_save.ExtensionBlocks = NULL;
841     temp_save.ExtensionBlockCount = 0;
842
843     do {
844         if (DGifGetRecordType(GifFile, &RecordType) == GIF_ERROR)
845             return (GIF_ERROR);
846
847         switch (RecordType) {
848           case IMAGE_DESC_RECORD_TYPE:
849               if (DGifGetImageDesc(GifFile) == GIF_ERROR)
850                   return (GIF_ERROR);
851
852               sp = &GifFile->SavedImages[GifFile->ImageCount - 1];
853               ImageSize = sp->ImageDesc.Width * sp->ImageDesc.Height;
854
855               sp->RasterBits = ungif_alloc(ImageSize * sizeof(GifPixelType));
856               if (sp->RasterBits == NULL) {
857                   return GIF_ERROR;
858               }
859               if (DGifGetLine(GifFile, sp->RasterBits, ImageSize) ==
860                   GIF_ERROR)
861                   return (GIF_ERROR);
862               if (temp_save.ExtensionBlocks) {
863                   sp->ExtensionBlocks = temp_save.ExtensionBlocks;
864                   sp->ExtensionBlockCount = temp_save.ExtensionBlockCount;
865
866                   temp_save.ExtensionBlocks = NULL;
867                   temp_save.ExtensionBlockCount = 0;
868
869                   /* FIXME: The following is wrong.  It is left in only for
870                    * backwards compatibility.  Someday it should go away. Use
871                    * the sp->ExtensionBlocks->Function variable instead. */
872                   sp->Function = sp->ExtensionBlocks[0].Function;
873               }
874               break;
875
876           case EXTENSION_RECORD_TYPE:
877               if (DGifGetExtension(GifFile, &temp_save.Function, &ExtData) ==
878                   GIF_ERROR)
879                   return (GIF_ERROR);
880               while (ExtData != NULL) {
881
882                   /* Create an extension block with our data */
883                   if (AddExtensionBlock(&temp_save, ExtData[0], &ExtData[1])
884                       == GIF_ERROR)
885                       return (GIF_ERROR);
886
887                   if (DGifGetExtensionNext(GifFile, &ExtData) == GIF_ERROR)
888                       return (GIF_ERROR);
889                   temp_save.Function = 0;
890               }
891               break;
892
893           case TERMINATE_RECORD_TYPE:
894               break;
895
896           default:    /* Should be trapped by DGifGetRecordType */
897               break;
898         }
899     } while (RecordType != TERMINATE_RECORD_TYPE);
900
901     /* Just in case the Gif has an extension block without an associated
902      * image... (Should we save this into a savefile structure with no image
903      * instead? Have to check if the present writing code can handle that as
904      * well.... */
905     if (temp_save.ExtensionBlocks)
906         FreeExtension(&temp_save);
907
908     return (GIF_OK);
909 }
910
911 /******************************************************************************
912  * GifFileType constructor with user supplied input function (TVT)
913  *****************************************************************************/
914 GifFileType *
915 DGifOpen(void *userData,
916          InputFunc readFunc) {
917
918     unsigned char Buf[GIF_STAMP_LEN + 1];
919     GifFileType *GifFile;
920     GifFilePrivateType *Private;
921
922     GifFile = ungif_alloc(sizeof(GifFileType));
923     if (GifFile == NULL) {
924         return NULL;
925     }
926
927     memset(GifFile, '\0', sizeof(GifFileType));
928
929     Private = ungif_alloc(sizeof(GifFilePrivateType));
930     if (!Private) {
931         ungif_free(GifFile);
932         return NULL;
933     }
934
935     GifFile->Private = (void*)Private;
936
937     Private->Read = readFunc;    /* TVT */
938     GifFile->UserData = userData;    /* TVT */
939
940     /* Lets see if this is a GIF file: */
941     if (READ(GifFile, Buf, GIF_STAMP_LEN) != GIF_STAMP_LEN) {
942         ungif_free(Private);
943         ungif_free(GifFile);
944         return NULL;
945     }
946
947     /* The GIF Version number is ignored at this time. Maybe we should do
948      * something more useful with it. */
949     Buf[GIF_STAMP_LEN] = 0;
950     if (memcmp(GIF_STAMP, Buf, GIF_VERSION_POS) != 0) {
951         ungif_free(Private);
952         ungif_free(GifFile);
953         return NULL;
954     }
955
956     if (DGifGetScreenDesc(GifFile) == GIF_ERROR) {
957         ungif_free(Private);
958         ungif_free(GifFile);
959         return NULL;
960     }
961
962     return GifFile;
963 }
964
965 /******************************************************************************
966  * This routine should be called last, to close the GIF file.
967  *****************************************************************************/
968 int
969 DGifCloseFile(GifFileType * GifFile) {
970
971     GifFilePrivateType *Private;
972
973     if (GifFile == NULL)
974         return GIF_ERROR;
975
976     Private = (GifFilePrivateType *) GifFile->Private;
977
978     if (GifFile->Image.ColorMap) {
979         FreeMapObject(GifFile->Image.ColorMap);
980         GifFile->Image.ColorMap = NULL;
981     }
982
983     if (GifFile->SColorMap) {
984         FreeMapObject(GifFile->SColorMap);
985         GifFile->SColorMap = NULL;
986     }
987
988     ungif_free(Private);
989     Private = NULL;
990
991     if (GifFile->SavedImages) {
992         FreeSavedImages(GifFile);
993         GifFile->SavedImages = NULL;
994     }
995
996     ungif_free(GifFile);
997
998     return GIF_OK;
999 }