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 /*
41 The Graphics Interchange Format(c) is the copyright property of CompuServe
42 Incorporated. Only CompuServe Incorporated is authorized to define, redefine,
43 enhance, alter, modify or change in any way the definition of the format.
44 
45 CompuServe Incorporated hereby grants a limited, non-exclusive, royalty-free
46 license for the use of the Graphics Interchange Format(sm) in computer
47 software; computer software utilizing GIF(sm) must acknowledge ownership of the
48 Graphics Interchange Format and its Service Mark by CompuServe Incorporated, in
49 User and Technical Documentation. Computer software utilizing GIF, which is
50 distributed or may be distributed without User or Technical Documentation must
51 display to the screen or printer a message acknowledging ownership of the
52 Graphics Interchange Format and the Service Mark by CompuServe Incorporated; in
53 this case, the acknowledgement may be displayed in an opening screen or leading
54 banner, or a closing screen or trailing banner. A message such as the following
55 may 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 
61 For 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 
69 CompuServe Incorporated maintains a mailing list with all those individuals and
70 organizations who wish to receive copies of this document when it is corrected
71 or revised. This service is offered free of charge; please provide us with your
72 mailing 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.
outputRow(const unsigned char * rowBegin)100 bool 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     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 >= m_frameContext->height()) {
163                     ipass++;
164                     irow = 4;
165                 }
166                 break;
167 
168             case 2:
169                 irow += 8;
170                 if (irow >= m_frameContext->height()) {
171                     ipass++;
172                     irow = 2;
173                 }
174                 break;
175 
176             case 3:
177                 irow += 4;
178                 if (irow >= m_frameContext->height()) {
179                     ipass++;
180                     irow = 1;
181                 }
182                 break;
183 
184             case 4:
185                 irow += 2;
186                 if (irow >= m_frameContext->height()) {
187                     ipass++;
188                     irow = 0;
189                 }
190                 break;
191 
192             default:
193                 break;
194             }
195         } while (irow > (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.
doLZW(const unsigned char * block,size_t bytesInBlock)203 bool SkGIFLZWContext::doLZW(const unsigned char* block, size_t bytesInBlock)
204 {
205     const size_t 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 
buildTable(SkStreamBuffer * streamBuffer,SkColorType colorType,size_t transparentPixel) const308 sk_sp<SkColorTable> SkGIFColorMap::buildTable(SkStreamBuffer* streamBuffer, SkColorType colorType,
309                                               size_t 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 > (unsigned) 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 (size_t 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 (size_t 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 
getColorTable(SkColorType colorType,size_t index)349 sk_sp<SkColorTable> SkGifImageReader::getColorTable(SkColorType colorType, size_t index) {
350     if (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 size_t 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.
decode(SkStreamBuffer * streamBuffer,SkGifCodec * client,bool * frameComplete)369 bool 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 (m_currentLzwBlock < m_lzwBlocks.size() && m_lzwContext->hasRemainingRows()) {
389         const auto& block = m_lzwBlocks[m_currentLzwBlock];
390         const size_t len = block.blockSize;
391 
392         sk_sp<SkData> data(streamBuffer->getDataAtPosition(block.blockPosition, len));
393         if (!data) {
394             return false;
395         }
396         if (!m_lzwContext->doLZW(reinterpret_cast<const unsigned char*>(data->data()), len)) {
397             return false;
398         }
399         ++m_currentLzwBlock;
400     }
401 
402     // If this frame is data complete then the previous loop must have completely decoded all LZW blocks.
403     // There will be no more decoding for this frame so it's time to cleanup.
404     if (isComplete()) {
405         *frameComplete = true;
406         m_lzwContext.reset();
407     }
408     return true;
409 }
410 
411 // Decode a frame.
412 // This method uses SkGIFFrameContext:decode() to decode the frame; decoding error is reported to client as a critical failure.
413 // Return true if decoding has progressed. Return false if an error has occurred.
decode(size_t frameIndex,bool * frameComplete)414 bool SkGifImageReader::decode(size_t frameIndex, bool* frameComplete)
415 {
416     SkGIFFrameContext* currentFrame = m_frames[frameIndex].get();
417 
418     return currentFrame->decode(&m_streamBuffer, m_client, frameComplete);
419 }
420 
421 // Parse incoming GIF data stream into internal data structures.
422 // Return true if parsing has progressed or there is not enough data.
423 // Return false if a fatal error is encountered.
parse(SkGifImageReader::SkGIFParseQuery query)424 bool SkGifImageReader::parse(SkGifImageReader::SkGIFParseQuery query)
425 {
426     if (m_parseCompleted) {
427         return true;
428     }
429 
430     if (SkGIFLoopCountQuery == query && m_loopCount != cLoopCountNotSeen) {
431         // Loop count has already been parsed.
432         return true;
433     }
434 
435     // SkGIFSizeQuery and SkGIFFrameCountQuery are negative, so this is only meaningful when >= 0.
436     const int lastFrameToParse = (int) query;
437     if (lastFrameToParse >= 0 && (int) m_frames.size() > lastFrameToParse
438                 && m_frames[lastFrameToParse]->isComplete()) {
439         // We have already parsed this frame.
440         return true;
441     }
442 
443     while (true) {
444         if (!m_streamBuffer.buffer(m_bytesToConsume)) {
445             // The stream does not yet have enough data.
446             return true;
447         }
448 
449         switch (m_state) {
450         case SkGIFLZW: {
451             SkASSERT(!m_frames.empty());
452             auto* frame = m_frames.back().get();
453             frame->addLzwBlock(m_streamBuffer.markPosition(), m_bytesToConsume);
454             GETN(1, SkGIFSubBlock);
455             break;
456         }
457         case SkGIFLZWStart: {
458             SkASSERT(!m_frames.empty());
459             auto* currentFrame = m_frames.back().get();
460 
461             currentFrame->setDataSize(this->getOneByte());
462             GETN(1, SkGIFSubBlock);
463             break;
464         }
465 
466         case SkGIFType: {
467             const char* currentComponent = m_streamBuffer.get();
468 
469             // All GIF files begin with "GIF87a" or "GIF89a".
470             if (!memcmp(currentComponent, "GIF89a", 6))
471                 m_version = 89;
472             else if (!memcmp(currentComponent, "GIF87a", 6))
473                 m_version = 87;
474             else {
475                 // This prevents attempting to continue reading this invalid stream.
476                 GETN(0, SkGIFDone);
477                 return false;
478             }
479             GETN(7, SkGIFGlobalHeader);
480             break;
481         }
482 
483         case SkGIFGlobalHeader: {
484             const unsigned char* currentComponent =
485                 reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
486 
487             // This is the height and width of the "screen" or frame into which
488             // images are rendered. The individual images can be smaller than
489             // the screen size and located with an origin anywhere within the
490             // screen.
491             // Note that we don't inform the client of the size yet, as it might
492             // change after we read the first frame's image header.
493             m_screenWidth = GETINT16(currentComponent);
494             m_screenHeight = GETINT16(currentComponent + 2);
495 
496             const size_t globalColorMapColors = 2 << (currentComponent[4] & 0x07);
497 
498             if ((currentComponent[4] & 0x80) && globalColorMapColors > 0) { /* global map */
499                 m_globalColorMap.setNumColors(globalColorMapColors);
500                 GETN(SK_BYTES_PER_COLORMAP_ENTRY * globalColorMapColors, SkGIFGlobalColormap);
501                 break;
502             }
503 
504             GETN(1, SkGIFImageStart);
505             break;
506         }
507 
508         case SkGIFGlobalColormap: {
509             m_globalColorMap.setTablePosition(m_streamBuffer.markPosition());
510             GETN(1, SkGIFImageStart);
511             break;
512         }
513 
514         case SkGIFImageStart: {
515             const char currentComponent = m_streamBuffer.get()[0];
516 
517             if (currentComponent == '!') { // extension.
518                 GETN(2, SkGIFExtension);
519                 break;
520             }
521 
522             if (currentComponent == ',') { // image separator.
523                 GETN(9, SkGIFImageHeader);
524                 break;
525             }
526 
527             // If we get anything other than ',' (image separator), '!'
528             // (extension), or ';' (trailer), there is extraneous data
529             // between blocks. The GIF87a spec tells us to keep reading
530             // until we find an image separator, but GIF89a says such
531             // a file is corrupt. We follow Mozilla's implementation and
532             // proceed as if the file were correctly terminated, so the
533             // GIF will display.
534             GETN(0, SkGIFDone);
535             break;
536         }
537 
538         case SkGIFExtension: {
539             const unsigned char* currentComponent =
540                 reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
541 
542             size_t bytesInBlock = currentComponent[1];
543             SkGIFState exceptionState = SkGIFSkipBlock;
544 
545             switch (*currentComponent) {
546             case 0xf9:
547                 // The GIF spec mandates that the GIFControlExtension header block length is 4 bytes,
548                 exceptionState = SkGIFControlExtension;
549                 // and the parser for this block reads 4 bytes, so we must enforce that the buffer
550                 // contains at least this many bytes. If the GIF specifies a different length, we
551                 // allow that, so long as it's larger; the additional data will simply be ignored.
552                 bytesInBlock = std::max(bytesInBlock, static_cast<size_t>(4));
553                 break;
554 
555             // The GIF spec also specifies the lengths of the following two extensions' headers
556             // (as 12 and 11 bytes, respectively). Because we ignore the plain text extension entirely
557             // and sanity-check the actual length of the application extension header before reading it,
558             // we allow GIFs to deviate from these values in either direction. This is important for
559             // real-world compatibility, as GIFs in the wild exist with application extension headers
560             // that are both shorter and longer than 11 bytes.
561             case 0x01:
562                 // ignoring plain text extension
563                 break;
564 
565             case 0xff:
566                 exceptionState = SkGIFApplicationExtension;
567                 break;
568 
569             case 0xfe:
570                 exceptionState = SkGIFConsumeComment;
571                 break;
572             }
573 
574             if (bytesInBlock)
575                 GETN(bytesInBlock, exceptionState);
576             else
577                 GETN(1, SkGIFImageStart);
578             break;
579         }
580 
581         case SkGIFConsumeBlock: {
582             const unsigned char currentComponent = this->getOneByte();
583             if (!currentComponent)
584                 GETN(1, SkGIFImageStart);
585             else
586                 GETN(currentComponent, SkGIFSkipBlock);
587             break;
588         }
589 
590         case SkGIFSkipBlock: {
591             GETN(1, SkGIFConsumeBlock);
592             break;
593         }
594 
595         case SkGIFControlExtension: {
596             const unsigned char* currentComponent =
597                 reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
598 
599             addFrameIfNecessary();
600             SkGIFFrameContext* currentFrame = m_frames.back().get();
601             if (*currentComponent & 0x1)
602                 currentFrame->setTransparentPixel(currentComponent[3]);
603 
604             // We ignore the "user input" bit.
605 
606             // NOTE: This relies on the values in the FrameDisposalMethod enum
607             // matching those in the GIF spec!
608             int rawDisposalMethod = ((*currentComponent) >> 2) & 0x7;
609             switch (rawDisposalMethod) {
610             case 1:
611             case 2:
612             case 3:
613                 currentFrame->setDisposalMethod((SkCodecAnimation::DisposalMethod) rawDisposalMethod);
614                 break;
615             case 4:
616                 // Some specs say that disposal method 3 is "overwrite previous", others that setting
617                 // the third bit of the field (i.e. method 4) is. We map both to the same value.
618                 currentFrame->setDisposalMethod(SkCodecAnimation::RestorePrevious_DisposalMethod);
619                 break;
620             default:
621                 // Other values use the default.
622                 currentFrame->setDisposalMethod(SkCodecAnimation::Keep_DisposalMethod);
623                 break;
624             }
625             currentFrame->setDelayTime(GETINT16(currentComponent + 1) * 10);
626             GETN(1, SkGIFConsumeBlock);
627             break;
628         }
629 
630         case SkGIFCommentExtension: {
631             const unsigned char currentComponent = this->getOneByte();
632             if (currentComponent)
633                 GETN(currentComponent, SkGIFConsumeComment);
634             else
635                 GETN(1, SkGIFImageStart);
636             break;
637         }
638 
639         case SkGIFConsumeComment: {
640             GETN(1, SkGIFCommentExtension);
641             break;
642         }
643 
644         case SkGIFApplicationExtension: {
645             // Check for netscape application extension.
646             if (m_bytesToConsume == 11) {
647                 const unsigned char* currentComponent =
648                     reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
649 
650                 if (!memcmp(currentComponent, "NETSCAPE2.0", 11) || !memcmp(currentComponent, "ANIMEXTS1.0", 11))
651                     GETN(1, SkGIFNetscapeExtensionBlock);
652             }
653 
654             if (m_state != SkGIFNetscapeExtensionBlock)
655                 GETN(1, SkGIFConsumeBlock);
656             break;
657         }
658 
659         // Netscape-specific GIF extension: animation looping.
660         case SkGIFNetscapeExtensionBlock: {
661             const int currentComponent = this->getOneByte();
662             // SkGIFConsumeNetscapeExtension always reads 3 bytes from the stream; we should at least wait for this amount.
663             if (currentComponent)
664                 GETN(std::max(3, currentComponent), SkGIFConsumeNetscapeExtension);
665             else
666                 GETN(1, SkGIFImageStart);
667             break;
668         }
669 
670         // Parse netscape-specific application extensions
671         case SkGIFConsumeNetscapeExtension: {
672             const unsigned char* currentComponent =
673                 reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
674 
675             int netscapeExtension = currentComponent[0] & 7;
676 
677             // Loop entire animation specified # of times. Only read the loop count during the first iteration.
678             if (netscapeExtension == 1) {
679                 m_loopCount = GETINT16(currentComponent + 1);
680 
681                 // Zero loop count is infinite animation loop request.
682                 if (!m_loopCount)
683                     m_loopCount = SkCodec::kRepetitionCountInfinite;
684 
685                 GETN(1, SkGIFNetscapeExtensionBlock);
686 
687                 if (SkGIFLoopCountQuery == query) {
688                     m_streamBuffer.flush();
689                     return true;
690                 }
691             } else if (netscapeExtension == 2) {
692                 // Wait for specified # of bytes to enter buffer.
693 
694                 // Don't do this, this extension doesn't exist (isn't used at all)
695                 // and doesn't do anything, as our streaming/buffering takes care of it all...
696                 // See: http://semmix.pl/color/exgraf/eeg24.htm
697                 GETN(1, SkGIFNetscapeExtensionBlock);
698             } else {
699                 // 0,3-7 are yet to be defined netscape extension codes
700                 // This prevents attempting to continue reading this invalid stream.
701                 GETN(0, SkGIFDone);
702                 return false;
703             }
704             break;
705         }
706 
707         case SkGIFImageHeader: {
708             unsigned height, width, xOffset, yOffset;
709             const unsigned char* currentComponent =
710                 reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
711 
712             /* Get image offsets, with respect to the screen origin */
713             xOffset = GETINT16(currentComponent);
714             yOffset = GETINT16(currentComponent + 2);
715 
716             /* Get image width and height. */
717             width  = GETINT16(currentComponent + 4);
718             height = GETINT16(currentComponent + 6);
719 
720             // Some GIF files have frames that don't fit in the specified
721             // overall image size. For the first frame, we can simply enlarge
722             // the image size to allow the frame to be visible.  We can't do
723             // this on subsequent frames because the rest of the decoding
724             // infrastructure assumes the image size won't change as we
725             // continue decoding, so any subsequent frames that are even
726             // larger will be cropped.
727             // Luckily, handling just the first frame is sufficient to deal
728             // with most cases, e.g. ones where the image size is erroneously
729             // set to zero, since usually the first frame completely fills
730             // the image.
731             if (currentFrameIsFirstFrame()) {
732                 m_screenHeight = std::max(m_screenHeight, yOffset + height);
733                 m_screenWidth = std::max(m_screenWidth, xOffset + width);
734             }
735 
736             // NOTE: Chromium placed this block after setHeaderDefined, down
737             // below we returned true when asked for the size. So Chromium
738             // created an image which would fail. Is this the correct behavior?
739             // We choose to return false early, so we will not create an
740             // SkCodec.
741 
742             // Work around more broken GIF files that have zero image width or
743             // height.
744             if (!height || !width) {
745                 height = m_screenHeight;
746                 width = m_screenWidth;
747                 if (!height || !width) {
748                     // This prevents attempting to continue reading this invalid stream.
749                     GETN(0, SkGIFDone);
750                     return false;
751                 }
752             }
753 
754             const bool isLocalColormapDefined = SkToBool(currentComponent[8] & 0x80);
755             // The three low-order bits of currentComponent[8] specify the bits per pixel.
756             const size_t numColors = 2 << (currentComponent[8] & 0x7);
757             if (currentFrameIsFirstFrame()) {
758                 if (hasTransparentPixel(0, isLocalColormapDefined, numColors)) {
759                     m_firstFrameHasAlpha = true;
760                     m_firstFrameSupportsIndex8 = true;
761                 } else {
762                     const bool frameIsSubset = xOffset > 0 || yOffset > 0
763                             || xOffset + width < m_screenWidth
764                             || yOffset + height < m_screenHeight;
765                     m_firstFrameHasAlpha = frameIsSubset;
766                     m_firstFrameSupportsIndex8 = !frameIsSubset;
767                 }
768             }
769 
770             addFrameIfNecessary();
771             SkGIFFrameContext* currentFrame = m_frames.back().get();
772             currentFrame->setHeaderDefined();
773 
774             if (query == SkGIFSizeQuery) {
775                 // The decoder needs to stop, so we return here, before
776                 // flushing the buffer. Next time through, we'll be in the same
777                 // state, requiring the same amount in the buffer.
778                 return true;
779             }
780 
781 
782             currentFrame->setRect(xOffset, yOffset, width, height);
783             currentFrame->setInterlaced(SkToBool(currentComponent[8] & 0x40));
784 
785             // Overlaying interlaced, transparent GIFs over
786             // existing image data using the Haeberli display hack
787             // requires saving the underlying image in order to
788             // avoid jaggies at the transparency edges. We are
789             // unprepared to deal with that, so don't display such
790             // images progressively. Which means only the first
791             // frame can be progressively displayed.
792             // FIXME: It is possible that a non-transparent frame
793             // can be interlaced and progressively displayed.
794             currentFrame->setProgressiveDisplay(currentFrameIsFirstFrame());
795 
796             if (isLocalColormapDefined) {
797                 currentFrame->localColorMap().setNumColors(numColors);
798                 GETN(SK_BYTES_PER_COLORMAP_ENTRY * numColors, SkGIFImageColormap);
799                 break;
800             }
801 
802             setRequiredFrame(currentFrame);
803             GETN(1, SkGIFLZWStart);
804             break;
805         }
806 
807         case SkGIFImageColormap: {
808             SkASSERT(!m_frames.empty());
809             auto* currentFrame = m_frames.back().get();
810             auto& cmap = currentFrame->localColorMap();
811             cmap.setTablePosition(m_streamBuffer.markPosition());
812             setRequiredFrame(currentFrame);
813             GETN(1, SkGIFLZWStart);
814             break;
815         }
816 
817         case SkGIFSubBlock: {
818             const size_t bytesInBlock = this->getOneByte();
819             if (bytesInBlock)
820                 GETN(bytesInBlock, SkGIFLZW);
821             else {
822                 // Finished parsing one frame; Process next frame.
823                 SkASSERT(!m_frames.empty());
824                 // Note that some broken GIF files do not have enough LZW blocks to fully
825                 // decode all rows but we treat it as frame complete.
826                 m_frames.back()->setComplete();
827                 GETN(1, SkGIFImageStart);
828                 if (lastFrameToParse >= 0 && (int) m_frames.size() > lastFrameToParse) {
829                     m_streamBuffer.flush();
830                     return true;
831                 }
832             }
833             break;
834         }
835 
836         case SkGIFDone: {
837             m_parseCompleted = true;
838             return true;
839         }
840 
841         default:
842             // We shouldn't ever get here.
843             // This prevents attempting to continue reading this invalid stream.
844             GETN(0, SkGIFDone);
845             return false;
846             break;
847         }   // switch
848         m_streamBuffer.flush();
849     }
850 
851     return true;
852 }
853 
hasTransparentPixel(size_t i,bool isLocalColormapDefined,size_t localColors)854 bool SkGifImageReader::hasTransparentPixel(size_t i, bool isLocalColormapDefined,
855                                            size_t localColors) {
856     if (m_frames.size() <= i) {
857         // This should only happen when parsing the first frame.
858         SkASSERT(0 == i);
859 
860         // We did not see a Graphics Control Extension, so no transparent
861         // pixel was specified. But if there is no color table, this frame is
862         // still transparent.
863         return !isLocalColormapDefined && m_globalColorMap.numColors() == 0;
864     }
865 
866     const size_t transparentPixel = m_frames[i]->transparentPixel();
867     if (isLocalColormapDefined) {
868         return transparentPixel < localColors;
869     }
870 
871     const size_t globalColors = m_globalColorMap.numColors();
872     if (!globalColors) {
873         // No color table for this frame, so the frame is empty.
874         // This is technically different from having a transparent
875         // pixel, but we'll treat it the same - nothing to draw here.
876         return true;
877     }
878 
879     // If there is a global color table, it will be parsed before reaching
880     // here. If its numColors is set, it will be defined.
881     SkASSERT(m_globalColorMap.isDefined());
882     return transparentPixel < globalColors;
883 }
884 
addFrameIfNecessary()885 void SkGifImageReader::addFrameIfNecessary()
886 {
887     if (m_frames.empty() || m_frames.back()->isComplete()) {
888         const size_t i = m_frames.size();
889         std::unique_ptr<SkGIFFrameContext> frame(new SkGIFFrameContext(i));
890         m_frames.push_back(std::move(frame));
891     }
892 }
893 
setRequiredFrame(SkGIFFrameContext * frame)894 void SkGifImageReader::setRequiredFrame(SkGIFFrameContext* frame) {
895     const size_t i = frame->frameId();
896     if (0 == i) {
897         frame->setRequiredFrame(SkCodec::kNone);
898         return;
899     }
900 
901     const SkGIFFrameContext* prevFrame = m_frames[i - 1].get();
902     if (prevFrame->getDisposalMethod() == SkCodecAnimation::RestorePrevious_DisposalMethod) {
903         frame->setRequiredFrame(prevFrame->getRequiredFrame());
904         return;
905     }
906 
907     // Note: We could correct these after decoding - i.e. some frames may turn out to be
908     // independent if they do not use the transparent pixel, but that would require
909     // checking whether each pixel used the transparent pixel.
910     const SkGIFColorMap& localMap = frame->localColorMap();
911     const bool transValid = hasTransparentPixel(i, localMap.isDefined(), localMap.numColors());
912 
913     const SkIRect prevFrameRect = prevFrame->frameRect();
914     const bool frameCoversPriorFrame = frame->frameRect().contains(prevFrameRect);
915 
916     if (!transValid && frameCoversPriorFrame) {
917         frame->setRequiredFrame(prevFrame->getRequiredFrame());
918         return;
919     }
920 
921     switch (prevFrame->getDisposalMethod()) {
922         case SkCodecAnimation::Keep_DisposalMethod:
923             frame->setRequiredFrame(i - 1);
924             break;
925         case SkCodecAnimation::RestorePrevious_DisposalMethod:
926             // This was already handled above.
927             SkASSERT(false);
928             break;
929         case SkCodecAnimation::RestoreBGColor_DisposalMethod:
930             // If the prior frame covers the whole image
931             if (prevFrameRect == SkIRect::MakeWH(m_screenWidth, m_screenHeight)
932                     // Or the prior frame was independent
933                     || prevFrame->getRequiredFrame() == SkCodec::kNone)
934             {
935                 // This frame is independent, since we clear everything in the
936                 // prior frame to the BG color
937                 frame->setRequiredFrame(SkCodec::kNone);
938             } else {
939                 frame->setRequiredFrame(i - 1);
940             }
941             break;
942     }
943 }
944 
945 // FIXME: Move this method to close to doLZW().
prepareToDecode()946 bool SkGIFLZWContext::prepareToDecode()
947 {
948     SkASSERT(m_frameContext->isDataSizeDefined() && m_frameContext->isHeaderDefined());
949 
950     // Since we use a codesize of 1 more than the datasize, we need to ensure
951     // that our datasize is strictly less than the SK_MAX_DICTIONARY_ENTRY_BITS.
952     if (m_frameContext->dataSize() >= SK_MAX_DICTIONARY_ENTRY_BITS)
953         return false;
954     clearCode = 1 << m_frameContext->dataSize();
955     avail = clearCode + 2;
956     oldcode = -1;
957     codesize = m_frameContext->dataSize() + 1;
958     codemask = (1 << codesize) - 1;
959     datum = bits = 0;
960     ipass = m_frameContext->interlaced() ? 1 : 0;
961     irow = 0;
962 
963     // We want to know the longest sequence encodable by a dictionary with
964     // SK_MAX_DICTIONARY_ENTRIES entries. If we ignore the need to encode the base
965     // values themselves at the beginning of the dictionary, as well as the need
966     // for a clear code or a termination code, we could use every entry to
967     // encode a series of multiple values. If the input value stream looked
968     // like "AAAAA..." (a long string of just one value), the first dictionary
969     // entry would encode AA, the next AAA, the next AAAA, and so forth. Thus
970     // the longest sequence would be SK_MAX_DICTIONARY_ENTRIES + 1 values.
971     //
972     // However, we have to account for reserved entries. The first |datasize|
973     // bits are reserved for the base values, and the next two entries are
974     // reserved for the clear code and termination code. In theory a GIF can
975     // set the datasize to 0, meaning we have just two reserved entries, making
976     // the longest sequence (SK_MAX_DICTIONARY_ENTIRES + 1) - 2 values long. Since
977     // each value is a byte, this is also the number of bytes in the longest
978     // encodable sequence.
979     const size_t maxBytes = SK_MAX_DICTIONARY_ENTRIES - 1;
980 
981     // Now allocate the output buffer. We decode directly into this buffer
982     // until we have at least one row worth of data, then call outputRow().
983     // This means worst case we may have (row width - 1) bytes in the buffer
984     // and then decode a sequence |maxBytes| long to append.
985     rowBuffer.reset(m_frameContext->width() - 1 + maxBytes);
986     rowIter = rowBuffer.begin();
987     rowsRemaining = m_frameContext->height();
988 
989     // Clearing the whole suffix table lets us be more tolerant of bad data.
990     for (int i = 0; i < clearCode; ++i) {
991         suffix[i] = i;
992         suffixLength[i] = 1;
993     }
994     return true;
995 }
996 
997