]> granicus.if.org Git - imagemagick/blob - coders/gif.c
(no commit message)
[imagemagick] / coders / gif.c
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-2011 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 \f
39 /*
40   Include declarations.
41 */
42 #include "magick/studio.h"
43 #include "magick/blob.h"
44 #include "magick/blob-private.h"
45 #include "magick/cache.h"
46 #include "magick/color.h"
47 #include "magick/color-private.h"
48 #include "magick/colormap.h"
49 #include "magick/colormap-private.h"
50 #include "magick/colorspace.h"
51 #include "magick/exception.h"
52 #include "magick/exception-private.h"
53 #include "magick/image.h"
54 #include "magick/image-private.h"
55 #include "magick/list.h"
56 #include "magick/profile.h"
57 #include "magick/magick.h"
58 #include "magick/memory_.h"
59 #include "magick/monitor.h"
60 #include "magick/monitor-private.h"
61 #include "magick/option.h"
62 #include "magick/property.h"
63 #include "magick/quantize.h"
64 #include "magick/quantum-private.h"
65 #include "magick/static.h"
66 #include "magick/string_.h"
67 #include "magick/module.h"
68 \f
69 /*
70   Define declarations.
71 */
72 #define MaximumLZWBits  12
73 #define MaximumLZWCode  (1UL << MaximumLZWBits)
74 \f
75 /*
76   Typdef declarations.
77 */
78 typedef struct _LZWCodeInfo
79 {
80   unsigned char
81     buffer[280];
82
83   size_t
84     count,
85     bit;
86
87   MagickBooleanType
88     eof;
89 } LZWCodeInfo;
90
91 typedef struct _LZWStack
92 {
93   size_t
94     *codes,
95     *index,
96     *top;
97 } LZWStack;
98
99 typedef struct _LZWInfo
100 {
101   Image
102     *image;
103
104   LZWStack
105     *stack;
106
107   MagickBooleanType
108     genesis;
109
110   size_t
111     data_size,
112     maximum_data_value,
113     clear_code,
114     end_code,
115     bits,
116     first_code,
117     last_code,
118     maximum_code,
119     slot,
120     *table[2];
121
122   LZWCodeInfo
123     code_info;
124 } LZWInfo;
125 \f
126 /*
127   Forward declarations.
128 */
129 static inline int
130   GetNextLZWCode(LZWInfo *,const size_t);
131
132 static MagickBooleanType
133   WriteGIFImage(const ImageInfo *,Image *);
134
135 static ssize_t
136   ReadBlobBlock(Image *,unsigned char *);
137 \f
138 /*
139 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
140 %                                                                             %
141 %                                                                             %
142 %                                                                             %
143 %   D e c o d e I m a g e                                                     %
144 %                                                                             %
145 %                                                                             %
146 %                                                                             %
147 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
148 %
149 %  DecodeImage uncompresses an image via GIF-coding.
150 %
151 %  The format of the DecodeImage method is:
152 %
153 %      MagickBooleanType DecodeImage(Image *image,const ssize_t opacity)
154 %
155 %  A description of each parameter follows:
156 %
157 %    o image: the address of a structure of type Image.
158 %
159 %    o opacity:  The colormap index associated with the transparent color.
160 %
161 */
162
163 static LZWInfo *RelinquishLZWInfo(LZWInfo *lzw_info)
164 {
165   if (lzw_info->table[0] != (size_t *) NULL)
166     lzw_info->table[0]=(size_t *) RelinquishMagickMemory(
167       lzw_info->table[0]);
168   if (lzw_info->table[1] != (size_t *) NULL)
169     lzw_info->table[1]=(size_t *) RelinquishMagickMemory(
170       lzw_info->table[1]);
171   if (lzw_info->stack != (LZWStack *) NULL)
172     {
173       if (lzw_info->stack->codes != (size_t *) NULL)
174         lzw_info->stack->codes=(size_t *) RelinquishMagickMemory(
175           lzw_info->stack->codes);
176       lzw_info->stack=(LZWStack *) RelinquishMagickMemory(lzw_info->stack);
177     }
178   lzw_info=(LZWInfo *) RelinquishMagickMemory(lzw_info);
179   return((LZWInfo *) NULL);
180 }
181
182 static inline void ResetLZWInfo(LZWInfo *lzw_info)
183 {
184   size_t
185     one;
186
187   lzw_info->bits=lzw_info->data_size+1;
188   one=1;
189   lzw_info->maximum_code=one << lzw_info->bits;
190   lzw_info->slot=lzw_info->maximum_data_value+3;
191   lzw_info->genesis=MagickTrue;
192 }
193
194 static LZWInfo *AcquireLZWInfo(Image *image,const size_t data_size)
195 {
196   LZWInfo
197     *lzw_info;
198
199   register ssize_t
200     i;
201
202   size_t
203     one;
204
205   lzw_info=(LZWInfo *) AcquireMagickMemory(sizeof(*lzw_info));
206   if (lzw_info == (LZWInfo *) NULL)
207     return((LZWInfo *) NULL);
208   (void) ResetMagickMemory(lzw_info,0,sizeof(*lzw_info));
209   lzw_info->image=image;
210   lzw_info->data_size=data_size;
211   one=1;
212   lzw_info->maximum_data_value=(one << data_size)-1;
213   lzw_info->clear_code=lzw_info->maximum_data_value+1;
214   lzw_info->end_code=lzw_info->maximum_data_value+2;
215   lzw_info->table[0]=(size_t *) AcquireQuantumMemory(MaximumLZWCode,
216     sizeof(*lzw_info->table));
217   lzw_info->table[1]=(size_t *) AcquireQuantumMemory(MaximumLZWCode,
218     sizeof(*lzw_info->table));
219   if ((lzw_info->table[0] == (size_t *) NULL) ||
220       (lzw_info->table[1] == (size_t *) NULL))
221     {
222       lzw_info=RelinquishLZWInfo(lzw_info);
223       return((LZWInfo *) NULL);
224     }
225   for (i=0; i <= (ssize_t) lzw_info->maximum_data_value; i++)
226   {
227     lzw_info->table[0][i]=0;
228     lzw_info->table[1][i]=(size_t) i;
229   }
230   ResetLZWInfo(lzw_info);
231   lzw_info->code_info.buffer[0]='\0';
232   lzw_info->code_info.buffer[1]='\0';
233   lzw_info->code_info.count=2;
234   lzw_info->code_info.bit=8*lzw_info->code_info.count;
235   lzw_info->code_info.eof=MagickFalse;
236   lzw_info->genesis=MagickTrue;
237   lzw_info->stack=(LZWStack *) AcquireMagickMemory(sizeof(*lzw_info->stack));
238   if (lzw_info->stack == (LZWStack *) NULL)
239     {
240       lzw_info=RelinquishLZWInfo(lzw_info);
241       return((LZWInfo *) NULL);
242     }
243   lzw_info->stack->codes=(size_t *) AcquireQuantumMemory(2UL*
244     MaximumLZWCode,sizeof(*lzw_info->stack->codes));
245   if (lzw_info->stack->codes == (size_t *) NULL)
246     {
247       lzw_info=RelinquishLZWInfo(lzw_info);
248       return((LZWInfo *) NULL);
249     }
250   lzw_info->stack->index=lzw_info->stack->codes;
251   lzw_info->stack->top=lzw_info->stack->codes+2*MaximumLZWCode;
252   return(lzw_info);
253 }
254
255 static inline int GetNextLZWCode(LZWInfo *lzw_info,const size_t bits)
256 {
257   int
258     code;
259
260   register ssize_t
261     i;
262
263   size_t
264     one;
265
266   while (((lzw_info->code_info.bit+bits) > (8*lzw_info->code_info.count)) &&
267          (lzw_info->code_info.eof == MagickFalse))
268   {
269     ssize_t
270       count;
271
272     lzw_info->code_info.buffer[0]=lzw_info->code_info.buffer[
273       lzw_info->code_info.count-2];
274     lzw_info->code_info.buffer[1]=lzw_info->code_info.buffer[
275       lzw_info->code_info.count-1];
276     lzw_info->code_info.bit-=8*(lzw_info->code_info.count-2);
277     lzw_info->code_info.count=2;
278     count=ReadBlobBlock(lzw_info->image,&lzw_info->code_info.buffer[
279       lzw_info->code_info.count]);
280     if (count > 0)
281       lzw_info->code_info.count+=count;
282     else
283       lzw_info->code_info.eof=MagickTrue;
284   }
285   if ((lzw_info->code_info.bit+bits) > (8*lzw_info->code_info.count))
286     return(-1);
287   code=0;
288   one=1;
289   for (i=0; i < (ssize_t) bits; i++)
290   {
291     code|=((lzw_info->code_info.buffer[lzw_info->code_info.bit/8] &
292       (one << (lzw_info->code_info.bit % 8))) != 0) << i;
293     lzw_info->code_info.bit++;
294   }
295   return(code);
296 }
297
298 static inline int PopLZWStack(LZWStack *stack_info)
299 {
300   if (stack_info->index <= stack_info->codes)
301     return(-1);
302   stack_info->index--;
303   return((int) *stack_info->index);
304 }
305
306 static inline void PushLZWStack(LZWStack *stack_info,const size_t value)
307 {
308   if (stack_info->index >= stack_info->top)
309     return;
310   *stack_info->index=value;
311   stack_info->index++;
312 }
313
314 static int ReadBlobLZWByte(LZWInfo *lzw_info)
315 {
316   int
317     code;
318
319   ssize_t
320     count;
321
322   size_t
323     one,
324     value;
325
326   if (lzw_info->stack->index != lzw_info->stack->codes)
327     return(PopLZWStack(lzw_info->stack));
328   if (lzw_info->genesis != MagickFalse)
329     {
330       lzw_info->genesis=MagickFalse;
331       do
332       {
333         lzw_info->first_code=(size_t) GetNextLZWCode(lzw_info,
334           lzw_info->bits);
335         lzw_info->last_code=lzw_info->first_code;
336       } while (lzw_info->first_code == lzw_info->clear_code);
337       return((int) lzw_info->first_code);
338     }
339   code=GetNextLZWCode(lzw_info,lzw_info->bits);
340   if (code < 0)
341     return(code);
342   if ((size_t) code == lzw_info->clear_code)
343     {
344       ResetLZWInfo(lzw_info);
345       return(ReadBlobLZWByte(lzw_info));
346     }
347   if ((size_t) code == lzw_info->end_code)
348     return(-1);
349   if ((size_t) code < lzw_info->slot)
350     value=(size_t) code;
351   else
352     {
353       PushLZWStack(lzw_info->stack,lzw_info->first_code);
354       value=lzw_info->last_code;
355     }
356   count=0;
357   while (value > lzw_info->maximum_data_value)
358   {
359     if ((size_t) count > MaximumLZWCode)
360       return(-1);
361     count++;
362     if ((size_t) value > MaximumLZWCode)
363       return(-1);
364     PushLZWStack(lzw_info->stack,lzw_info->table[1][value]);
365     value=lzw_info->table[0][value];
366   }
367   lzw_info->first_code=lzw_info->table[1][value];
368   PushLZWStack(lzw_info->stack,lzw_info->first_code);
369   one=1;
370   if (lzw_info->slot < MaximumLZWCode)
371     {
372       lzw_info->table[0][lzw_info->slot]=lzw_info->last_code;
373       lzw_info->table[1][lzw_info->slot]=lzw_info->first_code;
374       lzw_info->slot++;
375       if ((lzw_info->slot >= lzw_info->maximum_code) &&
376           (lzw_info->bits < MaximumLZWBits))
377         {
378           lzw_info->bits++;
379           lzw_info->maximum_code=one << lzw_info->bits;
380         }
381     }
382   lzw_info->last_code=(size_t) code;
383   return(PopLZWStack(lzw_info->stack));
384 }
385
386 static MagickBooleanType DecodeImage(Image *image,const ssize_t opacity)
387 {
388   ExceptionInfo
389     *exception;
390
391   IndexPacket
392     index;
393
394   int
395     c;
396
397   ssize_t
398     offset,
399     y;
400
401   LZWInfo
402     *lzw_info;
403
404   unsigned char
405     data_size;
406
407   size_t
408     pass;
409
410   /*
411     Allocate decoder tables.
412   */
413   assert(image != (Image *) NULL);
414   assert(image->signature == MagickSignature);
415   if (image->debug != MagickFalse)
416     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
417   data_size=(unsigned char) ReadBlobByte(image);
418   if (data_size > MaximumLZWBits)
419     ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename);
420   lzw_info=AcquireLZWInfo(image,data_size);
421   if (lzw_info == (LZWInfo *) NULL)
422     ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
423       image->filename);
424   exception=(&image->exception);
425   pass=0;
426   offset=0;
427   for (y=0; y < (ssize_t) image->rows; y++)
428   {
429     register IndexPacket
430       *restrict indexes;
431
432     register ssize_t
433       x;
434
435     register PixelPacket
436       *restrict q;
437
438     q=GetAuthenticPixels(image,0,offset,image->columns,1,exception);
439     if (q == (PixelPacket *) NULL)
440       break;
441     indexes=GetAuthenticIndexQueue(image);
442     for (x=0; x < (ssize_t) image->columns; )
443     {
444       c=ReadBlobLZWByte(lzw_info);
445       if (c < 0)
446         break;
447       index=ConstrainColormapIndex(image,(size_t) c);
448       SetIndexPixelComponent(indexes+x,index);
449       SetRedPixelComponent(q,image->colormap[(ssize_t) index].red);
450       SetGreenPixelComponent(q,image->colormap[(ssize_t) index].green);
451       SetBluePixelComponent(q,image->colormap[(ssize_t) index].blue);
452       SetOpacityPixelComponent(q,(ssize_t) index == opacity ?
453         TransparentOpacity : OpaqueOpacity);
454       x++;
455       q++;
456     }
457     if (x < (ssize_t) image->columns)
458       break;
459     if (image->interlace == NoInterlace)
460       offset++;
461     else
462       switch (pass)
463       {
464         case 0:
465         default:
466         {
467           offset+=8;
468           if (offset >= (ssize_t) image->rows)
469             {
470               pass++;
471               offset=4;
472             }
473           break;
474         }
475         case 1:
476         {
477           offset+=8;
478           if (offset >= (ssize_t) image->rows)
479             {
480               pass++;
481               offset=2;
482             }
483           break;
484         }
485         case 2:
486         {
487           offset+=4;
488           if (offset >= (ssize_t) image->rows)
489             {
490               pass++;
491               offset=1;
492             }
493           break;
494         }
495         case 3:
496         {
497           offset+=2;
498           break;
499         }
500       }
501     if (SyncAuthenticPixels(image,exception) == MagickFalse)
502       break;
503   }
504   lzw_info=RelinquishLZWInfo(lzw_info);
505   if (y < (ssize_t) image->rows)
506     ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename);
507   return(MagickTrue);
508 }
509 \f
510 /*
511 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
512 %                                                                             %
513 %                                                                             %
514 %                                                                             %
515 %   E n c o d e I m a g e                                                     %
516 %                                                                             %
517 %                                                                             %
518 %                                                                             %
519 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
520 %
521 %  EncodeImage compresses an image via GIF-coding.
522 %
523 %  The format of the EncodeImage method is:
524 %
525 %      MagickBooleanType EncodeImage(const ImageInfo *image_info,Image *image,
526 %        const size_t data_size)
527 %
528 %  A description of each parameter follows:
529 %
530 %    o image_info: the image info.
531 %
532 %    o image: the address of a structure of type Image.
533 %
534 %    o data_size:  The number of bits in the compressed packet.
535 %
536 */
537 static MagickBooleanType EncodeImage(const ImageInfo *image_info,Image *image,
538   const size_t data_size)
539 {
540 #define MaxCode(number_bits)  ((one << (number_bits))-1)
541 #define MaxHashTable  5003
542 #define MaxGIFBits  12UL
543 #define MaxGIFTable  (1UL << MaxGIFBits)
544 #define GIFOutputCode(code) \
545 { \
546   /*  \
547     Emit a code. \
548   */ \
549   if (bits > 0) \
550     datum|=(code) << bits; \
551   else \
552     datum=code; \
553   bits+=number_bits; \
554   while (bits >= 8) \
555   { \
556     /*  \
557       Add a character to current packet. \
558     */ \
559     packet[length++]=(unsigned char) (datum & 0xff); \
560     if (length >= 254) \
561       { \
562         (void) WriteBlobByte(image,(unsigned char) length); \
563         (void) WriteBlob(image,length,packet); \
564         length=0; \
565       } \
566     datum>>=8; \
567     bits-=8; \
568   } \
569   if (free_code > max_code)  \
570     { \
571       number_bits++; \
572       if (number_bits == MaxGIFBits) \
573         max_code=MaxGIFTable; \
574       else \
575         max_code=MaxCode(number_bits); \
576     } \
577 }
578
579   IndexPacket
580     index;
581
582   register ssize_t
583     i;
584
585   short
586     *hash_code,
587     *hash_prefix,
588     waiting_code;
589
590   size_t
591     bits,
592     clear_code,
593     datum,
594     end_of_information_code,
595     free_code,
596     length,
597     max_code,
598     next_pixel,
599     number_bits,
600     one,
601     pass;
602
603   ssize_t
604     displacement,
605     offset,
606     k,
607     y;
608
609   unsigned char
610     *packet,
611     *hash_suffix;
612
613   /*
614     Allocate encoder tables.
615   */
616   assert(image != (Image *) NULL);
617   one=1;
618   packet=(unsigned char *) AcquireQuantumMemory(256,sizeof(*packet));
619   hash_code=(short *) AcquireQuantumMemory(MaxHashTable,sizeof(*hash_code));
620   hash_prefix=(short *) AcquireQuantumMemory(MaxHashTable,sizeof(*hash_prefix));
621   hash_suffix=(unsigned char *) AcquireQuantumMemory(MaxHashTable,
622     sizeof(*hash_suffix));
623   if ((packet == (unsigned char *) NULL) || (hash_code == (short *) NULL) ||
624       (hash_prefix == (short *) NULL) ||
625       (hash_suffix == (unsigned char *) NULL))
626     {
627       if (packet != (unsigned char *) NULL)
628         packet=(unsigned char *) RelinquishMagickMemory(packet);
629       if (hash_code != (short *) NULL)
630         hash_code=(short *) RelinquishMagickMemory(hash_code);
631       if (hash_prefix != (short *) NULL)
632         hash_prefix=(short *) RelinquishMagickMemory(hash_prefix);
633       if (hash_suffix != (unsigned char *) NULL)
634         hash_suffix=(unsigned char *) RelinquishMagickMemory(hash_suffix);
635       return(MagickFalse);
636     }
637   /*
638     Initialize GIF encoder.
639   */
640   number_bits=data_size;
641   max_code=MaxCode(number_bits);
642   clear_code=((short) one << (data_size-1));
643   end_of_information_code=clear_code+1;
644   free_code=clear_code+2;
645   length=0;
646   datum=0;
647   bits=0;
648   for (i=0; i < MaxHashTable; i++)
649     hash_code[i]=0;
650   GIFOutputCode(clear_code);
651   /*
652     Encode pixels.
653   */
654   offset=0;
655   pass=0;
656   waiting_code=0;
657   for (y=0; y < (ssize_t) image->rows; y++)
658   {
659     register const IndexPacket
660       *restrict indexes;
661
662     register const PixelPacket
663       *restrict p;
664
665     register ssize_t
666       x;
667
668     p=GetVirtualPixels(image,0,offset,image->columns,1,&image->exception);
669     if (p == (const PixelPacket *) NULL)
670       break;
671     indexes=GetVirtualIndexQueue(image);
672     if (y == 0)
673       waiting_code=(short) (*indexes);
674     for (x=(ssize_t) (y == 0 ? 1 : 0); x < (ssize_t) image->columns; x++)
675     {
676       /*
677         Probe hash table.
678       */
679       index=(IndexPacket) ((size_t) GetIndexPixelComponent(indexes+x) & 0xff);
680       p++;
681       k=(ssize_t) (((size_t) index << (MaxGIFBits-8))+waiting_code);
682       if (k >= MaxHashTable)
683         k-=MaxHashTable;
684       next_pixel=MagickFalse;
685       displacement=1;
686       if (hash_code[k] > 0)
687         {
688           if ((hash_prefix[k] == waiting_code) &&
689               (hash_suffix[k] == (unsigned char) index))
690             {
691               waiting_code=hash_code[k];
692               continue;
693             }
694           if (k != 0)
695             displacement=MaxHashTable-k;
696           for ( ; ; )
697           {
698             k-=displacement;
699             if (k < 0)
700               k+=MaxHashTable;
701             if (hash_code[k] == 0)
702               break;
703             if ((hash_prefix[k] == waiting_code) &&
704                 (hash_suffix[k] == (unsigned char) index))
705               {
706                 waiting_code=hash_code[k];
707                 next_pixel=MagickTrue;
708                 break;
709               }
710           }
711           if (next_pixel == MagickTrue)
712             continue;
713         }
714       GIFOutputCode((size_t) waiting_code);
715       if (free_code < MaxGIFTable)
716         {
717           hash_code[k]=(short) free_code++;
718           hash_prefix[k]=waiting_code;
719           hash_suffix[k]=(unsigned char) index;
720         }
721       else
722         {
723           /*
724             Fill the hash table with empty entries.
725           */
726           for (k=0; k < MaxHashTable; k++)
727             hash_code[k]=0;
728           /*
729             Reset compressor and issue a clear code.
730           */
731           free_code=clear_code+2;
732           GIFOutputCode(clear_code);
733           number_bits=data_size;
734           max_code=MaxCode(number_bits);
735         }
736       waiting_code=(short) index;
737     }
738     if (image_info->interlace == NoInterlace)
739       offset++;
740     else
741       switch (pass)
742       {
743         case 0:
744         default:
745         {
746           offset+=8;
747           if (offset >= (ssize_t) image->rows)
748             {
749               pass++;
750               offset=4;
751             }
752           break;
753         }
754         case 1:
755         {
756           offset+=8;
757           if (offset >= (ssize_t) image->rows)
758             {
759               pass++;
760               offset=2;
761             }
762           break;
763         }
764         case 2:
765         {
766           offset+=4;
767           if (offset >= (ssize_t) image->rows)
768             {
769               pass++;
770               offset=1;
771             }
772           break;
773         }
774         case 3:
775         {
776           offset+=2;
777           break;
778         }
779       }
780   }
781   /*
782     Flush out the buffered code.
783   */
784   GIFOutputCode((size_t) waiting_code);
785   GIFOutputCode(end_of_information_code);
786   if (bits > 0)
787     {
788       /*
789         Add a character to current packet.
790       */
791       packet[length++]=(unsigned char) (datum & 0xff);
792       if (length >= 254)
793         {
794           (void) WriteBlobByte(image,(unsigned char) length);
795           (void) WriteBlob(image,length,packet);
796           length=0;
797         }
798     }
799   /*
800     Flush accumulated data.
801   */
802   if (length > 0)
803     {
804       (void) WriteBlobByte(image,(unsigned char) length);
805       (void) WriteBlob(image,length,packet);
806     }
807   /*
808     Free encoder memory.
809   */
810   hash_suffix=(unsigned char *) RelinquishMagickMemory(hash_suffix);
811   hash_prefix=(short *) RelinquishMagickMemory(hash_prefix);
812   hash_code=(short *) RelinquishMagickMemory(hash_code);
813   packet=(unsigned char *) RelinquishMagickMemory(packet);
814   return(MagickTrue);
815 }
816 \f
817 /*
818 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
819 %                                                                             %
820 %                                                                             %
821 %                                                                             %
822 %   I s G I F                                                                 %
823 %                                                                             %
824 %                                                                             %
825 %                                                                             %
826 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
827 %
828 %  IsGIF() returns MagickTrue if the image format type, identified by the
829 %  magick string, is GIF.
830 %
831 %  The format of the IsGIF method is:
832 %
833 %      MagickBooleanType IsGIF(const unsigned char *magick,const size_t length)
834 %
835 %  A description of each parameter follows:
836 %
837 %    o magick: compare image format pattern against these bytes.
838 %
839 %    o length: Specifies the length of the magick string.
840 %
841 */
842 static MagickBooleanType IsGIF(const unsigned char *magick,const size_t length)
843 {
844   if (length < 4)
845     return(MagickFalse);
846   if (LocaleNCompare((char *) magick,"GIF8",4) == 0)
847     return(MagickTrue);
848   return(MagickFalse);
849 }
850 \f
851 /*
852 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
853 %                                                                             %
854 %                                                                             %
855 %                                                                             %
856 +  R e a d B l o b B l o c k                                                  %
857 %                                                                             %
858 %                                                                             %
859 %                                                                             %
860 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
861 %
862 %  ReadBlobBlock() reads data from the image file and returns it.  The
863 %  amount of data is determined by first reading a count byte.  The number
864 %  of bytes read is returned.
865 %
866 %  The format of the ReadBlobBlock method is:
867 %
868 %      size_t ReadBlobBlock(Image *image,unsigned char *data)
869 %
870 %  A description of each parameter follows:
871 %
872 %    o image: the image.
873 %
874 %    o data:  Specifies an area to place the information requested from
875 %      the file.
876 %
877 */
878 static ssize_t ReadBlobBlock(Image *image,unsigned char *data)
879 {
880   ssize_t
881     count;
882
883   unsigned char
884     block_count;
885
886   assert(image != (Image *) NULL);
887   assert(image->signature == MagickSignature);
888   assert(data != (unsigned char *) NULL);
889   count=ReadBlob(image,1,&block_count);
890   if (count != 1)
891     return(0);
892   return(ReadBlob(image,(size_t) block_count,data));
893 }
894 \f
895 /*
896 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
897 %                                                                             %
898 %                                                                             %
899 %                                                                             %
900 %   R e a d G I F I m a g e                                                   %
901 %                                                                             %
902 %                                                                             %
903 %                                                                             %
904 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
905 %
906 %  ReadGIFImage() reads a Compuserve Graphics image file and returns it.
907 %  It allocates the memory necessary for the new Image structure and returns a
908 %  pointer to the new image.
909 %
910 %  The format of the ReadGIFImage method is:
911 %
912 %      Image *ReadGIFImage(const ImageInfo *image_info,ExceptionInfo *exception)
913 %
914 %  A description of each parameter follows:
915 %
916 %    o image_info: the image info.
917 %
918 %    o exception: return any errors or warnings in this structure.
919 %
920 */
921
922 static inline size_t MagickMax(const size_t x,const size_t y)
923 {
924   if (x > y)
925     return(x);
926   return(y);
927 }
928
929 static inline size_t MagickMin(const size_t x,const size_t y)
930 {
931   if (x < y)
932     return(x);
933   return(y);
934 }
935
936 static MagickBooleanType PingGIFImage(Image *image)
937 {
938   unsigned char
939     buffer[256],
940     length,
941     data_size;
942
943   assert(image != (Image *) NULL);
944   assert(image->signature == MagickSignature);
945   if (image->debug != MagickFalse)
946     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
947   if (ReadBlob(image,1,&data_size) != 1)
948     ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename);
949   if (data_size > MaximumLZWBits)
950     ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename);
951   if (ReadBlob(image,1,&length) != 1)
952     ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename);
953   while (length != 0)
954   {
955     if (ReadBlob(image,length,buffer) != (ssize_t) length)
956       ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename);
957     if (ReadBlob(image,1,&length) != 1)
958       ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename);
959   }
960   return(MagickTrue);
961 }
962
963 static Image *ReadGIFImage(const ImageInfo *image_info,ExceptionInfo *exception)
964 {
965 #define BitSet(byte,bit)  (((byte) & (bit)) == (bit))
966 #define LSBFirstOrder(x,y)  (((y) << 8) | (x))
967
968   Image
969     *image;
970
971   int
972     number_extensionss=0;
973
974   MagickBooleanType
975     status;
976
977   RectangleInfo
978     page;
979
980   register ssize_t
981     i;
982
983   register unsigned char
984     *p;
985
986   size_t
987     delay,
988     dispose,
989     global_colors,
990     image_count,
991     iterations,
992     one;
993
994   ssize_t
995     count,
996     opacity;
997
998   unsigned char
999     background,
1000     c,
1001     flag,
1002     *global_colormap,
1003     header[MaxTextExtent],
1004     magick[12];
1005
1006   /*
1007     Open image file.
1008   */
1009   assert(image_info != (const ImageInfo *) NULL);
1010   assert(image_info->signature == MagickSignature);
1011   if (image_info->debug != MagickFalse)
1012     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
1013       image_info->filename);
1014   assert(exception != (ExceptionInfo *) NULL);
1015   assert(exception->signature == MagickSignature);
1016   image=AcquireImage(image_info);
1017   status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
1018   if (status == MagickFalse)
1019     {
1020       image=DestroyImageList(image);
1021       return((Image *) NULL);
1022     }
1023   /*
1024     Determine if this a GIF file.
1025   */
1026   count=ReadBlob(image,6,magick);
1027   if ((count != 6) || ((LocaleNCompare((char *) magick,"GIF87",5) != 0) &&
1028       (LocaleNCompare((char *) magick,"GIF89",5) != 0)))
1029     ThrowReaderException(CorruptImageError,"ImproperImageHeader");
1030   page.width=ReadBlobLSBShort(image);
1031   page.height=ReadBlobLSBShort(image);
1032   flag=(unsigned char) ReadBlobByte(image);
1033   background=(unsigned char) ReadBlobByte(image);
1034   c=(unsigned char) ReadBlobByte(image);  /* reserved */
1035   one=1;
1036   global_colors=one << (((size_t) flag & 0x07)+1);
1037   global_colormap=(unsigned char *) AcquireQuantumMemory((size_t)
1038     MagickMax(global_colors,256),3UL*sizeof(*global_colormap));
1039   if (global_colormap == (unsigned char *) NULL)
1040     ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1041   if (BitSet((int) flag,0x80) != 0)
1042     count=ReadBlob(image,(size_t) (3*global_colors),global_colormap);
1043   delay=0;
1044   dispose=0;
1045   iterations=1;
1046   opacity=(-1);
1047   image_count=0;
1048   for ( ; ; )
1049   {
1050     count=ReadBlob(image,1,&c);
1051     if (count != 1)
1052       break;
1053     if (c == (unsigned char) ';')
1054       break;  /* terminator */
1055     if (c == (unsigned char) '!')
1056       {
1057         /*
1058           GIF Extension block.
1059         */
1060
1061         count=ReadBlob(image,1,&c);
1062         if (count != 1)
1063           {
1064             global_colormap=(unsigned char *) RelinquishMagickMemory(
1065               global_colormap);
1066             ThrowReaderException(CorruptImageError,
1067               "UnableToReadExtensionBlock");
1068           }
1069         switch (c)
1070         {
1071           case 0xf9:
1072           {
1073             /*
1074               Read graphics control extension.
1075             */
1076             while (ReadBlobBlock(image,header) != 0) ;
1077             dispose=(size_t) (header[0] >> 2);
1078             delay=(size_t) ((header[2] << 8) | header[1]);
1079             if ((ssize_t) (header[0] & 0x01) == 0x01)
1080               opacity=(ssize_t) header[3];
1081             break;
1082           }
1083           case 0xfe:
1084           {
1085             char
1086               *comments;
1087
1088             /*
1089               Read comment extension.
1090             */
1091             comments=AcquireString((char *) NULL);
1092             for ( ; ; )
1093             {
1094               count=(ssize_t) ReadBlobBlock(image,header);
1095               if (count == 0)
1096                 break;
1097               header[count]='\0';
1098               (void) ConcatenateString(&comments,(const char *) header);
1099             }
1100             (void) SetImageProperty(image,"comment",comments);
1101             comments=DestroyString(comments);
1102             break;
1103           }
1104           case 0xff:
1105           {
1106             /* Read GIF application extension */
1107
1108             MagickBooleanType
1109               loop;
1110
1111             /*
1112               Read Netscape Loop extension.
1113             */
1114             loop=MagickFalse;
1115             if (ReadBlobBlock(image,header) != 0)
1116               loop=LocaleNCompare((char *) header,"NETSCAPE2.0",11) == 0 ?
1117                 MagickTrue : MagickFalse;
1118             if (loop != MagickFalse)
1119               {
1120                 while (ReadBlobBlock(image,header) != 0)
1121                   iterations=(size_t) ((header[2] << 8) | header[1]);
1122                 break;
1123               }
1124             else
1125               {
1126                 char
1127                   name[MaxTextExtent];
1128
1129                 int
1130                   block_length,
1131                   info_length,
1132                   reserved_length;
1133
1134                 MagickBooleanType
1135                   i8bim,
1136                   icc,
1137                   iptc;
1138
1139                 StringInfo
1140                   *profile;
1141
1142                 unsigned char
1143                   *info;
1144
1145                 /*
1146                   Store GIF application extension as a generic profile.
1147                 */
1148                 i8bim=LocaleNCompare((char *) header,"MGK8BIM0000",11) == 0 ?
1149                   MagickTrue : MagickFalse;
1150                 icc=LocaleNCompare((char *) header,"ICCRGBG1012",11) == 0 ?
1151                   MagickTrue : MagickFalse;
1152                 iptc=LocaleNCompare((char *) header,"MGKIPTC0000",11) == 0 ?
1153                   MagickTrue : MagickFalse;
1154                 number_extensionss++;
1155                 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1156                   "    Reading GIF application extension");
1157                 info=(unsigned char *) AcquireQuantumMemory(255UL,
1158                   sizeof(*info));
1159                 reserved_length=255;
1160                 for (info_length=0; ; )
1161                 {
1162                   block_length=(int) ReadBlobBlock(image,&info[info_length]);
1163                   if (block_length == 0)
1164                     break;
1165                   info_length+=block_length;
1166                   if (info_length > (reserved_length-255))
1167                     {
1168                        reserved_length+=4096;
1169                        info=(unsigned char *) ResizeQuantumMemory(info,
1170                          (size_t) reserved_length,sizeof(*info));
1171                     }
1172                 }
1173                 info=(unsigned char *) ResizeQuantumMemory(info,(size_t)
1174                   (info_length+1),sizeof(*info));
1175                 profile=AcquireStringInfo((size_t) info_length);
1176                 SetStringInfoDatum(profile,(const unsigned char *) info);
1177                 if (i8bim == MagickTrue)
1178                   (void) CopyMagickString(name,"8bim",sizeof(name));
1179                 else if (icc == MagickTrue)
1180                   (void) CopyMagickString(name,"icc",sizeof(name));
1181                 else if (iptc == MagickTrue)
1182                   (void) CopyMagickString(name,"iptc",sizeof(name));
1183                 else
1184                   (void) FormatMagickString(name,sizeof(name),"gif:%.11s",
1185                     header);
1186                 (void) SetImageProfile(image,name,profile);
1187                 info=(unsigned char *) RelinquishMagickMemory(info);
1188                 profile=DestroyStringInfo(profile);
1189                 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1190                   "      profile name=%s",name);
1191               }
1192             break;
1193           }
1194           default:
1195           {
1196             while (ReadBlobBlock(image,header) != 0) ;
1197             break;
1198           }
1199         }
1200       }
1201     if (c != (unsigned char) ',')
1202       continue;
1203     if (image_count != 0)
1204       {
1205         /*
1206           Allocate next image structure.
1207         */
1208         AcquireNextImage(image_info,image);
1209         if (GetNextImageInList(image) == (Image *) NULL)
1210           {
1211             image=DestroyImageList(image);
1212             global_colormap=(unsigned char *) RelinquishMagickMemory(
1213               global_colormap);
1214             return((Image *) NULL);
1215           }
1216         image=SyncNextImageInList(image);
1217       }
1218     image_count++;
1219     /*
1220       Read image attributes.
1221     */
1222     image->storage_class=PseudoClass;
1223     image->compression=LZWCompression;
1224     page.x=(ssize_t) ReadBlobLSBShort(image);
1225     page.y=(ssize_t) ReadBlobLSBShort(image);
1226     image->columns=ReadBlobLSBShort(image);
1227     image->rows=ReadBlobLSBShort(image);
1228     image->depth=8;
1229     flag=(unsigned char) ReadBlobByte(image);
1230     image->interlace=BitSet((int) flag,0x40) != 0 ? GIFInterlace :
1231       NoInterlace;
1232     image->colors=BitSet((int) flag,0x80) == 0 ? global_colors :
1233       one << ((size_t) (flag & 0x07)+1);
1234     if (opacity >= (ssize_t) image->colors)
1235       opacity=(-1);
1236     image->page.width=page.width;
1237     image->page.height=page.height;
1238     image->page.y=page.y;
1239     image->page.x=page.x;
1240     image->delay=delay;
1241     image->ticks_per_second=100;
1242     image->dispose=(DisposeType) dispose;
1243     image->iterations=iterations;
1244     image->matte=opacity >= 0 ? MagickTrue : MagickFalse;
1245     delay=0;
1246     dispose=0;
1247     iterations=1;
1248     if ((image->columns == 0) || (image->rows == 0))
1249       {
1250         global_colormap=(unsigned char *) RelinquishMagickMemory(
1251           global_colormap);
1252         ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
1253       }
1254     /*
1255       Inititialize colormap.
1256     */
1257     if (AcquireImageColormap(image,image->colors) == MagickFalse)
1258       {
1259         global_colormap=(unsigned char *) RelinquishMagickMemory(
1260           global_colormap);
1261         ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1262       }
1263     if (BitSet((int) flag,0x80) == 0)
1264       {
1265         /*
1266           Use global colormap.
1267         */
1268         p=global_colormap;
1269         for (i=0; i < (ssize_t) image->colors; i++)
1270         {
1271           image->colormap[i].red=ScaleCharToQuantum(*p++);
1272           image->colormap[i].green=ScaleCharToQuantum(*p++);
1273           image->colormap[i].blue=ScaleCharToQuantum(*p++);
1274           if (i == opacity)
1275             {
1276               image->colormap[i].opacity=(Quantum) TransparentOpacity;
1277               image->transparent_color=image->colormap[opacity];
1278             }
1279         }
1280         image->background_color=image->colormap[MagickMin(background,
1281           image->colors-1)];
1282       }
1283     else
1284       {
1285         unsigned char
1286           *colormap;
1287
1288         /*
1289           Read local colormap.
1290         */
1291         colormap=(unsigned char *) AcquireQuantumMemory(image->colors,
1292           3*sizeof(*colormap));
1293         if (colormap == (unsigned char *) NULL)
1294           {
1295             global_colormap=(unsigned char *) RelinquishMagickMemory(
1296               global_colormap);
1297             ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1298           }
1299         count=ReadBlob(image,(3*image->colors)*sizeof(*colormap),colormap);
1300         if (count != (ssize_t) (3*image->colors))
1301           {
1302             global_colormap=(unsigned char *) RelinquishMagickMemory(
1303               global_colormap);
1304             colormap=(unsigned char *) RelinquishMagickMemory(colormap);
1305             ThrowReaderException(CorruptImageError,
1306               "InsufficientImageDataInFile");
1307           }
1308         p=colormap;
1309         for (i=0; i < (ssize_t) image->colors; i++)
1310         {
1311           image->colormap[i].red=ScaleCharToQuantum(*p++);
1312           image->colormap[i].green=ScaleCharToQuantum(*p++);
1313           image->colormap[i].blue=ScaleCharToQuantum(*p++);
1314           if (i == opacity)
1315             image->colormap[i].opacity=(Quantum) TransparentOpacity;
1316         }
1317         colormap=(unsigned char *) RelinquishMagickMemory(colormap);
1318       }
1319     if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
1320       if (image->scene >= (image_info->scene+image_info->number_scenes-1))
1321         break;
1322     /*
1323       Decode image.
1324     */
1325     if (image_info->ping != MagickFalse)
1326       status=PingGIFImage(image);
1327     else
1328       status=DecodeImage(image,opacity);
1329     if ((image_info->ping == MagickFalse) && (status == MagickFalse))
1330       {
1331         global_colormap=(unsigned char *) RelinquishMagickMemory(
1332           global_colormap);
1333         ThrowReaderException(CorruptImageError,"CorruptImage");
1334       }
1335     if (image_info->number_scenes != 0)
1336       if (image->scene >= (image_info->scene+image_info->number_scenes-1))
1337         break;
1338     opacity=(-1);
1339     status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) image->scene-
1340       1,image->scene);
1341     if (status == MagickFalse)
1342       break;
1343   }
1344   global_colormap=(unsigned char *) RelinquishMagickMemory(global_colormap);
1345   if ((image->columns == 0) || (image->rows == 0))
1346     ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
1347   (void) CloseBlob(image);
1348   return(GetFirstImageInList(image));
1349 }
1350 \f
1351 /*
1352 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1353 %                                                                             %
1354 %                                                                             %
1355 %                                                                             %
1356 %   R e g i s t e r G I F I m a g e                                           %
1357 %                                                                             %
1358 %                                                                             %
1359 %                                                                             %
1360 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1361 %
1362 %  RegisterGIFImage() adds properties for the GIF image format to
1363 %  the list of supported formats.  The properties include the image format
1364 %  tag, a method to read and/or write the format, whether the format
1365 %  supports the saving of more than one frame to the same file or blob,
1366 %  whether the format supports native in-memory I/O, and a brief
1367 %  description of the format.
1368 %
1369 %  The format of the RegisterGIFImage method is:
1370 %
1371 %      size_t RegisterGIFImage(void)
1372 %
1373 */
1374 ModuleExport size_t RegisterGIFImage(void)
1375 {
1376   MagickInfo
1377     *entry;
1378
1379   entry=SetMagickInfo("GIF");
1380   entry->decoder=(DecodeImageHandler *) ReadGIFImage;
1381   entry->encoder=(EncodeImageHandler *) WriteGIFImage;
1382   entry->magick=(IsImageFormatHandler *) IsGIF;
1383   entry->description=ConstantString("CompuServe graphics interchange format");
1384   entry->module=ConstantString("GIF");
1385   (void) RegisterMagickInfo(entry);
1386   entry=SetMagickInfo("GIF87");
1387   entry->decoder=(DecodeImageHandler *) ReadGIFImage;
1388   entry->encoder=(EncodeImageHandler *) WriteGIFImage;
1389   entry->magick=(IsImageFormatHandler *) IsGIF;
1390   entry->adjoin=MagickFalse;
1391   entry->description=ConstantString("CompuServe graphics interchange format");
1392   entry->version=ConstantString("version 87a");
1393   entry->module=ConstantString("GIF");
1394   (void) RegisterMagickInfo(entry);
1395   return(MagickImageCoderSignature);
1396 }
1397 \f
1398 /*
1399 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1400 %                                                                             %
1401 %                                                                             %
1402 %                                                                             %
1403 %   U n r e g i s t e r G I F I m a g e                                       %
1404 %                                                                             %
1405 %                                                                             %
1406 %                                                                             %
1407 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1408 %
1409 %  UnregisterGIFImage() removes format registrations made by the
1410 %  GIF module from the list of supported formats.
1411 %
1412 %  The format of the UnregisterGIFImage method is:
1413 %
1414 %      UnregisterGIFImage(void)
1415 %
1416 */
1417 ModuleExport void UnregisterGIFImage(void)
1418 {
1419   (void) UnregisterMagickInfo("GIF");
1420   (void) UnregisterMagickInfo("GIF87");
1421 }
1422 \f
1423 /*
1424 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1425 %                                                                             %
1426 %                                                                             %
1427 %                                                                             %
1428 %   W r i t e G I F I m a g e                                                 %
1429 %                                                                             %
1430 %                                                                             %
1431 %                                                                             %
1432 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1433 %
1434 %  WriteGIFImage() writes an image to a file in the Compuserve Graphics
1435 %  image format.
1436 %
1437 %  The format of the WriteGIFImage method is:
1438 %
1439 %      MagickBooleanType WriteGIFImage(const ImageInfo *image_info,Image *image)
1440 %
1441 %  A description of each parameter follows.
1442 %
1443 %    o image_info: the image info.
1444 %
1445 %    o image:  The image.
1446 %
1447 */
1448 static MagickBooleanType WriteGIFImage(const ImageInfo *image_info,Image *image)
1449 {
1450   Image
1451     *next_image;
1452
1453   int
1454     c;
1455
1456   ImageInfo
1457     *write_info;
1458
1459   InterlaceType
1460     interlace;
1461
1462   MagickBooleanType
1463     status;
1464
1465   MagickOffsetType
1466     scene;
1467
1468   RectangleInfo
1469     page;
1470
1471   register ssize_t
1472     i;
1473
1474   register unsigned char
1475     *q;
1476
1477   size_t
1478     bits_per_pixel,
1479     delay,
1480     length,
1481     one;
1482
1483   ssize_t
1484     j,
1485     opacity;
1486
1487   unsigned char
1488     *colormap,
1489     *global_colormap;
1490
1491   /*
1492     Open output image file.
1493   */
1494   assert(image_info != (const ImageInfo *) NULL);
1495   assert(image_info->signature == MagickSignature);
1496   assert(image != (Image *) NULL);
1497   assert(image->signature == MagickSignature);
1498   if (image->debug != MagickFalse)
1499     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1500   status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
1501   if (status == MagickFalse)
1502     return(status);
1503   /*
1504     Allocate colormap.
1505   */
1506   global_colormap=(unsigned char *) AcquireQuantumMemory(768UL,
1507     sizeof(*global_colormap));
1508   colormap=(unsigned char *) AcquireQuantumMemory(768UL,sizeof(*colormap));
1509   if ((global_colormap == (unsigned char *) NULL) ||
1510       (colormap == (unsigned char *) NULL))
1511     ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
1512   for (i=0; i < 768; i++)
1513     colormap[i]=(unsigned char) 0;
1514   /*
1515     Write GIF header.
1516   */
1517   write_info=CloneImageInfo(image_info);
1518   if (LocaleCompare(write_info->magick,"GIF87") != 0)
1519     (void) WriteBlob(image,6,(unsigned char *) "GIF89a");
1520   else
1521     {
1522       (void) WriteBlob(image,6,(unsigned char *) "GIF87a");
1523       write_info->adjoin=MagickFalse;
1524     }
1525   /*
1526     Determine image bounding box.
1527   */
1528   page.width=image->columns;
1529   page.height=image->rows;
1530   page.x=0;
1531   page.y=0;
1532   if (write_info->adjoin != MagickFalse)
1533     for (next_image=image; next_image != (Image *) NULL; )
1534     {
1535       page.x=next_image->page.x;
1536       page.y=next_image->page.y;
1537       if ((next_image->page.width+page.x) > page.width)
1538         page.width=next_image->page.width+page.x;
1539       if ((next_image->page.height+page.y) > page.height)
1540         page.height=next_image->page.height+page.y;
1541       next_image=GetNextImageInList(next_image);
1542     }
1543   page.x=image->page.x;
1544   page.y=image->page.y;
1545   if ((image->page.width != 0) && (image->page.height != 0))
1546     page=image->page;
1547   (void) WriteBlobLSBShort(image,(unsigned short) page.width);
1548   (void) WriteBlobLSBShort(image,(unsigned short) page.height);
1549   /*
1550     Write images to file.
1551   */
1552   interlace=write_info->interlace;
1553   if ((write_info->adjoin != MagickFalse) &&
1554       (GetNextImageInList(image) != (Image *) NULL))
1555     interlace=NoInterlace;
1556   scene=0;
1557   one=1;
1558   do
1559   {
1560     if (image->colorspace != RGBColorspace)
1561       (void) TransformImageColorspace(image,RGBColorspace);
1562     opacity=(-1);
1563     if (IsOpaqueImage(image,&image->exception) != MagickFalse)
1564       {
1565         if ((image->storage_class == DirectClass) || (image->colors > 256))
1566           (void) SetImageType(image,PaletteType);
1567       }
1568     else
1569       {
1570         MagickRealType
1571           alpha,
1572           beta;
1573
1574         /*
1575           Identify transparent colormap index.
1576         */
1577         if ((image->storage_class == DirectClass) || (image->colors > 256))
1578           (void) SetImageType(image,PaletteBilevelMatteType);
1579         for (i=0; i < (ssize_t) image->colors; i++)
1580           if (image->colormap[i].opacity != OpaqueOpacity)
1581             {
1582               if (opacity < 0)
1583                 {
1584                   opacity=i;
1585                   continue;
1586                 }
1587               alpha=(MagickRealType) TransparentOpacity-(MagickRealType)
1588                 image->colormap[i].opacity;
1589               beta=(MagickRealType) TransparentOpacity-(MagickRealType)
1590                 image->colormap[opacity].opacity;
1591               if (alpha < beta)
1592                 opacity=i;
1593             }
1594         if (opacity == -1)
1595           {
1596             (void) SetImageType(image,PaletteBilevelMatteType);
1597             for (i=0; i < (ssize_t) image->colors; i++)
1598               if (image->colormap[i].opacity != OpaqueOpacity)
1599                 {
1600                   if (opacity < 0)
1601                     {
1602                       opacity=i;
1603                       continue;
1604                     }
1605                   alpha=(Quantum) TransparentOpacity-(MagickRealType)
1606                     image->colormap[i].opacity;
1607                   beta=(Quantum) TransparentOpacity-(MagickRealType)
1608                     image->colormap[opacity].opacity;
1609                   if (alpha < beta)
1610                     opacity=i;
1611                 }
1612           }
1613         if (opacity >= 0)
1614           {
1615             image->colormap[opacity].red=image->transparent_color.red;
1616             image->colormap[opacity].green=image->transparent_color.green;
1617             image->colormap[opacity].blue=image->transparent_color.blue;
1618           }
1619       }
1620     if ((image->storage_class == DirectClass) || (image->colors > 256))
1621       ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
1622     for (bits_per_pixel=1; bits_per_pixel < 8; bits_per_pixel++)
1623       if ((one << bits_per_pixel) >= image->colors)
1624         break;
1625     q=colormap;
1626     for (i=0; i < (ssize_t) image->colors; i++)
1627     {
1628       *q++=ScaleQuantumToChar(image->colormap[i].red);
1629       *q++=ScaleQuantumToChar(image->colormap[i].green);
1630       *q++=ScaleQuantumToChar(image->colormap[i].blue);
1631     }
1632     for ( ; i < (ssize_t) (one << bits_per_pixel); i++)
1633     {
1634       *q++=(unsigned char) 0x0;
1635       *q++=(unsigned char) 0x0;
1636       *q++=(unsigned char) 0x0;
1637     }
1638     if ((GetPreviousImageInList(image) == (Image *) NULL) ||
1639         (write_info->adjoin == MagickFalse))
1640       {
1641         /*
1642           Write global colormap.
1643         */
1644         c=0x80;
1645         c|=(8-1) << 4;  /* color resolution */
1646         c|=(bits_per_pixel-1);   /* size of global colormap */
1647         (void) WriteBlobByte(image,(unsigned char) c);
1648         for (j=0; j < (ssize_t) image->colors; j++)
1649           if (IsColorEqual(&image->background_color,image->colormap+j))
1650             break;
1651         (void) WriteBlobByte(image,(unsigned char)
1652           (j == (ssize_t) image->colors ? 0 : j));  /* background color */
1653         (void) WriteBlobByte(image,(unsigned char) 0x00);  /* reserved */
1654         length=(size_t) (3*(one << bits_per_pixel));
1655         (void) WriteBlob(image,length,colormap);
1656         for (j=0; j < 768; j++)
1657           global_colormap[j]=colormap[j];
1658       }
1659     if (LocaleCompare(write_info->magick,"GIF87") != 0)
1660       {
1661         /*
1662           Write graphics control extension.
1663         */
1664         (void) WriteBlobByte(image,(unsigned char) 0x21);
1665         (void) WriteBlobByte(image,(unsigned char) 0xf9);
1666         (void) WriteBlobByte(image,(unsigned char) 0x04);
1667         c=image->dispose << 2;
1668         if (opacity >= 0)
1669           c|=0x01;
1670         (void) WriteBlobByte(image,(unsigned char) c);
1671         delay=(size_t) (100*image->delay/MagickMax((size_t)
1672           image->ticks_per_second,1));
1673         (void) WriteBlobLSBShort(image,(unsigned short) delay);
1674         (void) WriteBlobByte(image,(unsigned char) (opacity >= 0 ? opacity :
1675           0));
1676         (void) WriteBlobByte(image,(unsigned char) 0x00);
1677         if ((LocaleCompare(write_info->magick,"GIF87") != 0) &&
1678             (GetImageProperty(image,"comment") != (const char *) NULL))
1679           {
1680             const char
1681               *value;
1682
1683             register const char
1684               *p;
1685
1686             size_t
1687               count;
1688
1689             /*
1690               Write Comment extension.
1691             */
1692             (void) WriteBlobByte(image,(unsigned char) 0x21);
1693             (void) WriteBlobByte(image,(unsigned char) 0xfe);
1694             value=GetImageProperty(image,"comment");
1695             p=value;
1696             while (strlen(p) != 0)
1697             {
1698               count=MagickMin(strlen(p),255);
1699               (void) WriteBlobByte(image,(unsigned char) count);
1700               for (i=0; i < (ssize_t) count; i++)
1701                 (void) WriteBlobByte(image,(unsigned char) *p++);
1702             }
1703             (void) WriteBlobByte(image,(unsigned char) 0x00);
1704           }
1705         if ((GetPreviousImageInList(image) == (Image *) NULL) &&
1706             (GetNextImageInList(image) != (Image *) NULL) &&
1707             (image->iterations != 1))
1708           {
1709             /*
1710               Write Netscape Loop extension.
1711             */
1712             (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1713                "  Writing GIF Extension %s","NETSCAPE2.0");
1714             (void) WriteBlobByte(image,(unsigned char) 0x21);
1715             (void) WriteBlobByte(image,(unsigned char) 0xff);
1716             (void) WriteBlobByte(image,(unsigned char) 0x0b);
1717             (void) WriteBlob(image,11,(unsigned char *) "NETSCAPE2.0");
1718             (void) WriteBlobByte(image,(unsigned char) 0x03);
1719             (void) WriteBlobByte(image,(unsigned char) 0x01);
1720             (void) WriteBlobLSBShort(image,(unsigned short) image->iterations);
1721             (void) WriteBlobByte(image,(unsigned char) 0x00);
1722           }
1723         ResetImageProfileIterator(image);
1724         for ( ; ; )
1725         {
1726           char
1727             *name;
1728
1729           const StringInfo
1730             *profile;
1731
1732           name=GetNextImageProfile(image);
1733           if (name == (const char *) NULL)
1734             break;
1735           profile=GetImageProfile(image,name);
1736           if (profile != (StringInfo *) NULL)
1737           {
1738             if ((LocaleCompare(name,"ICC") == 0) ||
1739                 (LocaleCompare(name,"ICM") == 0) ||
1740                 (LocaleCompare(name,"IPTC") == 0) ||
1741                 (LocaleCompare(name,"8BIM") == 0) ||
1742                 (LocaleNCompare(name,"gif:",4) == 0))
1743             {
1744                size_t
1745                  length;
1746
1747                ssize_t
1748                  offset;
1749
1750                unsigned char
1751                  *datum;
1752
1753                datum=GetStringInfoDatum(profile);
1754                length=GetStringInfoLength(profile);
1755                (void) WriteBlobByte(image,(unsigned char) 0x21);
1756                (void) WriteBlobByte(image,(unsigned char) 0xff);
1757                (void) WriteBlobByte(image,(unsigned char) 0x0b);
1758                if ((LocaleCompare(name,"ICC") == 0) ||
1759                    (LocaleCompare(name,"ICM") == 0))
1760                  {
1761                    /*
1762                      Write ICC extension.
1763                    */
1764                    (void) WriteBlob(image,11,(unsigned char *)"ICCRGBG1012");
1765                    (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1766                        "  Writing GIF Extension %s","ICCRGBG1012");
1767                  }
1768                else
1769                  if ((LocaleCompare(name,"IPTC") == 0))
1770                    {
1771                      /*
1772                        write IPTC extension.
1773                      */
1774                      (void) WriteBlob(image,11,(unsigned char *)"MGKIPTC0000");
1775                      (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1776                          "  Writing GIF Extension %s","MGKIPTC0000");
1777                    }
1778                  else
1779                    if ((LocaleCompare(name,"8BIM") == 0))
1780                      {
1781                        /*
1782                          Write 8BIM extension>
1783                        */
1784                         (void) WriteBlob(image,11,(unsigned char *)
1785                           "MGK8BIM0000");
1786                         (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1787                           "  Writing GIF Extension %s","MGK8BIM0000");
1788                      }
1789                    else
1790                      {
1791                        char
1792                          extension[MaxTextExtent];
1793
1794                        /* write generic extension */
1795                        (void) CopyMagickString(extension,name+4,
1796                          sizeof(extension));
1797                        (void) WriteBlob(image,11,(unsigned char *) extension);
1798                        (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1799                           "  Writing GIF Extension %s",name);
1800                      }
1801                offset=0;
1802                while ((ssize_t) length > offset)
1803                {
1804                  size_t
1805                    block_length;
1806
1807                  if ((length-offset) < 255)
1808                    block_length=length-offset;
1809                  else
1810                    block_length=255;
1811                  (void) WriteBlobByte(image,(unsigned char) block_length);
1812                  (void) WriteBlob(image,(size_t) block_length,datum+offset);
1813                  offset+=(ssize_t) block_length;
1814                }
1815                (void) WriteBlobByte(image,(unsigned char) 0x00);
1816             }
1817           }
1818         }
1819       }
1820     (void) WriteBlobByte(image,',');  /* image separator */
1821     /*
1822       Write the image header.
1823     */
1824     page.x=image->page.x;
1825     page.y=image->page.y;
1826     if ((image->page.width != 0) && (image->page.height != 0))
1827       page=image->page;
1828     (void) WriteBlobLSBShort(image,(unsigned short) (page.x < 0 ? 0 : page.x));
1829     (void) WriteBlobLSBShort(image,(unsigned short) (page.y < 0 ? 0 : page.y));
1830     (void) WriteBlobLSBShort(image,(unsigned short) image->columns);
1831     (void) WriteBlobLSBShort(image,(unsigned short) image->rows);
1832     c=0x00;
1833     if (interlace != NoInterlace)
1834       c|=0x40;  /* pixel data is interlaced */
1835     for (j=0; j < (ssize_t) (3*image->colors); j++)
1836       if (colormap[j] != global_colormap[j])
1837         break;
1838     if (j == (ssize_t) (3*image->colors))
1839       (void) WriteBlobByte(image,(unsigned char) c);
1840     else
1841       {
1842         c|=0x80;
1843         c|=(bits_per_pixel-1);   /* size of local colormap */
1844         (void) WriteBlobByte(image,(unsigned char) c);
1845         length=(size_t) (3*(one << bits_per_pixel));
1846         (void) WriteBlob(image,length,colormap);
1847       }
1848     /*
1849       Write the image data.
1850     */
1851     c=(int) MagickMax(bits_per_pixel,2);
1852     (void) WriteBlobByte(image,(unsigned char) c);
1853     status=EncodeImage(write_info,image,(size_t) MagickMax(bits_per_pixel,2)+1);
1854     if (status == MagickFalse)
1855       {
1856         global_colormap=(unsigned char *) RelinquishMagickMemory(
1857           global_colormap);
1858         colormap=(unsigned char *) RelinquishMagickMemory(colormap);
1859         write_info=DestroyImageInfo(write_info);
1860         ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
1861       }
1862     (void) WriteBlobByte(image,(unsigned char) 0x00);
1863     if (GetNextImageInList(image) == (Image *) NULL)
1864       break;
1865     image=SyncNextImageInList(image);
1866     scene++;
1867     status=SetImageProgress(image,SaveImagesTag,scene,
1868       GetImageListLength(image));
1869     if (status == MagickFalse)
1870       break;
1871   } while (write_info->adjoin != MagickFalse);
1872   (void) WriteBlobByte(image,';'); /* terminator */
1873   global_colormap=(unsigned char *) RelinquishMagickMemory(global_colormap);
1874   colormap=(unsigned char *) RelinquishMagickMemory(colormap);
1875   write_info=DestroyImageInfo(write_info);
1876   (void) CloseBlob(image);
1877   return(MagickTrue);
1878 }