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/*
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
75#include "config.h"
76#include "GIFImageReader.h"
77
78#include <string.h>
79#include "GIFImageDecoder.h"
80#include "ImageSource.h"
81
82using 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.
101bool 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.
203bool GIFLZWContext::doLZW(const unsigned char* block, size_t bytesInBlock)
204{
205    int code;
206    int incode;
207    const unsigned char *ch;
208
209    if (rowPosition == rowBuffer.size())
210        return true;
211
212#define OUTPUT_ROW \
213    do { \
214        if (!outputRow()) \
215            return false; \
216        rowsRemaining--; \
217        rowPosition = 0; \
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                rowBuffer[rowPosition++] = suffix[code];
253                if (rowPosition == rowBuffer.size())
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                rowBuffer[rowPosition++] = stack[--stackp];
305                if (rowPosition == rowBuffer.size())
306                    OUTPUT_ROW;
307            } while (stackp > 0);
308        }
309    }
310
311    return true;
312}
313
314// Perform decoding for this frame. frameDecoded will be true if the entire frame is decoded.
315// Returns false if a decoding error occurred. This is a fatal error and causes the GIFImageReader to set the "decode failed" flag.
316// 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.
317bool GIFFrameContext::decode(const unsigned char* data, size_t length, WebCore::GIFImageDecoder* client, bool* frameDecoded)
318{
319    *frameDecoded = false;
320    if (!m_lzwContext) {
321        // Wait for more data to properly initialize GIFLZWContext.
322        if (!isDataSizeDefined() || !isHeaderDefined())
323            return true;
324
325        m_lzwContext = adoptPtr(new GIFLZWContext(client, this));
326        if (!m_lzwContext->prepareToDecode()) {
327            m_lzwContext.clear();
328            return false;
329        }
330
331        m_currentLzwBlock = 0;
332    }
333
334    // Some bad GIFs have extra blocks beyond the last row, which we don't want to decode.
335    while (m_currentLzwBlock < m_lzwBlocks.size() && m_lzwContext->hasRemainingRows()) {
336        size_t blockPosition = m_lzwBlocks[m_currentLzwBlock].blockPosition;
337        size_t blockSize = m_lzwBlocks[m_currentLzwBlock].blockSize;
338        if (blockPosition + blockSize > length)
339            return false;
340        if (!m_lzwContext->doLZW(data + blockPosition, blockSize))
341            return false;
342        ++m_currentLzwBlock;
343    }
344
345    // If this frame is data complete then the previous loop must have completely decoded all LZW blocks.
346    // There will be no more decoding for this frame so it's time to cleanup.
347    if (isComplete()) {
348        *frameDecoded = true;
349        m_lzwContext.clear();
350    }
351    return true;
352}
353
354// Decode all frames before haltAtFrame.
355// This method uses GIFFrameContext:decode() to decode each frame; decoding error is reported to client as a critical failure.
356// Return true if decoding has progressed. Return false if an error has occurred.
357bool GIFImageReader::decode(GIFImageDecoder::GIFQuery query, unsigned haltAtFrame)
358{
359    ASSERT(m_bytesRead <= m_data->size());
360
361    if (!parse(m_bytesRead, m_data->size() - m_bytesRead, query == GIFImageDecoder::GIFSizeQuery))
362        return false;
363
364    if (query != GIFImageDecoder::GIFFullQuery)
365        return true;
366
367    while (m_currentDecodingFrame < std::min(m_frames.size(), static_cast<size_t>(haltAtFrame))) {
368        bool frameDecoded = false;
369        GIFFrameContext* currentFrame = m_frames[m_currentDecodingFrame].get();
370
371        if (!currentFrame->decode(data(0), m_data->size(), m_client, &frameDecoded))
372            return false;
373
374        // We need more data to continue decoding.
375        if (!frameDecoded)
376            break;
377
378        if (!m_client->frameComplete(m_currentDecodingFrame, currentFrame->delayTime, currentFrame->disposalMethod))
379            return false;
380        ++m_currentDecodingFrame;
381    }
382
383    // All frames decoded.
384    if (m_currentDecodingFrame == m_frames.size() && m_parseCompleted)
385        m_client->gifComplete();
386    return true;
387}
388
389// Parse incoming GIF data stream into internal data structures.
390// Return true if parsing has progressed or there is not enough data.
391// Return false if a fatal error is encountered.
392bool GIFImageReader::parse(size_t dataPosition, size_t len, bool parseSizeOnly)
393{
394    if (!len) {
395        // No new data has come in since the last call, just ignore this call.
396        return true;
397    }
398
399    if (len < m_bytesToConsume)
400        return true;
401
402    // This loop reads as many components from |m_data| as possible.
403    // At the beginning of each iteration, dataPosition will be advanced by m_bytesToConsume to
404    // point to the next component. len will be decremented accordingly.
405    while (len >= m_bytesToConsume) {
406        const size_t currentComponentPosition = dataPosition;
407        const unsigned char* currentComponent = data(dataPosition);
408
409        // Mark the current component as consumed. Note that currentComponent will remain pointed at this
410        // component until the next loop iteration.
411        dataPosition += m_bytesToConsume;
412        len -= m_bytesToConsume;
413
414        switch (m_state) {
415        case GIFLZW:
416            ASSERT(!m_frames.isEmpty());
417            // m_bytesToConsume is the current component size because it hasn't been updated.
418            m_frames.last()->addLzwBlock(currentComponentPosition, m_bytesToConsume);
419            GETN(1, GIFSubBlock);
420            break;
421
422        case GIFLZWStart: {
423            ASSERT(!m_frames.isEmpty());
424            m_frames.last()->setDataSize(*currentComponent);
425            GETN(1, GIFSubBlock);
426            break;
427        }
428
429        case GIFType: {
430            // All GIF files begin with "GIF87a" or "GIF89a".
431            if (!strncmp((char*)currentComponent, "GIF89a", 6))
432                m_version = 89;
433            else if (!strncmp((char*)currentComponent, "GIF87a", 6))
434                m_version = 87;
435            else
436                return false;
437            GETN(7, GIFGlobalHeader);
438            break;
439        }
440
441        case GIFGlobalHeader: {
442            // This is the height and width of the "screen" or frame into which images are rendered. The
443            // individual images can be smaller than the screen size and located with an origin anywhere
444            // within the screen.
445            m_screenWidth = GETINT16(currentComponent);
446            m_screenHeight = GETINT16(currentComponent + 2);
447
448            // CALLBACK: Inform the decoderplugin of our size.
449            // Note: A subsequent frame might have dimensions larger than the "screen" dimensions.
450            if (m_client && !m_client->setSize(m_screenWidth, m_screenHeight))
451                return false;
452
453            m_screenBgcolor = currentComponent[5];
454            m_globalColormapSize = 2 << (currentComponent[4] & 0x07);
455
456            if ((currentComponent[4] & 0x80) && m_globalColormapSize > 0) { /* global map */
457                // Get the global colormap
458                const size_t globalColormapBytes = 3 * m_globalColormapSize;
459                m_globalColormapPosition = dataPosition;
460
461                if (len < globalColormapBytes) {
462                    // Wait until we have enough bytes to consume the entire colormap at once.
463                    GETN(globalColormapBytes, GIFGlobalColormap);
464                    break;
465                }
466
467                m_isGlobalColormapDefined = true;
468                dataPosition += globalColormapBytes;
469                len -= globalColormapBytes;
470            }
471
472            GETN(1, GIFImageStart);
473
474            // currentComponent[6] = Pixel Aspect Ratio
475            //   Not used
476            //   float aspect = (float)((currentComponent[6] + 15) / 64.0);
477            break;
478        }
479
480        case GIFGlobalColormap: {
481            m_isGlobalColormapDefined = true;
482            GETN(1, GIFImageStart);
483            break;
484        }
485
486        case GIFImageStart: {
487            if (*currentComponent == ';') { // terminator.
488                GETN(0, GIFDone);
489                break;
490            }
491
492            if (*currentComponent == '!') { // extension.
493                GETN(2, GIFExtension);
494                break;
495            }
496
497            // If we get anything other than ',' (image separator), '!'
498            // (extension), or ';' (trailer), there is extraneous data
499            // between blocks. The GIF87a spec tells us to keep reading
500            // until we find an image separator, but GIF89a says such
501            // a file is corrupt. We follow GIF89a and bail out.
502            if (*currentComponent != ',')
503                return false;
504
505            GETN(9, GIFImageHeader);
506            break;
507        }
508
509        case GIFExtension: {
510            size_t bytesInBlock = currentComponent[1];
511            GIFState es = GIFSkipBlock;
512
513            switch (*currentComponent) {
514            case 0xf9:
515                es = GIFControlExtension;
516                // The GIF spec mandates that the GIFControlExtension header block length is 4 bytes,
517                // and the parser for this block reads 4 bytes, so we must enforce that the buffer
518                // contains at least this many bytes. If the GIF specifies a different length, we
519                // allow that, so long as it's larger; the additional data will simply be ignored.
520                bytesInBlock = std::max(bytesInBlock, static_cast<size_t>(4));
521                break;
522
523            // The GIF spec also specifies the lengths of the following two extensions' headers
524            // (as 12 and 11 bytes, respectively). Because we ignore the plain text extension entirely
525            // and sanity-check the actual length of the application extension header before reading it,
526            // we allow GIFs to deviate from these values in either direction. This is important for
527            // real-world compatibility, as GIFs in the wild exist with application extension headers
528            // that are both shorter and longer than 11 bytes.
529            case 0x01:
530                // ignoring plain text extension
531                break;
532
533            case 0xff:
534                es = GIFApplicationExtension;
535                break;
536
537            case 0xfe:
538                es = GIFConsumeComment;
539                break;
540            }
541
542            if (bytesInBlock)
543                GETN(bytesInBlock, es);
544            else
545                GETN(1, GIFImageStart);
546            break;
547        }
548
549        case GIFConsumeBlock: {
550            if (!*currentComponent)
551                GETN(1, GIFImageStart);
552            else
553                GETN(*currentComponent, GIFSkipBlock);
554            break;
555        }
556
557        case GIFSkipBlock: {
558            GETN(1, GIFConsumeBlock);
559            break;
560        }
561
562        case GIFControlExtension: {
563            addFrameIfNecessary();
564            GIFFrameContext* currentFrame = m_frames.last().get();
565            currentFrame->isTransparent = *currentComponent & 0x1;
566            if (currentFrame->isTransparent)
567                currentFrame->tpixel = currentComponent[3];
568
569            // We ignore the "user input" bit.
570
571            // NOTE: This relies on the values in the FrameDisposalMethod enum
572            // matching those in the GIF spec!
573            int disposalMethod = ((*currentComponent) >> 2) & 0x7;
574            currentFrame->disposalMethod = static_cast<WebCore::ImageFrame::FrameDisposalMethod>(disposalMethod);
575            // Some specs say that disposal method 3 is "overwrite previous", others that setting
576            // the third bit of the field (i.e. method 4) is. We map both to the same value.
577            if (disposalMethod == 4)
578                currentFrame->disposalMethod = WebCore::ImageFrame::DisposeOverwritePrevious;
579            currentFrame->delayTime = GETINT16(currentComponent + 1) * 10;
580            GETN(1, GIFConsumeBlock);
581            break;
582        }
583
584        case GIFCommentExtension: {
585            if (*currentComponent)
586                GETN(*currentComponent, GIFConsumeComment);
587            else
588                GETN(1, GIFImageStart);
589            break;
590        }
591
592        case GIFConsumeComment: {
593            GETN(1, GIFCommentExtension);
594            break;
595        }
596
597        case GIFApplicationExtension: {
598            // Check for netscape application extension.
599            if (m_bytesToConsume == 11
600                && (!strncmp((char*)currentComponent, "NETSCAPE2.0", 11) || !strncmp((char*)currentComponent, "ANIMEXTS1.0", 11)))
601                GETN(1, GIFNetscapeExtensionBlock);
602            else
603                GETN(1, GIFConsumeBlock);
604            break;
605        }
606
607        // Netscape-specific GIF extension: animation looping.
608        case GIFNetscapeExtensionBlock: {
609            // GIFConsumeNetscapeExtension always reads 3 bytes from the stream; we should at least wait for this amount.
610            if (*currentComponent)
611                GETN(std::max(3, static_cast<int>(*currentComponent)), GIFConsumeNetscapeExtension);
612            else
613                GETN(1, GIFImageStart);
614            break;
615        }
616
617        // Parse netscape-specific application extensions
618        case GIFConsumeNetscapeExtension: {
619            int netscapeExtension = currentComponent[0] & 7;
620
621            // Loop entire animation specified # of times. Only read the loop count during the first iteration.
622            if (netscapeExtension == 1) {
623                m_loopCount = GETINT16(currentComponent + 1);
624
625                // Zero loop count is infinite animation loop request.
626                if (!m_loopCount)
627                    m_loopCount = WebCore::cAnimationLoopInfinite;
628
629                GETN(1, GIFNetscapeExtensionBlock);
630            } else if (netscapeExtension == 2) {
631                // Wait for specified # of bytes to enter buffer.
632
633                // Don't do this, this extension doesn't exist (isn't used at all)
634                // and doesn't do anything, as our streaming/buffering takes care of it all...
635                // See: http://semmix.pl/color/exgraf/eeg24.htm
636                GETN(1, GIFNetscapeExtensionBlock);
637            } else {
638                // 0,3-7 are yet to be defined netscape extension codes
639                return false;
640            }
641            break;
642        }
643
644        case GIFImageHeader: {
645            unsigned height, width, xOffset, yOffset;
646
647            /* Get image offsets, with respect to the screen origin */
648            xOffset = GETINT16(currentComponent);
649            yOffset = GETINT16(currentComponent + 2);
650
651            /* Get image width and height. */
652            width  = GETINT16(currentComponent + 4);
653            height = GETINT16(currentComponent + 6);
654
655            /* Work around broken GIF files where the logical screen
656             * size has weird width or height.  We assume that GIF87a
657             * files don't contain animations.
658             */
659            if (currentFrameIsFirstFrame()
660                && ((m_screenHeight < height) || (m_screenWidth < width) || (m_version == 87))) {
661                m_screenHeight = height;
662                m_screenWidth = width;
663                xOffset = 0;
664                yOffset = 0;
665
666                // CALLBACK: Inform the decoderplugin of our size.
667                if (m_client && !m_client->setSize(m_screenWidth, m_screenHeight))
668                    return false;
669            }
670
671            // Work around more broken GIF files that have zero image width or height
672            if (!height || !width) {
673                height = m_screenHeight;
674                width = m_screenWidth;
675                if (!height || !width)
676                    return false;
677            }
678
679            if (parseSizeOnly) {
680                // The decoder needs to stop. Hand back the number of bytes we consumed from
681                // buffer minus 9 (the amount we consumed to read the header).
682                setRemainingBytes(len + 9);
683                GETN(9, GIFImageHeader);
684                return true;
685            }
686
687            addFrameIfNecessary();
688            GIFFrameContext* currentFrame = m_frames.last().get();
689
690            currentFrame->setHeaderDefined();
691            currentFrame->xOffset = xOffset;
692            currentFrame->yOffset = yOffset;
693            currentFrame->height = height;
694            currentFrame->width = width;
695            m_screenWidth = std::max(m_screenWidth, width);
696            m_screenHeight = std::max(m_screenHeight, height);
697            currentFrame->interlaced = currentComponent[8] & 0x40;
698
699            // Overlaying interlaced, transparent GIFs over
700            // existing image data using the Haeberli display hack
701            // requires saving the underlying image in order to
702            // avoid jaggies at the transparency edges. We are
703            // unprepared to deal with that, so don't display such
704            // images progressively. Which means only the first
705            // frame can be progressively displayed.
706            // FIXME: It is possible that a non-transparent frame
707            // can be interlaced and progressively displayed.
708            currentFrame->progressiveDisplay = currentFrameIsFirstFrame();
709
710            const bool isLocalColormapDefined = currentComponent[8] & 0x80;
711            if (isLocalColormapDefined) {
712                // The three low-order bits of currentComponent[8] specify the bits per pixel.
713                int numColors = 2 << (currentComponent[8] & 0x7);
714                const size_t localColormapBytes = 3 * numColors;
715
716                // Switch to the new local palette after it loads
717                currentFrame->localColormapPosition = dataPosition;
718                currentFrame->localColormapSize = numColors;
719
720                if (len < localColormapBytes) {
721                    // Wait until we have enough bytes to consume the entire colormap at once.
722                    GETN(localColormapBytes, GIFImageColormap);
723                    break;
724                }
725
726                currentFrame->isLocalColormapDefined = true;
727                dataPosition += localColormapBytes;
728                len -= localColormapBytes;
729            } else {
730                // Switch back to the global palette
731                currentFrame->isLocalColormapDefined = false;
732            }
733            GETN(1, GIFLZWStart);
734            break;
735        }
736
737        case GIFImageColormap: {
738            ASSERT(!m_frames.isEmpty());
739            m_frames.last()->isLocalColormapDefined = true;
740            GETN(1, GIFLZWStart);
741            break;
742        }
743
744        case GIFSubBlock: {
745            const size_t bytesInBlock = *currentComponent;
746            if (bytesInBlock)
747                GETN(bytesInBlock, GIFLZW);
748            else {
749                // Finished parsing one frame; Process next frame.
750                ASSERT(!m_frames.isEmpty());
751                // Note that some broken GIF files do not have enough LZW blocks to fully
752                // decode all rows but we treat it as frame complete.
753                m_frames.last()->setComplete();
754                GETN(1, GIFImageStart);
755            }
756            break;
757        }
758
759        case GIFDone: {
760            m_parseCompleted = true;
761            return true;
762        }
763
764        default:
765            // We shouldn't ever get here.
766            return false;
767            break;
768        }
769    }
770
771    setRemainingBytes(len);
772    return true;
773}
774
775void GIFImageReader::setRemainingBytes(size_t remainingBytes)
776{
777    ASSERT(remainingBytes <= m_data->size());
778    m_bytesRead = m_data->size() - remainingBytes;
779}
780
781void GIFImageReader::addFrameIfNecessary()
782{
783    if (m_frames.isEmpty() || m_frames.last()->isComplete())
784        m_frames.append(adoptPtr(new GIFFrameContext(m_frames.size())));
785}
786
787// FIXME: Move this method to close to doLZW().
788bool GIFLZWContext::prepareToDecode()
789{
790    ASSERT(m_frameContext->isDataSizeDefined() && m_frameContext->isHeaderDefined());
791
792    // Since we use a codesize of 1 more than the datasize, we need to ensure
793    // that our datasize is strictly less than the MAX_LZW_BITS value (12).
794    // This sets the largest possible codemask correctly at 4095.
795    if (m_frameContext->datasize >= MAX_LZW_BITS)
796        return false;
797    clearCode = 1 << m_frameContext->datasize;
798    if (clearCode >= MAX_BYTES)
799        return false;
800
801    avail = clearCode + 2;
802    oldcode = -1;
803    codesize = m_frameContext->datasize + 1;
804    codemask = (1 << codesize) - 1;
805    datum = bits = 0;
806    ipass = m_frameContext->interlaced ? 1 : 0;
807    irow = 0;
808
809    // Initialize the tables lazily, this allows frame count query to use less memory.
810    suffix.resize(MAX_BYTES);
811    stack.resize(MAX_BYTES);
812    prefix.resize(MAX_BYTES);
813
814    // Initialize output row buffer.
815    rowBuffer.resize(m_frameContext->width);
816    rowPosition = 0;
817    rowsRemaining = m_frameContext->height;
818
819    // Clearing the whole suffix table lets us be more tolerant of bad data.
820    suffix.fill(0);
821    for (int i = 0; i < clearCode; i++)
822        suffix[i] = i;
823    stackp = 0;
824    return true;
825}
826