blob: 0ffc7ca72a4b7e5ea2e8b30ddebff8c97edf79ba [file] [log] [blame]
scroggo19b91532016-10-24 09:03:26 -07001/* -*- 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
scroggo3d3a65c2016-10-24 12:28:30 -070075#include "SkGifImageReader.h"
scroggo19b91532016-10-24 09:03:26 -070076#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.
scroggo3d3a65c2016-10-24 12:28:30 -070088// So a fixed buffer in SkGifImageReader is good enough.
scroggo19b91532016-10-24 09:03:26 -070089// 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.
scroggof9acbe22016-10-25 12:43:21 -0700100bool SkGIFLZWContext::outputRow(const unsigned char* rowBegin)
scroggo19b91532016-10-24 09:03:26 -0700101{
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
scroggo1285f412016-10-26 13:48:03 -0700149 bool writeTransparentPixels = alwaysWriteTransparentPixels ||
150 (m_frameContext->progressiveDisplay() && m_frameContext->interlaced() && ipass > 1);
scroggo19b91532016-10-24 09:03:26 -0700151 // CALLBACK: Let the client know we have decoded a row.
152 if (!m_client->haveDecodedRow(m_frameContext->frameId(), rowBegin,
scroggo1285f412016-10-26 13:48:03 -0700153 drowStart, drowEnd - drowStart + 1, writeTransparentPixels))
scroggo19b91532016-10-24 09:03:26 -0700154 return false;
155
156 if (!m_frameContext->interlaced())
157 irow++;
158 else {
159 do {
160 switch (ipass) {
161 case 1:
162 irow += 8;
163 if (irow >= m_frameContext->height()) {
164 ipass++;
165 irow = 4;
166 }
167 break;
168
169 case 2:
170 irow += 8;
171 if (irow >= m_frameContext->height()) {
172 ipass++;
173 irow = 2;
174 }
175 break;
176
177 case 3:
178 irow += 4;
179 if (irow >= m_frameContext->height()) {
180 ipass++;
181 irow = 1;
182 }
183 break;
184
185 case 4:
186 irow += 2;
187 if (irow >= m_frameContext->height()) {
188 ipass++;
189 irow = 0;
190 }
191 break;
192
193 default:
194 break;
195 }
196 } while (irow > (m_frameContext->height() - 1));
197 }
198 return true;
199}
200
201// Perform Lempel-Ziv-Welch decoding.
202// Returns true if decoding was successful. In this case the block will have been completely consumed and/or rowsRemaining will be 0.
scroggo3d3a65c2016-10-24 12:28:30 -0700203// Otherwise, decoding failed; returns false in this case, which will always cause the SkGifImageReader to set the "decode failed" flag.
scroggof9acbe22016-10-25 12:43:21 -0700204bool SkGIFLZWContext::doLZW(const unsigned char* block, size_t bytesInBlock)
scroggo19b91532016-10-24 09:03:26 -0700205{
206 const size_t width = m_frameContext->width();
207
208 if (rowIter == rowBuffer.end())
209 return true;
210
211 for (const unsigned char* ch = block; bytesInBlock-- > 0; ch++) {
212 // Feed the next byte into the decoder's 32-bit input buffer.
213 datum += ((int) *ch) << bits;
214 bits += 8;
215
216 // Check for underflow of decoder's 32-bit input buffer.
217 while (bits >= codesize) {
218 // Get the leading variable-length symbol from the data stream.
219 int code = datum & codemask;
220 datum >>= codesize;
221 bits -= codesize;
222
223 // Reset the dictionary to its original state, if requested.
224 if (code == clearCode) {
225 codesize = m_frameContext->dataSize() + 1;
226 codemask = (1 << codesize) - 1;
227 avail = clearCode + 2;
228 oldcode = -1;
229 continue;
230 }
231
232 // Check for explicit end-of-stream code.
233 if (code == (clearCode + 1)) {
234 // end-of-stream should only appear after all image data.
235 if (!rowsRemaining)
236 return true;
237 return false;
238 }
239
240 const int tempCode = code;
241 unsigned short codeLength = 0;
242 if (code < avail) {
243 // This is a pre-existing code, so we already know what it
244 // encodes.
245 codeLength = suffixLength[code];
246 rowIter += codeLength;
247 } else if (code == avail && oldcode != -1) {
248 // This is a new code just being added to the dictionary.
249 // It must encode the contents of the previous code, plus
250 // the first character of the previous code again.
251 codeLength = suffixLength[oldcode] + 1;
252 rowIter += codeLength;
253 *--rowIter = firstchar;
254 code = oldcode;
255 } else {
256 // This is an invalid code. The dictionary is just initialized
257 // and the code is incomplete. We don't know how to handle
258 // this case.
259 return false;
260 }
261
262 while (code >= clearCode) {
263 *--rowIter = suffix[code];
264 code = prefix[code];
265 }
266
267 *--rowIter = firstchar = suffix[code];
268
269 // Define a new codeword in the dictionary as long as we've read
270 // more than one value from the stream.
scroggof9acbe22016-10-25 12:43:21 -0700271 if (avail < SK_MAX_DICTIONARY_ENTRIES && oldcode != -1) {
scroggo19b91532016-10-24 09:03:26 -0700272 prefix[avail] = oldcode;
273 suffix[avail] = firstchar;
274 suffixLength[avail] = suffixLength[oldcode] + 1;
275 ++avail;
276
277 // If we've used up all the codewords of a given length
278 // increase the length of codewords by one bit, but don't
279 // exceed the specified maximum codeword size.
scroggof9acbe22016-10-25 12:43:21 -0700280 if (!(avail & codemask) && avail < SK_MAX_DICTIONARY_ENTRIES) {
scroggo19b91532016-10-24 09:03:26 -0700281 ++codesize;
282 codemask += avail;
283 }
284 }
285 oldcode = tempCode;
286 rowIter += codeLength;
287
288 // Output as many rows as possible.
289 unsigned char* rowBegin = rowBuffer.begin();
290 for (; rowBegin + width <= rowIter; rowBegin += width) {
291 if (!outputRow(rowBegin))
292 return false;
293 rowsRemaining--;
294 if (!rowsRemaining)
295 return true;
296 }
297
298 if (rowBegin != rowBuffer.begin()) {
299 // Move the remaining bytes to the beginning of the buffer.
300 const size_t bytesToCopy = rowIter - rowBegin;
301 memcpy(&rowBuffer.front(), rowBegin, bytesToCopy);
302 rowIter = rowBuffer.begin() + bytesToCopy;
303 }
304 }
305 }
306 return true;
307}
308
scroggof9acbe22016-10-25 12:43:21 -0700309sk_sp<SkColorTable> SkGIFColorMap::buildTable(SkColorType colorType, size_t transparentPixel) const
scroggo19b91532016-10-24 09:03:26 -0700310{
311 if (!m_isDefined)
312 return nullptr;
313
314 const PackColorProc proc = choose_pack_color_proc(false, colorType);
315 if (m_table) {
316 if (transparentPixel > (unsigned) m_table->count()
317 || m_table->operator[](transparentPixel) == SK_ColorTRANSPARENT) {
318 if (proc == m_packColorProc) {
319 // This SkColorTable has already been built with the same transparent color and
320 // packing proc. Reuse it.
321 return m_table;
322 }
323 }
324 }
325 m_packColorProc = proc;
326
scroggof9acbe22016-10-25 12:43:21 -0700327 SkASSERT(m_colors <= SK_MAX_COLORS);
scroggo19b91532016-10-24 09:03:26 -0700328 const uint8_t* srcColormap = m_rawData->bytes();
scroggof9acbe22016-10-25 12:43:21 -0700329 SkPMColor colorStorage[SK_MAX_COLORS];
scroggo19b91532016-10-24 09:03:26 -0700330 for (size_t i = 0; i < m_colors; i++) {
331 if (i == transparentPixel) {
332 colorStorage[i] = SK_ColorTRANSPARENT;
333 } else {
334 colorStorage[i] = proc(255, srcColormap[0], srcColormap[1], srcColormap[2]);
335 }
scroggof9acbe22016-10-25 12:43:21 -0700336 srcColormap += SK_BYTES_PER_COLORMAP_ENTRY;
scroggo19b91532016-10-24 09:03:26 -0700337 }
scroggof9acbe22016-10-25 12:43:21 -0700338 for (size_t i = m_colors; i < SK_MAX_COLORS; i++) {
scroggo19b91532016-10-24 09:03:26 -0700339 colorStorage[i] = SK_ColorTRANSPARENT;
340 }
scroggof9acbe22016-10-25 12:43:21 -0700341 m_table = sk_sp<SkColorTable>(new SkColorTable(colorStorage, SK_MAX_COLORS));
scroggo19b91532016-10-24 09:03:26 -0700342 return m_table;
343}
344
scroggo3d3a65c2016-10-24 12:28:30 -0700345sk_sp<SkColorTable> SkGifImageReader::getColorTable(SkColorType colorType, size_t index) const {
scroggo19b91532016-10-24 09:03:26 -0700346 if (index >= m_frames.size()) {
347 return nullptr;
348 }
349
scroggof9acbe22016-10-25 12:43:21 -0700350 const SkGIFFrameContext* frameContext = m_frames[index].get();
351 const SkGIFColorMap& localColorMap = frameContext->localColorMap();
scroggo19b91532016-10-24 09:03:26 -0700352 if (localColorMap.isDefined()) {
353 return localColorMap.buildTable(colorType, frameContext->transparentPixel());
354 }
355 if (m_globalColorMap.isDefined()) {
356 return m_globalColorMap.buildTable(colorType, frameContext->transparentPixel());
357 }
358 return nullptr;
359}
360
361// Perform decoding for this frame. frameComplete will be true if the entire frame is decoded.
scroggo3d3a65c2016-10-24 12:28:30 -0700362// Returns false if a decoding error occurred. This is a fatal error and causes the SkGifImageReader to set the "decode failed" flag.
scroggo19b91532016-10-24 09:03:26 -0700363// 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.
scroggo53f63b62016-10-27 08:29:13 -0700364bool SkGIFFrameContext::decode(SkGifCodec* client, const SkGIFColorMap& globalMap, bool* frameComplete)
scroggo19b91532016-10-24 09:03:26 -0700365{
366 *frameComplete = false;
367 if (!m_lzwContext) {
scroggof9acbe22016-10-25 12:43:21 -0700368 // Wait for more data to properly initialize SkGIFLZWContext.
scroggo19b91532016-10-24 09:03:26 -0700369 if (!isDataSizeDefined() || !isHeaderDefined())
370 return true;
371
scroggof9acbe22016-10-25 12:43:21 -0700372 m_lzwContext.reset(new SkGIFLZWContext(client, this));
scroggo53f63b62016-10-27 08:29:13 -0700373 if (!m_lzwContext->prepareToDecode(globalMap)) {
scroggo19b91532016-10-24 09:03:26 -0700374 m_lzwContext.reset();
375 return false;
376 }
377
378 m_currentLzwBlock = 0;
379 }
380
381 // Some bad GIFs have extra blocks beyond the last row, which we don't want to decode.
382 while (m_currentLzwBlock < m_lzwBlocks.size() && m_lzwContext->hasRemainingRows()) {
383 if (!m_lzwContext->doLZW(reinterpret_cast<const unsigned char*>(m_lzwBlocks[m_currentLzwBlock]->data()),
384 m_lzwBlocks[m_currentLzwBlock]->size())) {
385 return false;
386 }
387 ++m_currentLzwBlock;
388 }
389
390 // If this frame is data complete then the previous loop must have completely decoded all LZW blocks.
391 // There will be no more decoding for this frame so it's time to cleanup.
392 if (isComplete()) {
393 *frameComplete = true;
394 m_lzwContext.reset();
395 }
396 return true;
397}
398
399// Decode a frame.
scroggof9acbe22016-10-25 12:43:21 -0700400// This method uses SkGIFFrameContext:decode() to decode the frame; decoding error is reported to client as a critical failure.
scroggo19b91532016-10-24 09:03:26 -0700401// Return true if decoding has progressed. Return false if an error has occurred.
scroggo3d3a65c2016-10-24 12:28:30 -0700402bool SkGifImageReader::decode(size_t frameIndex, bool* frameComplete)
scroggo19b91532016-10-24 09:03:26 -0700403{
scroggof9acbe22016-10-25 12:43:21 -0700404 SkGIFFrameContext* currentFrame = m_frames[frameIndex].get();
scroggo19b91532016-10-24 09:03:26 -0700405
scroggo53f63b62016-10-27 08:29:13 -0700406 return currentFrame->decode(m_client, m_globalColorMap, frameComplete);
scroggo19b91532016-10-24 09:03:26 -0700407}
408
409// Parse incoming GIF data stream into internal data structures.
410// Return true if parsing has progressed or there is not enough data.
411// Return false if a fatal error is encountered.
scroggof9acbe22016-10-25 12:43:21 -0700412bool SkGifImageReader::parse(SkGifImageReader::SkGIFParseQuery query)
scroggo19b91532016-10-24 09:03:26 -0700413{
414 if (m_parseCompleted) {
415 return true;
416 }
417
scroggoe71b1a12016-11-01 08:28:28 -0700418 if (SkGIFLoopCountQuery == query && m_loopCount != cLoopCountNotSeen) {
419 // Loop count has already been parsed.
420 return true;
421 }
422
scroggof9acbe22016-10-25 12:43:21 -0700423 // SkGIFSizeQuery and SkGIFFrameCountQuery are negative, so this is only meaningful when >= 0.
scroggo19b91532016-10-24 09:03:26 -0700424 const int lastFrameToParse = (int) query;
425 if (lastFrameToParse >= 0 && (int) m_frames.size() > lastFrameToParse
426 && m_frames[lastFrameToParse]->isComplete()) {
427 // We have already parsed this frame.
428 return true;
429 }
430
431 while (true) {
432 const size_t bytesBuffered = m_streamBuffer.buffer(m_bytesToConsume);
433 if (bytesBuffered < m_bytesToConsume) {
434 // The stream does not yet have enough data. Mark that we need less next time around,
435 // and return.
436 m_bytesToConsume -= bytesBuffered;
437 return true;
438 }
439
440 switch (m_state) {
scroggof9acbe22016-10-25 12:43:21 -0700441 case SkGIFLZW:
scroggo19b91532016-10-24 09:03:26 -0700442 SkASSERT(!m_frames.empty());
443 // FIXME: All this copying might be wasteful for e.g. SkMemoryStream
444 m_frames.back()->addLzwBlock(m_streamBuffer.get(), m_streamBuffer.bytesBuffered());
scroggof9acbe22016-10-25 12:43:21 -0700445 GETN(1, SkGIFSubBlock);
scroggo19b91532016-10-24 09:03:26 -0700446 break;
447
scroggof9acbe22016-10-25 12:43:21 -0700448 case SkGIFLZWStart: {
scroggo19b91532016-10-24 09:03:26 -0700449 SkASSERT(!m_frames.empty());
450 m_frames.back()->setDataSize(this->getOneByte());
scroggof9acbe22016-10-25 12:43:21 -0700451 GETN(1, SkGIFSubBlock);
scroggo19b91532016-10-24 09:03:26 -0700452 break;
453 }
454
scroggof9acbe22016-10-25 12:43:21 -0700455 case SkGIFType: {
scroggo19b91532016-10-24 09:03:26 -0700456 const char* currentComponent = m_streamBuffer.get();
457
458 // All GIF files begin with "GIF87a" or "GIF89a".
459 if (!memcmp(currentComponent, "GIF89a", 6))
460 m_version = 89;
461 else if (!memcmp(currentComponent, "GIF87a", 6))
462 m_version = 87;
463 else {
464 // This prevents attempting to continue reading this invalid stream.
scroggof9acbe22016-10-25 12:43:21 -0700465 GETN(0, SkGIFDone);
scroggo19b91532016-10-24 09:03:26 -0700466 return false;
467 }
scroggof9acbe22016-10-25 12:43:21 -0700468 GETN(7, SkGIFGlobalHeader);
scroggo19b91532016-10-24 09:03:26 -0700469 break;
470 }
471
scroggof9acbe22016-10-25 12:43:21 -0700472 case SkGIFGlobalHeader: {
scroggo19b91532016-10-24 09:03:26 -0700473 const unsigned char* currentComponent =
474 reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
475
476 // This is the height and width of the "screen" or frame into which
477 // images are rendered. The individual images can be smaller than
478 // the screen size and located with an origin anywhere within the
479 // screen.
480 // Note that we don't inform the client of the size yet, as it might
481 // change after we read the first frame's image header.
482 m_screenWidth = GETINT16(currentComponent);
483 m_screenHeight = GETINT16(currentComponent + 2);
484
485 const size_t globalColorMapColors = 2 << (currentComponent[4] & 0x07);
486
487 if ((currentComponent[4] & 0x80) && globalColorMapColors > 0) { /* global map */
488 m_globalColorMap.setNumColors(globalColorMapColors);
scroggof9acbe22016-10-25 12:43:21 -0700489 GETN(SK_BYTES_PER_COLORMAP_ENTRY * globalColorMapColors, SkGIFGlobalColormap);
scroggo19b91532016-10-24 09:03:26 -0700490 break;
491 }
492
scroggof9acbe22016-10-25 12:43:21 -0700493 GETN(1, SkGIFImageStart);
scroggo19b91532016-10-24 09:03:26 -0700494 break;
495 }
496
scroggof9acbe22016-10-25 12:43:21 -0700497 case SkGIFGlobalColormap: {
scroggo19b91532016-10-24 09:03:26 -0700498 m_globalColorMap.setRawData(m_streamBuffer.get(), m_streamBuffer.bytesBuffered());
scroggof9acbe22016-10-25 12:43:21 -0700499 GETN(1, SkGIFImageStart);
scroggo19b91532016-10-24 09:03:26 -0700500 break;
501 }
502
scroggof9acbe22016-10-25 12:43:21 -0700503 case SkGIFImageStart: {
scroggo19b91532016-10-24 09:03:26 -0700504 const char currentComponent = m_streamBuffer.get()[0];
505
506 if (currentComponent == '!') { // extension.
scroggof9acbe22016-10-25 12:43:21 -0700507 GETN(2, SkGIFExtension);
scroggo19b91532016-10-24 09:03:26 -0700508 break;
509 }
510
511 if (currentComponent == ',') { // image separator.
scroggof9acbe22016-10-25 12:43:21 -0700512 GETN(9, SkGIFImageHeader);
scroggo19b91532016-10-24 09:03:26 -0700513 break;
514 }
515
516 // If we get anything other than ',' (image separator), '!'
517 // (extension), or ';' (trailer), there is extraneous data
518 // between blocks. The GIF87a spec tells us to keep reading
519 // until we find an image separator, but GIF89a says such
520 // a file is corrupt. We follow Mozilla's implementation and
521 // proceed as if the file were correctly terminated, so the
522 // GIF will display.
scroggof9acbe22016-10-25 12:43:21 -0700523 GETN(0, SkGIFDone);
scroggo19b91532016-10-24 09:03:26 -0700524 break;
525 }
526
scroggof9acbe22016-10-25 12:43:21 -0700527 case SkGIFExtension: {
scroggo19b91532016-10-24 09:03:26 -0700528 const unsigned char* currentComponent =
529 reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
530
531 size_t bytesInBlock = currentComponent[1];
scroggof9acbe22016-10-25 12:43:21 -0700532 SkGIFState exceptionState = SkGIFSkipBlock;
scroggo19b91532016-10-24 09:03:26 -0700533
534 switch (*currentComponent) {
535 case 0xf9:
scroggo19b91532016-10-24 09:03:26 -0700536 // The GIF spec mandates that the GIFControlExtension header block length is 4 bytes,
scroggof9acbe22016-10-25 12:43:21 -0700537 exceptionState = SkGIFControlExtension;
scroggo19b91532016-10-24 09:03:26 -0700538 // and the parser for this block reads 4 bytes, so we must enforce that the buffer
539 // contains at least this many bytes. If the GIF specifies a different length, we
540 // allow that, so long as it's larger; the additional data will simply be ignored.
541 bytesInBlock = std::max(bytesInBlock, static_cast<size_t>(4));
542 break;
543
544 // The GIF spec also specifies the lengths of the following two extensions' headers
545 // (as 12 and 11 bytes, respectively). Because we ignore the plain text extension entirely
546 // and sanity-check the actual length of the application extension header before reading it,
547 // we allow GIFs to deviate from these values in either direction. This is important for
548 // real-world compatibility, as GIFs in the wild exist with application extension headers
549 // that are both shorter and longer than 11 bytes.
550 case 0x01:
551 // ignoring plain text extension
552 break;
553
554 case 0xff:
scroggof9acbe22016-10-25 12:43:21 -0700555 exceptionState = SkGIFApplicationExtension;
scroggo19b91532016-10-24 09:03:26 -0700556 break;
557
558 case 0xfe:
scroggof9acbe22016-10-25 12:43:21 -0700559 exceptionState = SkGIFConsumeComment;
scroggo19b91532016-10-24 09:03:26 -0700560 break;
561 }
562
563 if (bytesInBlock)
564 GETN(bytesInBlock, exceptionState);
565 else
scroggof9acbe22016-10-25 12:43:21 -0700566 GETN(1, SkGIFImageStart);
scroggo19b91532016-10-24 09:03:26 -0700567 break;
568 }
569
scroggof9acbe22016-10-25 12:43:21 -0700570 case SkGIFConsumeBlock: {
scroggo19b91532016-10-24 09:03:26 -0700571 const unsigned char currentComponent = this->getOneByte();
572 if (!currentComponent)
scroggof9acbe22016-10-25 12:43:21 -0700573 GETN(1, SkGIFImageStart);
scroggo19b91532016-10-24 09:03:26 -0700574 else
scroggof9acbe22016-10-25 12:43:21 -0700575 GETN(currentComponent, SkGIFSkipBlock);
scroggo19b91532016-10-24 09:03:26 -0700576 break;
577 }
578
scroggof9acbe22016-10-25 12:43:21 -0700579 case SkGIFSkipBlock: {
580 GETN(1, SkGIFConsumeBlock);
scroggo19b91532016-10-24 09:03:26 -0700581 break;
582 }
583
scroggof9acbe22016-10-25 12:43:21 -0700584 case SkGIFControlExtension: {
scroggo19b91532016-10-24 09:03:26 -0700585 const unsigned char* currentComponent =
586 reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
587
588 addFrameIfNecessary();
scroggof9acbe22016-10-25 12:43:21 -0700589 SkGIFFrameContext* currentFrame = m_frames.back().get();
scroggo19b91532016-10-24 09:03:26 -0700590 if (*currentComponent & 0x1)
591 currentFrame->setTransparentPixel(currentComponent[3]);
592
593 // We ignore the "user input" bit.
594
595 // NOTE: This relies on the values in the FrameDisposalMethod enum
596 // matching those in the GIF spec!
597 int rawDisposalMethod = ((*currentComponent) >> 2) & 0x7;
598 switch (rawDisposalMethod) {
599 case 1:
600 case 2:
601 case 3:
602 currentFrame->setDisposalMethod((SkCodecAnimation::DisposalMethod) rawDisposalMethod);
603 break;
604 case 4:
605 // Some specs say that disposal method 3 is "overwrite previous", others that setting
606 // the third bit of the field (i.e. method 4) is. We map both to the same value.
607 currentFrame->setDisposalMethod(SkCodecAnimation::RestorePrevious_DisposalMethod);
608 break;
609 default:
610 // Other values use the default.
611 currentFrame->setDisposalMethod(SkCodecAnimation::Keep_DisposalMethod);
612 break;
613 }
614 currentFrame->setDelayTime(GETINT16(currentComponent + 1) * 10);
scroggof9acbe22016-10-25 12:43:21 -0700615 GETN(1, SkGIFConsumeBlock);
scroggo19b91532016-10-24 09:03:26 -0700616 break;
617 }
618
scroggof9acbe22016-10-25 12:43:21 -0700619 case SkGIFCommentExtension: {
scroggo19b91532016-10-24 09:03:26 -0700620 const unsigned char currentComponent = this->getOneByte();
621 if (currentComponent)
scroggof9acbe22016-10-25 12:43:21 -0700622 GETN(currentComponent, SkGIFConsumeComment);
scroggo19b91532016-10-24 09:03:26 -0700623 else
scroggof9acbe22016-10-25 12:43:21 -0700624 GETN(1, SkGIFImageStart);
scroggo19b91532016-10-24 09:03:26 -0700625 break;
626 }
627
scroggof9acbe22016-10-25 12:43:21 -0700628 case SkGIFConsumeComment: {
629 GETN(1, SkGIFCommentExtension);
scroggo19b91532016-10-24 09:03:26 -0700630 break;
631 }
632
scroggof9acbe22016-10-25 12:43:21 -0700633 case SkGIFApplicationExtension: {
scroggo19b91532016-10-24 09:03:26 -0700634 // Check for netscape application extension.
635 if (m_streamBuffer.bytesBuffered() == 11) {
636 const unsigned char* currentComponent =
637 reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
638
639 if (!memcmp(currentComponent, "NETSCAPE2.0", 11) || !memcmp(currentComponent, "ANIMEXTS1.0", 11))
scroggof9acbe22016-10-25 12:43:21 -0700640 GETN(1, SkGIFNetscapeExtensionBlock);
scroggo19b91532016-10-24 09:03:26 -0700641 }
642
scroggof9acbe22016-10-25 12:43:21 -0700643 if (m_state != SkGIFNetscapeExtensionBlock)
644 GETN(1, SkGIFConsumeBlock);
scroggo19b91532016-10-24 09:03:26 -0700645 break;
646 }
647
648 // Netscape-specific GIF extension: animation looping.
scroggof9acbe22016-10-25 12:43:21 -0700649 case SkGIFNetscapeExtensionBlock: {
scroggo19b91532016-10-24 09:03:26 -0700650 const int currentComponent = this->getOneByte();
scroggof9acbe22016-10-25 12:43:21 -0700651 // SkGIFConsumeNetscapeExtension always reads 3 bytes from the stream; we should at least wait for this amount.
scroggo19b91532016-10-24 09:03:26 -0700652 if (currentComponent)
scroggof9acbe22016-10-25 12:43:21 -0700653 GETN(std::max(3, currentComponent), SkGIFConsumeNetscapeExtension);
scroggo19b91532016-10-24 09:03:26 -0700654 else
scroggof9acbe22016-10-25 12:43:21 -0700655 GETN(1, SkGIFImageStart);
scroggo19b91532016-10-24 09:03:26 -0700656 break;
657 }
658
659 // Parse netscape-specific application extensions
scroggof9acbe22016-10-25 12:43:21 -0700660 case SkGIFConsumeNetscapeExtension: {
scroggo19b91532016-10-24 09:03:26 -0700661 const unsigned char* currentComponent =
662 reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
663
664 int netscapeExtension = currentComponent[0] & 7;
665
666 // Loop entire animation specified # of times. Only read the loop count during the first iteration.
667 if (netscapeExtension == 1) {
668 m_loopCount = GETINT16(currentComponent + 1);
669
670 // Zero loop count is infinite animation loop request.
671 if (!m_loopCount)
scroggoe71b1a12016-11-01 08:28:28 -0700672 m_loopCount = SkCodec::kRepetitionCountInfinite;
scroggo19b91532016-10-24 09:03:26 -0700673
scroggof9acbe22016-10-25 12:43:21 -0700674 GETN(1, SkGIFNetscapeExtensionBlock);
scroggoe71b1a12016-11-01 08:28:28 -0700675
676 if (SkGIFLoopCountQuery == query) {
677 m_streamBuffer.flush();
678 return true;
679 }
scroggo19b91532016-10-24 09:03:26 -0700680 } else if (netscapeExtension == 2) {
681 // Wait for specified # of bytes to enter buffer.
682
683 // Don't do this, this extension doesn't exist (isn't used at all)
684 // and doesn't do anything, as our streaming/buffering takes care of it all...
685 // See: http://semmix.pl/color/exgraf/eeg24.htm
scroggof9acbe22016-10-25 12:43:21 -0700686 GETN(1, SkGIFNetscapeExtensionBlock);
scroggo19b91532016-10-24 09:03:26 -0700687 } else {
688 // 0,3-7 are yet to be defined netscape extension codes
689 // This prevents attempting to continue reading this invalid stream.
scroggof9acbe22016-10-25 12:43:21 -0700690 GETN(0, SkGIFDone);
scroggo19b91532016-10-24 09:03:26 -0700691 return false;
692 }
693 break;
694 }
695
scroggof9acbe22016-10-25 12:43:21 -0700696 case SkGIFImageHeader: {
scroggo19b91532016-10-24 09:03:26 -0700697 unsigned height, width, xOffset, yOffset;
698 const unsigned char* currentComponent =
699 reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
700
701 /* Get image offsets, with respect to the screen origin */
702 xOffset = GETINT16(currentComponent);
703 yOffset = GETINT16(currentComponent + 2);
704
705 /* Get image width and height. */
706 width = GETINT16(currentComponent + 4);
707 height = GETINT16(currentComponent + 6);
708
709 // Some GIF files have frames that don't fit in the specified
710 // overall image size. For the first frame, we can simply enlarge
711 // the image size to allow the frame to be visible. We can't do
712 // this on subsequent frames because the rest of the decoding
713 // infrastructure assumes the image size won't change as we
714 // continue decoding, so any subsequent frames that are even
715 // larger will be cropped.
716 // Luckily, handling just the first frame is sufficient to deal
717 // with most cases, e.g. ones where the image size is erroneously
718 // set to zero, since usually the first frame completely fills
719 // the image.
720 if (currentFrameIsFirstFrame()) {
721 m_screenHeight = std::max(m_screenHeight, yOffset + height);
722 m_screenWidth = std::max(m_screenWidth, xOffset + width);
723 }
724
725 // NOTE: Chromium placed this block after setHeaderDefined, down
726 // below we returned true when asked for the size. So Chromium
727 // created an image which would fail. Is this the correct behavior?
728 // We choose to return false early, so we will not create an
729 // SkCodec.
730
731 // Work around more broken GIF files that have zero image width or
732 // height.
733 if (!height || !width) {
734 height = m_screenHeight;
735 width = m_screenWidth;
736 if (!height || !width) {
737 // This prevents attempting to continue reading this invalid stream.
scroggof9acbe22016-10-25 12:43:21 -0700738 GETN(0, SkGIFDone);
scroggo19b91532016-10-24 09:03:26 -0700739 return false;
740 }
741 }
742
Jim Van Verth3cfdf6c2016-10-26 09:45:23 -0400743 const bool isLocalColormapDefined = SkToBool(currentComponent[8] & 0x80);
scroggo19b91532016-10-24 09:03:26 -0700744 // The three low-order bits of currentComponent[8] specify the bits per pixel.
745 const size_t numColors = 2 << (currentComponent[8] & 0x7);
746 if (currentFrameIsFirstFrame()) {
747 bool hasTransparentPixel;
748 if (m_frames.size() == 0) {
749 // We did not see a Graphics Control Extension, so no transparent
scroggo2f7068a2016-10-31 04:45:10 -0700750 // pixel was specified. But if there is no color table, this frame is
751 // still transparent.
752 hasTransparentPixel = !isLocalColormapDefined
753 && m_globalColorMap.numColors() == 0;
scroggo19b91532016-10-24 09:03:26 -0700754 } else {
755 // This means we did see a Graphics Control Extension, which specifies
756 // the transparent pixel
757 const size_t transparentPixel = m_frames[0]->transparentPixel();
758 if (isLocalColormapDefined) {
759 hasTransparentPixel = transparentPixel < numColors;
760 } else {
761 const size_t globalColors = m_globalColorMap.numColors();
762 if (!globalColors) {
763 // No color table for this frame, so the frame is empty.
764 // This is technically different from having a transparent
765 // pixel, but we'll treat it the same - nothing to draw here.
766 hasTransparentPixel = true;
767 } else {
768 hasTransparentPixel = transparentPixel < globalColors;
769 }
770 }
771 }
772
773 if (hasTransparentPixel) {
774 m_firstFrameHasAlpha = true;
775 m_firstFrameSupportsIndex8 = true;
776 } else {
777 const bool frameIsSubset = xOffset > 0 || yOffset > 0
778 || xOffset + width < m_screenWidth
779 || yOffset + height < m_screenHeight;
780 m_firstFrameHasAlpha = frameIsSubset;
781 m_firstFrameSupportsIndex8 = !frameIsSubset;
782 }
783 }
784
scroggof9acbe22016-10-25 12:43:21 -0700785 if (query == SkGIFSizeQuery) {
scroggo19b91532016-10-24 09:03:26 -0700786 // The decoder needs to stop, so we return here, before
787 // flushing the buffer. Next time through, we'll be in the same
788 // state, requiring the same amount in the buffer.
789 m_bytesToConsume = 0;
790 return true;
791 }
792
793 addFrameIfNecessary();
scroggof9acbe22016-10-25 12:43:21 -0700794 SkGIFFrameContext* currentFrame = m_frames.back().get();
scroggo19b91532016-10-24 09:03:26 -0700795
796 currentFrame->setHeaderDefined();
797
798 currentFrame->setRect(xOffset, yOffset, width, height);
Jim Van Verth3cfdf6c2016-10-26 09:45:23 -0400799 currentFrame->setInterlaced(SkToBool(currentComponent[8] & 0x40));
scroggo19b91532016-10-24 09:03:26 -0700800
801 // Overlaying interlaced, transparent GIFs over
802 // existing image data using the Haeberli display hack
803 // requires saving the underlying image in order to
804 // avoid jaggies at the transparency edges. We are
805 // unprepared to deal with that, so don't display such
806 // images progressively. Which means only the first
807 // frame can be progressively displayed.
808 // FIXME: It is possible that a non-transparent frame
809 // can be interlaced and progressively displayed.
810 currentFrame->setProgressiveDisplay(currentFrameIsFirstFrame());
811
812 if (isLocalColormapDefined) {
813 currentFrame->localColorMap().setNumColors(numColors);
scroggof9acbe22016-10-25 12:43:21 -0700814 GETN(SK_BYTES_PER_COLORMAP_ENTRY * numColors, SkGIFImageColormap);
scroggo19b91532016-10-24 09:03:26 -0700815 break;
816 }
817
scroggof9acbe22016-10-25 12:43:21 -0700818 GETN(1, SkGIFLZWStart);
scroggo19b91532016-10-24 09:03:26 -0700819 break;
820 }
821
scroggof9acbe22016-10-25 12:43:21 -0700822 case SkGIFImageColormap: {
scroggo19b91532016-10-24 09:03:26 -0700823 SkASSERT(!m_frames.empty());
824 m_frames.back()->localColorMap().setRawData(m_streamBuffer.get(), m_streamBuffer.bytesBuffered());
scroggof9acbe22016-10-25 12:43:21 -0700825 GETN(1, SkGIFLZWStart);
scroggo19b91532016-10-24 09:03:26 -0700826 break;
827 }
828
scroggof9acbe22016-10-25 12:43:21 -0700829 case SkGIFSubBlock: {
scroggo19b91532016-10-24 09:03:26 -0700830 const size_t bytesInBlock = this->getOneByte();
831 if (bytesInBlock)
scroggof9acbe22016-10-25 12:43:21 -0700832 GETN(bytesInBlock, SkGIFLZW);
scroggo19b91532016-10-24 09:03:26 -0700833 else {
834 // Finished parsing one frame; Process next frame.
835 SkASSERT(!m_frames.empty());
836 // Note that some broken GIF files do not have enough LZW blocks to fully
837 // decode all rows but we treat it as frame complete.
838 m_frames.back()->setComplete();
scroggof9acbe22016-10-25 12:43:21 -0700839 GETN(1, SkGIFImageStart);
scroggo19b91532016-10-24 09:03:26 -0700840 if (lastFrameToParse >= 0 && (int) m_frames.size() > lastFrameToParse) {
841 m_streamBuffer.flush();
842 return true;
843 }
844 }
845 break;
846 }
847
scroggof9acbe22016-10-25 12:43:21 -0700848 case SkGIFDone: {
scroggo19b91532016-10-24 09:03:26 -0700849 m_parseCompleted = true;
850 return true;
851 }
852
853 default:
854 // We shouldn't ever get here.
855 // This prevents attempting to continue reading this invalid stream.
scroggof9acbe22016-10-25 12:43:21 -0700856 GETN(0, SkGIFDone);
scroggo19b91532016-10-24 09:03:26 -0700857 return false;
858 break;
859 } // switch
860 m_streamBuffer.flush();
861 }
862
863 return true;
864}
865
scroggo3d3a65c2016-10-24 12:28:30 -0700866void SkGifImageReader::addFrameIfNecessary()
scroggo19b91532016-10-24 09:03:26 -0700867{
868 if (m_frames.empty() || m_frames.back()->isComplete()) {
869 const size_t i = m_frames.size();
scroggof9acbe22016-10-25 12:43:21 -0700870 std::unique_ptr<SkGIFFrameContext> frame(new SkGIFFrameContext(i));
scroggo19b91532016-10-24 09:03:26 -0700871 if (0 == i) {
872 frame->setRequiredFrame(SkCodec::kNone);
873 } else {
874 // FIXME: We could correct these after decoding (i.e. some frames may turn out to be
875 // independent although we did not determine that here).
scroggof9acbe22016-10-25 12:43:21 -0700876 const SkGIFFrameContext* prevFrameContext = m_frames[i - 1].get();
scroggo19b91532016-10-24 09:03:26 -0700877 switch (prevFrameContext->getDisposalMethod()) {
878 case SkCodecAnimation::Keep_DisposalMethod:
879 frame->setRequiredFrame(i - 1);
880 break;
881 case SkCodecAnimation::RestorePrevious_DisposalMethod:
882 frame->setRequiredFrame(prevFrameContext->getRequiredFrame());
883 break;
884 case SkCodecAnimation::RestoreBGColor_DisposalMethod:
885 // If the prior frame covers the whole image
886 if (prevFrameContext->frameRect() == SkIRect::MakeWH(m_screenWidth,
887 m_screenHeight)
888 // Or the prior frame was independent
889 || prevFrameContext->getRequiredFrame() == SkCodec::kNone)
890 {
891 // This frame is independent, since we clear everything
892 // prior frame to the BG color
893 frame->setRequiredFrame(SkCodec::kNone);
894 } else {
895 frame->setRequiredFrame(i - 1);
896 }
897 break;
898 }
899 }
900 m_frames.push_back(std::move(frame));
901 }
902}
903
904// FIXME: Move this method to close to doLZW().
scroggo53f63b62016-10-27 08:29:13 -0700905bool SkGIFLZWContext::prepareToDecode(const SkGIFColorMap& globalMap)
scroggo19b91532016-10-24 09:03:26 -0700906{
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
scroggof9acbe22016-10-25 12:43:21 -0700910 // that our datasize is strictly less than the SK_MAX_DICTIONARY_ENTRY_BITS.
911 if (m_frameContext->dataSize() >= SK_MAX_DICTIONARY_ENTRY_BITS)
scroggo19b91532016-10-24 09:03:26 -0700912 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;
scroggo53f63b62016-10-27 08:29:13 -0700921 alwaysWriteTransparentPixels = false;
922 if (m_frameContext->getRequiredFrame() == SkCodec::kNone) {
923 if (!m_frameContext->interlaced()) {
924 alwaysWriteTransparentPixels = true;
925 } else {
926 // The frame is interlaced, so we do not want to write transparent
927 // pixels. But if there are no transparent pixels anyway, there is
928 // no harm in taking the alwaysWriteTransparentPixels path, which
929 // is faster, and it also supports 565.
930 // Since the frame is independent, it does not matter whether the
931 // frame is subset (nothing behind it needs to show through). So we
932 // only need to know whether there is a valid transparent pixel.
933 // This is a little counterintuitive - we want to "always write
934 // transparent pixels" if there ARE NO transparent pixels, so we
935 // check to see whether the pixel index is >= numColors.
936 const auto& localMap = m_frameContext->localColorMap();
937 const auto trans = m_frameContext->transparentPixel();
938 if (localMap.isDefined()) {
939 alwaysWriteTransparentPixels = trans >= localMap.numColors();
940 } else {
941 // Note that if the map is not defined, the value of
942 // alwaysWriteTransparentPixels is meaningless, since without
943 // any color table, we will skip drawing entirely.
944 // FIXME: We could even skip calling prepareToDecode in that
945 // case, meaning we can SkASSERT(globalMap.isDefined())
946 alwaysWriteTransparentPixels = trans >= globalMap.numColors();
947 }
948 }
949 }
scroggo19b91532016-10-24 09:03:26 -0700950
951 // We want to know the longest sequence encodable by a dictionary with
scroggof9acbe22016-10-25 12:43:21 -0700952 // SK_MAX_DICTIONARY_ENTRIES entries. If we ignore the need to encode the base
scroggo19b91532016-10-24 09:03:26 -0700953 // values themselves at the beginning of the dictionary, as well as the need
954 // for a clear code or a termination code, we could use every entry to
955 // encode a series of multiple values. If the input value stream looked
956 // like "AAAAA..." (a long string of just one value), the first dictionary
957 // entry would encode AA, the next AAA, the next AAAA, and so forth. Thus
scroggof9acbe22016-10-25 12:43:21 -0700958 // the longest sequence would be SK_MAX_DICTIONARY_ENTRIES + 1 values.
scroggo19b91532016-10-24 09:03:26 -0700959 //
960 // However, we have to account for reserved entries. The first |datasize|
961 // bits are reserved for the base values, and the next two entries are
962 // reserved for the clear code and termination code. In theory a GIF can
963 // set the datasize to 0, meaning we have just two reserved entries, making
scroggof9acbe22016-10-25 12:43:21 -0700964 // the longest sequence (SK_MAX_DICTIONARY_ENTIRES + 1) - 2 values long. Since
scroggo19b91532016-10-24 09:03:26 -0700965 // each value is a byte, this is also the number of bytes in the longest
966 // encodable sequence.
scroggof9acbe22016-10-25 12:43:21 -0700967 const size_t maxBytes = SK_MAX_DICTIONARY_ENTRIES - 1;
scroggo19b91532016-10-24 09:03:26 -0700968
969 // Now allocate the output buffer. We decode directly into this buffer
970 // until we have at least one row worth of data, then call outputRow().
971 // This means worst case we may have (row width - 1) bytes in the buffer
972 // and then decode a sequence |maxBytes| long to append.
973 rowBuffer.reset(m_frameContext->width() - 1 + maxBytes);
974 rowIter = rowBuffer.begin();
975 rowsRemaining = m_frameContext->height();
976
977 // Clearing the whole suffix table lets us be more tolerant of bad data.
978 for (int i = 0; i < clearCode; ++i) {
979 suffix[i] = i;
980 suffixLength[i] = 1;
981 }
982 return true;
983}
984