• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* libs/graphics/images/SkImageDecoder_libgif.cpp
2 **
3 ** Copyright 2006, The Android Open Source Project
4 **
5 ** Licensed under the Apache License, Version 2.0 (the "License");
6 ** you may not use this file except in compliance with the License.
7 ** You may obtain a copy of the License at
8 **
9 **     http://www.apache.org/licenses/LICENSE-2.0
10 **
11 ** Unless required by applicable law or agreed to in writing, software
12 ** distributed under the License is distributed on an "AS IS" BASIS,
13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 ** See the License for the specific language governing permissions and
15 ** limitations under the License.
16 */
17 
18 #include "SkImageDecoder.h"
19 #include "SkColor.h"
20 #include "SkColorPriv.h"
21 #include "SkStream.h"
22 #include "SkTemplates.h"
23 #include "SkPackBits.h"
24 
25 #include "gif_lib.h"
26 
27 class SkGIFImageDecoder : public SkImageDecoder {
28 public:
getFormat() const29     virtual Format getFormat() const {
30         return kGIF_Format;
31     }
32 
33 protected:
34     virtual bool onDecode(SkStream* stream, SkBitmap* bm,
35                           SkBitmap::Config pref, Mode mode);
36 };
37 
38 static const uint8_t gStartingIterlaceYValue[] = {
39     0, 4, 2, 1
40 };
41 static const uint8_t gDeltaIterlaceYValue[] = {
42     8, 8, 4, 2
43 };
44 
45 /*  Implement the GIF interlace algorithm in an iterator.
46     1) grab every 8th line beginning at 0
47     2) grab every 8th line beginning at 4
48     3) grab every 4th line beginning at 2
49     4) grab every 2nd line beginning at 1
50 */
51 class GifInterlaceIter {
52 public:
GifInterlaceIter(int height)53     GifInterlaceIter(int height) : fHeight(height) {
54         fStartYPtr = gStartingIterlaceYValue;
55         fDeltaYPtr = gDeltaIterlaceYValue;
56 
57         fCurrY = *fStartYPtr++;
58         fDeltaY = *fDeltaYPtr++;
59     }
60 
currY() const61     int currY() const {
62         SkASSERT(fStartYPtr);
63         SkASSERT(fDeltaYPtr);
64         return fCurrY;
65     }
66 
next()67     void next() {
68         SkASSERT(fStartYPtr);
69         SkASSERT(fDeltaYPtr);
70 
71         int y = fCurrY + fDeltaY;
72         // We went from an if statement to a while loop so that we iterate
73         // through fStartYPtr until a valid row is found. This is so that images
74         // that are smaller than 5x5 will not trash memory.
75         while (y >= fHeight) {
76             if (gStartingIterlaceYValue +
77                     SK_ARRAY_COUNT(gStartingIterlaceYValue) == fStartYPtr) {
78                 // we done
79                 SkDEBUGCODE(fStartYPtr = NULL;)
80                 SkDEBUGCODE(fDeltaYPtr = NULL;)
81                 y = 0;
82             } else {
83                 y = *fStartYPtr++;
84                 fDeltaY = *fDeltaYPtr++;
85             }
86         }
87         fCurrY = y;
88     }
89 
90 private:
91     const int fHeight;
92     int fCurrY;
93     int fDeltaY;
94     const uint8_t* fStartYPtr;
95     const uint8_t* fDeltaYPtr;
96 };
97 
98 ///////////////////////////////////////////////////////////////////////////////
99 
100 //#define GIF_STAMP       "GIF"    /* First chars in file - GIF stamp. */
101 //#define GIF_STAMP_LEN   (sizeof(GIF_STAMP) - 1)
102 
DecodeCallBackProc(GifFileType * fileType,GifByteType * out,int size)103 static int DecodeCallBackProc(GifFileType* fileType, GifByteType* out,
104                               int size) {
105     SkStream* stream = (SkStream*) fileType->UserData;
106     return (int) stream->read(out, size);
107 }
108 
CheckFreeExtension(SavedImage * Image)109 void CheckFreeExtension(SavedImage* Image) {
110     if (Image->ExtensionBlocks) {
111         FreeExtension(Image);
112     }
113 }
114 
115 // return NULL on failure
find_colormap(const GifFileType * gif)116 static const ColorMapObject* find_colormap(const GifFileType* gif) {
117     const ColorMapObject* cmap = gif->Image.ColorMap;
118     if (NULL == cmap) {
119         cmap = gif->SColorMap;
120     }
121     // some sanity checks
122     if ((unsigned)cmap->ColorCount > 256 ||
123             cmap->ColorCount != (1 << cmap->BitsPerPixel)) {
124         cmap = NULL;
125     }
126     return cmap;
127 }
128 
129 // return -1 if not found (i.e. we're completely opaque)
find_transpIndex(const SavedImage & image,int colorCount)130 static int find_transpIndex(const SavedImage& image, int colorCount) {
131     int transpIndex = -1;
132     for (int i = 0; i < image.ExtensionBlockCount; ++i) {
133         const ExtensionBlock* eb = image.ExtensionBlocks + i;
134         if (eb->Function == 0xF9 && eb->ByteCount == 4) {
135             if (eb->Bytes[0] & 1) {
136                 transpIndex = (unsigned char)eb->Bytes[3];
137                 // check for valid transpIndex
138                 if (transpIndex >= colorCount) {
139                     transpIndex = -1;
140                 }
141                 break;
142             }
143         }
144     }
145     return transpIndex;
146 }
147 
error_return(GifFileType * gif,const SkBitmap & bm,const char msg[])148 static bool error_return(GifFileType* gif, const SkBitmap& bm,
149                          const char msg[]) {
150 #if 0
151     SkDebugf("libgif error <%s> bitmap [%d %d] pixels %p colortable %p\n",
152              msg, bm.width(), bm.height(), bm.getPixels(), bm.getColorTable());
153 #endif
154     return false;
155 }
156 
onDecode(SkStream * sk_stream,SkBitmap * bm,SkBitmap::Config prefConfig,Mode mode)157 bool SkGIFImageDecoder::onDecode(SkStream* sk_stream, SkBitmap* bm,
158                                  SkBitmap::Config prefConfig, Mode mode) {
159     GifFileType* gif = DGifOpen(sk_stream, DecodeCallBackProc);
160     if (NULL == gif) {
161         return error_return(gif, *bm, "DGifOpen");
162     }
163 
164     SkAutoTCallIProc<GifFileType, DGifCloseFile> acp(gif);
165 
166     SavedImage temp_save;
167     temp_save.ExtensionBlocks=NULL;
168     temp_save.ExtensionBlockCount=0;
169     SkAutoTCallVProc<SavedImage, CheckFreeExtension> acp2(&temp_save);
170 
171     int width, height;
172     GifRecordType recType;
173     GifByteType *extData;
174     int transpIndex = -1;   // -1 means we don't have it (yet)
175 
176     do {
177         if (DGifGetRecordType(gif, &recType) == GIF_ERROR) {
178             return error_return(gif, *bm, "DGifGetRecordType");
179         }
180 
181         switch (recType) {
182         case IMAGE_DESC_RECORD_TYPE: {
183             if (DGifGetImageDesc(gif) == GIF_ERROR) {
184                 return error_return(gif, *bm, "IMAGE_DESC_RECORD_TYPE");
185             }
186 
187             if (gif->ImageCount < 1) {    // sanity check
188                 return error_return(gif, *bm, "ImageCount < 1");
189             }
190 
191             width = gif->SWidth;
192             height = gif->SHeight;
193             if (width <= 0 || height <= 0 ||
194                 !this->chooseFromOneChoice(SkBitmap::kIndex8_Config,
195                                            width, height)) {
196                 return error_return(gif, *bm, "chooseFromOneChoice");
197             }
198 
199             bm->setConfig(SkBitmap::kIndex8_Config, width, height);
200             if (SkImageDecoder::kDecodeBounds_Mode == mode)
201                 return true;
202 
203             SavedImage* image = &gif->SavedImages[gif->ImageCount-1];
204             const GifImageDesc& desc = image->ImageDesc;
205 
206             // check for valid descriptor
207             if (   (desc.Top | desc.Left) < 0 ||
208                     desc.Left + desc.Width > width ||
209                     desc.Top + desc.Height > height) {
210                 return error_return(gif, *bm, "TopLeft");
211             }
212 
213             // now we decode the colortable
214             int colorCount = 0;
215             {
216                 const ColorMapObject* cmap = find_colormap(gif);
217                 if (NULL == cmap) {
218                     return error_return(gif, *bm, "null cmap");
219                 }
220 
221                 colorCount = cmap->ColorCount;
222                 SkColorTable* ctable = SkNEW_ARGS(SkColorTable, (colorCount));
223                 SkPMColor* colorPtr = ctable->lockColors();
224                 for (int index = 0; index < colorCount; index++)
225                     colorPtr[index] = SkPackARGB32(0xFF,
226                                                    cmap->Colors[index].Red,
227                                                    cmap->Colors[index].Green,
228                                                    cmap->Colors[index].Blue);
229 
230                 transpIndex = find_transpIndex(temp_save, colorCount);
231                 if (transpIndex < 0)
232                     ctable->setFlags(ctable->getFlags() | SkColorTable::kColorsAreOpaque_Flag);
233                 else
234                     colorPtr[transpIndex] = 0; // ram in a transparent SkPMColor
235                 ctable->unlockColors(true);
236 
237                 SkAutoUnref aurts(ctable);
238                 if (!this->allocPixelRef(bm, ctable)) {
239                     return error_return(gif, *bm, "allocPixelRef");
240                 }
241             }
242 
243             SkAutoLockPixels alp(*bm);
244 
245             // time to decode the scanlines
246             //
247             uint8_t*  scanline = bm->getAddr8(0, 0);
248             const int rowBytes = bm->rowBytes();
249             const int innerWidth = desc.Width;
250             const int innerHeight = desc.Height;
251 
252             // abort if either inner dimension is <= 0
253             if (innerWidth <= 0 || innerHeight <= 0) {
254                 return error_return(gif, *bm, "non-pos inner width/height");
255             }
256 
257             // are we only a subset of the total bounds?
258             if ((desc.Top | desc.Left) > 0 ||
259                  innerWidth < width || innerHeight < height)
260             {
261                 int fill;
262                 if (transpIndex >= 0) {
263                     fill = transpIndex;
264                 } else {
265                     fill = gif->SBackGroundColor;
266                 }
267                 // check for valid fill index/color
268                 if (static_cast<unsigned>(fill) >=
269                         static_cast<unsigned>(colorCount)) {
270                     fill = 0;
271                 }
272                 memset(scanline, fill, bm->getSize());
273                 // bump our starting address
274                 scanline += desc.Top * rowBytes + desc.Left;
275             }
276 
277             // now decode each scanline
278             if (gif->Image.Interlace)
279             {
280                 GifInterlaceIter iter(innerHeight);
281                 for (int y = 0; y < innerHeight; y++)
282                 {
283                     uint8_t* row = scanline + iter.currY() * rowBytes;
284                     if (DGifGetLine(gif, row, innerWidth) == GIF_ERROR) {
285                         return error_return(gif, *bm, "interlace DGifGetLine");
286                     }
287                     iter.next();
288                 }
289             }
290             else
291             {
292                 // easy, non-interlace case
293                 for (int y = 0; y < innerHeight; y++) {
294                     if (DGifGetLine(gif, scanline, innerWidth) == GIF_ERROR) {
295                         return error_return(gif, *bm, "DGifGetLine");
296                     }
297                     scanline += rowBytes;
298                 }
299             }
300             goto DONE;
301             } break;
302 
303         case EXTENSION_RECORD_TYPE:
304             if (DGifGetExtension(gif, &temp_save.Function,
305                                  &extData) == GIF_ERROR) {
306                 return error_return(gif, *bm, "DGifGetExtension");
307             }
308 
309             while (extData != NULL) {
310                 /* Create an extension block with our data */
311                 if (AddExtensionBlock(&temp_save, extData[0],
312                                       &extData[1]) == GIF_ERROR) {
313                     return error_return(gif, *bm, "AddExtensionBlock");
314                 }
315                 if (DGifGetExtensionNext(gif, &extData) == GIF_ERROR) {
316                     return error_return(gif, *bm, "DGifGetExtensionNext");
317                 }
318                 temp_save.Function = 0;
319             }
320             break;
321 
322         case TERMINATE_RECORD_TYPE:
323             break;
324 
325         default:	/* Should be trapped by DGifGetRecordType */
326             break;
327         }
328     } while (recType != TERMINATE_RECORD_TYPE);
329 
330 DONE:
331     return true;
332 }
333 
334 ///////////////////////////////////////////////////////////////////////////////
335 
336 #include "SkTRegistry.h"
337 
Factory(SkStream * stream)338 static SkImageDecoder* Factory(SkStream* stream) {
339     char buf[GIF_STAMP_LEN];
340     if (stream->read(buf, GIF_STAMP_LEN) == GIF_STAMP_LEN) {
341         if (memcmp(GIF_STAMP,   buf, GIF_STAMP_LEN) == 0 ||
342                 memcmp(GIF87_STAMP, buf, GIF_STAMP_LEN) == 0 ||
343                 memcmp(GIF89_STAMP, buf, GIF_STAMP_LEN) == 0) {
344             return SkNEW(SkGIFImageDecoder);
345         }
346     }
347     return NULL;
348 }
349 
350 static SkTRegistry<SkImageDecoder*, SkStream*> gReg(Factory);
351