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