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 ((unsigned)((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 (drowEnd >= m_frameContext->height())
142            drowEnd = m_frameContext->height() - 1;
143    }
144
145    // Protect against too much image data.
146    if (drowStart >= m_frameContext->height())
147        return true;
148
149    // CALLBACK: Let the client know we have decoded a row.
150    const bool writeTransparentPixels = (SkCodec::kNone == m_frameContext->getRequiredFrame());
151    if (!m_client->haveDecodedRow(m_frameContext->frameId(), rowBegin,
152        drowStart, drowEnd - drowStart + 1, writeTransparentPixels))
153        return false;
154
155    if (!m_frameContext->interlaced())
156        irow++;
157    else {
158        do {
159            switch (ipass) {
160            case 1:
161                irow += 8;
162                if (irow >= (unsigned) m_frameContext->height()) {
163                    ipass++;
164                    irow = 4;
165                }
166                break;
167
168            case 2:
169                irow += 8;
170                if (irow >= (unsigned) m_frameContext->height()) {
171                    ipass++;
172                    irow = 2;
173                }
174                break;
175
176            case 3:
177                irow += 4;
178                if (irow >= (unsigned) m_frameContext->height()) {
179                    ipass++;
180                    irow = 1;
181                }
182                break;
183
184            case 4:
185                irow += 2;
186                if (irow >= (unsigned) m_frameContext->height()) {
187                    ipass++;
188                    irow = 0;
189                }
190                break;
191
192            default:
193                break;
194            }
195        } while (irow > (unsigned) (m_frameContext->height() - 1));
196    }
197    return true;
198}
199
200// Perform Lempel-Ziv-Welch decoding.
201// Returns true if decoding was successful. In this case the block will have been completely consumed and/or rowsRemaining will be 0.
202// Otherwise, decoding failed; returns false in this case, which will always cause the SkGifImageReader to set the "decode failed" flag.
203bool SkGIFLZWContext::doLZW(const unsigned char* block, size_t bytesInBlock)
204{
205    const int width = m_frameContext->width();
206
207    if (rowIter == rowBuffer.end())
208        return true;
209
210    for (const unsigned char* ch = block; bytesInBlock-- > 0; ch++) {
211        // Feed the next byte into the decoder's 32-bit input buffer.
212        datum += ((int) *ch) << bits;
213        bits += 8;
214
215        // Check for underflow of decoder's 32-bit input buffer.
216        while (bits >= codesize) {
217            // Get the leading variable-length symbol from the data stream.
218            int code = datum & codemask;
219            datum >>= codesize;
220            bits -= codesize;
221
222            // Reset the dictionary to its original state, if requested.
223            if (code == clearCode) {
224                codesize = m_frameContext->dataSize() + 1;
225                codemask = (1 << codesize) - 1;
226                avail = clearCode + 2;
227                oldcode = -1;
228                continue;
229            }
230
231            // Check for explicit end-of-stream code.
232            if (code == (clearCode + 1)) {
233                // end-of-stream should only appear after all image data.
234                if (!rowsRemaining)
235                    return true;
236                return false;
237            }
238
239            const int tempCode = code;
240            unsigned short codeLength = 0;
241            if (code < avail) {
242                // This is a pre-existing code, so we already know what it
243                // encodes.
244                codeLength = suffixLength[code];
245                rowIter += codeLength;
246            } else if (code == avail && oldcode != -1) {
247                // This is a new code just being added to the dictionary.
248                // It must encode the contents of the previous code, plus
249                // the first character of the previous code again.
250                codeLength = suffixLength[oldcode] + 1;
251                rowIter += codeLength;
252                *--rowIter = firstchar;
253                code = oldcode;
254            } else {
255                // This is an invalid code. The dictionary is just initialized
256                // and the code is incomplete. We don't know how to handle
257                // this case.
258                return false;
259            }
260
261            while (code >= clearCode) {
262                *--rowIter = suffix[code];
263                code = prefix[code];
264            }
265
266            *--rowIter = firstchar = suffix[code];
267
268            // Define a new codeword in the dictionary as long as we've read
269            // more than one value from the stream.
270            if (avail < SK_MAX_DICTIONARY_ENTRIES && oldcode != -1) {
271                prefix[avail] = oldcode;
272                suffix[avail] = firstchar;
273                suffixLength[avail] = suffixLength[oldcode] + 1;
274                ++avail;
275
276                // If we've used up all the codewords of a given length
277                // increase the length of codewords by one bit, but don't
278                // exceed the specified maximum codeword size.
279                if (!(avail & codemask) && avail < SK_MAX_DICTIONARY_ENTRIES) {
280                    ++codesize;
281                    codemask += avail;
282                }
283            }
284            oldcode = tempCode;
285            rowIter += codeLength;
286
287            // Output as many rows as possible.
288            unsigned char* rowBegin = rowBuffer.begin();
289            for (; rowBegin + width <= rowIter; rowBegin += width) {
290                if (!outputRow(rowBegin))
291                    return false;
292                rowsRemaining--;
293                if (!rowsRemaining)
294                    return true;
295            }
296
297            if (rowBegin != rowBuffer.begin()) {
298                // Move the remaining bytes to the beginning of the buffer.
299                const size_t bytesToCopy = rowIter - rowBegin;
300                memcpy(&rowBuffer.front(), rowBegin, bytesToCopy);
301                rowIter = rowBuffer.begin() + bytesToCopy;
302            }
303        }
304    }
305    return true;
306}
307
308sk_sp<SkColorTable> SkGIFColorMap::buildTable(SkStreamBuffer* streamBuffer, SkColorType colorType,
309                                              int transparentPixel) const
310{
311    if (!m_isDefined)
312        return nullptr;
313
314    const PackColorProc proc = choose_pack_color_proc(false, colorType);
315    if (m_table && proc == m_packColorProc && m_transPixel == transparentPixel) {
316        SkASSERT(transparentPixel == kNotFound || transparentPixel > m_table->count()
317                || m_table->operator[](transparentPixel) == SK_ColorTRANSPARENT);
318        // This SkColorTable has already been built with the same transparent color and
319        // packing proc. Reuse it.
320        return m_table;
321    }
322    m_packColorProc = proc;
323    m_transPixel = transparentPixel;
324
325    const size_t bytes = m_colors * SK_BYTES_PER_COLORMAP_ENTRY;
326    sk_sp<SkData> rawData(streamBuffer->getDataAtPosition(m_position, bytes));
327    if (!rawData) {
328        return nullptr;
329    }
330
331    SkASSERT(m_colors <= SK_MAX_COLORS);
332    const uint8_t* srcColormap = rawData->bytes();
333    SkPMColor colorStorage[SK_MAX_COLORS];
334    for (int i = 0; i < m_colors; i++) {
335        if (i == transparentPixel) {
336            colorStorage[i] = SK_ColorTRANSPARENT;
337        } else {
338            colorStorage[i] = proc(255, srcColormap[0], srcColormap[1], srcColormap[2]);
339        }
340        srcColormap += SK_BYTES_PER_COLORMAP_ENTRY;
341    }
342    for (int i = m_colors; i < SK_MAX_COLORS; i++) {
343        colorStorage[i] = SK_ColorTRANSPARENT;
344    }
345    m_table = sk_sp<SkColorTable>(new SkColorTable(colorStorage, SK_MAX_COLORS));
346    return m_table;
347}
348
349sk_sp<SkColorTable> SkGifImageReader::getColorTable(SkColorType colorType, int index) {
350    if (index < 0 || static_cast<size_t>(index) >= m_frames.size()) {
351        return nullptr;
352    }
353
354    const SkGIFFrameContext* frameContext = m_frames[index].get();
355    const SkGIFColorMap& localColorMap = frameContext->localColorMap();
356    const int transPix = frameContext->transparentPixel();
357    if (localColorMap.isDefined()) {
358        return localColorMap.buildTable(&m_streamBuffer, colorType, transPix);
359    }
360    if (m_globalColorMap.isDefined()) {
361        return m_globalColorMap.buildTable(&m_streamBuffer, colorType, transPix);
362    }
363    return nullptr;
364}
365
366// Perform decoding for this frame. frameComplete will be true if the entire frame is decoded.
367// Returns false if a decoding error occurred. This is a fatal error and causes the SkGifImageReader to set the "decode failed" flag.
368// 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.
369bool SkGIFFrameContext::decode(SkStreamBuffer* streamBuffer, SkGifCodec* client,
370                               bool* frameComplete)
371{
372    *frameComplete = false;
373    if (!m_lzwContext) {
374        // Wait for more data to properly initialize SkGIFLZWContext.
375        if (!isDataSizeDefined() || !isHeaderDefined())
376            return true;
377
378        m_lzwContext.reset(new SkGIFLZWContext(client, this));
379        if (!m_lzwContext->prepareToDecode()) {
380            m_lzwContext.reset();
381            return false;
382        }
383
384        m_currentLzwBlock = 0;
385    }
386
387    // Some bad GIFs have extra blocks beyond the last row, which we don't want to decode.
388    while (static_cast<size_t>(m_currentLzwBlock) < m_lzwBlocks.size()
389           && m_lzwContext->hasRemainingRows()) {
390        const auto& block = m_lzwBlocks[m_currentLzwBlock];
391        const size_t len = block.blockSize;
392
393        sk_sp<SkData> data(streamBuffer->getDataAtPosition(block.blockPosition, len));
394        if (!data) {
395            return false;
396        }
397        if (!m_lzwContext->doLZW(reinterpret_cast<const unsigned char*>(data->data()), len)) {
398            return false;
399        }
400        ++m_currentLzwBlock;
401    }
402
403    // If this frame is data complete then the previous loop must have completely decoded all LZW blocks.
404    // There will be no more decoding for this frame so it's time to cleanup.
405    if (isComplete()) {
406        *frameComplete = true;
407        m_lzwContext.reset();
408    }
409    return true;
410}
411
412// Decode a frame.
413// This method uses SkGIFFrameContext:decode() to decode the frame; decoding error is reported to client as a critical failure.
414// Return true if decoding has progressed. Return false if an error has occurred.
415bool SkGifImageReader::decode(int frameIndex, bool* frameComplete)
416{
417    SkGIFFrameContext* currentFrame = m_frames[frameIndex].get();
418
419    return currentFrame->decode(&m_streamBuffer, m_client, frameComplete);
420}
421
422// Parse incoming GIF data stream into internal data structures.
423SkCodec::Result SkGifImageReader::parse(SkGifImageReader::SkGIFParseQuery query)
424{
425    if (m_parseCompleted) {
426        return SkCodec::kSuccess;
427    }
428
429    if (SkGIFLoopCountQuery == query && m_loopCount != cLoopCountNotSeen) {
430        // Loop count has already been parsed.
431        return SkCodec::kSuccess;
432    }
433
434    // SkGIFSizeQuery and SkGIFFrameCountQuery are negative, so this is only meaningful when >= 0.
435    const int lastFrameToParse = (int) query;
436    if (lastFrameToParse >= 0 && (int) m_frames.size() > lastFrameToParse
437                && m_frames[lastFrameToParse]->isComplete()) {
438        // We have already parsed this frame.
439        return SkCodec::kSuccess;
440    }
441
442    while (true) {
443        if (!m_streamBuffer.buffer(m_bytesToConsume)) {
444            // The stream does not yet have enough data.
445            return SkCodec::kIncompleteInput;
446        }
447
448        switch (m_state) {
449        case SkGIFLZW: {
450            SkASSERT(!m_frames.empty());
451            auto* frame = m_frames.back().get();
452            frame->addLzwBlock(m_streamBuffer.markPosition(), m_bytesToConsume);
453            GETN(1, SkGIFSubBlock);
454            break;
455        }
456        case SkGIFLZWStart: {
457            SkASSERT(!m_frames.empty());
458            auto* currentFrame = m_frames.back().get();
459
460            currentFrame->setDataSize(this->getOneByte());
461            GETN(1, SkGIFSubBlock);
462            break;
463        }
464
465        case SkGIFType: {
466            const char* currentComponent = m_streamBuffer.get();
467
468            // All GIF files begin with "GIF87a" or "GIF89a".
469            if (!memcmp(currentComponent, "GIF89a", 6))
470                m_version = 89;
471            else if (!memcmp(currentComponent, "GIF87a", 6))
472                m_version = 87;
473            else {
474                // This prevents attempting to continue reading this invalid stream.
475                GETN(0, SkGIFDone);
476                return SkCodec::kInvalidInput;
477            }
478            GETN(7, SkGIFGlobalHeader);
479            break;
480        }
481
482        case SkGIFGlobalHeader: {
483            const unsigned char* currentComponent =
484                reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
485
486            // This is the height and width of the "screen" or frame into which
487            // images are rendered. The individual images can be smaller than
488            // the screen size and located with an origin anywhere within the
489            // screen.
490            // Note that we don't inform the client of the size yet, as it might
491            // change after we read the first frame's image header.
492            fScreenWidth = GETINT16(currentComponent);
493            fScreenHeight = GETINT16(currentComponent + 2);
494
495            const int globalColorMapColors = 2 << (currentComponent[4] & 0x07);
496
497            if ((currentComponent[4] & 0x80) && globalColorMapColors > 0) { /* global map */
498                m_globalColorMap.setNumColors(globalColorMapColors);
499                GETN(SK_BYTES_PER_COLORMAP_ENTRY * globalColorMapColors, SkGIFGlobalColormap);
500                break;
501            }
502
503            GETN(1, SkGIFImageStart);
504            break;
505        }
506
507        case SkGIFGlobalColormap: {
508            m_globalColorMap.setTablePosition(m_streamBuffer.markPosition());
509            GETN(1, SkGIFImageStart);
510            break;
511        }
512
513        case SkGIFImageStart: {
514            const char currentComponent = m_streamBuffer.get()[0];
515
516            if (currentComponent == '!') { // extension.
517                GETN(2, SkGIFExtension);
518                break;
519            }
520
521            if (currentComponent == ',') { // image separator.
522                GETN(9, SkGIFImageHeader);
523                break;
524            }
525
526            // If we get anything other than ',' (image separator), '!'
527            // (extension), or ';' (trailer), there is extraneous data
528            // between blocks. The GIF87a spec tells us to keep reading
529            // until we find an image separator, but GIF89a says such
530            // a file is corrupt. We follow Mozilla's implementation and
531            // proceed as if the file were correctly terminated, so the
532            // GIF will display.
533            GETN(0, SkGIFDone);
534            break;
535        }
536
537        case SkGIFExtension: {
538            const unsigned char* currentComponent =
539                reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
540
541            size_t bytesInBlock = currentComponent[1];
542            SkGIFState exceptionState = SkGIFSkipBlock;
543
544            switch (*currentComponent) {
545            case 0xf9:
546                // The GIF spec mandates that the GIFControlExtension header block length is 4 bytes,
547                exceptionState = SkGIFControlExtension;
548                // and the parser for this block reads 4 bytes, so we must enforce that the buffer
549                // contains at least this many bytes. If the GIF specifies a different length, we
550                // allow that, so long as it's larger; the additional data will simply be ignored.
551                bytesInBlock = std::max(bytesInBlock, static_cast<size_t>(4));
552                break;
553
554            // The GIF spec also specifies the lengths of the following two extensions' headers
555            // (as 12 and 11 bytes, respectively). Because we ignore the plain text extension entirely
556            // and sanity-check the actual length of the application extension header before reading it,
557            // we allow GIFs to deviate from these values in either direction. This is important for
558            // real-world compatibility, as GIFs in the wild exist with application extension headers
559            // that are both shorter and longer than 11 bytes.
560            case 0x01:
561                // ignoring plain text extension
562                break;
563
564            case 0xff:
565                exceptionState = SkGIFApplicationExtension;
566                break;
567
568            case 0xfe:
569                exceptionState = SkGIFConsumeComment;
570                break;
571            }
572
573            if (bytesInBlock)
574                GETN(bytesInBlock, exceptionState);
575            else
576                GETN(1, SkGIFImageStart);
577            break;
578        }
579
580        case SkGIFConsumeBlock: {
581            const unsigned char currentComponent = this->getOneByte();
582            if (!currentComponent)
583                GETN(1, SkGIFImageStart);
584            else
585                GETN(currentComponent, SkGIFSkipBlock);
586            break;
587        }
588
589        case SkGIFSkipBlock: {
590            GETN(1, SkGIFConsumeBlock);
591            break;
592        }
593
594        case SkGIFControlExtension: {
595            const unsigned char* currentComponent =
596                reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
597
598            addFrameIfNecessary();
599            SkGIFFrameContext* currentFrame = m_frames.back().get();
600            if (*currentComponent & 0x1)
601                currentFrame->setTransparentPixel(currentComponent[3]);
602
603            // We ignore the "user input" bit.
604
605            // NOTE: This relies on the values in the FrameDisposalMethod enum
606            // matching those in the GIF spec!
607            int rawDisposalMethod = ((*currentComponent) >> 2) & 0x7;
608            switch (rawDisposalMethod) {
609            case 1:
610            case 2:
611            case 3:
612                currentFrame->setDisposalMethod((SkCodecAnimation::DisposalMethod) rawDisposalMethod);
613                break;
614            case 4:
615                // Some specs say that disposal method 3 is "overwrite previous", others that setting
616                // the third bit of the field (i.e. method 4) is. We map both to the same value.
617                currentFrame->setDisposalMethod(SkCodecAnimation::DisposalMethod::kRestorePrevious);
618                break;
619            default:
620                // Other values use the default.
621                currentFrame->setDisposalMethod(SkCodecAnimation::DisposalMethod::kKeep);
622                break;
623            }
624            currentFrame->setDuration(GETINT16(currentComponent + 1) * 10);
625            GETN(1, SkGIFConsumeBlock);
626            break;
627        }
628
629        case SkGIFCommentExtension: {
630            const unsigned char currentComponent = this->getOneByte();
631            if (currentComponent)
632                GETN(currentComponent, SkGIFConsumeComment);
633            else
634                GETN(1, SkGIFImageStart);
635            break;
636        }
637
638        case SkGIFConsumeComment: {
639            GETN(1, SkGIFCommentExtension);
640            break;
641        }
642
643        case SkGIFApplicationExtension: {
644            // Check for netscape application extension.
645            if (m_bytesToConsume == 11) {
646                const unsigned char* currentComponent =
647                    reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
648
649                if (!memcmp(currentComponent, "NETSCAPE2.0", 11) || !memcmp(currentComponent, "ANIMEXTS1.0", 11))
650                    GETN(1, SkGIFNetscapeExtensionBlock);
651            }
652
653            if (m_state != SkGIFNetscapeExtensionBlock)
654                GETN(1, SkGIFConsumeBlock);
655            break;
656        }
657
658        // Netscape-specific GIF extension: animation looping.
659        case SkGIFNetscapeExtensionBlock: {
660            const int currentComponent = this->getOneByte();
661            // SkGIFConsumeNetscapeExtension always reads 3 bytes from the stream; we should at least wait for this amount.
662            if (currentComponent)
663                GETN(std::max(3, currentComponent), SkGIFConsumeNetscapeExtension);
664            else
665                GETN(1, SkGIFImageStart);
666            break;
667        }
668
669        // Parse netscape-specific application extensions
670        case SkGIFConsumeNetscapeExtension: {
671            const unsigned char* currentComponent =
672                reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
673
674            int netscapeExtension = currentComponent[0] & 7;
675
676            // Loop entire animation specified # of times. Only read the loop count during the first iteration.
677            if (netscapeExtension == 1) {
678                m_loopCount = GETINT16(currentComponent + 1);
679
680                // Zero loop count is infinite animation loop request.
681                if (!m_loopCount)
682                    m_loopCount = SkCodec::kRepetitionCountInfinite;
683
684                GETN(1, SkGIFNetscapeExtensionBlock);
685
686                if (SkGIFLoopCountQuery == query) {
687                    m_streamBuffer.flush();
688                    return SkCodec::kSuccess;
689                }
690            } else if (netscapeExtension == 2) {
691                // Wait for specified # of bytes to enter buffer.
692
693                // Don't do this, this extension doesn't exist (isn't used at all)
694                // and doesn't do anything, as our streaming/buffering takes care of it all...
695                // See: http://semmix.pl/color/exgraf/eeg24.htm
696                GETN(1, SkGIFNetscapeExtensionBlock);
697            } else {
698                // 0,3-7 are yet to be defined netscape extension codes
699                // This prevents attempting to continue reading this invalid stream.
700                GETN(0, SkGIFDone);
701                return SkCodec::kInvalidInput;
702            }
703            break;
704        }
705
706        case SkGIFImageHeader: {
707            int height, width, xOffset, yOffset;
708            const unsigned char* currentComponent =
709                reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
710
711            /* Get image offsets, with respect to the screen origin */
712            xOffset = GETINT16(currentComponent);
713            yOffset = GETINT16(currentComponent + 2);
714
715            /* Get image width and height. */
716            width  = GETINT16(currentComponent + 4);
717            height = GETINT16(currentComponent + 6);
718
719            // Some GIF files have frames that don't fit in the specified
720            // overall image size. For the first frame, we can simply enlarge
721            // the image size to allow the frame to be visible.  We can't do
722            // this on subsequent frames because the rest of the decoding
723            // infrastructure assumes the image size won't change as we
724            // continue decoding, so any subsequent frames that are even
725            // larger will be cropped.
726            // Luckily, handling just the first frame is sufficient to deal
727            // with most cases, e.g. ones where the image size is erroneously
728            // set to zero, since usually the first frame completely fills
729            // the image.
730            if (currentFrameIsFirstFrame()) {
731                fScreenHeight = std::max(fScreenHeight, yOffset + height);
732                fScreenWidth = std::max(fScreenWidth, xOffset + width);
733            }
734
735            // NOTE: Chromium placed this block after setHeaderDefined, down
736            // below we returned true when asked for the size. So Chromium
737            // created an image which would fail. Is this the correct behavior?
738            // We choose to return false early, so we will not create an
739            // SkCodec.
740
741            // Work around more broken GIF files that have zero image width or
742            // height.
743            if (!height || !width) {
744                height = fScreenHeight;
745                width = fScreenWidth;
746                if (!height || !width) {
747                    // This prevents attempting to continue reading this invalid stream.
748                    GETN(0, SkGIFDone);
749                    return SkCodec::kInvalidInput;
750                }
751            }
752
753            const bool isLocalColormapDefined = SkToBool(currentComponent[8] & 0x80);
754            // The three low-order bits of currentComponent[8] specify the bits per pixel.
755            const int numColors = 2 << (currentComponent[8] & 0x7);
756            if (currentFrameIsFirstFrame()) {
757                const int transPix = m_frames.empty() ? SkGIFColorMap::kNotFound
758                                                      : m_frames[0]->transparentPixel();
759                if (this->hasTransparency(transPix,
760                        isLocalColormapDefined, numColors))
761                {
762                    m_firstFrameHasAlpha = true;
763                } else {
764                    const bool frameIsSubset = xOffset > 0 || yOffset > 0
765                            || width < fScreenWidth
766                            || height < fScreenHeight;
767                    m_firstFrameHasAlpha = frameIsSubset;
768                }
769            }
770
771            addFrameIfNecessary();
772            SkGIFFrameContext* currentFrame = m_frames.back().get();
773            currentFrame->setHeaderDefined();
774
775            if (query == SkGIFSizeQuery) {
776                // The decoder needs to stop, so we return here, before
777                // flushing the buffer. Next time through, we'll be in the same
778                // state, requiring the same amount in the buffer.
779                return SkCodec::kSuccess;
780            }
781
782
783            currentFrame->setXYWH(xOffset, yOffset, width, height);
784            currentFrame->setInterlaced(SkToBool(currentComponent[8] & 0x40));
785
786            // Overlaying interlaced, transparent GIFs over
787            // existing image data using the Haeberli display hack
788            // requires saving the underlying image in order to
789            // avoid jaggies at the transparency edges. We are
790            // unprepared to deal with that, so don't display such
791            // images progressively. Which means only the first
792            // frame can be progressively displayed.
793            // FIXME: It is possible that a non-transparent frame
794            // can be interlaced and progressively displayed.
795            currentFrame->setProgressiveDisplay(currentFrameIsFirstFrame());
796
797            if (isLocalColormapDefined) {
798                currentFrame->localColorMap().setNumColors(numColors);
799                GETN(SK_BYTES_PER_COLORMAP_ENTRY * numColors, SkGIFImageColormap);
800                break;
801            }
802
803            setAlphaAndRequiredFrame(currentFrame);
804            GETN(1, SkGIFLZWStart);
805            break;
806        }
807
808        case SkGIFImageColormap: {
809            SkASSERT(!m_frames.empty());
810            auto* currentFrame = m_frames.back().get();
811            auto& cmap = currentFrame->localColorMap();
812            cmap.setTablePosition(m_streamBuffer.markPosition());
813            setAlphaAndRequiredFrame(currentFrame);
814            GETN(1, SkGIFLZWStart);
815            break;
816        }
817
818        case SkGIFSubBlock: {
819            const size_t bytesInBlock = this->getOneByte();
820            if (bytesInBlock)
821                GETN(bytesInBlock, SkGIFLZW);
822            else {
823                // Finished parsing one frame; Process next frame.
824                SkASSERT(!m_frames.empty());
825                // Note that some broken GIF files do not have enough LZW blocks to fully
826                // decode all rows but we treat it as frame complete.
827                m_frames.back()->setComplete();
828                GETN(1, SkGIFImageStart);
829                if (lastFrameToParse >= 0 && (int) m_frames.size() > lastFrameToParse) {
830                    m_streamBuffer.flush();
831                    return SkCodec::kSuccess;
832                }
833            }
834            break;
835        }
836
837        case SkGIFDone: {
838            m_parseCompleted = true;
839            return SkCodec::kSuccess;
840        }
841
842        default:
843            // We shouldn't ever get here.
844            // This prevents attempting to continue reading this invalid stream.
845            GETN(0, SkGIFDone);
846            return SkCodec::kInvalidInput;
847            break;
848        }   // switch
849        m_streamBuffer.flush();
850    }
851}
852
853bool SkGifImageReader::hasTransparency(int transparentPixel, bool isLocalColormapDefined,
854                                       int localColors) const {
855    const int globalColors = m_globalColorMap.numColors();
856    if (!isLocalColormapDefined && globalColors == 0) {
857        // No color table for this frame, so it is completely transparent.
858        return true;
859    }
860
861    if (transparentPixel < 0) {
862        SkASSERT(SkGIFColorMap::kNotFound == transparentPixel);
863        return false;
864    }
865
866    if (isLocalColormapDefined) {
867        return transparentPixel < localColors;
868    }
869
870    // If there is a global color table, it will be parsed before reaching
871    // here. If its numColors is set, it will be defined.
872    SkASSERT(globalColors > 0);
873    SkASSERT(m_globalColorMap.isDefined());
874    return transparentPixel < globalColors;
875}
876
877void SkGifImageReader::addFrameIfNecessary()
878{
879    if (m_frames.empty() || m_frames.back()->isComplete()) {
880        const size_t i = m_frames.size();
881        std::unique_ptr<SkGIFFrameContext> frame(new SkGIFFrameContext(this, static_cast<int>(i)));
882        m_frames.push_back(std::move(frame));
883    }
884}
885
886static SkIRect frame_rect_on_screen(SkIRect frameRect,
887                                    const SkIRect& screenRect) {
888    if (!frameRect.intersect(screenRect)) {
889        return SkIRect::MakeEmpty();
890    }
891
892    return frameRect;
893}
894
895static bool independent(const SkFrame& frame) {
896    return frame.getRequiredFrame() == SkCodec::kNone;
897}
898
899static bool restore_bg(const SkFrame& frame) {
900    return frame.getDisposalMethod() == SkCodecAnimation::DisposalMethod::kRestoreBGColor;
901}
902
903bool SkGIFFrameContext::onReportsAlpha() const {
904    // Note: We could correct these after decoding - i.e. some frames may turn out to be
905    // independent and opaque if they do not use the transparent pixel, but that would require
906    // checking whether each pixel used the transparent index.
907    return m_owner->hasTransparency(this->transparentPixel(),
908            m_localColorMap.isDefined(), m_localColorMap.numColors());
909}
910
911void SkFrameHolder::setAlphaAndRequiredFrame(SkFrame* frame) {
912    const bool reportsAlpha = frame->reportsAlpha();
913    const auto screenRect = SkIRect::MakeWH(fScreenWidth, fScreenHeight);
914    const auto frameRect = frame_rect_on_screen(frame->frameRect(), screenRect);
915
916    const int i = frame->frameId();
917    if (0 == i) {
918        frame->setHasAlpha(reportsAlpha || frameRect != screenRect);
919        frame->setRequiredFrame(SkCodec::kNone);
920        return;
921    }
922
923
924    const bool blendWithPrevFrame = frame->getBlend() == SkCodecAnimation::Blend::kPriorFrame;
925    if ((!reportsAlpha || !blendWithPrevFrame) && frameRect == screenRect) {
926        frame->setHasAlpha(reportsAlpha);
927        frame->setRequiredFrame(SkCodec::kNone);
928        return;
929    }
930
931    const SkFrame* prevFrame = this->getFrame(i-1);
932    while (prevFrame->getDisposalMethod() == SkCodecAnimation::DisposalMethod::kRestorePrevious) {
933        const int prevId = prevFrame->frameId();
934        if (0 == prevId) {
935            frame->setHasAlpha(true);
936            frame->setRequiredFrame(SkCodec::kNone);
937            return;
938        }
939
940        prevFrame = this->getFrame(prevId - 1);
941    }
942
943    const bool clearPrevFrame = restore_bg(*prevFrame);
944    auto prevFrameRect = frame_rect_on_screen(prevFrame->frameRect(), screenRect);
945
946    if (clearPrevFrame) {
947        if (prevFrameRect == screenRect || independent(*prevFrame)) {
948            frame->setHasAlpha(true);
949            frame->setRequiredFrame(SkCodec::kNone);
950            return;
951        }
952    }
953
954    if (reportsAlpha && blendWithPrevFrame) {
955        // Note: We could be more aggressive here. If prevFrame clears
956        // to background color and covers its required frame (and that
957        // frame is independent), prevFrame could be marked independent.
958        // Would this extra complexity be worth it?
959        frame->setRequiredFrame(prevFrame->frameId());
960        frame->setHasAlpha(prevFrame->hasAlpha() || clearPrevFrame);
961        return;
962    }
963
964    while (frameRect.contains(prevFrameRect)) {
965        const int prevRequiredFrame = prevFrame->getRequiredFrame();
966        if (prevRequiredFrame == SkCodec::kNone) {
967            frame->setRequiredFrame(SkCodec::kNone);
968            frame->setHasAlpha(true);
969            return;
970        }
971
972        prevFrame = this->getFrame(prevRequiredFrame);
973        prevFrameRect = frame_rect_on_screen(prevFrame->frameRect(), screenRect);
974    }
975
976    if (restore_bg(*prevFrame)) {
977        frame->setHasAlpha(true);
978        if (prevFrameRect == screenRect || independent(*prevFrame)) {
979            frame->setRequiredFrame(SkCodec::kNone);
980        } else {
981            // Note: As above, frame could still be independent, e.g. if
982            // prevFrame covers its required frame and that frame is
983            // independent.
984            frame->setRequiredFrame(prevFrame->frameId());
985        }
986        return;
987    }
988
989    SkASSERT(prevFrame->getDisposalMethod() == SkCodecAnimation::DisposalMethod::kKeep);
990    frame->setRequiredFrame(prevFrame->frameId());
991    frame->setHasAlpha(prevFrame->hasAlpha() || (reportsAlpha && !blendWithPrevFrame));
992}
993
994// FIXME: Move this method to close to doLZW().
995bool SkGIFLZWContext::prepareToDecode()
996{
997    SkASSERT(m_frameContext->isDataSizeDefined() && m_frameContext->isHeaderDefined());
998
999    // Since we use a codesize of 1 more than the datasize, we need to ensure
1000    // that our datasize is strictly less than the SK_MAX_DICTIONARY_ENTRY_BITS.
1001    if (m_frameContext->dataSize() >= SK_MAX_DICTIONARY_ENTRY_BITS)
1002        return false;
1003    clearCode = 1 << m_frameContext->dataSize();
1004    avail = clearCode + 2;
1005    oldcode = -1;
1006    codesize = m_frameContext->dataSize() + 1;
1007    codemask = (1 << codesize) - 1;
1008    datum = bits = 0;
1009    ipass = m_frameContext->interlaced() ? 1 : 0;
1010    irow = 0;
1011
1012    // We want to know the longest sequence encodable by a dictionary with
1013    // SK_MAX_DICTIONARY_ENTRIES entries. If we ignore the need to encode the base
1014    // values themselves at the beginning of the dictionary, as well as the need
1015    // for a clear code or a termination code, we could use every entry to
1016    // encode a series of multiple values. If the input value stream looked
1017    // like "AAAAA..." (a long string of just one value), the first dictionary
1018    // entry would encode AA, the next AAA, the next AAAA, and so forth. Thus
1019    // the longest sequence would be SK_MAX_DICTIONARY_ENTRIES + 1 values.
1020    //
1021    // However, we have to account for reserved entries. The first |datasize|
1022    // bits are reserved for the base values, and the next two entries are
1023    // reserved for the clear code and termination code. In theory a GIF can
1024    // set the datasize to 0, meaning we have just two reserved entries, making
1025    // the longest sequence (SK_MAX_DICTIONARY_ENTIRES + 1) - 2 values long. Since
1026    // each value is a byte, this is also the number of bytes in the longest
1027    // encodable sequence.
1028    const size_t maxBytes = SK_MAX_DICTIONARY_ENTRIES - 1;
1029
1030    // Now allocate the output buffer. We decode directly into this buffer
1031    // until we have at least one row worth of data, then call outputRow().
1032    // This means worst case we may have (row width - 1) bytes in the buffer
1033    // and then decode a sequence |maxBytes| long to append.
1034    rowBuffer.reset(m_frameContext->width() - 1 + maxBytes);
1035    rowIter = rowBuffer.begin();
1036    rowsRemaining = m_frameContext->height();
1037
1038    // Clearing the whole suffix table lets us be more tolerant of bad data.
1039    for (int i = 0; i < clearCode; ++i) {
1040        suffix[i] = i;
1041        suffixLength[i] = 1;
1042    }
1043    return true;
1044}
1045
1046