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