SkImageDecoder_libgif.cpp revision dac4a1d518a4788c3e2475d68cbe8683b4a448ff
1/*
2 * Copyright 2006 The Android Open Source Project
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8
9#include "SkColor.h"
10#include "SkColorPriv.h"
11#include "SkColorTable.h"
12#include "SkImageDecoder.h"
13#include "SkScaledBitmapSampler.h"
14#include "SkStream.h"
15#include "SkTemplates.h"
16
17#include "gif_lib.h"
18
19class SkGIFImageDecoder : public SkImageDecoder {
20public:
21    virtual Format getFormat() const SK_OVERRIDE {
22        return kGIF_Format;
23    }
24
25protected:
26    virtual bool onDecode(SkStream* stream, SkBitmap* bm, Mode mode) SK_OVERRIDE;
27
28private:
29    typedef SkImageDecoder INHERITED;
30};
31
32static const uint8_t gStartingIterlaceYValue[] = {
33    0, 4, 2, 1
34};
35static const uint8_t gDeltaIterlaceYValue[] = {
36    8, 8, 4, 2
37};
38
39/*  Implement the GIF interlace algorithm in an iterator.
40    1) grab every 8th line beginning at 0
41    2) grab every 8th line beginning at 4
42    3) grab every 4th line beginning at 2
43    4) grab every 2nd line beginning at 1
44*/
45class GifInterlaceIter {
46public:
47    GifInterlaceIter(int height) : fHeight(height) {
48        fStartYPtr = gStartingIterlaceYValue;
49        fDeltaYPtr = gDeltaIterlaceYValue;
50
51        fCurrY = *fStartYPtr++;
52        fDeltaY = *fDeltaYPtr++;
53    }
54
55    int currY() const {
56        SkASSERT(fStartYPtr);
57        SkASSERT(fDeltaYPtr);
58        return fCurrY;
59    }
60
61    void next() {
62        SkASSERT(fStartYPtr);
63        SkASSERT(fDeltaYPtr);
64
65        int y = fCurrY + fDeltaY;
66        // We went from an if statement to a while loop so that we iterate
67        // through fStartYPtr until a valid row is found. This is so that images
68        // that are smaller than 5x5 will not trash memory.
69        while (y >= fHeight) {
70            if (gStartingIterlaceYValue +
71                    SK_ARRAY_COUNT(gStartingIterlaceYValue) == fStartYPtr) {
72                // we done
73                SkDEBUGCODE(fStartYPtr = NULL;)
74                SkDEBUGCODE(fDeltaYPtr = NULL;)
75                y = 0;
76            } else {
77                y = *fStartYPtr++;
78                fDeltaY = *fDeltaYPtr++;
79            }
80        }
81        fCurrY = y;
82    }
83
84private:
85    const int fHeight;
86    int fCurrY;
87    int fDeltaY;
88    const uint8_t* fStartYPtr;
89    const uint8_t* fDeltaYPtr;
90};
91
92///////////////////////////////////////////////////////////////////////////////
93
94static int DecodeCallBackProc(GifFileType* fileType, GifByteType* out,
95                              int size) {
96    SkStream* stream = (SkStream*) fileType->UserData;
97    return (int) stream->read(out, size);
98}
99
100void CheckFreeExtension(SavedImage* Image) {
101    if (Image->ExtensionBlocks) {
102#if GIFLIB_MAJOR < 5
103        FreeExtension(Image);
104#else
105        GifFreeExtensions(&Image->ExtensionBlockCount, &Image->ExtensionBlocks);
106#endif
107    }
108}
109
110// return NULL on failure
111static const ColorMapObject* find_colormap(const GifFileType* gif) {
112    const ColorMapObject* cmap = gif->Image.ColorMap;
113    if (NULL == cmap) {
114        cmap = gif->SColorMap;
115    }
116
117    if (NULL == cmap) {
118        // no colormap found
119        return NULL;
120    }
121    // some sanity checks
122    if (cmap && ((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)
130static 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
148static 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
157/**
158 *  Skip rows in the source gif image.
159 *  @param gif Source image.
160 *  @param dst Scratch output needed by gif library call. Must be >= width bytes.
161 *  @param width Bytes per row in the source image.
162 *  @param rowsToSkip Number of rows to skip.
163 *  @return True on success, false on GIF_ERROR.
164 */
165static bool skip_src_rows(GifFileType* gif, uint8_t* dst, int width, int rowsToSkip) {
166    for (int i = 0; i < rowsToSkip; i++) {
167        if (DGifGetLine(gif, dst, width) == GIF_ERROR) {
168            return false;
169        }
170    }
171    return true;
172}
173
174bool SkGIFImageDecoder::onDecode(SkStream* sk_stream, SkBitmap* bm, Mode mode) {
175#if GIFLIB_MAJOR < 5
176    GifFileType* gif = DGifOpen(sk_stream, DecodeCallBackProc);
177#else
178    GifFileType* gif = DGifOpen(sk_stream, DecodeCallBackProc, NULL);
179#endif
180    if (NULL == gif) {
181        return error_return(gif, *bm, "DGifOpen");
182    }
183
184    SkAutoTCallIProc<GifFileType, DGifCloseFile> acp(gif);
185
186    SavedImage temp_save;
187    temp_save.ExtensionBlocks=NULL;
188    temp_save.ExtensionBlockCount=0;
189    SkAutoTCallVProc<SavedImage, CheckFreeExtension> acp2(&temp_save);
190
191    int width, height;
192    GifRecordType recType;
193    GifByteType *extData;
194#if GIFLIB_MAJOR >= 5
195    int extFunction;
196#endif
197    int transpIndex = -1;   // -1 means we don't have it (yet)
198
199    do {
200        if (DGifGetRecordType(gif, &recType) == GIF_ERROR) {
201            return error_return(gif, *bm, "DGifGetRecordType");
202        }
203
204        switch (recType) {
205        case IMAGE_DESC_RECORD_TYPE: {
206            if (DGifGetImageDesc(gif) == GIF_ERROR) {
207                return error_return(gif, *bm, "IMAGE_DESC_RECORD_TYPE");
208            }
209
210            if (gif->ImageCount < 1) {    // sanity check
211                return error_return(gif, *bm, "ImageCount < 1");
212            }
213
214            width = gif->SWidth;
215            height = gif->SHeight;
216            if (width <= 0 || height <= 0) {
217                return error_return(gif, *bm, "invalid dimensions");
218            }
219
220            // FIXME: We could give the caller a choice of images or configs.
221            if (!this->chooseFromOneChoice(SkBitmap::kIndex8_Config, width, height)) {
222                return error_return(gif, *bm, "chooseFromOneChoice");
223            }
224
225            SkScaledBitmapSampler sampler(width, height, this->getSampleSize());
226
227            bm->setConfig(SkBitmap::kIndex8_Config, sampler.scaledWidth(),
228                          sampler.scaledHeight());
229
230            if (SkImageDecoder::kDecodeBounds_Mode == mode) {
231                return true;
232            }
233
234            SavedImage* image = &gif->SavedImages[gif->ImageCount-1];
235            const GifImageDesc& desc = image->ImageDesc;
236
237            // check for valid descriptor
238            if (   (desc.Top | desc.Left) < 0 ||
239                    desc.Left + desc.Width > width ||
240                    desc.Top + desc.Height > height) {
241                return error_return(gif, *bm, "TopLeft");
242            }
243
244            // now we decode the colortable
245            int colorCount = 0;
246            {
247                const ColorMapObject* cmap = find_colormap(gif);
248                if (NULL == cmap) {
249                    return error_return(gif, *bm, "null cmap");
250                }
251
252                colorCount = cmap->ColorCount;
253                SkAutoTMalloc<SkPMColor> colorStorage(colorCount);
254                SkPMColor* colorPtr = colorStorage.get();
255                for (int index = 0; index < colorCount; index++) {
256                    colorPtr[index] = SkPackARGB32(0xFF,
257                                                   cmap->Colors[index].Red,
258                                                   cmap->Colors[index].Green,
259                                                   cmap->Colors[index].Blue);
260                }
261
262                transpIndex = find_transpIndex(temp_save, colorCount);
263                bool reallyHasAlpha = transpIndex >= 0;
264                if (reallyHasAlpha) {
265                    colorPtr[transpIndex] = SK_ColorTRANSPARENT; // ram in a transparent SkPMColor
266                }
267
268                SkAutoTUnref<SkColorTable> ctable(SkNEW_ARGS(SkColorTable, (colorPtr, colorCount)));
269                ctable->setIsOpaque(!reallyHasAlpha);
270                if (!this->allocPixelRef(bm, ctable)) {
271                    return error_return(gif, *bm, "allocPixelRef");
272                }
273            }
274
275            const int innerWidth = desc.Width;
276            const int innerHeight = desc.Height;
277
278            // abort if either inner dimension is <= 0
279            if (innerWidth <= 0 || innerHeight <= 0) {
280                return error_return(gif, *bm, "non-pos inner width/height");
281            }
282
283            SkAutoLockPixels alp(*bm);
284
285            SkAutoMalloc storage(innerWidth);
286            uint8_t* scanline = (uint8_t*) storage.get();
287
288            // GIF has an option to store the scanlines of an image, plus a larger background,
289            // filled by a fill color. In this case, we will use a subset of the larger bitmap
290            // for sampling.
291            SkBitmap subset;
292            SkBitmap* workingBitmap;
293            // are we only a subset of the total bounds?
294            if ((desc.Top | desc.Left) > 0 ||
295                 innerWidth < width || innerHeight < height) {
296                int fill;
297                if (transpIndex >= 0) {
298                    fill = transpIndex;
299                } else {
300                    fill = gif->SBackGroundColor;
301                }
302                // check for valid fill index/color
303                if (static_cast<unsigned>(fill) >=
304                        static_cast<unsigned>(colorCount)) {
305                    fill = 0;
306                }
307                // Fill the background.
308                memset(bm->getPixels(), fill, bm->getSize());
309
310                // Create a subset of the bitmap.
311                SkIRect subsetRect(SkIRect::MakeXYWH(desc.Left / sampler.srcDX(),
312                                                     desc.Top / sampler.srcDY(),
313                                                     innerWidth / sampler.srcDX(),
314                                                     innerHeight / sampler.srcDY()));
315                if (!bm->extractSubset(&subset, subsetRect)) {
316                    return error_return(gif, *bm, "Extract failed.");
317                }
318                // Update the sampler. We'll now be only sampling into the subset.
319                sampler = SkScaledBitmapSampler(innerWidth, innerHeight, this->getSampleSize());
320                workingBitmap = &subset;
321            } else {
322                workingBitmap = bm;
323            }
324
325            // bm is already locked, but if we had to take a subset, it must be locked also,
326            // so that getPixels() will point to its pixels.
327            SkAutoLockPixels alpWorking(*workingBitmap);
328
329            if (!sampler.begin(workingBitmap, SkScaledBitmapSampler::kIndex, *this)) {
330                return error_return(gif, *bm, "Sampler failed to begin.");
331            }
332
333            // now decode each scanline
334            if (gif->Image.Interlace) {
335                // Iterate over the height of the source data. The sampler will
336                // take care of skipping unneeded rows.
337                GifInterlaceIter iter(innerHeight);
338                for (int y = 0; y < innerHeight; y++){
339                    if (DGifGetLine(gif, scanline, innerWidth) == GIF_ERROR) {
340                        return error_return(gif, *bm, "interlace DGifGetLine");
341                    }
342                    sampler.sampleInterlaced(scanline, iter.currY());
343                    iter.next();
344                }
345            } else {
346                // easy, non-interlace case
347                const int outHeight = workingBitmap->height();
348                skip_src_rows(gif, scanline, innerWidth, sampler.srcY0());
349                for (int y = 0; y < outHeight; y++) {
350                    if (DGifGetLine(gif, scanline, innerWidth) == GIF_ERROR) {
351                        return error_return(gif, *bm, "DGifGetLine");
352                    }
353                    // scanline now contains the raw data. Sample it.
354                    sampler.next(scanline);
355                    if (y < outHeight - 1) {
356                        skip_src_rows(gif, scanline, innerWidth, sampler.srcDY() - 1);
357                    }
358                }
359                // skip the rest of the rows (if any)
360                int read = (outHeight - 1) * sampler.srcDY() + sampler.srcY0() + 1;
361                SkASSERT(read <= innerHeight);
362                skip_src_rows(gif, scanline, innerWidth, innerHeight - read);
363            }
364            goto DONE;
365            } break;
366
367        case EXTENSION_RECORD_TYPE:
368#if GIFLIB_MAJOR < 5
369            if (DGifGetExtension(gif, &temp_save.Function,
370                                 &extData) == GIF_ERROR) {
371#else
372            if (DGifGetExtension(gif, &extFunction, &extData) == GIF_ERROR) {
373#endif
374                return error_return(gif, *bm, "DGifGetExtension");
375            }
376
377            while (extData != NULL) {
378                /* Create an extension block with our data */
379#if GIFLIB_MAJOR < 5
380                if (AddExtensionBlock(&temp_save, extData[0],
381                                      &extData[1]) == GIF_ERROR) {
382#else
383                if (GifAddExtensionBlock(&gif->ExtensionBlockCount,
384                                         &gif->ExtensionBlocks,
385                                         extFunction,
386                                         extData[0],
387                                         &extData[1]) == GIF_ERROR) {
388#endif
389                    return error_return(gif, *bm, "AddExtensionBlock");
390                }
391                if (DGifGetExtensionNext(gif, &extData) == GIF_ERROR) {
392                    return error_return(gif, *bm, "DGifGetExtensionNext");
393                }
394#if GIFLIB_MAJOR < 5
395                temp_save.Function = 0;
396#endif
397            }
398            break;
399
400        case TERMINATE_RECORD_TYPE:
401            break;
402
403        default:    /* Should be trapped by DGifGetRecordType */
404            break;
405        }
406    } while (recType != TERMINATE_RECORD_TYPE);
407
408DONE:
409    return true;
410}
411
412///////////////////////////////////////////////////////////////////////////////
413DEFINE_DECODER_CREATOR(GIFImageDecoder);
414///////////////////////////////////////////////////////////////////////////////
415
416static bool is_gif(SkStreamRewindable* stream) {
417    char buf[GIF_STAMP_LEN];
418    if (stream->read(buf, GIF_STAMP_LEN) == GIF_STAMP_LEN) {
419        if (memcmp(GIF_STAMP,   buf, GIF_STAMP_LEN) == 0 ||
420                memcmp(GIF87_STAMP, buf, GIF_STAMP_LEN) == 0 ||
421                memcmp(GIF89_STAMP, buf, GIF_STAMP_LEN) == 0) {
422            return true;
423        }
424    }
425    return false;
426}
427
428static SkImageDecoder* sk_libgif_dfactory(SkStreamRewindable* stream) {
429    if (is_gif(stream)) {
430        return SkNEW(SkGIFImageDecoder);
431    }
432    return NULL;
433}
434
435static SkImageDecoder_DecodeReg gReg(sk_libgif_dfactory);
436
437static SkImageDecoder::Format get_format_gif(SkStreamRewindable* stream) {
438    if (is_gif(stream)) {
439        return SkImageDecoder::kGIF_Format;
440    }
441    return SkImageDecoder::kUnknown_Format;
442}
443
444static SkImageDecoder_FormatReg gFormatReg(get_format_gif);
445