SkGifImageReader.cpp revision 3cfdf6c8b1f0c6ebe59ddd0d2750976c2dd1921d
1/* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2/* ***** BEGIN LICENSE BLOCK *****
3 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
4 *
5 * The contents of this file are subject to the Mozilla Public License Version
6 * 1.1 (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 * http://www.mozilla.org/MPL/
9 *
10 * Software distributed under the License is distributed on an "AS IS" basis,
11 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
12 * for the specific language governing rights and limitations under the
13 * License.
14 *
15 * The Original Code is mozilla.org code.
16 *
17 * The Initial Developer of the Original Code is
18 * Netscape Communications Corporation.
19 * Portions created by the Initial Developer are Copyright (C) 1998
20 * the Initial Developer. All Rights Reserved.
21 *
22 * Contributor(s):
23 *   Chris Saari <saari@netscape.com>
24 *   Apple Computer
25 *
26 * Alternatively, the contents of this file may be used under the terms of
27 * either the GNU General Public License Version 2 or later (the "GPL"), or
28 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
29 * in which case the provisions of the GPL or the LGPL are applicable instead
30 * of those above. If you wish to allow use of your version of this file only
31 * under the terms of either the GPL or the LGPL, and not to allow others to
32 * use your version of this file under the terms of the MPL, indicate your
33 * decision by deleting the provisions above and replace them with the notice
34 * and other provisions required by the GPL or the LGPL. If you do not delete
35 * the provisions above, a recipient may use your version of this file under
36 * the terms of any one of the MPL, the GPL or the LGPL.
37 *
38 * ***** END LICENSE BLOCK ***** */
39
40/*
41The Graphics Interchange Format(c) is the copyright property of CompuServe
42Incorporated. Only CompuServe Incorporated is authorized to define, redefine,
43enhance, alter, modify or change in any way the definition of the format.
44
45CompuServe Incorporated hereby grants a limited, non-exclusive, royalty-free
46license for the use of the Graphics Interchange Format(sm) in computer
47software; computer software utilizing GIF(sm) must acknowledge ownership of the
48Graphics Interchange Format and its Service Mark by CompuServe Incorporated, in
49User and Technical Documentation. Computer software utilizing GIF, which is
50distributed or may be distributed without User or Technical Documentation must
51display to the screen or printer a message acknowledging ownership of the
52Graphics Interchange Format and the Service Mark by CompuServe Incorporated; in
53this case, the acknowledgement may be displayed in an opening screen or leading
54banner, or a closing screen or trailing banner. A message such as the following
55may be used:
56
57    "The Graphics Interchange Format(c) is the Copyright property of
58    CompuServe Incorporated. GIF(sm) is a Service Mark property of
59    CompuServe Incorporated."
60
61For further information, please contact :
62
63    CompuServe Incorporated
64    Graphics Technology Department
65    5000 Arlington Center Boulevard
66    Columbus, Ohio  43220
67    U. S. A.
68
69CompuServe Incorporated maintains a mailing list with all those individuals and
70organizations who wish to receive copies of this document when it is corrected
71or revised. This service is offered free of charge; please provide us with your
72mailing address.
73*/
74
75#include "SkGifImageReader.h"
76#include "SkColorPriv.h"
77#include "SkGifCodec.h"
78
79#include <algorithm>
80#include <string.h>
81
82
83// GETN(n, s) requests at least 'n' bytes available from 'q', at start of state 's'.
84//
85// Note, the hold will never need to be bigger than 256 bytes to gather up in the hold,
86// as each GIF block (except colormaps) can never be bigger than 256 bytes.
87// Colormaps are directly copied in the resp. global_colormap or dynamically allocated local_colormap.
88// So a fixed buffer in SkGifImageReader is good enough.
89// This buffer is only needed to copy left-over data from one GifWrite call to the next
90#define GETN(n, s) \
91    do { \
92        m_bytesToConsume = (n); \
93        m_state = (s); \
94    } while (0)
95
96// Get a 16-bit value stored in little-endian format.
97#define GETINT16(p)   ((p)[1]<<8|(p)[0])
98
99// Send the data to the display front-end.
100bool SkGIFLZWContext::outputRow(const unsigned char* rowBegin)
101{
102    int drowStart = irow;
103    int drowEnd = irow;
104
105    // Haeberli-inspired hack for interlaced GIFs: Replicate lines while
106    // displaying to diminish the "venetian-blind" effect as the image is
107    // loaded. Adjust pixel vertical positions to avoid the appearance of the
108    // image crawling up the screen as successive passes are drawn.
109    if (m_frameContext->progressiveDisplay() && m_frameContext->interlaced() && ipass < 4) {
110        unsigned rowDup = 0;
111        unsigned rowShift = 0;
112
113        switch (ipass) {
114        case 1:
115            rowDup = 7;
116            rowShift = 3;
117            break;
118        case 2:
119            rowDup = 3;
120            rowShift = 1;
121            break;
122        case 3:
123            rowDup = 1;
124            rowShift = 0;
125            break;
126        default:
127            break;
128        }
129
130        drowStart -= rowShift;
131        drowEnd = drowStart + rowDup;
132
133        // Extend if bottom edge isn't covered because of the shift upward.
134        if (((m_frameContext->height() - 1) - drowEnd) <= rowShift)
135            drowEnd = m_frameContext->height() - 1;
136
137        // Clamp first and last rows to upper and lower edge of image.
138        if (drowStart < 0)
139            drowStart = 0;
140
141        if ((unsigned)drowEnd >= m_frameContext->height())
142            drowEnd = m_frameContext->height() - 1;
143    }
144
145    // Protect against too much image data.
146    if ((unsigned)drowStart >= m_frameContext->height())
147        return true;
148
149    // CALLBACK: Let the client know we have decoded a row.
150    if (!m_client->haveDecodedRow(m_frameContext->frameId(), rowBegin,
151        drowStart, drowEnd - drowStart + 1, m_frameContext->progressiveDisplay() && m_frameContext->interlaced() && ipass > 1))
152        return false;
153
154    if (!m_frameContext->interlaced())
155        irow++;
156    else {
157        do {
158            switch (ipass) {
159            case 1:
160                irow += 8;
161                if (irow >= m_frameContext->height()) {
162                    ipass++;
163                    irow = 4;
164                }
165                break;
166
167            case 2:
168                irow += 8;
169                if (irow >= m_frameContext->height()) {
170                    ipass++;
171                    irow = 2;
172                }
173                break;
174
175            case 3:
176                irow += 4;
177                if (irow >= m_frameContext->height()) {
178                    ipass++;
179                    irow = 1;
180                }
181                break;
182
183            case 4:
184                irow += 2;
185                if (irow >= m_frameContext->height()) {
186                    ipass++;
187                    irow = 0;
188                }
189                break;
190
191            default:
192                break;
193            }
194        } while (irow > (m_frameContext->height() - 1));
195    }
196    return true;
197}
198
199// Perform Lempel-Ziv-Welch decoding.
200// Returns true if decoding was successful. In this case the block will have been completely consumed and/or rowsRemaining will be 0.
201// Otherwise, decoding failed; returns false in this case, which will always cause the SkGifImageReader to set the "decode failed" flag.
202bool SkGIFLZWContext::doLZW(const unsigned char* block, size_t bytesInBlock)
203{
204    const size_t width = m_frameContext->width();
205
206    if (rowIter == rowBuffer.end())
207        return true;
208
209    for (const unsigned char* ch = block; bytesInBlock-- > 0; ch++) {
210        // Feed the next byte into the decoder's 32-bit input buffer.
211        datum += ((int) *ch) << bits;
212        bits += 8;
213
214        // Check for underflow of decoder's 32-bit input buffer.
215        while (bits >= codesize) {
216            // Get the leading variable-length symbol from the data stream.
217            int code = datum & codemask;
218            datum >>= codesize;
219            bits -= codesize;
220
221            // Reset the dictionary to its original state, if requested.
222            if (code == clearCode) {
223                codesize = m_frameContext->dataSize() + 1;
224                codemask = (1 << codesize) - 1;
225                avail = clearCode + 2;
226                oldcode = -1;
227                continue;
228            }
229
230            // Check for explicit end-of-stream code.
231            if (code == (clearCode + 1)) {
232                // end-of-stream should only appear after all image data.
233                if (!rowsRemaining)
234                    return true;
235                return false;
236            }
237
238            const int tempCode = code;
239            unsigned short codeLength = 0;
240            if (code < avail) {
241                // This is a pre-existing code, so we already know what it
242                // encodes.
243                codeLength = suffixLength[code];
244                rowIter += codeLength;
245            } else if (code == avail && oldcode != -1) {
246                // This is a new code just being added to the dictionary.
247                // It must encode the contents of the previous code, plus
248                // the first character of the previous code again.
249                codeLength = suffixLength[oldcode] + 1;
250                rowIter += codeLength;
251                *--rowIter = firstchar;
252                code = oldcode;
253            } else {
254                // This is an invalid code. The dictionary is just initialized
255                // and the code is incomplete. We don't know how to handle
256                // this case.
257                return false;
258            }
259
260            while (code >= clearCode) {
261                *--rowIter = suffix[code];
262                code = prefix[code];
263            }
264
265            *--rowIter = firstchar = suffix[code];
266
267            // Define a new codeword in the dictionary as long as we've read
268            // more than one value from the stream.
269            if (avail < SK_MAX_DICTIONARY_ENTRIES && oldcode != -1) {
270                prefix[avail] = oldcode;
271                suffix[avail] = firstchar;
272                suffixLength[avail] = suffixLength[oldcode] + 1;
273                ++avail;
274
275                // If we've used up all the codewords of a given length
276                // increase the length of codewords by one bit, but don't
277                // exceed the specified maximum codeword size.
278                if (!(avail & codemask) && avail < SK_MAX_DICTIONARY_ENTRIES) {
279                    ++codesize;
280                    codemask += avail;
281                }
282            }
283            oldcode = tempCode;
284            rowIter += codeLength;
285
286            // Output as many rows as possible.
287            unsigned char* rowBegin = rowBuffer.begin();
288            for (; rowBegin + width <= rowIter; rowBegin += width) {
289                if (!outputRow(rowBegin))
290                    return false;
291                rowsRemaining--;
292                if (!rowsRemaining)
293                    return true;
294            }
295
296            if (rowBegin != rowBuffer.begin()) {
297                // Move the remaining bytes to the beginning of the buffer.
298                const size_t bytesToCopy = rowIter - rowBegin;
299                memcpy(&rowBuffer.front(), rowBegin, bytesToCopy);
300                rowIter = rowBuffer.begin() + bytesToCopy;
301            }
302        }
303    }
304    return true;
305}
306
307sk_sp<SkColorTable> SkGIFColorMap::buildTable(SkColorType colorType, size_t transparentPixel) const
308{
309    if (!m_isDefined)
310        return nullptr;
311
312    const PackColorProc proc = choose_pack_color_proc(false, colorType);
313    if (m_table) {
314        if (transparentPixel > (unsigned) m_table->count()
315                || m_table->operator[](transparentPixel) == SK_ColorTRANSPARENT) {
316            if (proc == m_packColorProc) {
317                // This SkColorTable has already been built with the same transparent color and
318                // packing proc. Reuse it.
319                return m_table;
320            }
321        }
322    }
323    m_packColorProc = proc;
324
325    SkASSERT(m_colors <= SK_MAX_COLORS);
326    const uint8_t* srcColormap = m_rawData->bytes();
327    SkPMColor colorStorage[SK_MAX_COLORS];
328    for (size_t i = 0; i < m_colors; i++) {
329        if (i == transparentPixel) {
330            colorStorage[i] = SK_ColorTRANSPARENT;
331        } else {
332            colorStorage[i] = proc(255, srcColormap[0], srcColormap[1], srcColormap[2]);
333        }
334        srcColormap += SK_BYTES_PER_COLORMAP_ENTRY;
335    }
336    for (size_t i = m_colors; i < SK_MAX_COLORS; i++) {
337        colorStorage[i] = SK_ColorTRANSPARENT;
338    }
339    m_table = sk_sp<SkColorTable>(new SkColorTable(colorStorage, SK_MAX_COLORS));
340    return m_table;
341}
342
343sk_sp<SkColorTable> SkGifImageReader::getColorTable(SkColorType colorType, size_t index) const {
344    if (index >= m_frames.size()) {
345        return nullptr;
346    }
347
348    const SkGIFFrameContext* frameContext = m_frames[index].get();
349    const SkGIFColorMap& localColorMap = frameContext->localColorMap();
350    if (localColorMap.isDefined()) {
351        return localColorMap.buildTable(colorType, frameContext->transparentPixel());
352    }
353    if (m_globalColorMap.isDefined()) {
354        return m_globalColorMap.buildTable(colorType, frameContext->transparentPixel());
355    }
356    return nullptr;
357}
358
359// Perform decoding for this frame. frameComplete will be true if the entire frame is decoded.
360// Returns false if a decoding error occurred. This is a fatal error and causes the SkGifImageReader to set the "decode failed" flag.
361// Otherwise, either not enough data is available to decode further than before, or the new data has been decoded successfully; returns true in this case.
362bool SkGIFFrameContext::decode(SkGifCodec* client, bool* frameComplete)
363{
364    *frameComplete = false;
365    if (!m_lzwContext) {
366        // Wait for more data to properly initialize SkGIFLZWContext.
367        if (!isDataSizeDefined() || !isHeaderDefined())
368            return true;
369
370        m_lzwContext.reset(new SkGIFLZWContext(client, this));
371        if (!m_lzwContext->prepareToDecode()) {
372            m_lzwContext.reset();
373            return false;
374        }
375
376        m_currentLzwBlock = 0;
377    }
378
379    // Some bad GIFs have extra blocks beyond the last row, which we don't want to decode.
380    while (m_currentLzwBlock < m_lzwBlocks.size() && m_lzwContext->hasRemainingRows()) {
381        if (!m_lzwContext->doLZW(reinterpret_cast<const unsigned char*>(m_lzwBlocks[m_currentLzwBlock]->data()),
382                                                                        m_lzwBlocks[m_currentLzwBlock]->size())) {
383            return false;
384        }
385        ++m_currentLzwBlock;
386    }
387
388    // If this frame is data complete then the previous loop must have completely decoded all LZW blocks.
389    // There will be no more decoding for this frame so it's time to cleanup.
390    if (isComplete()) {
391        *frameComplete = true;
392        m_lzwContext.reset();
393    }
394    return true;
395}
396
397// Decode a frame.
398// This method uses SkGIFFrameContext:decode() to decode the frame; decoding error is reported to client as a critical failure.
399// Return true if decoding has progressed. Return false if an error has occurred.
400bool SkGifImageReader::decode(size_t frameIndex, bool* frameComplete)
401{
402    SkGIFFrameContext* currentFrame = m_frames[frameIndex].get();
403
404    return currentFrame->decode(m_client, frameComplete);
405}
406
407// Parse incoming GIF data stream into internal data structures.
408// Return true if parsing has progressed or there is not enough data.
409// Return false if a fatal error is encountered.
410bool SkGifImageReader::parse(SkGifImageReader::SkGIFParseQuery query)
411{
412    if (m_parseCompleted) {
413        return true;
414    }
415
416    // SkGIFSizeQuery and SkGIFFrameCountQuery are negative, so this is only meaningful when >= 0.
417    const int lastFrameToParse = (int) query;
418    if (lastFrameToParse >= 0 && (int) m_frames.size() > lastFrameToParse
419                && m_frames[lastFrameToParse]->isComplete()) {
420        // We have already parsed this frame.
421        return true;
422    }
423
424    while (true) {
425        const size_t bytesBuffered = m_streamBuffer.buffer(m_bytesToConsume);
426        if (bytesBuffered < m_bytesToConsume) {
427            // The stream does not yet have enough data. Mark that we need less next time around,
428            // and return.
429            m_bytesToConsume -= bytesBuffered;
430            return true;
431        }
432
433        switch (m_state) {
434        case SkGIFLZW:
435            SkASSERT(!m_frames.empty());
436            // FIXME: All this copying might be wasteful for e.g. SkMemoryStream
437            m_frames.back()->addLzwBlock(m_streamBuffer.get(), m_streamBuffer.bytesBuffered());
438            GETN(1, SkGIFSubBlock);
439            break;
440
441        case SkGIFLZWStart: {
442            SkASSERT(!m_frames.empty());
443            m_frames.back()->setDataSize(this->getOneByte());
444            GETN(1, SkGIFSubBlock);
445            break;
446        }
447
448        case SkGIFType: {
449            const char* currentComponent = m_streamBuffer.get();
450
451            // All GIF files begin with "GIF87a" or "GIF89a".
452            if (!memcmp(currentComponent, "GIF89a", 6))
453                m_version = 89;
454            else if (!memcmp(currentComponent, "GIF87a", 6))
455                m_version = 87;
456            else {
457                // This prevents attempting to continue reading this invalid stream.
458                GETN(0, SkGIFDone);
459                return false;
460            }
461            GETN(7, SkGIFGlobalHeader);
462            break;
463        }
464
465        case SkGIFGlobalHeader: {
466            const unsigned char* currentComponent =
467                reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
468
469            // This is the height and width of the "screen" or frame into which
470            // images are rendered. The individual images can be smaller than
471            // the screen size and located with an origin anywhere within the
472            // screen.
473            // Note that we don't inform the client of the size yet, as it might
474            // change after we read the first frame's image header.
475            m_screenWidth = GETINT16(currentComponent);
476            m_screenHeight = GETINT16(currentComponent + 2);
477
478            const size_t globalColorMapColors = 2 << (currentComponent[4] & 0x07);
479
480            if ((currentComponent[4] & 0x80) && globalColorMapColors > 0) { /* global map */
481                m_globalColorMap.setNumColors(globalColorMapColors);
482                GETN(SK_BYTES_PER_COLORMAP_ENTRY * globalColorMapColors, SkGIFGlobalColormap);
483                break;
484            }
485
486            GETN(1, SkGIFImageStart);
487            break;
488        }
489
490        case SkGIFGlobalColormap: {
491            m_globalColorMap.setRawData(m_streamBuffer.get(), m_streamBuffer.bytesBuffered());
492            GETN(1, SkGIFImageStart);
493            break;
494        }
495
496        case SkGIFImageStart: {
497            const char currentComponent = m_streamBuffer.get()[0];
498
499            if (currentComponent == '!') { // extension.
500                GETN(2, SkGIFExtension);
501                break;
502            }
503
504            if (currentComponent == ',') { // image separator.
505                GETN(9, SkGIFImageHeader);
506                break;
507            }
508
509            // If we get anything other than ',' (image separator), '!'
510            // (extension), or ';' (trailer), there is extraneous data
511            // between blocks. The GIF87a spec tells us to keep reading
512            // until we find an image separator, but GIF89a says such
513            // a file is corrupt. We follow Mozilla's implementation and
514            // proceed as if the file were correctly terminated, so the
515            // GIF will display.
516            GETN(0, SkGIFDone);
517            break;
518        }
519
520        case SkGIFExtension: {
521            const unsigned char* currentComponent =
522                reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
523
524            size_t bytesInBlock = currentComponent[1];
525            SkGIFState exceptionState = SkGIFSkipBlock;
526
527            switch (*currentComponent) {
528            case 0xf9:
529                // The GIF spec mandates that the GIFControlExtension header block length is 4 bytes,
530                exceptionState = SkGIFControlExtension;
531                // and the parser for this block reads 4 bytes, so we must enforce that the buffer
532                // contains at least this many bytes. If the GIF specifies a different length, we
533                // allow that, so long as it's larger; the additional data will simply be ignored.
534                bytesInBlock = std::max(bytesInBlock, static_cast<size_t>(4));
535                break;
536
537            // The GIF spec also specifies the lengths of the following two extensions' headers
538            // (as 12 and 11 bytes, respectively). Because we ignore the plain text extension entirely
539            // and sanity-check the actual length of the application extension header before reading it,
540            // we allow GIFs to deviate from these values in either direction. This is important for
541            // real-world compatibility, as GIFs in the wild exist with application extension headers
542            // that are both shorter and longer than 11 bytes.
543            case 0x01:
544                // ignoring plain text extension
545                break;
546
547            case 0xff:
548                exceptionState = SkGIFApplicationExtension;
549                break;
550
551            case 0xfe:
552                exceptionState = SkGIFConsumeComment;
553                break;
554            }
555
556            if (bytesInBlock)
557                GETN(bytesInBlock, exceptionState);
558            else
559                GETN(1, SkGIFImageStart);
560            break;
561        }
562
563        case SkGIFConsumeBlock: {
564            const unsigned char currentComponent = this->getOneByte();
565            if (!currentComponent)
566                GETN(1, SkGIFImageStart);
567            else
568                GETN(currentComponent, SkGIFSkipBlock);
569            break;
570        }
571
572        case SkGIFSkipBlock: {
573            GETN(1, SkGIFConsumeBlock);
574            break;
575        }
576
577        case SkGIFControlExtension: {
578            const unsigned char* currentComponent =
579                reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
580
581            addFrameIfNecessary();
582            SkGIFFrameContext* currentFrame = m_frames.back().get();
583            if (*currentComponent & 0x1)
584                currentFrame->setTransparentPixel(currentComponent[3]);
585
586            // We ignore the "user input" bit.
587
588            // NOTE: This relies on the values in the FrameDisposalMethod enum
589            // matching those in the GIF spec!
590            int rawDisposalMethod = ((*currentComponent) >> 2) & 0x7;
591            switch (rawDisposalMethod) {
592            case 1:
593            case 2:
594            case 3:
595                currentFrame->setDisposalMethod((SkCodecAnimation::DisposalMethod) rawDisposalMethod);
596                break;
597            case 4:
598                // Some specs say that disposal method 3 is "overwrite previous", others that setting
599                // the third bit of the field (i.e. method 4) is. We map both to the same value.
600                currentFrame->setDisposalMethod(SkCodecAnimation::RestorePrevious_DisposalMethod);
601                break;
602            default:
603                // Other values use the default.
604                currentFrame->setDisposalMethod(SkCodecAnimation::Keep_DisposalMethod);
605                break;
606            }
607            currentFrame->setDelayTime(GETINT16(currentComponent + 1) * 10);
608            GETN(1, SkGIFConsumeBlock);
609            break;
610        }
611
612        case SkGIFCommentExtension: {
613            const unsigned char currentComponent = this->getOneByte();
614            if (currentComponent)
615                GETN(currentComponent, SkGIFConsumeComment);
616            else
617                GETN(1, SkGIFImageStart);
618            break;
619        }
620
621        case SkGIFConsumeComment: {
622            GETN(1, SkGIFCommentExtension);
623            break;
624        }
625
626        case SkGIFApplicationExtension: {
627            // Check for netscape application extension.
628            if (m_streamBuffer.bytesBuffered() == 11) {
629                const unsigned char* currentComponent =
630                    reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
631
632                if (!memcmp(currentComponent, "NETSCAPE2.0", 11) || !memcmp(currentComponent, "ANIMEXTS1.0", 11))
633                    GETN(1, SkGIFNetscapeExtensionBlock);
634            }
635
636            if (m_state != SkGIFNetscapeExtensionBlock)
637                GETN(1, SkGIFConsumeBlock);
638            break;
639        }
640
641        // Netscape-specific GIF extension: animation looping.
642        case SkGIFNetscapeExtensionBlock: {
643            const int currentComponent = this->getOneByte();
644            // SkGIFConsumeNetscapeExtension always reads 3 bytes from the stream; we should at least wait for this amount.
645            if (currentComponent)
646                GETN(std::max(3, currentComponent), SkGIFConsumeNetscapeExtension);
647            else
648                GETN(1, SkGIFImageStart);
649            break;
650        }
651
652        // Parse netscape-specific application extensions
653        case SkGIFConsumeNetscapeExtension: {
654            const unsigned char* currentComponent =
655                reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
656
657            int netscapeExtension = currentComponent[0] & 7;
658
659            // Loop entire animation specified # of times. Only read the loop count during the first iteration.
660            if (netscapeExtension == 1) {
661                m_loopCount = GETINT16(currentComponent + 1);
662
663                // Zero loop count is infinite animation loop request.
664                if (!m_loopCount)
665                    m_loopCount = SkCodecAnimation::kAnimationLoopInfinite;
666
667                GETN(1, SkGIFNetscapeExtensionBlock);
668            } else if (netscapeExtension == 2) {
669                // Wait for specified # of bytes to enter buffer.
670
671                // Don't do this, this extension doesn't exist (isn't used at all)
672                // and doesn't do anything, as our streaming/buffering takes care of it all...
673                // See: http://semmix.pl/color/exgraf/eeg24.htm
674                GETN(1, SkGIFNetscapeExtensionBlock);
675            } else {
676                // 0,3-7 are yet to be defined netscape extension codes
677                // This prevents attempting to continue reading this invalid stream.
678                GETN(0, SkGIFDone);
679                return false;
680            }
681            break;
682        }
683
684        case SkGIFImageHeader: {
685            unsigned height, width, xOffset, yOffset;
686            const unsigned char* currentComponent =
687                reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
688
689            /* Get image offsets, with respect to the screen origin */
690            xOffset = GETINT16(currentComponent);
691            yOffset = GETINT16(currentComponent + 2);
692
693            /* Get image width and height. */
694            width  = GETINT16(currentComponent + 4);
695            height = GETINT16(currentComponent + 6);
696
697            // Some GIF files have frames that don't fit in the specified
698            // overall image size. For the first frame, we can simply enlarge
699            // the image size to allow the frame to be visible.  We can't do
700            // this on subsequent frames because the rest of the decoding
701            // infrastructure assumes the image size won't change as we
702            // continue decoding, so any subsequent frames that are even
703            // larger will be cropped.
704            // Luckily, handling just the first frame is sufficient to deal
705            // with most cases, e.g. ones where the image size is erroneously
706            // set to zero, since usually the first frame completely fills
707            // the image.
708            if (currentFrameIsFirstFrame()) {
709                m_screenHeight = std::max(m_screenHeight, yOffset + height);
710                m_screenWidth = std::max(m_screenWidth, xOffset + width);
711            }
712
713            // NOTE: Chromium placed this block after setHeaderDefined, down
714            // below we returned true when asked for the size. So Chromium
715            // created an image which would fail. Is this the correct behavior?
716            // We choose to return false early, so we will not create an
717            // SkCodec.
718
719            // Work around more broken GIF files that have zero image width or
720            // height.
721            if (!height || !width) {
722                height = m_screenHeight;
723                width = m_screenWidth;
724                if (!height || !width) {
725                    // This prevents attempting to continue reading this invalid stream.
726                    GETN(0, SkGIFDone);
727                    return false;
728                }
729            }
730
731            const bool isLocalColormapDefined = SkToBool(currentComponent[8] & 0x80);
732            // The three low-order bits of currentComponent[8] specify the bits per pixel.
733            const size_t numColors = 2 << (currentComponent[8] & 0x7);
734            if (currentFrameIsFirstFrame()) {
735                bool hasTransparentPixel;
736                if (m_frames.size() == 0) {
737                    // We did not see a Graphics Control Extension, so no transparent
738                    // pixel was specified.
739                    hasTransparentPixel = false;
740                } else {
741                    // This means we did see a Graphics Control Extension, which specifies
742                    // the transparent pixel
743                    const size_t transparentPixel = m_frames[0]->transparentPixel();
744                    if (isLocalColormapDefined) {
745                        hasTransparentPixel = transparentPixel < numColors;
746                    } else {
747                        const size_t globalColors = m_globalColorMap.numColors();
748                        if (!globalColors) {
749                            // No color table for this frame, so the frame is empty.
750                            // This is technically different from having a transparent
751                            // pixel, but we'll treat it the same - nothing to draw here.
752                            hasTransparentPixel = true;
753                        } else {
754                            hasTransparentPixel = transparentPixel < globalColors;
755                        }
756                    }
757                }
758
759                if (hasTransparentPixel) {
760                    m_firstFrameHasAlpha = true;
761                    m_firstFrameSupportsIndex8 = true;
762                } else {
763                    const bool frameIsSubset = xOffset > 0 || yOffset > 0
764                            || xOffset + width < m_screenWidth
765                            || yOffset + height < m_screenHeight;
766                    m_firstFrameHasAlpha = frameIsSubset;
767                    m_firstFrameSupportsIndex8 = !frameIsSubset;
768                }
769            }
770
771            if (query == SkGIFSizeQuery) {
772                // The decoder needs to stop, so we return here, before
773                // flushing the buffer. Next time through, we'll be in the same
774                // state, requiring the same amount in the buffer.
775                m_bytesToConsume = 0;
776                return true;
777            }
778
779            addFrameIfNecessary();
780            SkGIFFrameContext* currentFrame = m_frames.back().get();
781
782            currentFrame->setHeaderDefined();
783
784            currentFrame->setRect(xOffset, yOffset, width, height);
785            currentFrame->setInterlaced(SkToBool(currentComponent[8] & 0x40));
786
787            // Overlaying interlaced, transparent GIFs over
788            // existing image data using the Haeberli display hack
789            // requires saving the underlying image in order to
790            // avoid jaggies at the transparency edges. We are
791            // unprepared to deal with that, so don't display such
792            // images progressively. Which means only the first
793            // frame can be progressively displayed.
794            // FIXME: It is possible that a non-transparent frame
795            // can be interlaced and progressively displayed.
796            currentFrame->setProgressiveDisplay(currentFrameIsFirstFrame());
797
798            if (isLocalColormapDefined) {
799                currentFrame->localColorMap().setNumColors(numColors);
800                GETN(SK_BYTES_PER_COLORMAP_ENTRY * numColors, SkGIFImageColormap);
801                break;
802            }
803
804            GETN(1, SkGIFLZWStart);
805            break;
806        }
807
808        case SkGIFImageColormap: {
809            SkASSERT(!m_frames.empty());
810            m_frames.back()->localColorMap().setRawData(m_streamBuffer.get(), m_streamBuffer.bytesBuffered());
811            GETN(1, SkGIFLZWStart);
812            break;
813        }
814
815        case SkGIFSubBlock: {
816            const size_t bytesInBlock = this->getOneByte();
817            if (bytesInBlock)
818                GETN(bytesInBlock, SkGIFLZW);
819            else {
820                // Finished parsing one frame; Process next frame.
821                SkASSERT(!m_frames.empty());
822                // Note that some broken GIF files do not have enough LZW blocks to fully
823                // decode all rows but we treat it as frame complete.
824                m_frames.back()->setComplete();
825                GETN(1, SkGIFImageStart);
826                if (lastFrameToParse >= 0 && (int) m_frames.size() > lastFrameToParse) {
827                    m_streamBuffer.flush();
828                    return true;
829                }
830            }
831            break;
832        }
833
834        case SkGIFDone: {
835            m_parseCompleted = true;
836            return true;
837        }
838
839        default:
840            // We shouldn't ever get here.
841            // This prevents attempting to continue reading this invalid stream.
842            GETN(0, SkGIFDone);
843            return false;
844            break;
845        }   // switch
846        m_streamBuffer.flush();
847    }
848
849    return true;
850}
851
852void SkGifImageReader::addFrameIfNecessary()
853{
854    if (m_frames.empty() || m_frames.back()->isComplete()) {
855        const size_t i = m_frames.size();
856        std::unique_ptr<SkGIFFrameContext> frame(new SkGIFFrameContext(i));
857        if (0 == i) {
858            frame->setRequiredFrame(SkCodec::kNone);
859        } else {
860            // FIXME: We could correct these after decoding (i.e. some frames may turn out to be
861            // independent although we did not determine that here).
862            const SkGIFFrameContext* prevFrameContext = m_frames[i - 1].get();
863            switch (prevFrameContext->getDisposalMethod()) {
864                case SkCodecAnimation::Keep_DisposalMethod:
865                    frame->setRequiredFrame(i - 1);
866                    break;
867                case SkCodecAnimation::RestorePrevious_DisposalMethod:
868                    frame->setRequiredFrame(prevFrameContext->getRequiredFrame());
869                    break;
870                case SkCodecAnimation::RestoreBGColor_DisposalMethod:
871                    // If the prior frame covers the whole image
872                    if (prevFrameContext->frameRect() == SkIRect::MakeWH(m_screenWidth,
873                                                                         m_screenHeight)
874                            // Or the prior frame was independent
875                            || prevFrameContext->getRequiredFrame() == SkCodec::kNone)
876                    {
877                        // This frame is independent, since we clear everything
878                        // prior frame to the BG color
879                        frame->setRequiredFrame(SkCodec::kNone);
880                    } else {
881                        frame->setRequiredFrame(i - 1);
882                    }
883                    break;
884            }
885        }
886        m_frames.push_back(std::move(frame));
887    }
888}
889
890// FIXME: Move this method to close to doLZW().
891bool SkGIFLZWContext::prepareToDecode()
892{
893    SkASSERT(m_frameContext->isDataSizeDefined() && m_frameContext->isHeaderDefined());
894
895    // Since we use a codesize of 1 more than the datasize, we need to ensure
896    // that our datasize is strictly less than the SK_MAX_DICTIONARY_ENTRY_BITS.
897    if (m_frameContext->dataSize() >= SK_MAX_DICTIONARY_ENTRY_BITS)
898        return false;
899    clearCode = 1 << m_frameContext->dataSize();
900    avail = clearCode + 2;
901    oldcode = -1;
902    codesize = m_frameContext->dataSize() + 1;
903    codemask = (1 << codesize) - 1;
904    datum = bits = 0;
905    ipass = m_frameContext->interlaced() ? 1 : 0;
906    irow = 0;
907
908    // We want to know the longest sequence encodable by a dictionary with
909    // SK_MAX_DICTIONARY_ENTRIES entries. If we ignore the need to encode the base
910    // values themselves at the beginning of the dictionary, as well as the need
911    // for a clear code or a termination code, we could use every entry to
912    // encode a series of multiple values. If the input value stream looked
913    // like "AAAAA..." (a long string of just one value), the first dictionary
914    // entry would encode AA, the next AAA, the next AAAA, and so forth. Thus
915    // the longest sequence would be SK_MAX_DICTIONARY_ENTRIES + 1 values.
916    //
917    // However, we have to account for reserved entries. The first |datasize|
918    // bits are reserved for the base values, and the next two entries are
919    // reserved for the clear code and termination code. In theory a GIF can
920    // set the datasize to 0, meaning we have just two reserved entries, making
921    // the longest sequence (SK_MAX_DICTIONARY_ENTIRES + 1) - 2 values long. Since
922    // each value is a byte, this is also the number of bytes in the longest
923    // encodable sequence.
924    const size_t maxBytes = SK_MAX_DICTIONARY_ENTRIES - 1;
925
926    // Now allocate the output buffer. We decode directly into this buffer
927    // until we have at least one row worth of data, then call outputRow().
928    // This means worst case we may have (row width - 1) bytes in the buffer
929    // and then decode a sequence |maxBytes| long to append.
930    rowBuffer.reset(m_frameContext->width() - 1 + maxBytes);
931    rowIter = rowBuffer.begin();
932    rowsRemaining = m_frameContext->height();
933
934    // Clearing the whole suffix table lets us be more tolerant of bad data.
935    for (int i = 0; i < clearCode; ++i) {
936        suffix[i] = i;
937        suffixLength[i] = 1;
938    }
939    return true;
940}
941
942