blob: eeaee68c1d6a059f7aa020e14aff1e6a90a1964f [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
scroggof9acbe22016-10-25 12:43:21 -0700418 // SkGIFSizeQuery and SkGIFFrameCountQuery are negative, so this is only meaningful when >= 0.
scroggo19b91532016-10-24 09:03:26 -0700419 const int lastFrameToParse = (int) query;
420 if (lastFrameToParse >= 0 && (int) m_frames.size() > lastFrameToParse
421 && m_frames[lastFrameToParse]->isComplete()) {
422 // We have already parsed this frame.
423 return true;
424 }
425
426 while (true) {
427 const size_t bytesBuffered = m_streamBuffer.buffer(m_bytesToConsume);
428 if (bytesBuffered < m_bytesToConsume) {
429 // The stream does not yet have enough data. Mark that we need less next time around,
430 // and return.
431 m_bytesToConsume -= bytesBuffered;
432 return true;
433 }
434
435 switch (m_state) {
scroggof9acbe22016-10-25 12:43:21 -0700436 case SkGIFLZW:
scroggo19b91532016-10-24 09:03:26 -0700437 SkASSERT(!m_frames.empty());
438 // FIXME: All this copying might be wasteful for e.g. SkMemoryStream
439 m_frames.back()->addLzwBlock(m_streamBuffer.get(), m_streamBuffer.bytesBuffered());
scroggof9acbe22016-10-25 12:43:21 -0700440 GETN(1, SkGIFSubBlock);
scroggo19b91532016-10-24 09:03:26 -0700441 break;
442
scroggof9acbe22016-10-25 12:43:21 -0700443 case SkGIFLZWStart: {
scroggo19b91532016-10-24 09:03:26 -0700444 SkASSERT(!m_frames.empty());
445 m_frames.back()->setDataSize(this->getOneByte());
scroggof9acbe22016-10-25 12:43:21 -0700446 GETN(1, SkGIFSubBlock);
scroggo19b91532016-10-24 09:03:26 -0700447 break;
448 }
449
scroggof9acbe22016-10-25 12:43:21 -0700450 case SkGIFType: {
scroggo19b91532016-10-24 09:03:26 -0700451 const char* currentComponent = m_streamBuffer.get();
452
453 // All GIF files begin with "GIF87a" or "GIF89a".
454 if (!memcmp(currentComponent, "GIF89a", 6))
455 m_version = 89;
456 else if (!memcmp(currentComponent, "GIF87a", 6))
457 m_version = 87;
458 else {
459 // This prevents attempting to continue reading this invalid stream.
scroggof9acbe22016-10-25 12:43:21 -0700460 GETN(0, SkGIFDone);
scroggo19b91532016-10-24 09:03:26 -0700461 return false;
462 }
scroggof9acbe22016-10-25 12:43:21 -0700463 GETN(7, SkGIFGlobalHeader);
scroggo19b91532016-10-24 09:03:26 -0700464 break;
465 }
466
scroggof9acbe22016-10-25 12:43:21 -0700467 case SkGIFGlobalHeader: {
scroggo19b91532016-10-24 09:03:26 -0700468 const unsigned char* currentComponent =
469 reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
470
471 // This is the height and width of the "screen" or frame into which
472 // images are rendered. The individual images can be smaller than
473 // the screen size and located with an origin anywhere within the
474 // screen.
475 // Note that we don't inform the client of the size yet, as it might
476 // change after we read the first frame's image header.
477 m_screenWidth = GETINT16(currentComponent);
478 m_screenHeight = GETINT16(currentComponent + 2);
479
480 const size_t globalColorMapColors = 2 << (currentComponent[4] & 0x07);
481
482 if ((currentComponent[4] & 0x80) && globalColorMapColors > 0) { /* global map */
483 m_globalColorMap.setNumColors(globalColorMapColors);
scroggof9acbe22016-10-25 12:43:21 -0700484 GETN(SK_BYTES_PER_COLORMAP_ENTRY * globalColorMapColors, SkGIFGlobalColormap);
scroggo19b91532016-10-24 09:03:26 -0700485 break;
486 }
487
scroggof9acbe22016-10-25 12:43:21 -0700488 GETN(1, SkGIFImageStart);
scroggo19b91532016-10-24 09:03:26 -0700489 break;
490 }
491
scroggof9acbe22016-10-25 12:43:21 -0700492 case SkGIFGlobalColormap: {
scroggo19b91532016-10-24 09:03:26 -0700493 m_globalColorMap.setRawData(m_streamBuffer.get(), m_streamBuffer.bytesBuffered());
scroggof9acbe22016-10-25 12:43:21 -0700494 GETN(1, SkGIFImageStart);
scroggo19b91532016-10-24 09:03:26 -0700495 break;
496 }
497
scroggof9acbe22016-10-25 12:43:21 -0700498 case SkGIFImageStart: {
scroggo19b91532016-10-24 09:03:26 -0700499 const char currentComponent = m_streamBuffer.get()[0];
500
501 if (currentComponent == '!') { // extension.
scroggof9acbe22016-10-25 12:43:21 -0700502 GETN(2, SkGIFExtension);
scroggo19b91532016-10-24 09:03:26 -0700503 break;
504 }
505
506 if (currentComponent == ',') { // image separator.
scroggof9acbe22016-10-25 12:43:21 -0700507 GETN(9, SkGIFImageHeader);
scroggo19b91532016-10-24 09:03:26 -0700508 break;
509 }
510
511 // If we get anything other than ',' (image separator), '!'
512 // (extension), or ';' (trailer), there is extraneous data
513 // between blocks. The GIF87a spec tells us to keep reading
514 // until we find an image separator, but GIF89a says such
515 // a file is corrupt. We follow Mozilla's implementation and
516 // proceed as if the file were correctly terminated, so the
517 // GIF will display.
scroggof9acbe22016-10-25 12:43:21 -0700518 GETN(0, SkGIFDone);
scroggo19b91532016-10-24 09:03:26 -0700519 break;
520 }
521
scroggof9acbe22016-10-25 12:43:21 -0700522 case SkGIFExtension: {
scroggo19b91532016-10-24 09:03:26 -0700523 const unsigned char* currentComponent =
524 reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
525
526 size_t bytesInBlock = currentComponent[1];
scroggof9acbe22016-10-25 12:43:21 -0700527 SkGIFState exceptionState = SkGIFSkipBlock;
scroggo19b91532016-10-24 09:03:26 -0700528
529 switch (*currentComponent) {
530 case 0xf9:
scroggo19b91532016-10-24 09:03:26 -0700531 // The GIF spec mandates that the GIFControlExtension header block length is 4 bytes,
scroggof9acbe22016-10-25 12:43:21 -0700532 exceptionState = SkGIFControlExtension;
scroggo19b91532016-10-24 09:03:26 -0700533 // and the parser for this block reads 4 bytes, so we must enforce that the buffer
534 // contains at least this many bytes. If the GIF specifies a different length, we
535 // allow that, so long as it's larger; the additional data will simply be ignored.
536 bytesInBlock = std::max(bytesInBlock, static_cast<size_t>(4));
537 break;
538
539 // The GIF spec also specifies the lengths of the following two extensions' headers
540 // (as 12 and 11 bytes, respectively). Because we ignore the plain text extension entirely
541 // and sanity-check the actual length of the application extension header before reading it,
542 // we allow GIFs to deviate from these values in either direction. This is important for
543 // real-world compatibility, as GIFs in the wild exist with application extension headers
544 // that are both shorter and longer than 11 bytes.
545 case 0x01:
546 // ignoring plain text extension
547 break;
548
549 case 0xff:
scroggof9acbe22016-10-25 12:43:21 -0700550 exceptionState = SkGIFApplicationExtension;
scroggo19b91532016-10-24 09:03:26 -0700551 break;
552
553 case 0xfe:
scroggof9acbe22016-10-25 12:43:21 -0700554 exceptionState = SkGIFConsumeComment;
scroggo19b91532016-10-24 09:03:26 -0700555 break;
556 }
557
558 if (bytesInBlock)
559 GETN(bytesInBlock, exceptionState);
560 else
scroggof9acbe22016-10-25 12:43:21 -0700561 GETN(1, SkGIFImageStart);
scroggo19b91532016-10-24 09:03:26 -0700562 break;
563 }
564
scroggof9acbe22016-10-25 12:43:21 -0700565 case SkGIFConsumeBlock: {
scroggo19b91532016-10-24 09:03:26 -0700566 const unsigned char currentComponent = this->getOneByte();
567 if (!currentComponent)
scroggof9acbe22016-10-25 12:43:21 -0700568 GETN(1, SkGIFImageStart);
scroggo19b91532016-10-24 09:03:26 -0700569 else
scroggof9acbe22016-10-25 12:43:21 -0700570 GETN(currentComponent, SkGIFSkipBlock);
scroggo19b91532016-10-24 09:03:26 -0700571 break;
572 }
573
scroggof9acbe22016-10-25 12:43:21 -0700574 case SkGIFSkipBlock: {
575 GETN(1, SkGIFConsumeBlock);
scroggo19b91532016-10-24 09:03:26 -0700576 break;
577 }
578
scroggof9acbe22016-10-25 12:43:21 -0700579 case SkGIFControlExtension: {
scroggo19b91532016-10-24 09:03:26 -0700580 const unsigned char* currentComponent =
581 reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
582
583 addFrameIfNecessary();
scroggof9acbe22016-10-25 12:43:21 -0700584 SkGIFFrameContext* currentFrame = m_frames.back().get();
scroggo19b91532016-10-24 09:03:26 -0700585 if (*currentComponent & 0x1)
586 currentFrame->setTransparentPixel(currentComponent[3]);
587
588 // We ignore the "user input" bit.
589
590 // NOTE: This relies on the values in the FrameDisposalMethod enum
591 // matching those in the GIF spec!
592 int rawDisposalMethod = ((*currentComponent) >> 2) & 0x7;
593 switch (rawDisposalMethod) {
594 case 1:
595 case 2:
596 case 3:
597 currentFrame->setDisposalMethod((SkCodecAnimation::DisposalMethod) rawDisposalMethod);
598 break;
599 case 4:
600 // Some specs say that disposal method 3 is "overwrite previous", others that setting
601 // the third bit of the field (i.e. method 4) is. We map both to the same value.
602 currentFrame->setDisposalMethod(SkCodecAnimation::RestorePrevious_DisposalMethod);
603 break;
604 default:
605 // Other values use the default.
606 currentFrame->setDisposalMethod(SkCodecAnimation::Keep_DisposalMethod);
607 break;
608 }
609 currentFrame->setDelayTime(GETINT16(currentComponent + 1) * 10);
scroggof9acbe22016-10-25 12:43:21 -0700610 GETN(1, SkGIFConsumeBlock);
scroggo19b91532016-10-24 09:03:26 -0700611 break;
612 }
613
scroggof9acbe22016-10-25 12:43:21 -0700614 case SkGIFCommentExtension: {
scroggo19b91532016-10-24 09:03:26 -0700615 const unsigned char currentComponent = this->getOneByte();
616 if (currentComponent)
scroggof9acbe22016-10-25 12:43:21 -0700617 GETN(currentComponent, SkGIFConsumeComment);
scroggo19b91532016-10-24 09:03:26 -0700618 else
scroggof9acbe22016-10-25 12:43:21 -0700619 GETN(1, SkGIFImageStart);
scroggo19b91532016-10-24 09:03:26 -0700620 break;
621 }
622
scroggof9acbe22016-10-25 12:43:21 -0700623 case SkGIFConsumeComment: {
624 GETN(1, SkGIFCommentExtension);
scroggo19b91532016-10-24 09:03:26 -0700625 break;
626 }
627
scroggof9acbe22016-10-25 12:43:21 -0700628 case SkGIFApplicationExtension: {
scroggo19b91532016-10-24 09:03:26 -0700629 // Check for netscape application extension.
630 if (m_streamBuffer.bytesBuffered() == 11) {
631 const unsigned char* currentComponent =
632 reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
633
634 if (!memcmp(currentComponent, "NETSCAPE2.0", 11) || !memcmp(currentComponent, "ANIMEXTS1.0", 11))
scroggof9acbe22016-10-25 12:43:21 -0700635 GETN(1, SkGIFNetscapeExtensionBlock);
scroggo19b91532016-10-24 09:03:26 -0700636 }
637
scroggof9acbe22016-10-25 12:43:21 -0700638 if (m_state != SkGIFNetscapeExtensionBlock)
639 GETN(1, SkGIFConsumeBlock);
scroggo19b91532016-10-24 09:03:26 -0700640 break;
641 }
642
643 // Netscape-specific GIF extension: animation looping.
scroggof9acbe22016-10-25 12:43:21 -0700644 case SkGIFNetscapeExtensionBlock: {
scroggo19b91532016-10-24 09:03:26 -0700645 const int currentComponent = this->getOneByte();
scroggof9acbe22016-10-25 12:43:21 -0700646 // SkGIFConsumeNetscapeExtension always reads 3 bytes from the stream; we should at least wait for this amount.
scroggo19b91532016-10-24 09:03:26 -0700647 if (currentComponent)
scroggof9acbe22016-10-25 12:43:21 -0700648 GETN(std::max(3, currentComponent), SkGIFConsumeNetscapeExtension);
scroggo19b91532016-10-24 09:03:26 -0700649 else
scroggof9acbe22016-10-25 12:43:21 -0700650 GETN(1, SkGIFImageStart);
scroggo19b91532016-10-24 09:03:26 -0700651 break;
652 }
653
654 // Parse netscape-specific application extensions
scroggof9acbe22016-10-25 12:43:21 -0700655 case SkGIFConsumeNetscapeExtension: {
scroggo19b91532016-10-24 09:03:26 -0700656 const unsigned char* currentComponent =
657 reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
658
659 int netscapeExtension = currentComponent[0] & 7;
660
661 // Loop entire animation specified # of times. Only read the loop count during the first iteration.
662 if (netscapeExtension == 1) {
663 m_loopCount = GETINT16(currentComponent + 1);
664
665 // Zero loop count is infinite animation loop request.
666 if (!m_loopCount)
667 m_loopCount = SkCodecAnimation::kAnimationLoopInfinite;
668
scroggof9acbe22016-10-25 12:43:21 -0700669 GETN(1, SkGIFNetscapeExtensionBlock);
scroggo19b91532016-10-24 09:03:26 -0700670 } else if (netscapeExtension == 2) {
671 // Wait for specified # of bytes to enter buffer.
672
673 // Don't do this, this extension doesn't exist (isn't used at all)
674 // and doesn't do anything, as our streaming/buffering takes care of it all...
675 // See: http://semmix.pl/color/exgraf/eeg24.htm
scroggof9acbe22016-10-25 12:43:21 -0700676 GETN(1, SkGIFNetscapeExtensionBlock);
scroggo19b91532016-10-24 09:03:26 -0700677 } else {
678 // 0,3-7 are yet to be defined netscape extension codes
679 // This prevents attempting to continue reading this invalid stream.
scroggof9acbe22016-10-25 12:43:21 -0700680 GETN(0, SkGIFDone);
scroggo19b91532016-10-24 09:03:26 -0700681 return false;
682 }
683 break;
684 }
685
scroggof9acbe22016-10-25 12:43:21 -0700686 case SkGIFImageHeader: {
scroggo19b91532016-10-24 09:03:26 -0700687 unsigned height, width, xOffset, yOffset;
688 const unsigned char* currentComponent =
689 reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
690
691 /* Get image offsets, with respect to the screen origin */
692 xOffset = GETINT16(currentComponent);
693 yOffset = GETINT16(currentComponent + 2);
694
695 /* Get image width and height. */
696 width = GETINT16(currentComponent + 4);
697 height = GETINT16(currentComponent + 6);
698
699 // Some GIF files have frames that don't fit in the specified
700 // overall image size. For the first frame, we can simply enlarge
701 // the image size to allow the frame to be visible. We can't do
702 // this on subsequent frames because the rest of the decoding
703 // infrastructure assumes the image size won't change as we
704 // continue decoding, so any subsequent frames that are even
705 // larger will be cropped.
706 // Luckily, handling just the first frame is sufficient to deal
707 // with most cases, e.g. ones where the image size is erroneously
708 // set to zero, since usually the first frame completely fills
709 // the image.
710 if (currentFrameIsFirstFrame()) {
711 m_screenHeight = std::max(m_screenHeight, yOffset + height);
712 m_screenWidth = std::max(m_screenWidth, xOffset + width);
713 }
714
715 // NOTE: Chromium placed this block after setHeaderDefined, down
716 // below we returned true when asked for the size. So Chromium
717 // created an image which would fail. Is this the correct behavior?
718 // We choose to return false early, so we will not create an
719 // SkCodec.
720
721 // Work around more broken GIF files that have zero image width or
722 // height.
723 if (!height || !width) {
724 height = m_screenHeight;
725 width = m_screenWidth;
726 if (!height || !width) {
727 // This prevents attempting to continue reading this invalid stream.
scroggof9acbe22016-10-25 12:43:21 -0700728 GETN(0, SkGIFDone);
scroggo19b91532016-10-24 09:03:26 -0700729 return false;
730 }
731 }
732
Jim Van Verth3cfdf6c2016-10-26 09:45:23 -0400733 const bool isLocalColormapDefined = SkToBool(currentComponent[8] & 0x80);
scroggo19b91532016-10-24 09:03:26 -0700734 // The three low-order bits of currentComponent[8] specify the bits per pixel.
735 const size_t numColors = 2 << (currentComponent[8] & 0x7);
736 if (currentFrameIsFirstFrame()) {
737 bool hasTransparentPixel;
738 if (m_frames.size() == 0) {
739 // We did not see a Graphics Control Extension, so no transparent
740 // pixel was specified.
741 hasTransparentPixel = false;
742 } else {
743 // This means we did see a Graphics Control Extension, which specifies
744 // the transparent pixel
745 const size_t transparentPixel = m_frames[0]->transparentPixel();
746 if (isLocalColormapDefined) {
747 hasTransparentPixel = transparentPixel < numColors;
748 } else {
749 const size_t globalColors = m_globalColorMap.numColors();
750 if (!globalColors) {
751 // No color table for this frame, so the frame is empty.
752 // This is technically different from having a transparent
753 // pixel, but we'll treat it the same - nothing to draw here.
754 hasTransparentPixel = true;
755 } else {
756 hasTransparentPixel = transparentPixel < globalColors;
757 }
758 }
759 }
760
761 if (hasTransparentPixel) {
762 m_firstFrameHasAlpha = true;
763 m_firstFrameSupportsIndex8 = true;
764 } else {
765 const bool frameIsSubset = xOffset > 0 || yOffset > 0
766 || xOffset + width < m_screenWidth
767 || yOffset + height < m_screenHeight;
768 m_firstFrameHasAlpha = frameIsSubset;
769 m_firstFrameSupportsIndex8 = !frameIsSubset;
770 }
771 }
772
scroggof9acbe22016-10-25 12:43:21 -0700773 if (query == SkGIFSizeQuery) {
scroggo19b91532016-10-24 09:03:26 -0700774 // The decoder needs to stop, so we return here, before
775 // flushing the buffer. Next time through, we'll be in the same
776 // state, requiring the same amount in the buffer.
777 m_bytesToConsume = 0;
778 return true;
779 }
780
781 addFrameIfNecessary();
scroggof9acbe22016-10-25 12:43:21 -0700782 SkGIFFrameContext* currentFrame = m_frames.back().get();
scroggo19b91532016-10-24 09:03:26 -0700783
784 currentFrame->setHeaderDefined();
785
786 currentFrame->setRect(xOffset, yOffset, width, height);
Jim Van Verth3cfdf6c2016-10-26 09:45:23 -0400787 currentFrame->setInterlaced(SkToBool(currentComponent[8] & 0x40));
scroggo19b91532016-10-24 09:03:26 -0700788
789 // Overlaying interlaced, transparent GIFs over
790 // existing image data using the Haeberli display hack
791 // requires saving the underlying image in order to
792 // avoid jaggies at the transparency edges. We are
793 // unprepared to deal with that, so don't display such
794 // images progressively. Which means only the first
795 // frame can be progressively displayed.
796 // FIXME: It is possible that a non-transparent frame
797 // can be interlaced and progressively displayed.
798 currentFrame->setProgressiveDisplay(currentFrameIsFirstFrame());
799
800 if (isLocalColormapDefined) {
801 currentFrame->localColorMap().setNumColors(numColors);
scroggof9acbe22016-10-25 12:43:21 -0700802 GETN(SK_BYTES_PER_COLORMAP_ENTRY * numColors, SkGIFImageColormap);
scroggo19b91532016-10-24 09:03:26 -0700803 break;
804 }
805
scroggof9acbe22016-10-25 12:43:21 -0700806 GETN(1, SkGIFLZWStart);
scroggo19b91532016-10-24 09:03:26 -0700807 break;
808 }
809
scroggof9acbe22016-10-25 12:43:21 -0700810 case SkGIFImageColormap: {
scroggo19b91532016-10-24 09:03:26 -0700811 SkASSERT(!m_frames.empty());
812 m_frames.back()->localColorMap().setRawData(m_streamBuffer.get(), m_streamBuffer.bytesBuffered());
scroggof9acbe22016-10-25 12:43:21 -0700813 GETN(1, SkGIFLZWStart);
scroggo19b91532016-10-24 09:03:26 -0700814 break;
815 }
816
scroggof9acbe22016-10-25 12:43:21 -0700817 case SkGIFSubBlock: {
scroggo19b91532016-10-24 09:03:26 -0700818 const size_t bytesInBlock = this->getOneByte();
819 if (bytesInBlock)
scroggof9acbe22016-10-25 12:43:21 -0700820 GETN(bytesInBlock, SkGIFLZW);
scroggo19b91532016-10-24 09:03:26 -0700821 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();
scroggof9acbe22016-10-25 12:43:21 -0700827 GETN(1, SkGIFImageStart);
scroggo19b91532016-10-24 09:03:26 -0700828 if (lastFrameToParse >= 0 && (int) m_frames.size() > lastFrameToParse) {
829 m_streamBuffer.flush();
830 return true;
831 }
832 }
833 break;
834 }
835
scroggof9acbe22016-10-25 12:43:21 -0700836 case SkGIFDone: {
scroggo19b91532016-10-24 09:03:26 -0700837 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.
scroggof9acbe22016-10-25 12:43:21 -0700844 GETN(0, SkGIFDone);
scroggo19b91532016-10-24 09:03:26 -0700845 return false;
846 break;
847 } // switch
848 m_streamBuffer.flush();
849 }
850
851 return true;
852}
853
scroggo3d3a65c2016-10-24 12:28:30 -0700854void SkGifImageReader::addFrameIfNecessary()
scroggo19b91532016-10-24 09:03:26 -0700855{
856 if (m_frames.empty() || m_frames.back()->isComplete()) {
857 const size_t i = m_frames.size();
scroggof9acbe22016-10-25 12:43:21 -0700858 std::unique_ptr<SkGIFFrameContext> frame(new SkGIFFrameContext(i));
scroggo19b91532016-10-24 09:03:26 -0700859 if (0 == i) {
860 frame->setRequiredFrame(SkCodec::kNone);
861 } else {
862 // FIXME: We could correct these after decoding (i.e. some frames may turn out to be
863 // independent although we did not determine that here).
scroggof9acbe22016-10-25 12:43:21 -0700864 const SkGIFFrameContext* prevFrameContext = m_frames[i - 1].get();
scroggo19b91532016-10-24 09:03:26 -0700865 switch (prevFrameContext->getDisposalMethod()) {
866 case SkCodecAnimation::Keep_DisposalMethod:
867 frame->setRequiredFrame(i - 1);
868 break;
869 case SkCodecAnimation::RestorePrevious_DisposalMethod:
870 frame->setRequiredFrame(prevFrameContext->getRequiredFrame());
871 break;
872 case SkCodecAnimation::RestoreBGColor_DisposalMethod:
873 // If the prior frame covers the whole image
874 if (prevFrameContext->frameRect() == SkIRect::MakeWH(m_screenWidth,
875 m_screenHeight)
876 // Or the prior frame was independent
877 || prevFrameContext->getRequiredFrame() == SkCodec::kNone)
878 {
879 // This frame is independent, since we clear everything
880 // prior frame to the BG color
881 frame->setRequiredFrame(SkCodec::kNone);
882 } else {
883 frame->setRequiredFrame(i - 1);
884 }
885 break;
886 }
887 }
888 m_frames.push_back(std::move(frame));
889 }
890}
891
892// FIXME: Move this method to close to doLZW().
scroggo53f63b62016-10-27 08:29:13 -0700893bool SkGIFLZWContext::prepareToDecode(const SkGIFColorMap& globalMap)
scroggo19b91532016-10-24 09:03:26 -0700894{
895 SkASSERT(m_frameContext->isDataSizeDefined() && m_frameContext->isHeaderDefined());
896
897 // Since we use a codesize of 1 more than the datasize, we need to ensure
scroggof9acbe22016-10-25 12:43:21 -0700898 // that our datasize is strictly less than the SK_MAX_DICTIONARY_ENTRY_BITS.
899 if (m_frameContext->dataSize() >= SK_MAX_DICTIONARY_ENTRY_BITS)
scroggo19b91532016-10-24 09:03:26 -0700900 return false;
901 clearCode = 1 << m_frameContext->dataSize();
902 avail = clearCode + 2;
903 oldcode = -1;
904 codesize = m_frameContext->dataSize() + 1;
905 codemask = (1 << codesize) - 1;
906 datum = bits = 0;
907 ipass = m_frameContext->interlaced() ? 1 : 0;
908 irow = 0;
scroggo53f63b62016-10-27 08:29:13 -0700909 alwaysWriteTransparentPixels = false;
910 if (m_frameContext->getRequiredFrame() == SkCodec::kNone) {
911 if (!m_frameContext->interlaced()) {
912 alwaysWriteTransparentPixels = true;
913 } else {
914 // The frame is interlaced, so we do not want to write transparent
915 // pixels. But if there are no transparent pixels anyway, there is
916 // no harm in taking the alwaysWriteTransparentPixels path, which
917 // is faster, and it also supports 565.
918 // Since the frame is independent, it does not matter whether the
919 // frame is subset (nothing behind it needs to show through). So we
920 // only need to know whether there is a valid transparent pixel.
921 // This is a little counterintuitive - we want to "always write
922 // transparent pixels" if there ARE NO transparent pixels, so we
923 // check to see whether the pixel index is >= numColors.
924 const auto& localMap = m_frameContext->localColorMap();
925 const auto trans = m_frameContext->transparentPixel();
926 if (localMap.isDefined()) {
927 alwaysWriteTransparentPixels = trans >= localMap.numColors();
928 } else {
929 // Note that if the map is not defined, the value of
930 // alwaysWriteTransparentPixels is meaningless, since without
931 // any color table, we will skip drawing entirely.
932 // FIXME: We could even skip calling prepareToDecode in that
933 // case, meaning we can SkASSERT(globalMap.isDefined())
934 alwaysWriteTransparentPixels = trans >= globalMap.numColors();
935 }
936 }
937 }
scroggo19b91532016-10-24 09:03:26 -0700938
939 // We want to know the longest sequence encodable by a dictionary with
scroggof9acbe22016-10-25 12:43:21 -0700940 // SK_MAX_DICTIONARY_ENTRIES entries. If we ignore the need to encode the base
scroggo19b91532016-10-24 09:03:26 -0700941 // values themselves at the beginning of the dictionary, as well as the need
942 // for a clear code or a termination code, we could use every entry to
943 // encode a series of multiple values. If the input value stream looked
944 // like "AAAAA..." (a long string of just one value), the first dictionary
945 // entry would encode AA, the next AAA, the next AAAA, and so forth. Thus
scroggof9acbe22016-10-25 12:43:21 -0700946 // the longest sequence would be SK_MAX_DICTIONARY_ENTRIES + 1 values.
scroggo19b91532016-10-24 09:03:26 -0700947 //
948 // However, we have to account for reserved entries. The first |datasize|
949 // bits are reserved for the base values, and the next two entries are
950 // reserved for the clear code and termination code. In theory a GIF can
951 // set the datasize to 0, meaning we have just two reserved entries, making
scroggof9acbe22016-10-25 12:43:21 -0700952 // the longest sequence (SK_MAX_DICTIONARY_ENTIRES + 1) - 2 values long. Since
scroggo19b91532016-10-24 09:03:26 -0700953 // each value is a byte, this is also the number of bytes in the longest
954 // encodable sequence.
scroggof9acbe22016-10-25 12:43:21 -0700955 const size_t maxBytes = SK_MAX_DICTIONARY_ENTRIES - 1;
scroggo19b91532016-10-24 09:03:26 -0700956
957 // Now allocate the output buffer. We decode directly into this buffer
958 // until we have at least one row worth of data, then call outputRow().
959 // This means worst case we may have (row width - 1) bytes in the buffer
960 // and then decode a sequence |maxBytes| long to append.
961 rowBuffer.reset(m_frameContext->width() - 1 + maxBytes);
962 rowIter = rowBuffer.begin();
963 rowsRemaining = m_frameContext->height();
964
965 // Clearing the whole suffix table lets us be more tolerant of bad data.
966 for (int i = 0; i < clearCode; ++i) {
967 suffix[i] = i;
968 suffixLength[i] = 1;
969 }
970 return true;
971}
972