1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/gifdecod.cpp
3 // Purpose: wxGIFDecoder, GIF reader for wxImage and wxAnimation
4 // Author: Guillermo Rodriguez Garcia <guille@iies.es>
7 // Copyright: (c) Guillermo Rodriguez Garcia
8 // Licence: wxWindows licence
9 /////////////////////////////////////////////////////////////////////////////
11 // For compilers that support precompilation, includes "wx.h".
12 #include "wx/wxprec.h"
18 #if wxUSE_STREAMS && wxUSE_GIF
21 #include "wx/palette.h"
28 #include "wx/gifdecod.h"
29 #include "wx/scopedptr.h"
30 #include "wx/scopeguard.h"
34 GIF_MARKER_EXT
= '!', // 0x21
35 GIF_MARKER_SEP
= ',', // 0x2C
36 GIF_MARKER_ENDOFDATA
= ';', // 0x3B
38 GIF_MARKER_EXT_GRAPHICS_CONTROL
= 0xF9,
39 GIF_MARKER_EXT_COMMENT
= 0xFE,
40 GIF_MARKER_EXT_APP
= 0xFF
43 //---------------------------------------------------------------------------
45 //---------------------------------------------------------------------------
47 // internal class for storing GIF image data
54 unsigned int w
; // width
55 unsigned int h
; // height
56 unsigned int left
; // x coord (in logical screen)
57 unsigned int top
; // y coord (in logical screen)
58 int transparent
; // transparent color index (-1 = none)
59 wxAnimationDisposal disposal
; // disposal method
60 long delay
; // delay in ms (-1 = unused)
61 unsigned char *p
; // bitmap
62 unsigned char *pal
; // palette
63 unsigned int ncolours
; // number of colours
65 wxDECLARE_NO_COPY_CLASS(GIFImage
);
68 wxDECLARE_SCOPED_PTR(GIFImage
, GIFImagePtr
)
69 wxDEFINE_SCOPED_PTR(GIFImage
, GIFImagePtr
)
72 //---------------------------------------------------------------------------
73 // GIFImage constructor
74 //---------------------------------------------------------------------------
82 disposal
= wxANIM_DONOTREMOVE
;
84 p
= (unsigned char *) NULL
;
85 pal
= (unsigned char *) NULL
;
89 //---------------------------------------------------------------------------
90 // wxGIFDecoder constructor and destructor
91 //---------------------------------------------------------------------------
93 wxGIFDecoder::wxGIFDecoder()
97 wxGIFDecoder::~wxGIFDecoder()
102 void wxGIFDecoder::Destroy()
104 wxASSERT(m_nFrames
==m_frames
.GetCount());
105 for (unsigned int i
=0; i
<m_nFrames
; i
++)
107 GIFImage
*f
= (GIFImage
*)m_frames
[i
];
118 //---------------------------------------------------------------------------
119 // Convert this image to a wxImage object
120 //---------------------------------------------------------------------------
122 // This function was designed by Vaclav Slavik
124 bool wxGIFDecoder::ConvertToImage(unsigned int frame
, wxImage
*image
) const
126 unsigned char *src
, *dst
, *pal
;
134 wxSize sz
= GetFrameSize(frame
);
135 image
->Create(sz
.GetWidth(), sz
.GetHeight());
136 image
->SetType(wxBITMAP_TYPE_GIF
);
141 pal
= GetPalette(frame
);
142 src
= GetData(frame
);
143 dst
= image
->GetData();
144 transparent
= GetTransparentColourIndex(frame
);
146 // set transparent colour mask
147 if (transparent
!= -1)
149 for (i
= 0; i
< GetNcolours(frame
); i
++)
151 if ((pal
[3 * i
+ 0] == 255) &&
152 (pal
[3 * i
+ 1] == 0) &&
153 (pal
[3 * i
+ 2] == 255))
155 pal
[3 * i
+ 2] = 254;
159 pal
[3 * transparent
+ 0] = 255,
160 pal
[3 * transparent
+ 1] = 0,
161 pal
[3 * transparent
+ 2] = 255;
163 image
->SetMaskColour(255, 0, 255);
166 image
->SetMask(false);
169 unsigned char r
[256];
170 unsigned char g
[256];
171 unsigned char b
[256];
173 for (i
= 0; i
< 256; i
++)
180 image
->SetPalette(wxPalette(GetNcolours(frame
), r
, g
, b
));
181 #endif // wxUSE_PALETTE
184 unsigned long npixel
= sz
.GetWidth() * sz
.GetHeight();
185 for (i
= 0; i
< npixel
; i
++, src
++)
187 *(dst
++) = pal
[3 * (*src
) + 0];
188 *(dst
++) = pal
[3 * (*src
) + 1];
189 *(dst
++) = pal
[3 * (*src
) + 2];
196 //---------------------------------------------------------------------------
198 //---------------------------------------------------------------------------
200 #define GetFrame(n) ((GIFImage*)m_frames[n])
203 // Get data for current frame
205 wxSize
wxGIFDecoder::GetFrameSize(unsigned int frame
) const
207 return wxSize(GetFrame(frame
)->w
, GetFrame(frame
)->h
);
210 wxPoint
wxGIFDecoder::GetFramePosition(unsigned int frame
) const
212 return wxPoint(GetFrame(frame
)->left
, GetFrame(frame
)->top
);
215 wxAnimationDisposal
wxGIFDecoder::GetDisposalMethod(unsigned int frame
) const
217 return GetFrame(frame
)->disposal
;
220 long wxGIFDecoder::GetDelay(unsigned int frame
) const
222 return GetFrame(frame
)->delay
;
225 wxColour
wxGIFDecoder::GetTransparentColour(unsigned int frame
) const
227 unsigned char *pal
= GetFrame(frame
)->pal
;
228 int n
= GetFrame(frame
)->transparent
;
232 return wxColour(pal
[n
*3 + 0],
237 unsigned char* wxGIFDecoder::GetData(unsigned int frame
) const { return (GetFrame(frame
)->p
); }
238 unsigned char* wxGIFDecoder::GetPalette(unsigned int frame
) const { return (GetFrame(frame
)->pal
); }
239 unsigned int wxGIFDecoder::GetNcolours(unsigned int frame
) const { return (GetFrame(frame
)->ncolours
); }
240 int wxGIFDecoder::GetTransparentColourIndex(unsigned int frame
) const { return (GetFrame(frame
)->transparent
); }
244 //---------------------------------------------------------------------------
245 // GIF reading and decoding
246 //---------------------------------------------------------------------------
249 // Reads the next code from the file stream, with size 'bits'
251 int wxGIFDecoder::getcode(wxInputStream
& stream
, int bits
, int ab_fin
)
253 unsigned int mask
; // bit mask
254 unsigned int code
; // code (result)
256 // get remaining bits from last byte read
257 mask
= (1 << bits
) - 1;
258 code
= (m_lastbyte
>> (8 - m_restbits
)) & mask
;
260 // keep reading new bytes while needed
261 while (bits
> m_restbits
)
263 // if no bytes left in this block, read the next block
266 m_restbyte
= stream
.GetC();
268 /* Some encoders are a bit broken: instead of issuing
269 * an end-of-image symbol (ab_fin) they come up with
270 * a zero-length subblock!! We catch this here so
271 * that the decoder sees an ab_fin code.
280 stream
.Read((void *) m_buffer
, m_restbyte
);
281 if (stream
.LastRead() != m_restbyte
)
289 // read next byte and isolate the bits we need
290 m_lastbyte
= (unsigned char) (*m_bufp
++);
291 mask
= (1 << (bits
- m_restbits
)) - 1;
292 code
= code
+ ((m_lastbyte
& mask
) << m_restbits
);
295 // adjust total number of bits extracted from the buffer
296 m_restbits
= m_restbits
+ 8;
299 // find number of bits remaining for next code
300 m_restbits
= (m_restbits
- bits
);
307 // GIF decoding function. The initial code size (aka root size)
308 // is 'bits'. Supports interlaced images (interl == 1).
309 // Returns wxGIF_OK (== 0) on success, or an error code if something
310 // fails (see header file for details)
312 wxGIFDecoder::dgif(wxInputStream
& stream
, GIFImage
*img
, int interl
, int bits
)
314 static const int allocSize
= 4096 + 1;
315 int *ab_prefix
= new int[allocSize
]; // alphabet (prefixes)
316 if (ab_prefix
== NULL
)
321 int *ab_tail
= new int[allocSize
]; // alphabet (tails)
328 int *stack
= new int[allocSize
]; // decompression stack
336 int ab_clr
; // clear code
337 int ab_fin
; // end of info code
338 int ab_bits
; // actual symbol width, in bits
339 int ab_free
; // first free position in alphabet
340 int ab_max
; // last possible character in alphabet
341 int pass
; // pass number in interlaced images
342 int pos
; // index into decompresion stack
343 unsigned int x
, y
; // position in image buffer
345 int code
, readcode
, lastcode
, abcabca
;
347 // these won't change
348 ab_clr
= (1 << bits
);
349 ab_fin
= (1 << bits
) + 1;
351 // these will change through the decompression proccess
353 ab_free
= (1 << bits
) + 2;
354 ab_max
= (1 << ab_bits
) - 1;
360 // reset decoder vars
368 readcode
= code
= getcode(stream
, ab_bits
, ab_fin
);
371 if (code
== ab_fin
) break;
376 // reset main variables
378 ab_free
= (1 << bits
) + 2;
379 ab_max
= (1 << ab_bits
) - 1;
387 // unknown code: special case (like in ABCABCA)
390 code
= lastcode
; // take last string
391 stack
[pos
++] = abcabca
; // add first character
394 // build the string for this code in the stack
395 while (code
> ab_clr
)
397 stack
[pos
++] = ab_tail
[code
];
398 code
= ab_prefix
[code
];
400 // Don't overflow. This shouldn't happen with normal
401 // GIF files, the allocSize of 4096+1 is enough. This
402 // will only happen with badly formed GIFs.
403 if (pos
>= allocSize
)
408 return wxGIF_INVFORMAT
;
412 if (pos
>= allocSize
)
417 return wxGIF_INVFORMAT
;
420 stack
[pos
] = code
; // push last code into the stack
421 abcabca
= code
; // save for special case
423 // make new entry in alphabet (only if NOT just cleared)
426 // Normally, after the alphabet is full and can't grow any
427 // further (ab_free == 4096), encoder should (must?) emit CLEAR
428 // to reset it. This checks whether we really got it, otherwise
429 // the GIF is damaged.
430 if (ab_free
> ab_max
)
435 return wxGIF_INVFORMAT
;
438 // This assert seems unnecessary since the condition above
439 // eliminates the only case in which it went false. But I really
440 // don't like being forced to ask "Who in .text could have
441 // written there?!" And I wouldn't have been forced to ask if
442 // this line had already been here.
443 wxASSERT(ab_free
< allocSize
);
445 ab_prefix
[ab_free
] = lastcode
;
446 ab_tail
[ab_free
] = code
;
449 if ((ab_free
> ab_max
) && (ab_bits
< 12))
452 ab_max
= (1 << ab_bits
) - 1;
456 // dump stack data to the image buffer
459 (img
->p
)[x
+ (y
* (img
->w
))] = (char) stack
[pos
];
468 // support for interlaced images
471 case 1: y
+= 8; break;
472 case 2: y
+= 8; break;
473 case 3: y
+= 4; break;
474 case 4: y
+= 2; break;
477 /* loop until a valid y coordinate has been
478 found, Or if the maximum number of passes has
479 been reached, exit the loop, and stop image
480 decoding (At this point the image is successfully
482 If we don't loop, but merely set y to some other
483 value, that new value might still be invalid depending
484 on the height of the image. This would cause out of
487 while (y
>= (img
->h
))
491 case 2: y
= 4; break;
492 case 3: y
= 2; break;
493 case 4: y
= 1; break;
497 It's possible we arrive here. For example this
498 happens when the image is interlaced, and the
499 height is 1. Looking at the above cases, the
500 lowest possible y is 1. While the only valid
501 one would be 0 for an image of height 1. So
502 'eventually' the loop will arrive here.
503 This case makes sure this while loop is
504 exited, as well as the 2 other ones.
507 // Set y to a valid coordinate so the local
508 // while loop will be exited. (y = 0 always
509 // is >= img->h since if img->h == 0 the
510 // image is never decoded)
513 // This will exit the other outer while loop
516 // This will halt image decoding.
528 Normally image decoding is finished when an End of Information code is
529 encountered (code == ab_fin) however some broken encoders write wrong
530 "block byte counts" (The first byte value after the "code size" byte),
531 being one value too high. It might very well be possible other variants
532 of this problem occur as well. The only sensible solution seems to
533 be to check for clipping.
534 Example of wrong encoding:
535 (1 * 1 B/W image, raster data stream follows in hex bytes)
537 02 << B/W images have a code size of 2
538 02 << Block byte count
540 00 << Zero byte count (terminates data stream)
542 Because the block byte count is 2, the zero byte count is used in the
543 decoding process, and decoding is continued after this byte. (While it
544 should signal an end of image)
550 01 << When decoded this correctly includes the End of Information code
558 (The 44 doesn't include an End of Information code, but at least the
559 decoder correctly skips to 00 now after decoding, and signals this
560 as an End of Information itself)
574 while (code
!= ab_fin
);
576 delete [] ab_prefix
;
585 // Returns true if the file looks like a valid GIF, false otherwise.
587 bool wxGIFDecoder::DoCanRead(wxInputStream
&stream
) const
589 unsigned char buf
[3];
591 if ( !stream
.Read(buf
, WXSIZEOF(buf
)) )
594 return memcmp(buf
, "GIF", WXSIZEOF(buf
)) == 0;
599 // Reads and decodes one or more GIF images, depending on whether
600 // animated GIF support is enabled. Can read GIFs with any bit
601 // size (color depth), but the output images are always expanded
602 // to 8 bits per pixel. Also, the image palettes always contain
603 // 256 colors, although some of them may be unused. Returns wxGIF_OK
604 // (== 0) on success, or an error code if something fails (see
605 // header file for details)
607 wxGIFErrorCode
wxGIFDecoder::LoadGIF(wxInputStream
& stream
)
609 unsigned int global_ncolors
= 0;
611 wxAnimationDisposal disposal
;
614 unsigned char type
= 0;
615 unsigned char pal
[768];
616 unsigned char buf
[16];
619 // check GIF signature
620 if (!CanRead(stream
))
621 return wxGIF_INVFORMAT
;
623 // check for animated GIF support (ver. >= 89a)
625 static const unsigned int headerSize
= (3 + 3);
626 stream
.Read(buf
, headerSize
);
627 if (stream
.LastRead() != headerSize
)
629 return wxGIF_INVFORMAT
;
632 if (memcmp(buf
+ 3, "89a", 3) < 0)
637 // read logical screen descriptor block (LSDB)
638 static const unsigned int lsdbSize
= (2 + 2 + 1 + 1 + 1);
639 stream
.Read(buf
, lsdbSize
);
640 if (stream
.LastRead() != lsdbSize
)
642 return wxGIF_INVFORMAT
;
645 m_szAnimation
.SetWidth( buf
[0] + 256 * buf
[1] );
646 m_szAnimation
.SetHeight( buf
[2] + 256 * buf
[3] );
648 if (anim
&& ((m_szAnimation
.GetWidth() == 0) || (m_szAnimation
.GetHeight() == 0)))
650 return wxGIF_INVFORMAT
;
653 // load global color map if available
654 if ((buf
[4] & 0x80) == 0x80)
656 int backgroundColIndex
= buf
[5];
658 global_ncolors
= 2 << (buf
[4] & 0x07);
659 unsigned int numBytes
= 3 * global_ncolors
;
660 stream
.Read(pal
, numBytes
);
661 if (stream
.LastRead() != numBytes
)
663 return wxGIF_INVFORMAT
;
666 m_background
.Set(pal
[backgroundColIndex
*3 + 0],
667 pal
[backgroundColIndex
*3 + 1],
668 pal
[backgroundColIndex
*3 + 2]);
671 // transparent colour, disposal method and delay default to unused
672 int transparent
= -1;
673 disposal
= wxANIM_UNSPECIFIED
;
679 type
= stream
.GetC();
682 If the end of file has been reached (or an error) and a ";"
683 (GIF_MARKER_ENDOFDATA) hasn't been encountered yet, exit the loop. (Without this
684 check the while loop would loop endlessly.) Later on, in the next while
685 loop, the file will be treated as being truncated (But still
686 be decoded as far as possible). returning wxGIF_TRUNCATED is not
687 possible here since some init code is done after this loop.
689 if (stream
.Eof())// || !stream.IsOk())
692 type is set to some bogus value, so there's no
693 need to continue evaluating it.
695 break; // Alternative : "return wxGIF_INVFORMAT;"
700 case GIF_MARKER_ENDOFDATA
:
704 if (stream
.GetC() == GIF_MARKER_EXT_GRAPHICS_CONTROL
)
705 // graphics control extension, parse it
707 static const unsigned int gceSize
= 6;
708 stream
.Read(buf
, gceSize
);
709 if (stream
.LastRead() != gceSize
)
712 return wxGIF_INVFORMAT
;
715 // read delay and convert from 1/100 of a second to ms
716 delay
= 10 * (buf
[2] + 256 * buf
[3]);
718 // read transparent colour index, if used
719 transparent
= buf
[1] & 0x01 ? buf
[4] : -1;
721 // read disposal method
722 disposal
= (wxAnimationDisposal
)(((buf
[1] & 0x1C) >> 2) - 1);
725 // other extension, skip
727 while ((i
= stream
.GetC()) != 0)
729 if (stream
.Eof() || (stream
.LastRead() == 0) ||
730 stream
.SeekI(i
, wxFromCurrent
) == wxInvalidOffset
)
740 // allocate memory for IMAGEN struct
741 GIFImagePtr
pimg(new GIFImage());
743 wxScopeGuard guardDestroy
= wxMakeObjGuard(*this, &wxGIFDecoder::Destroy
);
749 static const unsigned int idbSize
= (2 + 2 + 2 + 2 + 1);
750 stream
.Read(buf
, idbSize
);
751 if (stream
.LastRead() != idbSize
)
752 return wxGIF_INVFORMAT
;
754 pimg
->left
= buf
[0] + 256 * buf
[1];
755 pimg
->top
= buf
[2] + 256 * buf
[3];
757 pimg->left = buf[4] + 256 * buf[5];
758 pimg->top = buf[4] + 256 * buf[5];
760 pimg
->w
= buf
[4] + 256 * buf
[5];
761 pimg
->h
= buf
[6] + 256 * buf
[7];
765 // some GIF images specify incorrect animation size but we can
766 // still open them if we fix up the animation size, see #9465
767 if ( m_nFrames
== 0 )
769 if ( pimg
->w
> (unsigned)m_szAnimation
.x
)
770 m_szAnimation
.x
= pimg
->w
;
771 if ( pimg
->h
> (unsigned)m_szAnimation
.y
)
772 m_szAnimation
.y
= pimg
->h
;
774 else // subsequent frames
776 // check that we have valid size
777 if ( (!pimg
->w
|| pimg
->w
> (unsigned)m_szAnimation
.x
) ||
778 (!pimg
->h
|| pimg
->h
> (unsigned)m_szAnimation
.y
) )
780 wxLogError(_("Incorrect GIF frame size (%u, %d) for "
782 pimg
->w
, pimg
->h
, m_nFrames
);
783 return wxGIF_INVFORMAT
;
788 interl
= ((buf
[8] & 0x40)? 1 : 0);
789 size
= pimg
->w
* pimg
->h
;
791 pimg
->transparent
= transparent
;
792 pimg
->disposal
= disposal
;
795 // allocate memory for image and palette
796 pimg
->p
= (unsigned char *) malloc((unsigned int)size
);
797 pimg
->pal
= (unsigned char *) malloc(768);
799 if ((!pimg
->p
) || (!pimg
->pal
))
802 // load local color map if available, else use global map
803 if ((buf
[8] & 0x80) == 0x80)
805 unsigned int local_ncolors
= 2 << (buf
[8] & 0x07);
806 unsigned int numBytes
= 3 * local_ncolors
;
807 stream
.Read(pimg
->pal
, numBytes
);
808 pimg
->ncolours
= local_ncolors
;
809 if (stream
.LastRead() != numBytes
)
810 return wxGIF_INVFORMAT
;
814 memcpy(pimg
->pal
, pal
, 768);
815 pimg
->ncolours
= global_ncolors
;
818 // get initial code size from first byte in raster data
819 bits
= stream
.GetC();
821 return wxGIF_INVFORMAT
;
824 wxGIFErrorCode result
= dgif(stream
, pimg
.get(), interl
, bits
);
825 if (result
!= wxGIF_OK
)
828 guardDestroy
.Dismiss();
830 // add the image to our frame array
831 m_frames
.Add(pimg
.release());
834 // if this is not an animated GIF, exit after first image
845 return wxGIF_INVFORMAT
;
848 // try to read to the end of the stream
849 while (type
!= GIF_MARKER_ENDOFDATA
)
852 return wxGIF_TRUNCATED
;
854 type
= stream
.GetC();
860 (void) stream
.GetC();
863 while ((i
= stream
.GetC()) != 0)
865 if (stream
.Eof() || (stream
.LastRead() == 0) ||
866 stream
.SeekI(i
, wxFromCurrent
) == wxInvalidOffset
)
869 return wxGIF_INVFORMAT
;
875 // image descriptor block
876 static const unsigned int idbSize
= (2 + 2 + 2 + 2 + 1);
877 stream
.Read(buf
, idbSize
);
878 if (stream
.LastRead() != idbSize
)
881 return wxGIF_INVFORMAT
;
885 if ((buf
[8] & 0x80) == 0x80)
887 unsigned int local_ncolors
= 2 << (buf
[8] & 0x07);
888 wxFileOffset numBytes
= 3 * local_ncolors
;
889 if (stream
.SeekI(numBytes
, wxFromCurrent
) == wxInvalidOffset
)
892 return wxGIF_INVFORMAT
;
897 (void) stream
.GetC();
898 if (stream
.Eof() || (stream
.LastRead() == 0))
901 return wxGIF_INVFORMAT
;
905 while ((i
= stream
.GetC()) != 0)
907 if (stream
.Eof() || (stream
.LastRead() == 0) ||
908 stream
.SeekI(i
, wxFromCurrent
) == wxInvalidOffset
)
911 return wxGIF_INVFORMAT
;
917 if ((type
!= GIF_MARKER_ENDOFDATA
) && (type
!= 00)) // testing
919 // images are OK, but couldn't read to the end of the stream
920 return wxGIF_TRUNCATED
;
929 #endif // wxUSE_STREAMS && wxUSE_GIF