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