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