dmsynth: Correctly handle internal connections with controls.
[wine.git] / dlls / windowscodecs / ungif.c
blob63aa02427c68a492fe3b4dbe502d88bffa0999e1
1 /*
2 * Gif extracting routines - derived from libungif
4 * Portions Copyright 2006 Mike McCormack
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.
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.
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
22 * Original copyright notice:
24 * The GIFLIB distribution is Copyright (c) 1997 Eric S. Raymond
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:
33 * The above copyright notice and this permission notice shall be included in
34 * all copies or substantial portions of the Software.
38 /******************************************************************************
39 * "Gif-Lib" - Yet another gif library.
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 *****************************************************************************/
50 #include <stdlib.h>
51 #include <string.h>
53 #include <stdarg.h>
54 #include "windef.h"
55 #include "winbase.h"
56 #include "ungif.h"
57 #include "wine/debug.h"
59 WINE_DEFAULT_DEBUG_CHANNEL(wincodecs);
61 #define LZ_MAX_CODE 4095 /* Biggest code possible in 12 bits. */
62 #define LZ_BITS 12
64 #define NO_SUCH_CODE 4098 /* Impossible code, to signal empty. */
66 typedef struct GifFilePrivateType {
67 GifWord BitsPerPixel, /* Bits per pixel (Codes uses at least this + 1). */
68 ClearCode, /* The CLEAR LZ code. */
69 EOFCode, /* The EOF LZ code. */
70 RunningCode, /* The next code algorithm can generate. */
71 RunningBits, /* The number of bits required to represent RunningCode. */
72 MaxCode1, /* 1 bigger than max. possible code, in RunningBits bits. */
73 LastCode, /* The code before the current code. */
74 CrntCode, /* Current algorithm code. */
75 StackPtr, /* For character stack (see below). */
76 CrntShiftState; /* Number of bits in CrntShiftDWord. */
77 unsigned long CrntShiftDWord; /* For bytes decomposition into codes. */
78 unsigned long PixelCount; /* Number of pixels in image. */
79 InputFunc Read; /* function to read gif input (TVT) */
80 GifByteType Buf[256]; /* Compressed input is buffered here. */
81 GifByteType Stack[LZ_MAX_CODE]; /* Decoded pixels are stacked here. */
82 GifByteType Suffix[LZ_MAX_CODE + 1]; /* So we can trace the codes. */
83 GifPrefixType Prefix[LZ_MAX_CODE + 1];
84 } GifFilePrivateType;
86 /* avoid extra function call in case we use fread (TVT) */
87 #define READ(_gif,_buf,_len) \
88 ((GifFilePrivateType*)_gif->Private)->Read(_gif,_buf,_len)
90 static int DGifGetWord(GifFileType *GifFile, GifWord *Word);
91 static int DGifSetupDecompress(GifFileType *GifFile);
92 static int DGifDecompressLine(GifFileType *GifFile, GifPixelType *Line, int LineLen);
93 static int DGifGetPrefixChar(const GifPrefixType *Prefix, int Code, int ClearCode);
94 static int DGifDecompressInput(GifFileType *GifFile, int *Code);
95 static int DGifBufferedInput(GifFileType *GifFile, GifByteType *Buf,
96 GifByteType *NextByte);
98 static int DGifGetExtensionNext(GifFileType * GifFile, GifByteType ** GifExtension);
99 static int DGifGetCodeNext(GifFileType * GifFile, GifByteType ** GifCodeBlock);
101 /******************************************************************************
102 * Miscellaneous utility functions
103 *****************************************************************************/
105 /* return smallest bitfield size n will fit in */
106 static int
107 BitSize(int n) {
109 register int i;
111 for (i = 1; i <= 8; i++)
112 if ((1 << i) >= n)
113 break;
114 return (i);
117 /******************************************************************************
118 * Color map object functions
119 *****************************************************************************/
122 * Allocate a color map of given size; initialize with contents of
123 * ColorMap if that pointer is non-NULL.
125 static ColorMapObject *
126 MakeMapObject(int ColorCount,
127 const GifColorType * ColorMap) {
129 ColorMapObject *Object;
131 /*** FIXME: Our ColorCount has to be a power of two. Is it necessary to
132 * make the user know that or should we automatically round up instead? */
133 if (ColorCount != (1 << BitSize(ColorCount))) {
134 return NULL;
137 Object = malloc(sizeof(ColorMapObject));
138 if (Object == NULL) {
139 return NULL;
142 Object->Colors = calloc(ColorCount, sizeof(GifColorType));
143 if (Object->Colors == NULL) {
144 free(Object);
145 return NULL;
148 Object->ColorCount = ColorCount;
149 Object->BitsPerPixel = BitSize(ColorCount);
151 if (ColorMap) {
152 memcpy(Object->Colors, ColorMap, ColorCount * sizeof(GifColorType));
155 return (Object);
159 * Free a color map object
161 static void
162 FreeMapObject(ColorMapObject * Object) {
164 if (Object != NULL) {
165 free(Object->Colors);
166 free(Object);
167 /*** FIXME:
168 * When we are willing to break API we need to make this function
169 * FreeMapObject(ColorMapObject **Object)
170 * and do this assignment to NULL here:
171 * *Object = NULL;
176 static int
177 AddExtensionBlock(Extensions *New,
178 int Len,
179 const unsigned char ExtData[]) {
181 ExtensionBlock *ep;
183 New->ExtensionBlocks = realloc(New->ExtensionBlocks,
184 sizeof(ExtensionBlock) *
185 (New->ExtensionBlockCount + 1));
187 if (New->ExtensionBlocks == NULL)
188 return (GIF_ERROR);
190 ep = &New->ExtensionBlocks[New->ExtensionBlockCount++];
192 ep->ByteCount=Len + 3;
193 ep->Bytes = malloc(ep->ByteCount + 3);
194 if (ep->Bytes == NULL)
195 return (GIF_ERROR);
197 /* Extension Header */
198 ep->Bytes[0] = 0x21;
199 ep->Bytes[1] = New->Function;
200 ep->Bytes[2] = Len;
202 if (ExtData) {
203 memcpy(ep->Bytes + 3, ExtData, Len);
204 ep->Function = New->Function;
207 return (GIF_OK);
210 static int
211 AppendExtensionBlock(Extensions *New,
212 int Len,
213 const unsigned char ExtData[])
215 ExtensionBlock *ep;
217 if (New->ExtensionBlocks == NULL)
218 return (GIF_ERROR);
220 ep = &New->ExtensionBlocks[New->ExtensionBlockCount - 1];
222 ep->Bytes = realloc(ep->Bytes, ep->ByteCount + Len + 1);
223 if (ep->Bytes == NULL)
224 return (GIF_ERROR);
226 ep->Bytes[ep->ByteCount] = Len;
228 if (ExtData)
229 memcpy(ep->Bytes + ep->ByteCount + 1, ExtData, Len);
231 ep->ByteCount += Len + 1;
233 return (GIF_OK);
236 static void
237 FreeExtension(Extensions *Extensions)
239 ExtensionBlock *ep;
241 if ((Extensions == NULL) || (Extensions->ExtensionBlocks == NULL)) {
242 return;
244 for (ep = Extensions->ExtensionBlocks;
245 ep < (Extensions->ExtensionBlocks + Extensions->ExtensionBlockCount); ep++)
246 free(ep->Bytes);
247 free(Extensions->ExtensionBlocks);
248 Extensions->ExtensionBlocks = NULL;
251 /******************************************************************************
252 * Image block allocation functions
253 ******************************************************************************/
255 static void
256 FreeSavedImages(GifFileType * GifFile) {
258 SavedImage *sp;
260 if ((GifFile == NULL) || (GifFile->SavedImages == NULL)) {
261 return;
263 for (sp = GifFile->SavedImages;
264 sp < GifFile->SavedImages + GifFile->ImageCount; sp++) {
265 if (sp->ImageDesc.ColorMap) {
266 FreeMapObject(sp->ImageDesc.ColorMap);
267 sp->ImageDesc.ColorMap = NULL;
270 free(sp->RasterBits);
272 if (sp->Extensions.ExtensionBlocks)
273 FreeExtension(&sp->Extensions);
275 free(GifFile->SavedImages);
276 GifFile->SavedImages=NULL;
279 /******************************************************************************
280 * This routine should be called before any other DGif calls. Note that
281 * this routine is called automatically from DGif file open routines.
282 *****************************************************************************/
283 static int
284 DGifGetScreenDesc(GifFileType * GifFile) {
286 int i, BitsPerPixel, SortFlag;
287 GifByteType Buf[3];
289 /* Put the screen descriptor into the file: */
290 if (DGifGetWord(GifFile, &GifFile->SWidth) == GIF_ERROR ||
291 DGifGetWord(GifFile, &GifFile->SHeight) == GIF_ERROR)
292 return GIF_ERROR;
294 if (READ(GifFile, Buf, 3) != 3) {
295 return GIF_ERROR;
297 GifFile->SColorResolution = (((Buf[0] & 0x70) + 1) >> 4) + 1;
298 SortFlag = (Buf[0] & 0x08) != 0;
299 BitsPerPixel = (Buf[0] & 0x07) + 1;
300 GifFile->SColorTableSize = 1 << BitsPerPixel;
301 GifFile->SBackGroundColor = Buf[1];
302 GifFile->SAspectRatio = Buf[2];
303 if (Buf[0] & 0x80) { /* Do we have global color map? */
305 GifFile->SColorMap = MakeMapObject(1 << BitsPerPixel, NULL);
306 if (GifFile->SColorMap == NULL) {
307 return GIF_ERROR;
310 /* Get the global color map: */
311 GifFile->SColorMap->SortFlag = SortFlag;
312 for (i = 0; i < GifFile->SColorMap->ColorCount; i++) {
313 if (READ(GifFile, Buf, 3) != 3) {
314 FreeMapObject(GifFile->SColorMap);
315 GifFile->SColorMap = NULL;
316 return GIF_ERROR;
318 GifFile->SColorMap->Colors[i].Red = Buf[0];
319 GifFile->SColorMap->Colors[i].Green = Buf[1];
320 GifFile->SColorMap->Colors[i].Blue = Buf[2];
322 } else {
323 GifFile->SColorMap = NULL;
326 return GIF_OK;
329 /******************************************************************************
330 * This routine should be called before any attempt to read an image.
331 *****************************************************************************/
332 static int
333 DGifGetRecordType(GifFileType * GifFile,
334 GifRecordType * Type) {
336 GifByteType Buf;
338 if (READ(GifFile, &Buf, 1) != 1) {
339 /* Wine-specific behavior: Native accepts broken GIF files that have no
340 * terminator, so we match this by treating EOF as a terminator. */
341 *Type = TERMINATE_RECORD_TYPE;
342 return GIF_OK;
345 switch (Buf) {
346 case ',':
347 *Type = IMAGE_DESC_RECORD_TYPE;
348 break;
349 case '!':
350 *Type = EXTENSION_RECORD_TYPE;
351 break;
352 case ';':
353 *Type = TERMINATE_RECORD_TYPE;
354 break;
355 default:
356 *Type = UNDEFINED_RECORD_TYPE;
357 return GIF_ERROR;
360 return GIF_OK;
363 /******************************************************************************
364 * This routine should be called before any attempt to read an image.
365 * Note it is assumed the Image desc. header (',') has been read.
366 *****************************************************************************/
367 static int
368 DGifGetImageDesc(GifFileType * GifFile) {
370 int i, BitsPerPixel, SortFlag;
371 GifByteType Buf[3];
372 GifFilePrivateType *Private = GifFile->Private;
373 SavedImage *sp;
375 if (DGifGetWord(GifFile, &GifFile->Image.Left) == GIF_ERROR ||
376 DGifGetWord(GifFile, &GifFile->Image.Top) == GIF_ERROR ||
377 DGifGetWord(GifFile, &GifFile->Image.Width) == GIF_ERROR ||
378 DGifGetWord(GifFile, &GifFile->Image.Height) == GIF_ERROR)
379 return GIF_ERROR;
380 if (READ(GifFile, Buf, 1) != 1) {
381 return GIF_ERROR;
383 BitsPerPixel = (Buf[0] & 0x07) + 1;
384 SortFlag = (Buf[0] & 0x20) != 0;
385 GifFile->Image.Interlace = (Buf[0] & 0x40);
386 if (Buf[0] & 0x80) { /* Does this image have local color map? */
388 FreeMapObject(GifFile->Image.ColorMap);
390 GifFile->Image.ColorMap = MakeMapObject(1 << BitsPerPixel, NULL);
391 if (GifFile->Image.ColorMap == NULL) {
392 return GIF_ERROR;
395 /* Get the image local color map: */
396 GifFile->Image.ColorMap->SortFlag = SortFlag;
397 for (i = 0; i < GifFile->Image.ColorMap->ColorCount; i++) {
398 if (READ(GifFile, Buf, 3) != 3) {
399 FreeMapObject(GifFile->Image.ColorMap);
400 GifFile->Image.ColorMap = NULL;
401 return GIF_ERROR;
403 GifFile->Image.ColorMap->Colors[i].Red = Buf[0];
404 GifFile->Image.ColorMap->Colors[i].Green = Buf[1];
405 GifFile->Image.ColorMap->Colors[i].Blue = Buf[2];
407 } else if (GifFile->Image.ColorMap) {
408 FreeMapObject(GifFile->Image.ColorMap);
409 GifFile->Image.ColorMap = NULL;
412 if ((GifFile->SavedImages = realloc(GifFile->SavedImages,
413 sizeof(SavedImage) *
414 (GifFile->ImageCount + 1))) == NULL) {
415 return GIF_ERROR;
418 sp = &GifFile->SavedImages[GifFile->ImageCount];
419 sp->ImageDesc = GifFile->Image;
420 if (GifFile->Image.ColorMap != NULL) {
421 sp->ImageDesc.ColorMap = MakeMapObject(
422 GifFile->Image.ColorMap->ColorCount,
423 GifFile->Image.ColorMap->Colors);
424 if (sp->ImageDesc.ColorMap == NULL) {
425 return GIF_ERROR;
427 sp->ImageDesc.ColorMap->SortFlag = GifFile->Image.ColorMap->SortFlag;
429 sp->RasterBits = NULL;
430 sp->Extensions.ExtensionBlockCount = 0;
431 sp->Extensions.ExtensionBlocks = NULL;
433 GifFile->ImageCount++;
435 Private->PixelCount = GifFile->Image.Width * GifFile->Image.Height;
437 DGifSetupDecompress(GifFile); /* Reset decompress algorithm parameters. */
439 return GIF_OK;
442 /******************************************************************************
443 * Get one full scanned line (Line) of length LineLen from GIF file.
444 *****************************************************************************/
445 static int
446 DGifGetLine(GifFileType * GifFile,
447 GifPixelType * Line,
448 int LineLen) {
450 GifByteType *Dummy;
451 GifFilePrivateType *Private = GifFile->Private;
453 if (!LineLen)
454 LineLen = GifFile->Image.Width;
456 if ((Private->PixelCount -= LineLen) > 0xffff0000UL) {
457 return GIF_ERROR;
460 if (DGifDecompressLine(GifFile, Line, LineLen) == GIF_OK) {
461 if (Private->PixelCount == 0) {
462 /* We probably would not be called any more, so lets clean
463 * everything before we return: need to flush out all rest of
464 * image until empty block (size 0) detected. We use GetCodeNext. */
466 if (DGifGetCodeNext(GifFile, &Dummy) == GIF_ERROR)
468 WARN("GIF is not properly terminated\n");
469 break;
471 while (Dummy != NULL) ;
473 return GIF_OK;
474 } else
475 return GIF_ERROR;
478 /******************************************************************************
479 * Get an extension block (see GIF manual) from gif file. This routine only
480 * returns the first data block, and DGifGetExtensionNext should be called
481 * after this one until NULL extension is returned.
482 * The Extension should NOT be freed by the user (not dynamically allocated).
483 * Note it is assumed the Extension desc. header ('!') has been read.
484 *****************************************************************************/
485 static int
486 DGifGetExtension(GifFileType * GifFile,
487 int *ExtCode,
488 GifByteType ** Extension) {
490 GifByteType Buf;
492 if (READ(GifFile, &Buf, 1) != 1) {
493 return GIF_ERROR;
495 *ExtCode = Buf;
497 return DGifGetExtensionNext(GifFile, Extension);
500 /******************************************************************************
501 * Get a following extension block (see GIF manual) from gif file. This
502 * routine should be called until NULL Extension is returned.
503 * The Extension should NOT be freed by the user (not dynamically allocated).
504 *****************************************************************************/
505 static int
506 DGifGetExtensionNext(GifFileType * GifFile,
507 GifByteType ** Extension) {
509 GifByteType Buf;
510 GifFilePrivateType *Private = GifFile->Private;
512 if (READ(GifFile, &Buf, 1) != 1) {
513 return GIF_ERROR;
515 if (Buf > 0) {
516 *Extension = Private->Buf; /* Use private unused buffer. */
517 (*Extension)[0] = Buf; /* Pascal strings notation (pos. 0 is len.). */
518 if (READ(GifFile, &((*Extension)[1]), Buf) != Buf) {
519 return GIF_ERROR;
521 } else
522 *Extension = NULL;
524 return GIF_OK;
527 /******************************************************************************
528 * Get 2 bytes (word) from the given file:
529 *****************************************************************************/
530 static int
531 DGifGetWord(GifFileType * GifFile,
532 GifWord *Word) {
534 unsigned char c[2];
536 if (READ(GifFile, c, 2) != 2) {
537 return GIF_ERROR;
540 *Word = (((unsigned int)c[1]) << 8) + c[0];
541 return GIF_OK;
544 /******************************************************************************
545 * Continue to get the image code in compressed form. This routine should be
546 * called until NULL block is returned.
547 * The block should NOT be freed by the user (not dynamically allocated).
548 *****************************************************************************/
549 static int
550 DGifGetCodeNext(GifFileType * GifFile,
551 GifByteType ** CodeBlock) {
553 GifByteType Buf;
554 GifFilePrivateType *Private = GifFile->Private;
556 if (READ(GifFile, &Buf, 1) != 1) {
557 return GIF_ERROR;
560 if (Buf > 0) {
561 *CodeBlock = Private->Buf; /* Use private unused buffer. */
562 (*CodeBlock)[0] = Buf; /* Pascal strings notation (pos. 0 is len.). */
563 if (READ(GifFile, &((*CodeBlock)[1]), Buf) != Buf) {
564 return GIF_ERROR;
566 } else {
567 *CodeBlock = NULL;
568 Private->Buf[0] = 0; /* Make sure the buffer is empty! */
569 Private->PixelCount = 0; /* And local info. indicate image read. */
572 return GIF_OK;
575 /******************************************************************************
576 * Setup the LZ decompression for this image:
577 *****************************************************************************/
578 static int
579 DGifSetupDecompress(GifFileType * GifFile) {
581 int i, BitsPerPixel;
582 GifByteType CodeSize;
583 GifPrefixType *Prefix;
584 GifFilePrivateType *Private = GifFile->Private;
586 READ(GifFile, &CodeSize, 1); /* Read Code size from file. */
587 BitsPerPixel = CodeSize;
589 Private->Buf[0] = 0; /* Input Buffer empty. */
590 Private->BitsPerPixel = BitsPerPixel;
591 Private->ClearCode = (1 << BitsPerPixel);
592 Private->EOFCode = Private->ClearCode + 1;
593 Private->RunningCode = Private->EOFCode + 1;
594 Private->RunningBits = BitsPerPixel + 1; /* Number of bits per code. */
595 Private->MaxCode1 = 1 << Private->RunningBits; /* Max. code + 1. */
596 Private->StackPtr = 0; /* No pixels on the pixel stack. */
597 Private->LastCode = NO_SUCH_CODE;
598 Private->CrntShiftState = 0; /* No information in CrntShiftDWord. */
599 Private->CrntShiftDWord = 0;
601 Prefix = Private->Prefix;
602 for (i = 0; i <= LZ_MAX_CODE; i++)
603 Prefix[i] = NO_SUCH_CODE;
605 return GIF_OK;
608 /******************************************************************************
609 * The LZ decompression routine:
610 * This version decompress the given gif file into Line of length LineLen.
611 * This routine can be called few times (one per scan line, for example), in
612 * order the complete the whole image.
613 *****************************************************************************/
614 static int
615 DGifDecompressLine(GifFileType * GifFile,
616 GifPixelType * Line,
617 int LineLen) {
619 int i = 0;
620 int j, CrntCode, EOFCode, ClearCode, CrntPrefix, LastCode, StackPtr;
621 GifByteType *Stack, *Suffix;
622 GifPrefixType *Prefix;
623 GifFilePrivateType *Private = GifFile->Private;
625 StackPtr = Private->StackPtr;
626 Prefix = Private->Prefix;
627 Suffix = Private->Suffix;
628 Stack = Private->Stack;
629 EOFCode = Private->EOFCode;
630 ClearCode = Private->ClearCode;
631 LastCode = Private->LastCode;
633 if (StackPtr != 0) {
634 /* Let pop the stack off before continuing to read the gif file: */
635 while (StackPtr != 0 && i < LineLen)
636 Line[i++] = Stack[--StackPtr];
639 while (i < LineLen) { /* Decode LineLen items. */
640 if (DGifDecompressInput(GifFile, &CrntCode) == GIF_ERROR)
641 return GIF_ERROR;
643 if (CrntCode == EOFCode) {
644 /* Note, however, that usually we will not be here as we will stop
645 * decoding as soon as we got all the pixel, or EOF code will
646 * not be read at all, and DGifGetLine/Pixel clean everything. */
647 if (i != LineLen - 1 || Private->PixelCount != 0) {
648 return GIF_ERROR;
650 i++;
651 } else if (CrntCode == ClearCode) {
652 /* We need to start over again: */
653 for (j = 0; j <= LZ_MAX_CODE; j++)
654 Prefix[j] = NO_SUCH_CODE;
655 Private->RunningCode = Private->EOFCode + 1;
656 Private->RunningBits = Private->BitsPerPixel + 1;
657 Private->MaxCode1 = 1 << Private->RunningBits;
658 LastCode = Private->LastCode = NO_SUCH_CODE;
659 } else {
660 /* It's a regular code - if in pixel range simply add it to output
661 * stream, otherwise trace to codes linked list until the prefix
662 * is in pixel range: */
663 if (CrntCode < ClearCode) {
664 /* This is simple - its pixel scalar, so add it to output: */
665 Line[i++] = CrntCode;
666 } else {
667 /* It's a code to be traced: trace the linked list
668 * until the prefix is a pixel, while pushing the suffix
669 * pixels on our stack. If we done, pop the stack in reverse
670 * order (that's what stack is good for!) for output. */
671 if (Prefix[CrntCode] == NO_SUCH_CODE) {
672 /* Only allowed if CrntCode is exactly the running code:
673 * In that case CrntCode = XXXCode, CrntCode or the
674 * prefix code is last code and the suffix char is
675 * exactly the prefix of last code! */
676 if (CrntCode == Private->RunningCode - 2) {
677 CrntPrefix = LastCode;
678 Suffix[Private->RunningCode - 2] =
679 Stack[StackPtr++] = DGifGetPrefixChar(Prefix,
680 LastCode,
681 ClearCode);
682 } else {
683 return GIF_ERROR;
685 } else
686 CrntPrefix = CrntCode;
688 /* Now (if image is O.K.) we should not get a NO_SUCH_CODE
689 * during the trace. As we might loop forever, in case of
690 * defective image, we count the number of loops we trace
691 * and stop if we got LZ_MAX_CODE. Obviously we cannot
692 * loop more than that. */
693 j = 0;
694 while (j++ <= LZ_MAX_CODE &&
695 CrntPrefix > ClearCode && CrntPrefix <= LZ_MAX_CODE) {
696 Stack[StackPtr++] = Suffix[CrntPrefix];
697 CrntPrefix = Prefix[CrntPrefix];
699 if (j >= LZ_MAX_CODE || CrntPrefix > LZ_MAX_CODE) {
700 return GIF_ERROR;
702 /* Push the last character on stack: */
703 Stack[StackPtr++] = CrntPrefix;
705 /* Now lets pop all the stack into output: */
706 while (StackPtr != 0 && i < LineLen)
707 Line[i++] = Stack[--StackPtr];
709 if (LastCode != NO_SUCH_CODE) {
710 Prefix[Private->RunningCode - 2] = LastCode;
712 if (CrntCode == Private->RunningCode - 2) {
713 /* Only allowed if CrntCode is exactly the running code:
714 * In that case CrntCode = XXXCode, CrntCode or the
715 * prefix code is last code and the suffix char is
716 * exactly the prefix of last code! */
717 Suffix[Private->RunningCode - 2] =
718 DGifGetPrefixChar(Prefix, LastCode, ClearCode);
719 } else {
720 Suffix[Private->RunningCode - 2] =
721 DGifGetPrefixChar(Prefix, CrntCode, ClearCode);
724 LastCode = CrntCode;
728 Private->LastCode = LastCode;
729 Private->StackPtr = StackPtr;
731 return GIF_OK;
734 /******************************************************************************
735 * Routine to trace the Prefixes linked list until we get a prefix which is
736 * not code, but a pixel value (less than ClearCode). Returns that pixel value.
737 * If image is defective, we might loop here forever, so we limit the loops to
738 * the maximum possible if image O.k. - LZ_MAX_CODE times.
739 *****************************************************************************/
740 static int
741 DGifGetPrefixChar(const GifPrefixType *Prefix,
742 int Code,
743 int ClearCode) {
745 int i = 0;
747 while (Code > ClearCode && i++ <= LZ_MAX_CODE)
748 Code = Prefix[Code];
749 return Code;
752 /******************************************************************************
753 * The LZ decompression input routine:
754 * This routine is responsible for the decompression of the bit stream from
755 * 8 bits (bytes) packets, into the real codes.
756 * Returns GIF_OK if read successfully.
757 *****************************************************************************/
758 static int
759 DGifDecompressInput(GifFileType * GifFile,
760 int *Code) {
762 GifFilePrivateType *Private = GifFile->Private;
764 GifByteType NextByte;
765 static const unsigned short CodeMasks[] = {
766 0x0000, 0x0001, 0x0003, 0x0007,
767 0x000f, 0x001f, 0x003f, 0x007f,
768 0x00ff, 0x01ff, 0x03ff, 0x07ff,
769 0x0fff
771 /* The image can't contain more than LZ_BITS per code. */
772 if (Private->RunningBits > LZ_BITS) {
773 return GIF_ERROR;
776 while (Private->CrntShiftState < Private->RunningBits) {
777 /* Needs to get more bytes from input stream for next code: */
778 if (DGifBufferedInput(GifFile, Private->Buf, &NextByte) == GIF_ERROR) {
779 return GIF_ERROR;
781 Private->CrntShiftDWord |=
782 ((unsigned long)NextByte) << Private->CrntShiftState;
783 Private->CrntShiftState += 8;
785 *Code = Private->CrntShiftDWord & CodeMasks[Private->RunningBits];
787 Private->CrntShiftDWord >>= Private->RunningBits;
788 Private->CrntShiftState -= Private->RunningBits;
790 /* If code cannot fit into RunningBits bits, must raise its size. Note
791 * however that codes above 4095 are used for special signaling.
792 * If we're using LZ_BITS bits already and we're at the max code, just
793 * keep using the table as it is, don't increment Private->RunningCode.
795 if (Private->RunningCode < LZ_MAX_CODE + 2 &&
796 ++Private->RunningCode > Private->MaxCode1 &&
797 Private->RunningBits < LZ_BITS) {
798 Private->MaxCode1 <<= 1;
799 Private->RunningBits++;
801 return GIF_OK;
804 /******************************************************************************
805 * This routines read one gif data block at a time and buffers it internally
806 * so that the decompression routine could access it.
807 * The routine returns the next byte from its internal buffer (or read next
808 * block in if buffer empty) and returns GIF_OK if successful.
809 *****************************************************************************/
810 static int
811 DGifBufferedInput(GifFileType * GifFile,
812 GifByteType * Buf,
813 GifByteType * NextByte) {
815 if (Buf[0] == 0) {
816 /* Needs to read the next buffer - this one is empty: */
817 if (READ(GifFile, Buf, 1) != 1) {
818 return GIF_ERROR;
820 /* There shouldn't be any empty data blocks here as the LZW spec
821 * says the LZW termination code should come first. Therefore we
822 * shouldn't be inside this routine at that point.
824 if (Buf[0] == 0) {
825 return GIF_ERROR;
827 if (READ(GifFile, &Buf[1], Buf[0]) != Buf[0]) {
828 return GIF_ERROR;
830 *NextByte = Buf[1];
831 Buf[1] = 2; /* We use now the second place as last char read! */
832 Buf[0]--;
833 } else {
834 *NextByte = Buf[Buf[1]++];
835 Buf[0]--;
838 return GIF_OK;
841 /******************************************************************************
842 * This routine reads an entire GIF into core, hanging all its state info off
843 * the GifFileType pointer. Call DGifOpenFileName() or DGifOpenFileHandle()
844 * first to initialize I/O. Its inverse is EGifSpew().
845 ******************************************************************************/
847 DGifSlurp(GifFileType * GifFile) {
849 int ImageSize;
850 GifRecordType RecordType;
851 SavedImage *sp;
852 GifByteType *ExtData;
853 Extensions temp_save;
855 temp_save.ExtensionBlocks = NULL;
856 temp_save.ExtensionBlockCount = 0;
858 do {
859 if (DGifGetRecordType(GifFile, &RecordType) == GIF_ERROR)
860 return (GIF_ERROR);
862 switch (RecordType) {
863 case IMAGE_DESC_RECORD_TYPE:
864 if (DGifGetImageDesc(GifFile) == GIF_ERROR)
865 return (GIF_ERROR);
867 sp = &GifFile->SavedImages[GifFile->ImageCount - 1];
868 ImageSize = sp->ImageDesc.Width * sp->ImageDesc.Height;
870 sp->RasterBits = malloc(ImageSize * sizeof(GifPixelType));
871 if (sp->RasterBits == NULL) {
872 return GIF_ERROR;
874 if (DGifGetLine(GifFile, sp->RasterBits, ImageSize) ==
875 GIF_ERROR)
876 return (GIF_ERROR);
877 if (temp_save.ExtensionBlocks) {
878 sp->Extensions.ExtensionBlocks = temp_save.ExtensionBlocks;
879 sp->Extensions.ExtensionBlockCount = temp_save.ExtensionBlockCount;
881 temp_save.ExtensionBlocks = NULL;
882 temp_save.ExtensionBlockCount = 0;
884 /* FIXME: The following is wrong. It is left in only for
885 * backwards compatibility. Someday it should go away. Use
886 * the sp->ExtensionBlocks->Function variable instead. */
887 sp->Extensions.Function = sp->Extensions.ExtensionBlocks[0].Function;
889 break;
891 case EXTENSION_RECORD_TYPE:
893 int Function;
894 Extensions *Extensions;
896 if (DGifGetExtension(GifFile, &Function, &ExtData) == GIF_ERROR)
897 return (GIF_ERROR);
899 if (GifFile->ImageCount || Function == GRAPHICS_EXT_FUNC_CODE)
900 Extensions = &temp_save;
901 else
902 Extensions = &GifFile->Extensions;
904 Extensions->Function = Function;
906 if (ExtData)
908 /* Create an extension block with our data */
909 if (AddExtensionBlock(Extensions, ExtData[0], &ExtData[1]) == GIF_ERROR)
910 return (GIF_ERROR);
912 else /* Empty extension block */
914 if (AddExtensionBlock(Extensions, 0, NULL) == GIF_ERROR)
915 return (GIF_ERROR);
918 while (ExtData != NULL) {
919 int Len;
920 GifByteType *Data;
922 if (DGifGetExtensionNext(GifFile, &ExtData) == GIF_ERROR)
923 return (GIF_ERROR);
925 if (ExtData)
927 Len = ExtData[0];
928 Data = &ExtData[1];
930 else
932 Len = 0;
933 Data = NULL;
936 if (AppendExtensionBlock(Extensions, Len, Data) == GIF_ERROR)
937 return (GIF_ERROR);
939 break;
942 case TERMINATE_RECORD_TYPE:
943 break;
945 default: /* Should be trapped by DGifGetRecordType */
946 break;
948 } while (RecordType != TERMINATE_RECORD_TYPE);
950 /* Just in case the Gif has an extension block without an associated
951 * image... (Should we save this into a savefile structure with no image
952 * instead? Have to check if the present writing code can handle that as
953 * well.... */
954 if (temp_save.ExtensionBlocks)
955 FreeExtension(&temp_save);
957 return (GIF_OK);
960 /******************************************************************************
961 * GifFileType constructor with user supplied input function (TVT)
962 *****************************************************************************/
963 GifFileType *
964 DGifOpen(void *userData,
965 InputFunc readFunc) {
967 unsigned char Buf[GIF_STAMP_LEN + 1];
968 GifFileType *GifFile;
969 GifFilePrivateType *Private;
971 GifFile = malloc(sizeof(GifFileType));
972 if (GifFile == NULL) {
973 return NULL;
976 memset(GifFile, '\0', sizeof(GifFileType));
978 Private = malloc(sizeof(GifFilePrivateType));
979 if (!Private) {
980 free(GifFile);
981 return NULL;
984 GifFile->Private = (void*)Private;
986 Private->Read = readFunc; /* TVT */
987 GifFile->UserData = userData; /* TVT */
989 /* Lets see if this is a GIF file: */
990 if (READ(GifFile, Buf, GIF_STAMP_LEN) != GIF_STAMP_LEN) {
991 free(Private);
992 free(GifFile);
993 return NULL;
996 /* The GIF Version number is ignored at this time. Maybe we should do
997 * something more useful with it. */
998 Buf[GIF_STAMP_LEN] = 0;
999 if (memcmp(GIF_STAMP, Buf, GIF_VERSION_POS) != 0) {
1000 free(Private);
1001 free(GifFile);
1002 return NULL;
1005 if (DGifGetScreenDesc(GifFile) == GIF_ERROR) {
1006 free(Private);
1007 free(GifFile);
1008 return NULL;
1011 return GifFile;
1014 /******************************************************************************
1015 * This routine should be called last, to close the GIF file.
1016 *****************************************************************************/
1018 DGifCloseFile(GifFileType * GifFile) {
1020 GifFilePrivateType *Private;
1022 if (GifFile == NULL)
1023 return GIF_ERROR;
1025 Private = GifFile->Private;
1027 if (GifFile->Image.ColorMap) {
1028 FreeMapObject(GifFile->Image.ColorMap);
1029 GifFile->Image.ColorMap = NULL;
1032 if (GifFile->SColorMap) {
1033 FreeMapObject(GifFile->SColorMap);
1034 GifFile->SColorMap = NULL;
1037 free(Private);
1038 Private = NULL;
1040 if (GifFile->SavedImages) {
1041 FreeSavedImages(GifFile);
1042 GifFile->SavedImages = NULL;
1045 FreeExtension(&GifFile->Extensions);
1047 free(GifFile);
1049 return GIF_OK;