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