root / ImageMagick / trunk / coders / gif.c

Revision 12379, 57.7 kB (checked in by cristy, 3 weeks ago)
Line 
1/*
2%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3%                                                                             %
4%                                                                             %
5%                                                                             %
6%                             GGGG  IIIII  FFFFF                              %
7%                            G        I    F                                  %
8%                            G  GG    I    FFF                                %
9%                            G   G    I    F                                  %
10%                             GGG   IIIII  F                                  %
11%                                                                             %
12%                                                                             %
13%            Read/Write Compuserv Graphics Interchange Format.                %
14%                                                                             %
15%                              Software Design                                %
16%                                John Cristy                                  %
17%                                 July 1992                                   %
18%                                                                             %
19%                                                                             %
20%  Copyright 1999-2008 ImageMagick Studio LLC, a non-profit organization      %
21%  dedicated to making software imaging solutions freely available.           %
22%                                                                             %
23%  You may not use this file except in compliance with the License.  You may  %
24%  obtain a copy of the License at                                            %
25%                                                                             %
26%    http://www.imagemagick.org/script/license.php                            %
27%                                                                             %
28%  Unless required by applicable law or agreed to in writing, software        %
29%  distributed under the License is distributed on an "AS IS" BASIS,          %
30%  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   %
31%  See the License for the specific language governing permissions and        %
32%  limitations under the License.                                             %
33%                                                                             %
34%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35%
36%
37*/
38
39/*
40  Include declarations.
41*/
42#include "magick/studio.h"
43#include "magick/blob.h"
44#include "magick/blob-private.h"
45#include "magick/color.h"
46#include "magick/color-private.h"
47#include "magick/colorspace.h"
48#include "magick/exception.h"
49#include "magick/exception-private.h"
50#include "magick/image.h"
51#include "magick/image-private.h"
52#include "magick/list.h"
53#include "magick/profile.h"
54#include "magick/magick.h"
55#include "magick/memory_.h"
56#include "magick/monitor.h"
57#include "magick/monitor-private.h"
58#include "magick/option.h"
59#include "magick/property.h"
60#include "magick/quantize.h"
61#include "magick/quantum-private.h"
62#include "magick/static.h"
63#include "magick/string_.h"
64#include "magick/module.h"
65
66/*
67  Define declarations.
68*/
69#define MaximumLZWBits  12
70#define MaximumLZWCode  (1UL << MaximumLZWBits)
71
72/*
73  Typdef declarations.
74*/
75typedef struct _LZWCodeInfo
76{
77  unsigned char
78    buffer[280];
79
80  unsigned long
81    count,
82    bit;
83
84  MagickBooleanType
85    eof;
86} LZWCodeInfo;
87
88typedef struct _LZWStack
89{
90  unsigned long
91    *codes,
92    *index,
93    *top;
94} LZWStack;
95
96typedef struct _LZWInfo
97{
98  Image
99    *image;
100
101  LZWStack
102    *stack;
103
104  MagickBooleanType
105    genesis;
106
107  unsigned long
108    data_size,
109    maximum_data_value,
110    clear_code,
111    end_code,
112    bits,
113    first_code,
114    last_code,
115    maximum_code,
116    slot,
117    *table[2];
118
119  LZWCodeInfo
120    code_info;
121} LZWInfo;
122
123/*
124  Forward declarations.
125*/
126static inline int
127  GetNextLZWCode(LZWInfo *,const unsigned long);
128
129static MagickBooleanType
130  WriteGIFImage(const ImageInfo *,Image *);
131
132static ssize_t
133  ReadBlobBlock(Image *,unsigned char *);
134
135/*
136%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
137%                                                                             %
138%                                                                             %
139%                                                                             %
140%   D e c o d e I m a g e                                                     %
141%                                                                             %
142%                                                                             %
143%                                                                             %
144%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
145%
146%  DecodeImage uncompresses an image via GIF-coding.
147%
148%  The format of the DecodeImage method is:
149%
150%      MagickBooleanType DecodeImage(Image *image,const long opacity)
151%
152%  A description of each parameter follows:
153%
154%    o image: the address of a structure of type Image.
155%
156%    o opacity:  The colormap index associated with the transparent color.
157%
158*/
159
160static LZWInfo *RelinquishLZWInfo(LZWInfo *lzw_info)
161{
162  if (lzw_info->table[0] != (unsigned long *) NULL)
163    lzw_info->table[0]=(unsigned long *) RelinquishMagickMemory(
164      lzw_info->table[0]);
165  if (lzw_info->table[1] != (unsigned long *) NULL)
166    lzw_info->table[1]=(unsigned long *) RelinquishMagickMemory(
167      lzw_info->table[1]);
168  if (lzw_info->stack != (LZWStack *) NULL)
169    {
170      if (lzw_info->stack->codes != (unsigned long *) NULL)
171        lzw_info->stack->codes=(unsigned long *) RelinquishMagickMemory(
172          lzw_info->stack->codes);
173      lzw_info->stack=(LZWStack *) RelinquishMagickMemory(lzw_info->stack);
174    }
175  lzw_info=(LZWInfo *) RelinquishMagickMemory(lzw_info);
176  return((LZWInfo *) NULL);
177}
178
179static inline void ResetLZWInfo(LZWInfo *lzw_info)
180{
181  lzw_info->bits=lzw_info->data_size+1;
182  lzw_info->maximum_code=1UL << lzw_info->bits;
183  lzw_info->slot=lzw_info->maximum_data_value+3;
184  lzw_info->genesis=MagickTrue;
185}
186
187static LZWInfo *AcquireLZWInfo(Image *image,const unsigned long data_size)
188{
189  LZWInfo
190    *lzw_info;
191
192  register long
193    i;
194
195  lzw_info=(LZWInfo *) AcquireMagickMemory(sizeof(*lzw_info));
196  if (lzw_info == (LZWInfo *) NULL)
197    return((LZWInfo *) NULL);
198  (void) ResetMagickMemory(lzw_info,0,sizeof(*lzw_info));
199  lzw_info->image=image;
200  lzw_info->data_size=data_size;
201  lzw_info->maximum_data_value=(1UL << data_size)-1;
202  lzw_info->clear_code=lzw_info->maximum_data_value+1;
203  lzw_info->end_code=lzw_info->maximum_data_value+2;
204  lzw_info->table[0]=(unsigned long *) AcquireQuantumMemory(MaximumLZWCode,
205    sizeof(*lzw_info->table));
206  lzw_info->table[1]=(unsigned long *) AcquireQuantumMemory(MaximumLZWCode,
207    sizeof(*lzw_info->table));
208  if ((lzw_info->table[0] == (unsigned long *) NULL) ||
209      (lzw_info->table[1] == (unsigned long *) NULL))
210    {
211      lzw_info=RelinquishLZWInfo(lzw_info);
212      return((LZWInfo *) NULL);
213    }
214  for (i=0; i <= (long) lzw_info->maximum_data_value; i++)
215  {
216    lzw_info->table[0][i]=0;
217    lzw_info->table[1][i]=(unsigned long) i;
218  }
219  ResetLZWInfo(lzw_info);
220  lzw_info->code_info.buffer[0]='\0';
221  lzw_info->code_info.buffer[1]='\0';
222  lzw_info->code_info.count=2;
223  lzw_info->code_info.bit=8*lzw_info->code_info.count;
224  lzw_info->code_info.eof=MagickFalse;
225  lzw_info->genesis=MagickTrue;
226  lzw_info->stack=(LZWStack *) AcquireMagickMemory(sizeof(*lzw_info->stack));
227  if (lzw_info->stack == (LZWStack *) NULL)
228    {
229      lzw_info=RelinquishLZWInfo(lzw_info);
230      return((LZWInfo *) NULL);
231    }
232  lzw_info->stack->codes=(unsigned long *) AcquireQuantumMemory(2UL*
233    MaximumLZWCode,sizeof(*lzw_info->stack->codes));
234  if (lzw_info->stack->codes == (unsigned long *) NULL)
235    {
236      lzw_info=RelinquishLZWInfo(lzw_info);
237      return((LZWInfo *) NULL);
238    }
239  lzw_info->stack->index=lzw_info->stack->codes;
240  lzw_info->stack->top=lzw_info->stack->codes+2*MaximumLZWCode;
241  return(lzw_info);
242}
243
244static inline int GetNextLZWCode(LZWInfo *lzw_info,const unsigned long bits)
245{
246  int
247    code;
248
249  register long
250    i;
251
252  while (((lzw_info->code_info.bit+bits) > (8*lzw_info->code_info.count)) &&
253         (lzw_info->code_info.eof == MagickFalse))
254  {
255    ssize_t
256      count;
257
258    lzw_info->code_info.buffer[0]=lzw_info->code_info.buffer[
259      lzw_info->code_info.count-2];
260    lzw_info->code_info.buffer[1]=lzw_info->code_info.buffer[
261      lzw_info->code_info.count-1];
262    lzw_info->code_info.bit-=8*(lzw_info->code_info.count-2);
263    lzw_info->code_info.count=2;
264    count=ReadBlobBlock(lzw_info->image,&lzw_info->code_info.buffer[
265      lzw_info->code_info.count]);
266    if (count > 0)
267      lzw_info->code_info.count+=count;
268    else
269      lzw_info->code_info.eof=MagickTrue;
270  }
271  if ((lzw_info->code_info.bit+bits) > (8*lzw_info->code_info.count))
272    return(-1);
273  code=0;
274  for (i=0; i < (long) bits; i++)
275  {
276    code|=((lzw_info->code_info.buffer[lzw_info->code_info.bit/8] &
277      (1UL << (lzw_info->code_info.bit % 8))) != 0) << i;
278    lzw_info->code_info.bit++;
279  }
280  return(code);
281}
282
283static inline long PopLZWStack(LZWStack *stack_info)
284{
285  if (stack_info->index <= stack_info->codes)
286    return(-1);
287  stack_info->index--;
288  return((long) *stack_info->index);
289}
290
291static inline void PushLZWStack(LZWStack *stack_info,const unsigned long value)
292{
293  if (stack_info->index >= stack_info->top)
294    return;
295  *stack_info->index=value;
296  stack_info->index++;
297}
298
299static int ReadBlobLZWByte(LZWInfo *lzw_info)
300{
301  int
302    code;
303
304  ssize_t
305    count;
306
307  unsigned long
308    value;
309
310  if (lzw_info->stack->index != lzw_info->stack->codes)
311    return(PopLZWStack(lzw_info->stack));
312  if (lzw_info->genesis != MagickFalse)
313    {
314      lzw_info->genesis=MagickFalse;
315      do
316      {
317        lzw_info->first_code=(unsigned long) GetNextLZWCode(lzw_info,
318          lzw_info->bits);
319        lzw_info->last_code=lzw_info->first_code;
320      } while (lzw_info->first_code == lzw_info->clear_code);
321      return((int) lzw_info->first_code);
322    }
323  code=GetNextLZWCode(lzw_info,lzw_info->bits);
324  if (code < 0)
325    return(code);
326  if ((unsigned long) code == lzw_info->clear_code)
327    {
328      ResetLZWInfo(lzw_info);
329      return(ReadBlobLZWByte(lzw_info));
330    }
331  if ((unsigned long) code == lzw_info->end_code)
332    return(-1);
333  if ((unsigned long) code < lzw_info->slot)
334    value=(unsigned long) code;
335  else
336    {
337      PushLZWStack(lzw_info->stack,lzw_info->first_code);
338      value=lzw_info->last_code;
339    }
340  count=0;
341  while (value > lzw_info->maximum_data_value)
342  {
343    if ((size_t) count > MaximumLZWCode)
344      return(-1);
345    count++;
346    if ((size_t) value > MaximumLZWCode)
347      return(-1);
348    PushLZWStack(lzw_info->stack,lzw_info->table[1][value]);
349    value=lzw_info->table[0][value];
350  }
351  lzw_info->first_code=lzw_info->table[1][value];
352  PushLZWStack(lzw_info->stack,lzw_info->first_code);
353  if (lzw_info->slot < MaximumLZWCode)
354    {
355      lzw_info->table[0][lzw_info->slot]=lzw_info->last_code;
356      lzw_info->table[1][lzw_info->slot]=lzw_info->first_code;
357      lzw_info->slot++;
358      if ((lzw_info->slot >= lzw_info->maximum_code) &&
359          (lzw_info->bits < MaximumLZWBits))
360        {
361          lzw_info->bits++;
362          lzw_info->maximum_code=1UL << lzw_info->bits;
363        }
364    }
365  lzw_info->last_code=(unsigned long) code;
366  return(PopLZWStack(lzw_info->stack));
367}
368
369static MagickBooleanType DecodeImage(Image *image,const Quantum opacity)
370{
371  IndexPacket
372    index;
373
374  int
375    c;
376
377  long
378    offset,
379    y;
380
381  register IndexPacket
382    *indexes;
383
384  register long
385    x;
386
387  register PixelPacket
388    *q;
389
390  LZWInfo
391    *lzw_info;
392
393  unsigned char
394    data_size;
395
396  unsigned long
397    pass;
398
399  /*
400    Allocate decoder tables.
401  */
402  assert(image != (Image *) NULL);
403  assert(image->signature == MagickSignature);
404  if (image->debug != MagickFalse)
405    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
406  data_size=(unsigned char) ReadBlobByte(image);
407  if (data_size > MaximumLZWBits)
408    ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename);
409  lzw_info=AcquireLZWInfo(image,data_size);
410  if (lzw_info == (LZWInfo *) NULL)
411    ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
412      image->filename);
413  pass=0;
414  offset=0;
415  for (y=0; y < (long) image->rows; y++)
416  {
417    q=GetImagePixels(image,0,offset,image->columns,1);
418    if (q == (PixelPacket *) NULL)
419      break;
420    indexes=GetIndexes(image);
421    for (x=0; x < (long) image->columns; )
422    {
423      c=ReadBlobLZWByte(lzw_info);
424      if (c < 0)
425        break;
426      index=ConstrainColormapIndex(image,(unsigned long) c);
427      q->red=image->colormap[(long) index].red;
428      q->green=image->colormap[(long) index].green;
429      q->blue=image->colormap[(long) index].blue;
430      q->opacity=index == opacity ? (Quantum) TransparentOpacity :
431        (Quantum) OpaqueOpacity;
432      indexes[x]=index;
433      x++;
434      q++;
435    }
436    if (x < (long) image->columns)
437      break;
438    if (image->interlace == NoInterlace)
439      offset++;
440    else
441      switch (pass)
442      {
443        case 0:
444        default:
445        {
446          offset+=8;
447          if (offset >= (long) image->rows)
448            {
449              pass++;
450              offset=4;
451            }
452          break;
453        }
454        case 1:
455        {
456          offset+=8;
457          if (offset >= (long) image->rows)
458            {
459              pass++;
460              offset=2;
461            }
462          break;
463        }
464        case 2:
465        {
466          offset+=4;
467          if (offset >= (long) image->rows)
468            {
469              pass++;
470              offset=1;
471            }
472          break;
473        }
474        case 3:
475        {
476          offset+=2;
477          break;
478        }
479      }
480    if (SyncImagePixels(image) == MagickFalse)
481      break;
482  }
483  lzw_info=RelinquishLZWInfo(lzw_info);
484  if (y < (long) image->rows)
485    ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename);
486  return(MagickTrue);
487}
488
489/*
490%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
491%                                                                             %
492%                                                                             %
493%                                                                             %
494%   E n c o d e I m a g e                                                     %
495%                                                                             %
496%                                                                             %
497%                                                                             %
498%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
499%
500%  EncodeImage compresses an image via GIF-coding.
501%
502%  The format of the EncodeImage method is:
503%
504%      MagickBooleanType EncodeImage(const ImageInfo *image_info,Image *image,
505%        const unsigned long data_size)
506%
507%  A description of each parameter follows:
508%
509%    o image_info: the image info.
510%
511%    o image: the address of a structure of type Image.
512%
513%    o data_size:  The number of bits in the compressed packet.
514%
515*/
516static MagickBooleanType EncodeImage(const ImageInfo *image_info,Image *image,
517  const unsigned long data_size)
518{
519#define MaxCode(number_bits)  ((1UL << (number_bits))-1)
520#define MaxHashTable  5003
521#define MaxGIFBits  12UL
522#define MaxGIFTable  (1UL << MaxGIFBits)
523#define GIFOutputCode(code) \
524{ \
525  /*  \
526    Emit a code. \
527  */ \
528  if (bits > 0) \
529    datum|=(code) << bits; \
530  else \
531    datum=code; \
532  bits+=number_bits; \
533  while (bits >= 8) \
534  { \
535    /*  \
536      Add a character to current packet. \
537    */ \
538    packet[length++]=(unsigned char) (datum & 0xff); \
539    if (length >= 254) \
540      { \
541        (void) WriteBlobByte(image,(unsigned char) length); \
542        (void) WriteBlob(image,length,packet); \
543        length=0; \
544      } \
545    datum>>=8; \
546    bits-=8; \
547  } \
548  if (free_code > max_code)  \
549    { \
550      number_bits++; \
551      if (number_bits == MaxGIFBits) \
552        max_code=MaxGIFTable; \
553      else \
554        max_code=MaxCode(number_bits); \
555    } \
556}
557
558  IndexPacket
559    index;
560
561  long
562    displacement,
563    offset,
564    k,
565    y;
566
567  register const PixelPacket
568    *p;
569
570  register IndexPacket
571    *indexes;
572
573  register long
574    i,
575    x;
576
577  size_t
578    length;
579
580  short
581    *hash_code,
582    *hash_prefix,
583    waiting_code;
584
585  unsigned char
586    *packet,
587    *hash_suffix;
588
589  unsigned long
590    bits,
591    clear_code,
592    datum,
593    end_of_information_code,
594    free_code,
595    max_code,
596    next_pixel,
597    number_bits,
598    pass;
599
600  /*
601    Allocate encoder tables.
602  */
603  assert(image != (Image *) NULL);
604  packet=(unsigned char *) AcquireQuantumMemory(256,sizeof(*packet));
605  hash_code=(short *) AcquireQuantumMemory(MaxHashTable,sizeof(*hash_code));
606  hash_prefix=(short *) AcquireQuantumMemory(MaxHashTable,sizeof(*hash_prefix));
607  hash_suffix=(unsigned char *) AcquireQuantumMemory(MaxHashTable,
608    sizeof(*hash_suffix));
609  if ((packet == (unsigned char *) NULL) || (hash_code == (short *) NULL) ||
610      (hash_prefix == (short *) NULL) ||
611      (hash_suffix == (unsigned char *) NULL))
612    {
613      if (packet != (unsigned char *) NULL)
614        packet=(unsigned char *) RelinquishMagickMemory(packet);
615      if (hash_code != (short *) NULL)
616        hash_code=(short *) RelinquishMagickMemory(hash_code);
617      if (hash_prefix != (short *) NULL)
618        hash_prefix=(short *) RelinquishMagickMemory(hash_prefix);
619      if (hash_suffix != (unsigned char *) NULL)
620        hash_suffix=(unsigned char *) RelinquishMagickMemory(hash_suffix);
621      return(MagickFalse);
622    }
623  /*
624    Initialize GIF encoder.
625  */
626  number_bits=data_size;
627  max_code=MaxCode(number_bits);
628  clear_code=((short) 1UL << (data_size-1));
629  end_of_information_code=clear_code+1;
630  free_code=clear_code+2;
631  length=0;
632  datum=0;
633  bits=0;
634  for (i=0; i < MaxHashTable; i++)
635    hash_code[i]=0;
636  GIFOutputCode(clear_code);
637  /*
638    Encode pixels.
639  */
640  offset=0;
641  pass=0;
642  waiting_code=0;
643  for (y=0; y < (long) image->rows; y++)
644  {
645    p=AcquireImagePixels(image,0,offset,image->columns,1,&image->exception);
646    if (p == (const PixelPacket *) NULL)
647      break;
648    indexes=GetIndexes(image);
649    if (y == 0)
650      waiting_code=(short) (*indexes);
651    for (x=(y == 0) ? 1 : 0; x < (long) image->columns; x++)
652    {
653      /*
654        Probe hash table.
655      */
656      index=(IndexPacket) ((unsigned long) indexes[x] & 0xff);
657      p++;
658      k=(long) (((unsigned long) index << (MaxGIFBits-8))+waiting_code);
659      if (k >= MaxHashTable)
660        k-=MaxHashTable;
661      next_pixel=MagickFalse;
662      displacement=1;
663      if (hash_code[k] > 0)
664        {
665          if ((hash_prefix[k] == waiting_code) &&
666              (hash_suffix[k] == (unsigned char) index))
667            {
668              waiting_code=hash_code[k];
669              continue;
670            }
671          if (k != 0)
672            displacement=MaxHashTable-k;
673          for ( ; ; )
674          {
675            k-=displacement;
676            if (k < 0)
677              k+=MaxHashTable;
678            if (hash_code[k] == 0)
679              break;
680            if ((hash_prefix[k] == waiting_code) &&
681                (hash_suffix[k] == (unsigned char) index))
682              {
683                waiting_code=hash_code[k];
684                next_pixel=MagickTrue;
685                break;
686              }
687          }
688          if (next_pixel == MagickTrue)
689            continue;
690        }
691      GIFOutputCode((unsigned long) waiting_code);
692      if (free_code < MaxGIFTable)
693        {
694          hash_code[k]=(short) free_code++;
695          hash_prefix[k]=waiting_code;
696          hash_suffix[k]=(unsigned char) index;
697        }
698      else
699        {
700          /*
701            Fill the hash table with empty entries.
702          */
703          for (k=0; k < MaxHashTable; k++)
704            hash_code[k]=0;
705          /*
706            Reset compressor and issue a clear code.
707          */
708          free_code=clear_code+2;
709          GIFOutputCode(clear_code);
710          number_bits=data_size;
711          max_code=MaxCode(number_bits);
712        }
713      waiting_code=(short) index;
714    }
715    if (image_info->interlace == NoInterlace)
716      offset++;
717    else
718      switch (pass)
719      {
720        case 0:
721        default:
722        {
723          offset+=8;
724          if (offset >= (long) image->rows)
725            {
726              pass++;
727              offset=4;
728            }
729          break;
730        }
731        case 1:
732        {
733          offset+=8;
734          if (offset >= (long) image->rows)
735            {
736              pass++;
737              offset=2;
738            }
739          break;
740        }
741        case 2:
742        {
743          offset+=4;
744          if (offset >= (long) image->rows)
745            {
746              pass++;
747              offset=1;
748            }
749          break;
750        }
751        case 3:
752        {
753          offset+=2;
754          break;
755        }
756      }
757  }
758  /*
759    Flush out the buffered code.
760  */
761  GIFOutputCode((unsigned long) waiting_code);
762  GIFOutputCode(end_of_information_code);
763  if (bits > 0)
764    {
765      /*
766        Add a character to current packet.
767      */
768      packet[length++]=(unsigned char) (datum & 0xff);
769      if (length >= 254)
770        {
771          (void) WriteBlobByte(image,(unsigned char) length);
772          (void) WriteBlob(image,length,packet);
773          length=0;
774        }
775    }
776  /*
777    Flush accumulated data.
778  */
779  if (length > 0)
780    {
781      (void) WriteBlobByte(image,(unsigned char) length);
782      (void) WriteBlob(image,length,packet);
783    }
784  /*
785    Free encoder memory.
786  */
787  hash_suffix=(unsigned char *) RelinquishMagickMemory(hash_suffix);
788  hash_prefix=(short *) RelinquishMagickMemory(hash_prefix);
789  hash_code=(short *) RelinquishMagickMemory(hash_code);
790  packet=(unsigned char *) RelinquishMagickMemory(packet);
791  return(MagickTrue);
792}
793
794/*
795%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
796%                                                                             %
797%                                                                             %
798%                                                                             %
799%   I s G I F                                                                 %
800%                                                                             %
801%                                                                             %
802%                                                                             %
803%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
804%
805%  IsGIF() returns MagickTrue if the image format type, identified by the
806%  magick string, is GIF.
807%
808%  The format of the IsGIF method is:
809%
810%      MagickBooleanType IsGIF(const unsigned char *magick,const size_t length)
811%
812%  A description of each parameter follows:
813%
814%    o magick: This string is generally the first few bytes of an image file
815%      or blob.
816%
817%    o length: Specifies the length of the magick string.
818%
819*/
820static MagickBooleanType IsGIF(const unsigned char *magick,const size_t length)
821{
822  if (length < 4)
823    return(MagickFalse);
824  if (LocaleNCompare((char *) magick,"GIF8",4) == 0)
825    return(MagickTrue);
826  return(MagickFalse);
827}
828
829/*
830%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
831%                                                                             %
832%                                                                             %
833%                                                                             %
834+  R e a d B l o b B l o c k                                                  %
835%                                                                             %
836%                                                                             %
837%                                                                             %
838%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
839%
840%  ReadBlobBlock() reads data from the image file and returns it.  The
841%  amount of data is determined by first reading a count byte.  The number
842%  of bytes read is returned.
843%
844%  The format of the ReadBlobBlock method is:
845%
846%      size_t ReadBlobBlock(Image *image,unsigned char *data)
847%
848%  A description of each parameter follows:
849%
850%    o image: the image.
851%
852%    o data:  Specifies an area to place the information requested from
853%      the file.
854%
855*/
856static ssize_t ReadBlobBlock(Image *image,unsigned char *data)
857{
858  ssize_t
859    count;
860
861  unsigned char
862    block_count;
863
864  assert(image != (Image *) NULL);
865  assert(image->signature == MagickSignature);
866  assert(data != (unsigned char *) NULL);
867  count=ReadBlob(image,1,&block_count);
868  if (count != 1)
869    return(0);
870  return(ReadBlob(image,(size_t) block_count,data));
871}
872
873/*
874%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
875%                                                                             %
876%                                                                             %
877%                                                                             %
878%   R e a d G I F I m a g e                                                   %
879%                                                                             %
880%                                                                             %
881%                                                                             %
882%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
883%
884%  ReadGIFImage() reads a Compuserve Graphics image file and returns it.
885%  It allocates the memory necessary for the new Image structure and returns a
886%  pointer to the new image.
887%
888%  The format of the ReadGIFImage method is:
889%
890%      Image *ReadGIFImage(const ImageInfo *image_info,ExceptionInfo *exception)
891%
892%  A description of each parameter follows:
893%
894%    o image_info: the image info.
895%
896%    o exception: return any errors or warnings in this structure.
897%
898*/
899
900static inline size_t MagickMax(const size_t x,const size_t y)
901{
902  if (x > y)
903    return(x);
904  return(y);
905}
906
907static inline size_t MagickMin(const size_t x,const size_t y)
908{
909  if (x < y)
910    return(x);
911  return(y);
912}
913
914static MagickBooleanType PingGIFImage(Image *image)
915{
916  unsigned char
917    buffer[256],
918    length,
919    data_size;
920
921  assert(image != (Image *) NULL);
922  assert(image->signature == MagickSignature);
923  if (image->debug != MagickFalse)
924    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
925  if (ReadBlob(image,1,&data_size) != 1)
926    ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename);
927  if (data_size > MaximumLZWBits)
928    ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename);
929  if (ReadBlob(image,1,&length) != 1)
930    ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename);
931  while (length != 0)
932  {
933    if (ReadBlob(image,length,buffer) != (ssize_t) length)
934      ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename);
935    if (ReadBlob(image,1,&length) != 1)
936      ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename);
937  }
938  return(MagickTrue);
939}
940
941static Image *ReadGIFImage(const ImageInfo *image_info,ExceptionInfo *exception)
942{
943#define BitSet(byte,bit)  (((byte) & (bit)) == (bit))
944#define LSBFirstOrder(x,y)  (((y) << 8) | (x))
945
946  Image
947    *image;
948
949  int
950    number_extensionss=0;
951
952  long
953    opacity;
954
955  MagickBooleanType
956    status;
957
958  RectangleInfo
959    page;
960
961  register long
962    i;
963
964  register unsigned char
965    *p;
966
967  ssize_t
968    count;
969
970  unsigned char
971    background,
972    c,
973    flag,
974    *global_colormap,
975    header[MaxTextExtent],
976    magick[12];
977
978  unsigned long
979    delay,
980    dispose,
981    global_colors,
982    image_count,
983    iterations;
984
985  /*
986    Open image file.
987  */
988  assert(image_info != (const ImageInfo *) NULL);
989  assert(image_info->signature == MagickSignature);
990  if (image_info->debug != MagickFalse)
991    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
992      image_info->filename);
993  assert(exception != (ExceptionInfo *) NULL);
994  assert(exception->signature == MagickSignature);
995  image=AcquireImage(image_info);
996  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
997  if (status == MagickFalse)
998    {
999      image=DestroyImageList(image);
1000      return((Image *) NULL);
1001    }
1002  /*
1003    Determine if this a GIF file.
1004  */
1005  count=ReadBlob(image,6,magick);
1006  if ((count != 6) || ((LocaleNCompare((char *) magick,"GIF87",5) != 0) &&
1007      (LocaleNCompare((char *) magick,"GIF89",5) != 0)))
1008    ThrowReaderException(CorruptImageError,"ImproperImageHeader");
1009  page.width=ReadBlobLSBShort(image);
1010  page.height=ReadBlobLSBShort(image);
1011  flag=(unsigned char) ReadBlobByte(image);
1012  background=(unsigned char) ReadBlobByte(image);
1013  c=(unsigned char) ReadBlobByte(image);  /* reserved */
1014  global_colors=1UL << (((unsigned long) flag & 0x07)+1);
1015  global_colormap=(unsigned char *) AcquireQuantumMemory((size_t)
1016    MagickMax(global_colors,256),3UL*sizeof(*global_colormap));
1017  if (global_colormap == (unsigned char *) NULL)
1018    ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1019  if (BitSet((int) flag,0x80) != 0)
1020    count=ReadBlob(image,(size_t) (3*global_colors),global_colormap);
1021  delay=0;
1022  dispose=0;
1023  iterations=1;
1024  opacity=(-1);
1025  image_count=0;
1026  for ( ; ; )
1027  {
1028    count=ReadBlob(image,1,&c);
1029    if (count != 1)
1030      break;
1031    if (c == (unsigned