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