Home | History | Annotate | Download | only in gif
      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 (at) 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 "config.h"
     76 #include "core/platform/image-decoders/gif/GIFImageReader.h"
     77 
     78 #include <string.h>
     79 #include "core/platform/graphics/ImageSource.h"
     80 #include "core/platform/image-decoders/gif/GIFImageDecoder.h"
     81 
     82 using WebCore::GIFImageDecoder;
     83 
     84 // GETN(n, s) requests at least 'n' bytes available from 'q', at start of state 's'.
     85 //
     86 // Note, the hold will never need to be bigger than 256 bytes to gather up in the hold,
     87 // as each GIF block (except colormaps) can never be bigger than 256 bytes.
     88 // Colormaps are directly copied in the resp. global_colormap or dynamically allocated local_colormap.
     89 // So a fixed buffer in GIFImageReader is good enough.
     90 // This buffer is only needed to copy left-over data from one GifWrite call to the next
     91 #define GETN(n, s) \
     92     do { \
     93         m_bytesToConsume = (n); \
     94         m_state = (s); \
     95     } while (0)
     96 
     97 // Get a 16-bit value stored in little-endian format.
     98 #define GETINT16(p)   ((p)[1]<<8|(p)[0])
     99 
    100 // Send the data to the display front-end.
    101 bool GIFLZWContext::outputRow()
    102 {
    103     int drowStart = irow;
    104     int drowEnd = irow;
    105 
    106     // Haeberli-inspired hack for interlaced GIFs: Replicate lines while
    107     // displaying to diminish the "venetian-blind" effect as the image is
    108     // loaded. Adjust pixel vertical positions to avoid the appearance of the
    109     // image crawling up the screen as successive passes are drawn.
    110     if (m_frameContext->progressiveDisplay() && m_frameContext->interlaced() && ipass < 4) {
    111         unsigned rowDup = 0;
    112         unsigned rowShift = 0;
    113 
    114         switch (ipass) {
    115         case 1:
    116             rowDup = 7;
    117             rowShift = 3;
    118             break;
    119         case 2:
    120             rowDup = 3;
    121             rowShift = 1;
    122             break;
    123         case 3:
    124             rowDup = 1;
    125             rowShift = 0;
    126             break;
    127         default:
    128             break;
    129         }
    130 
    131         drowStart -= rowShift;
    132         drowEnd = drowStart + rowDup;
    133 
    134         // Extend if bottom edge isn't covered because of the shift upward.
    135         if (((m_frameContext->height() - 1) - drowEnd) <= rowShift)
    136             drowEnd = m_frameContext->height() - 1;
    137 
    138         // Clamp first and last rows to upper and lower edge of image.
    139         if (drowStart < 0)
    140             drowStart = 0;
    141 
    142         if ((unsigned)drowEnd >= m_frameContext->height())
    143             drowEnd = m_frameContext->height() - 1;
    144     }
    145 
    146     // Protect against too much image data.
    147     if ((unsigned)drowStart >= m_frameContext->height())
    148         return true;
    149 
    150     // CALLBACK: Let the client know we have decoded a row.
    151     if (!m_client->haveDecodedRow(m_frameContext->frameId(), rowBuffer, m_frameContext->width(),
    152         drowStart, drowEnd - drowStart + 1, m_frameContext->progressiveDisplay() && m_frameContext->interlaced() && ipass > 1))
    153         return false;
    154 
    155     if (!m_frameContext->interlaced())
    156         irow++;
    157     else {
    158         do {
    159             switch (ipass) {
    160             case 1:
    161                 irow += 8;
    162                 if (irow >= m_frameContext->height()) {
    163                     ipass++;
    164                     irow = 4;
    165                 }
    166                 break;
    167 
    168             case 2:
    169                 irow += 8;
    170                 if (irow >= m_frameContext->height()) {
    171                     ipass++;
    172                     irow = 2;
    173                 }
    174                 break;
    175 
    176             case 3:
    177                 irow += 4;
    178                 if (irow >= m_frameContext->height()) {
    179                     ipass++;
    180                     irow = 1;
    181                 }
    182                 break;
    183 
    184             case 4:
    185                 irow += 2;
    186                 if (irow >= m_frameContext->height()) {
    187                     ipass++;
    188                     irow = 0;
    189                 }
    190                 break;
    191 
    192             default:
    193                 break;
    194             }
    195         } while (irow > (m_frameContext->height() - 1));
    196     }
    197     return true;
    198 }
    199 
    200 // Perform Lempel-Ziv-Welch decoding.
    201 // Returns true if decoding was successful. In this case the block will have been completely consumed and/or rowsRemaining will be 0.
    202 // Otherwise, decoding failed; returns false in this case, which will always cause the GIFImageReader to set the "decode failed" flag.
    203 bool GIFLZWContext::doLZW(const unsigned char* block, size_t bytesInBlock)
    204 {
    205     int code;
    206     int incode;
    207     const unsigned char *ch;
    208 
    209     if (rowIter == rowBuffer.end())
    210         return true;
    211 
    212 #define OUTPUT_ROW \
    213     do { \
    214         if (!outputRow()) \
    215             return false; \
    216         rowsRemaining--; \
    217         rowIter = rowBuffer.begin(); \
    218         if (!rowsRemaining) \
    219             return true; \
    220     } while (0)
    221 
    222     for (ch = block; bytesInBlock-- > 0; ch++) {
    223         // Feed the next byte into the decoder's 32-bit input buffer.
    224         datum += ((int) *ch) << bits;
    225         bits += 8;
    226 
    227         // Check for underflow of decoder's 32-bit input buffer.
    228         while (bits >= codesize) {
    229             // Get the leading variable-length symbol from the data stream.
    230             code = datum & codemask;
    231             datum >>= codesize;
    232             bits -= codesize;
    233 
    234             // Reset the dictionary to its original state, if requested.
    235             if (code == clearCode) {
    236                 codesize = m_frameContext->dataSize() + 1;
    237                 codemask = (1 << codesize) - 1;
    238                 avail = clearCode + 2;
    239                 oldcode = -1;
    240                 continue;
    241             }
    242 
    243             // Check for explicit end-of-stream code.
    244             if (code == (clearCode + 1)) {
    245                 // end-of-stream should only appear after all image data.
    246                 if (!rowsRemaining)
    247                     return true;
    248                 return false;
    249             }
    250 
    251             if (oldcode == -1) {
    252                 *rowIter++ = suffix[code];
    253                 if (rowIter == rowBuffer.end())
    254                     OUTPUT_ROW;
    255 
    256                 firstchar = oldcode = code;
    257                 continue;
    258             }
    259 
    260             incode = code;
    261             if (code >= avail) {
    262                 stack[stackp++] = firstchar;
    263                 code = oldcode;
    264 
    265                 if (stackp == MAX_BYTES)
    266                     return false;
    267             }
    268 
    269             while (code >= clearCode) {
    270                 if (code >= MAX_BYTES || code == prefix[code])
    271                     return false;
    272 
    273                 // Even though suffix[] only holds characters through suffix[avail - 1],
    274                 // allowing code >= avail here lets us be more tolerant of malformed
    275                 // data. As long as code < MAX_BYTES, the only risk is a garbled image,
    276                 // which is no worse than refusing to display it.
    277                 stack[stackp++] = suffix[code];
    278                 code = prefix[code];
    279 
    280                 if (stackp == MAX_BYTES)
    281                     return false;
    282             }
    283 
    284             stack[stackp++] = firstchar = suffix[code];
    285 
    286             // Define a new codeword in the dictionary.
    287             if (avail < 4096) {
    288                 prefix[avail] = oldcode;
    289                 suffix[avail] = firstchar;
    290                 avail++;
    291 
    292                 // If we've used up all the codewords of a given length
    293                 // increase the length of codewords by one bit, but don't
    294                 // exceed the specified maximum codeword size of 12 bits.
    295                 if ((!(avail & codemask)) && (avail < 4096)) {
    296                     codesize++;
    297                     codemask += avail;
    298                 }
    299             }
    300             oldcode = incode;
    301 
    302             // Copy the decoded data out to the scanline buffer.
    303             do {
    304                 *rowIter++ = stack[--stackp];
    305                 if (rowIter == rowBuffer.end())
    306                     OUTPUT_ROW;
    307             } while (stackp > 0);
    308         }
    309     }
    310 
    311     return true;
    312 }
    313 
    314 void GIFColorMap::buildTable(const unsigned char* data, size_t length)
    315 {
    316     if (!m_isDefined || !m_table.isEmpty())
    317         return;
    318 
    319     RELEASE_ASSERT(m_position + m_colors * GIF_COLORS <= length);
    320     const unsigned char* srcColormap = data + m_position;
    321     m_table.resize(m_colors);
    322     for (Table::iterator iter = m_table.begin(); iter != m_table.end(); ++iter) {
    323         *iter = SkPackARGB32NoCheck(255, srcColormap[0], srcColormap[1], srcColormap[2]);
    324         srcColormap += GIF_COLORS;
    325     }
    326 }
    327 
    328 // Perform decoding for this frame. frameDecoded will be true if the entire frame is decoded.
    329 // Returns false if a decoding error occurred. This is a fatal error and causes the GIFImageReader to set the "decode failed" flag.
    330 // 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.
    331 bool GIFFrameContext::decode(const unsigned char* data, size_t length, WebCore::GIFImageDecoder* client, bool* frameDecoded)
    332 {
    333     m_localColorMap.buildTable(data, length);
    334 
    335     *frameDecoded = false;
    336     if (!m_lzwContext) {
    337         // Wait for more data to properly initialize GIFLZWContext.
    338         if (!isDataSizeDefined() || !isHeaderDefined())
    339             return true;
    340 
    341         m_lzwContext = adoptPtr(new GIFLZWContext(client, this));
    342         if (!m_lzwContext->prepareToDecode()) {
    343             m_lzwContext.clear();
    344             return false;
    345         }
    346 
    347         m_currentLzwBlock = 0;
    348     }
    349 
    350     // Some bad GIFs have extra blocks beyond the last row, which we don't want to decode.
    351     while (m_currentLzwBlock < m_lzwBlocks.size() && m_lzwContext->hasRemainingRows()) {
    352         size_t blockPosition = m_lzwBlocks[m_currentLzwBlock].blockPosition;
    353         size_t blockSize = m_lzwBlocks[m_currentLzwBlock].blockSize;
    354         if (blockPosition + blockSize > length)
    355             return false;
    356         if (!m_lzwContext->doLZW(data + blockPosition, blockSize))
    357             return false;
    358         ++m_currentLzwBlock;
    359     }
    360 
    361     // If this frame is data complete then the previous loop must have completely decoded all LZW blocks.
    362     // There will be no more decoding for this frame so it's time to cleanup.
    363     if (isComplete()) {
    364         *frameDecoded = true;
    365         m_lzwContext.clear();
    366     }
    367     return true;
    368 }
    369 
    370 // Decode a frame.
    371 // This method uses GIFFrameContext:decode() to decode the frame; decoding error is reported to client as a critical failure.
    372 // Return true if decoding has progressed. Return false if an error has occurred.
    373 bool GIFImageReader::decode(size_t frameIndex)
    374 {
    375     m_globalColorMap.buildTable(data(0), m_data->size());
    376 
    377     bool frameDecoded = false;
    378     GIFFrameContext* currentFrame = m_frames[frameIndex].get();
    379 
    380     return currentFrame->decode(data(0), m_data->size(), m_client, &frameDecoded)
    381         && (!frameDecoded || m_client->frameComplete(frameIndex));
    382 }
    383 
    384 bool GIFImageReader::parse(GIFImageDecoder::GIFParseQuery query)
    385 {
    386     ASSERT(m_bytesRead <= m_data->size());
    387 
    388     return parseData(m_bytesRead, m_data->size() - m_bytesRead, query);
    389 }
    390 
    391 // Parse incoming GIF data stream into internal data structures.
    392 // Return true if parsing has progressed or there is not enough data.
    393 // Return false if a fatal error is encountered.
    394 bool GIFImageReader::parseData(size_t dataPosition, size_t len, GIFImageDecoder::GIFParseQuery query)
    395 {
    396     if (!len) {
    397         // No new data has come in since the last call, just ignore this call.
    398         return true;
    399     }
    400 
    401     if (len < m_bytesToConsume)
    402         return true;
    403 
    404     // This loop reads as many components from |m_data| as possible.
    405     // At the beginning of each iteration, dataPosition will be advanced by m_bytesToConsume to
    406     // point to the next component. len will be decremented accordingly.
    407     while (len >= m_bytesToConsume) {
    408         const size_t currentComponentPosition = dataPosition;
    409         const unsigned char* currentComponent = data(dataPosition);
    410 
    411         // Mark the current component as consumed. Note that currentComponent will remain pointed at this
    412         // component until the next loop iteration.
    413         dataPosition += m_bytesToConsume;
    414         len -= m_bytesToConsume;
    415 
    416         switch (m_state) {
    417         case GIFLZW:
    418             ASSERT(!m_frames.isEmpty());
    419             // m_bytesToConsume is the current component size because it hasn't been updated.
    420             m_frames.last()->addLzwBlock(currentComponentPosition, m_bytesToConsume);
    421             GETN(1, GIFSubBlock);
    422             break;
    423 
    424         case GIFLZWStart: {
    425             ASSERT(!m_frames.isEmpty());
    426             m_frames.last()->setDataSize(*currentComponent);
    427             GETN(1, GIFSubBlock);
    428             break;
    429         }
    430 
    431         case GIFType: {
    432             // All GIF files begin with "GIF87a" or "GIF89a".
    433             if (!strncmp((char*)currentComponent, "GIF89a", 6))
    434                 m_version = 89;
    435             else if (!strncmp((char*)currentComponent, "GIF87a", 6))
    436                 m_version = 87;
    437             else
    438                 return false;
    439             GETN(7, GIFGlobalHeader);
    440             break;
    441         }
    442 
    443         case GIFGlobalHeader: {
    444             // This is the height and width of the "screen" or frame into which images are rendered. The
    445             // individual images can be smaller than the screen size and located with an origin anywhere
    446             // within the screen.
    447             m_screenWidth = GETINT16(currentComponent);
    448             m_screenHeight = GETINT16(currentComponent + 2);
    449 
    450             // CALLBACK: Inform the decoderplugin of our size.
    451             // Note: A subsequent frame might have dimensions larger than the "screen" dimensions.
    452             if (m_client && !m_client->setSize(m_screenWidth, m_screenHeight))
    453                 return false;
    454 
    455             const size_t globalColorMapColors = 2 << (currentComponent[4] & 0x07);
    456 
    457             if ((currentComponent[4] & 0x80) && globalColorMapColors > 0) { /* global map */
    458                 m_globalColorMap.setTablePositionAndSize(dataPosition, globalColorMapColors);
    459                 GETN(GIF_COLORS * globalColorMapColors, GIFGlobalColormap);
    460                 break;
    461             }
    462 
    463             GETN(1, GIFImageStart);
    464             break;
    465         }
    466 
    467         case GIFGlobalColormap: {
    468             m_globalColorMap.setDefined();
    469             GETN(1, GIFImageStart);
    470             break;
    471         }
    472 
    473         case GIFImageStart: {
    474             if (*currentComponent == '!') { // extension.
    475                 GETN(2, GIFExtension);
    476                 break;
    477             }
    478 
    479             if (*currentComponent == ',') { // image separator.
    480                 GETN(9, GIFImageHeader);
    481                 break;
    482             }
    483 
    484             // If we get anything other than ',' (image separator), '!'
    485             // (extension), or ';' (trailer), there is extraneous data
    486             // between blocks. The GIF87a spec tells us to keep reading
    487             // until we find an image separator, but GIF89a says such
    488             // a file is corrupt. We follow Mozilla's implementation and
    489             // proceed as if the file were correctly terminated, so the
    490             // GIF will display.
    491             GETN(0, GIFDone);
    492             break;
    493         }
    494 
    495         case GIFExtension: {
    496             size_t bytesInBlock = currentComponent[1];
    497             GIFState es = GIFSkipBlock;
    498 
    499             switch (*currentComponent) {
    500             case 0xf9:
    501                 es = GIFControlExtension;
    502                 // The GIF spec mandates that the GIFControlExtension header block length is 4 bytes,
    503                 // and the parser for this block reads 4 bytes, so we must enforce that the buffer
    504                 // contains at least this many bytes. If the GIF specifies a different length, we
    505                 // allow that, so long as it's larger; the additional data will simply be ignored.
    506                 bytesInBlock = std::max(bytesInBlock, static_cast<size_t>(4));
    507                 break;
    508 
    509             // The GIF spec also specifies the lengths of the following two extensions' headers
    510             // (as 12 and 11 bytes, respectively). Because we ignore the plain text extension entirely
    511             // and sanity-check the actual length of the application extension header before reading it,
    512             // we allow GIFs to deviate from these values in either direction. This is important for
    513             // real-world compatibility, as GIFs in the wild exist with application extension headers
    514             // that are both shorter and longer than 11 bytes.
    515             case 0x01:
    516                 // ignoring plain text extension
    517                 break;
    518 
    519             case 0xff:
    520                 es = GIFApplicationExtension;
    521                 break;
    522 
    523             case 0xfe:
    524                 es = GIFConsumeComment;
    525                 break;
    526             }
    527 
    528             if (bytesInBlock)
    529                 GETN(bytesInBlock, es);
    530             else
    531                 GETN(1, GIFImageStart);
    532             break;
    533         }
    534 
    535         case GIFConsumeBlock: {
    536             if (!*currentComponent)
    537                 GETN(1, GIFImageStart);
    538             else
    539                 GETN(*currentComponent, GIFSkipBlock);
    540             break;
    541         }
    542 
    543         case GIFSkipBlock: {
    544             GETN(1, GIFConsumeBlock);
    545             break;
    546         }
    547 
    548         case GIFControlExtension: {
    549             addFrameIfNecessary();
    550             GIFFrameContext* currentFrame = m_frames.last().get();
    551             if (*currentComponent & 0x1)
    552                 currentFrame->setTransparentPixel(currentComponent[3]);
    553 
    554             // We ignore the "user input" bit.
    555 
    556             // NOTE: This relies on the values in the FrameDisposalMethod enum
    557             // matching those in the GIF spec!
    558             int disposalMethod = ((*currentComponent) >> 2) & 0x7;
    559             currentFrame->setDisposalMethod(static_cast<WebCore::ImageFrame::FrameDisposalMethod>(disposalMethod));
    560             // Some specs say that disposal method 3 is "overwrite previous", others that setting
    561             // the third bit of the field (i.e. method 4) is. We map both to the same value.
    562             if (disposalMethod == 4)
    563                 currentFrame->setDisposalMethod(WebCore::ImageFrame::DisposeOverwritePrevious);
    564             currentFrame->setDelayTime(GETINT16(currentComponent + 1) * 10);
    565             GETN(1, GIFConsumeBlock);
    566             break;
    567         }
    568 
    569         case GIFCommentExtension: {
    570             if (*currentComponent)
    571                 GETN(*currentComponent, GIFConsumeComment);
    572             else
    573                 GETN(1, GIFImageStart);
    574             break;
    575         }
    576 
    577         case GIFConsumeComment: {
    578             GETN(1, GIFCommentExtension);
    579             break;
    580         }
    581 
    582         case GIFApplicationExtension: {
    583             // Check for netscape application extension.
    584             if (m_bytesToConsume == 11
    585                 && (!strncmp((char*)currentComponent, "NETSCAPE2.0", 11) || !strncmp((char*)currentComponent, "ANIMEXTS1.0", 11)))
    586                 GETN(1, GIFNetscapeExtensionBlock);
    587             else
    588                 GETN(1, GIFConsumeBlock);
    589             break;
    590         }
    591 
    592         // Netscape-specific GIF extension: animation looping.
    593         case GIFNetscapeExtensionBlock: {
    594             // GIFConsumeNetscapeExtension always reads 3 bytes from the stream; we should at least wait for this amount.
    595             if (*currentComponent)
    596                 GETN(std::max(3, static_cast<int>(*currentComponent)), GIFConsumeNetscapeExtension);
    597             else
    598                 GETN(1, GIFImageStart);
    599             break;
    600         }
    601 
    602         // Parse netscape-specific application extensions
    603         case GIFConsumeNetscapeExtension: {
    604             int netscapeExtension = currentComponent[0] & 7;
    605 
    606             // Loop entire animation specified # of times. Only read the loop count during the first iteration.
    607             if (netscapeExtension == 1) {
    608                 m_loopCount = GETINT16(currentComponent + 1);
    609 
    610                 // Zero loop count is infinite animation loop request.
    611                 if (!m_loopCount)
    612                     m_loopCount = WebCore::cAnimationLoopInfinite;
    613 
    614                 GETN(1, GIFNetscapeExtensionBlock);
    615             } else if (netscapeExtension == 2) {
    616                 // Wait for specified # of bytes to enter buffer.
    617 
    618                 // Don't do this, this extension doesn't exist (isn't used at all)
    619                 // and doesn't do anything, as our streaming/buffering takes care of it all...
    620                 // See: http://semmix.pl/color/exgraf/eeg24.htm
    621                 GETN(1, GIFNetscapeExtensionBlock);
    622             } else {
    623                 // 0,3-7 are yet to be defined netscape extension codes
    624                 return false;
    625             }
    626             break;
    627         }
    628 
    629         case GIFImageHeader: {
    630             unsigned height, width, xOffset, yOffset;
    631 
    632             /* Get image offsets, with respect to the screen origin */
    633             xOffset = GETINT16(currentComponent);
    634             yOffset = GETINT16(currentComponent + 2);
    635 
    636             /* Get image width and height. */
    637             width  = GETINT16(currentComponent + 4);
    638             height = GETINT16(currentComponent + 6);
    639 
    640             /* Work around broken GIF files where the logical screen
    641              * size has weird width or height.  We assume that GIF87a
    642              * files don't contain animations.
    643              */
    644             if (currentFrameIsFirstFrame()
    645                 && ((m_screenHeight < height) || (m_screenWidth < width) || (m_version == 87))) {
    646                 m_screenHeight = height;
    647                 m_screenWidth = width;
    648                 xOffset = 0;
    649                 yOffset = 0;
    650 
    651                 // CALLBACK: Inform the decoderplugin of our size.
    652                 if (m_client && !m_client->setSize(m_screenWidth, m_screenHeight))
    653                     return false;
    654             }
    655 
    656             // Work around more broken GIF files that have zero image width or height
    657             if (!height || !width) {
    658                 height = m_screenHeight;
    659                 width = m_screenWidth;
    660                 if (!height || !width)
    661                     return false;
    662             }
    663 
    664             if (query == GIFImageDecoder::GIFSizeQuery) {
    665                 // The decoder needs to stop. Hand back the number of bytes we consumed from
    666                 // buffer minus 9 (the amount we consumed to read the header).
    667                 setRemainingBytes(len + 9);
    668                 GETN(9, GIFImageHeader);
    669                 return true;
    670             }
    671 
    672             addFrameIfNecessary();
    673             GIFFrameContext* currentFrame = m_frames.last().get();
    674 
    675             currentFrame->setHeaderDefined();
    676             currentFrame->setRect(xOffset, yOffset, width, height);
    677             m_screenWidth = std::max(m_screenWidth, width);
    678             m_screenHeight = std::max(m_screenHeight, height);
    679             currentFrame->setInterlaced(currentComponent[8] & 0x40);
    680 
    681             // Overlaying interlaced, transparent GIFs over
    682             // existing image data using the Haeberli display hack
    683             // requires saving the underlying image in order to
    684             // avoid jaggies at the transparency edges. We are
    685             // unprepared to deal with that, so don't display such
    686             // images progressively. Which means only the first
    687             // frame can be progressively displayed.
    688             // FIXME: It is possible that a non-transparent frame
    689             // can be interlaced and progressively displayed.
    690             currentFrame->setProgressiveDisplay(currentFrameIsFirstFrame());
    691 
    692             const bool isLocalColormapDefined = currentComponent[8] & 0x80;
    693             if (isLocalColormapDefined) {
    694                 // The three low-order bits of currentComponent[8] specify the bits per pixel.
    695                 const size_t numColors = 2 << (currentComponent[8] & 0x7);
    696                 currentFrame->localColorMap().setTablePositionAndSize(dataPosition, numColors);
    697                 GETN(GIF_COLORS * numColors, GIFImageColormap);
    698                 break;
    699             }
    700 
    701             GETN(1, GIFLZWStart);
    702             break;
    703         }
    704 
    705         case GIFImageColormap: {
    706             ASSERT(!m_frames.isEmpty());
    707             m_frames.last()->localColorMap().setDefined();
    708             GETN(1, GIFLZWStart);
    709             break;
    710         }
    711 
    712         case GIFSubBlock: {
    713             const size_t bytesInBlock = *currentComponent;
    714             if (bytesInBlock)
    715                 GETN(bytesInBlock, GIFLZW);
    716             else {
    717                 // Finished parsing one frame; Process next frame.
    718                 ASSERT(!m_frames.isEmpty());
    719                 // Note that some broken GIF files do not have enough LZW blocks to fully
    720                 // decode all rows but we treat it as frame complete.
    721                 m_frames.last()->setComplete();
    722                 GETN(1, GIFImageStart);
    723             }
    724             break;
    725         }
    726 
    727         case GIFDone: {
    728             m_parseCompleted = true;
    729             return true;
    730         }
    731 
    732         default:
    733             // We shouldn't ever get here.
    734             return false;
    735             break;
    736         }
    737     }
    738 
    739     setRemainingBytes(len);
    740     return true;
    741 }
    742 
    743 void GIFImageReader::setRemainingBytes(size_t remainingBytes)
    744 {
    745     ASSERT(remainingBytes <= m_data->size());
    746     m_bytesRead = m_data->size() - remainingBytes;
    747 }
    748 
    749 void GIFImageReader::addFrameIfNecessary()
    750 {
    751     if (m_frames.isEmpty() || m_frames.last()->isComplete())
    752         m_frames.append(adoptPtr(new GIFFrameContext(m_frames.size())));
    753 }
    754 
    755 // FIXME: Move this method to close to doLZW().
    756 bool GIFLZWContext::prepareToDecode()
    757 {
    758     ASSERT(m_frameContext->isDataSizeDefined() && m_frameContext->isHeaderDefined());
    759 
    760     // Since we use a codesize of 1 more than the datasize, we need to ensure
    761     // that our datasize is strictly less than the MAX_LZW_BITS value (12).
    762     // This sets the largest possible codemask correctly at 4095.
    763     if (m_frameContext->dataSize() >= MAX_LZW_BITS)
    764         return false;
    765     clearCode = 1 << m_frameContext->dataSize();
    766     if (clearCode >= MAX_BYTES)
    767         return false;
    768 
    769     avail = clearCode + 2;
    770     oldcode = -1;
    771     codesize = m_frameContext->dataSize() + 1;
    772     codemask = (1 << codesize) - 1;
    773     datum = bits = 0;
    774     ipass = m_frameContext->interlaced() ? 1 : 0;
    775     irow = 0;
    776 
    777     // Initialize output row buffer.
    778     rowBuffer.resize(m_frameContext->width());
    779     rowIter = rowBuffer.begin();
    780     rowsRemaining = m_frameContext->height();
    781 
    782     // Clearing the whole suffix table lets us be more tolerant of bad data.
    783     memset(suffix, 0, sizeof(suffix));
    784 
    785     // Clearing the whole prefix table to prevent uninitialized access.
    786     memset(prefix, 0, sizeof(prefix));
    787     for (int i = 0; i < clearCode; i++)
    788         suffix[i] = i;
    789     stackp = 0;
    790     return true;
    791 }
    792