Home | History | Annotate | Download | only in gif
      1 /* -*- Mode: C; tab-width: 4; 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 Communicator client 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  *
     24  * Alternatively, the contents of this file may be used under the terms of
     25  * either the GNU General Public License Version 2 or later (the "GPL"), or
     26  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
     27  * in which case the provisions of the GPL or the LGPL are applicable instead
     28  * of those above. If you wish to allow use of your version of this file only
     29  * under the terms of either the GPL or the LGPL, and not to allow others to
     30  * use your version of this file under the terms of the MPL, indicate your
     31  * decision by deleting the provisions above and replace them with the notice
     32  * and other provisions required by the GPL or the LGPL. If you do not delete
     33  * the provisions above, a recipient may use your version of this file under
     34  * the terms of any one of the MPL, the GPL or the LGPL.
     35  *
     36  * ***** END LICENSE BLOCK ***** */
     37 
     38 #ifndef GIFImageReader_h
     39 #define GIFImageReader_h
     40 
     41 // Define ourselves as the clientPtr.  Mozilla just hacked their C++ callback class into this old C decoder,
     42 // so we will too.
     43 #include "core/platform/SharedBuffer.h"
     44 #include "core/platform/image-decoders/gif/GIFImageDecoder.h"
     45 #include "wtf/OwnPtr.h"
     46 #include "wtf/PassOwnPtr.h"
     47 #include "wtf/Vector.h"
     48 
     49 #define MAX_LZW_BITS          12
     50 #define MAX_BYTES           4097 /* 2^MAX_LZW_BITS+1 */
     51 #define MAX_COLORS           256
     52 #define GIF_COLORS             3
     53 
     54 const int cLoopCountNotSeen = -2;
     55 
     56 // List of possible parsing states.
     57 enum GIFState {
     58     GIFType,
     59     GIFGlobalHeader,
     60     GIFGlobalColormap,
     61     GIFImageStart,
     62     GIFImageHeader,
     63     GIFImageColormap,
     64     GIFImageBody,
     65     GIFLZWStart,
     66     GIFLZW,
     67     GIFSubBlock,
     68     GIFExtension,
     69     GIFControlExtension,
     70     GIFConsumeBlock,
     71     GIFSkipBlock,
     72     GIFDone,
     73     GIFCommentExtension,
     74     GIFApplicationExtension,
     75     GIFNetscapeExtensionBlock,
     76     GIFConsumeNetscapeExtension,
     77     GIFConsumeComment
     78 };
     79 
     80 struct GIFFrameContext;
     81 
     82 // LZW decoder state machine.
     83 class GIFLZWContext {
     84     WTF_MAKE_FAST_ALLOCATED;
     85 public:
     86     GIFLZWContext(WebCore::GIFImageDecoder* client, const GIFFrameContext* frameContext)
     87         : codesize(0)
     88         , codemask(0)
     89         , clearCode(0)
     90         , avail(0)
     91         , oldcode(0)
     92         , firstchar(0)
     93         , bits(0)
     94         , datum(0)
     95         , ipass(0)
     96         , irow(0)
     97         , rowsRemaining(0)
     98         , stackp(0)
     99         , rowIter(0)
    100         , m_client(client)
    101         , m_frameContext(frameContext)
    102     { }
    103 
    104     bool prepareToDecode();
    105     bool outputRow();
    106     bool doLZW(const unsigned char* block, size_t bytesInBlock);
    107     bool hasRemainingRows() { return rowsRemaining; }
    108 
    109 private:
    110     // LZW decoding states and output states.
    111     int codesize;
    112     int codemask;
    113     int clearCode; // Codeword used to trigger dictionary reset.
    114     int avail; // Index of next available slot in dictionary.
    115     int oldcode;
    116     unsigned char firstchar;
    117     int bits; // Number of unread bits in "datum".
    118     int datum; // 32-bit input buffer.
    119     int ipass; // Interlace pass; Ranges 1-4 if interlaced.
    120     size_t irow; // Current output row, starting at zero.
    121     size_t rowsRemaining; // Rows remaining to be output.
    122 
    123     unsigned short prefix[MAX_BYTES];
    124     unsigned char suffix[MAX_BYTES];
    125     unsigned char stack[MAX_BYTES];
    126     Vector<unsigned char> rowBuffer; // Single scanline temporary buffer.
    127 
    128     size_t stackp; // Current stack pointer.
    129     Vector<unsigned char>::iterator rowIter;
    130 
    131     // Initialized during construction and read-only.
    132     WebCore::GIFImageDecoder* m_client;
    133     const GIFFrameContext* m_frameContext;
    134 };
    135 
    136 // Data structure for one LZW block.
    137 struct GIFLZWBlock {
    138     WTF_MAKE_FAST_ALLOCATED;
    139 public:
    140     GIFLZWBlock(size_t position, size_t size)
    141         : blockPosition(position)
    142         , blockSize(size)
    143     {
    144     }
    145 
    146     size_t blockPosition;
    147     size_t blockSize;
    148 };
    149 
    150 class GIFColorMap {
    151     WTF_MAKE_FAST_ALLOCATED;
    152 public:
    153     typedef Vector<WebCore::ImageFrame::PixelData> Table;
    154 
    155     GIFColorMap()
    156         : m_isDefined(false)
    157         , m_position(0)
    158         , m_colors(0)
    159     {
    160     }
    161 
    162     // Set position and number of colors for the RGB table in the data stream.
    163     void setTablePositionAndSize(size_t position, size_t colors)
    164     {
    165         m_position = position;
    166         m_colors = colors;
    167     }
    168     void setDefined() { m_isDefined = true; }
    169     bool isDefined() const { return m_isDefined; }
    170 
    171     // Build RGBA table using the data stream.
    172     void buildTable(const unsigned char* data, size_t length);
    173     const Table& table() const { return m_table; }
    174 
    175 private:
    176     bool m_isDefined;
    177     size_t m_position;
    178     size_t m_colors;
    179     Table m_table;
    180 };
    181 
    182 // Frame output state machine.
    183 struct GIFFrameContext {
    184     WTF_MAKE_FAST_ALLOCATED;
    185 public:
    186     GIFFrameContext(int id)
    187         : m_frameId(id)
    188         , m_xOffset(0)
    189         , m_yOffset(0)
    190         , m_width(0)
    191         , m_height(0)
    192         , m_transparentPixel(notFound)
    193         , m_disposalMethod(WebCore::ImageFrame::DisposeNotSpecified)
    194         , m_dataSize(0)
    195         , m_progressiveDisplay(false)
    196         , m_interlaced(false)
    197         , m_delayTime(0)
    198         , m_currentLzwBlock(0)
    199         , m_isComplete(false)
    200         , m_isHeaderDefined(false)
    201         , m_isDataSizeDefined(false)
    202     {
    203     }
    204 
    205     ~GIFFrameContext()
    206     {
    207     }
    208 
    209     void addLzwBlock(size_t position, size_t size)
    210     {
    211         m_lzwBlocks.append(GIFLZWBlock(position, size));
    212     }
    213 
    214     bool decode(const unsigned char* data, size_t length, WebCore::GIFImageDecoder* client, bool* frameDecoded);
    215 
    216     int frameId() const { return m_frameId; }
    217     void setRect(unsigned x, unsigned y, unsigned width, unsigned height)
    218     {
    219         m_xOffset = x;
    220         m_yOffset = y;
    221         m_width = width;
    222         m_height = height;
    223     }
    224     WebCore::IntRect frameRect() const { return WebCore::IntRect(m_xOffset, m_yOffset, m_width, m_height); }
    225     unsigned xOffset() const { return m_xOffset; }
    226     unsigned yOffset() const { return m_yOffset; }
    227     unsigned width() const { return m_width; }
    228     unsigned height() const { return m_height; }
    229     size_t transparentPixel() const { return m_transparentPixel; }
    230     void setTransparentPixel(size_t pixel) { m_transparentPixel = pixel; }
    231     WebCore::ImageFrame::FrameDisposalMethod disposalMethod() const { return m_disposalMethod; }
    232     void setDisposalMethod(WebCore::ImageFrame::FrameDisposalMethod method) { m_disposalMethod = method; }
    233     unsigned delayTime() const { return m_delayTime; }
    234     void setDelayTime(unsigned delay) { m_delayTime = delay; }
    235     bool isComplete() const { return m_isComplete; }
    236     void setComplete() { m_isComplete = true; }
    237     bool isHeaderDefined() const { return m_isHeaderDefined; }
    238     void setHeaderDefined() { m_isHeaderDefined = true; }
    239     bool isDataSizeDefined() const { return m_isDataSizeDefined; }
    240     int dataSize() const { return m_dataSize; }
    241     void setDataSize(int size)
    242     {
    243         m_dataSize = size;
    244         m_isDataSizeDefined = true;
    245     }
    246     bool progressiveDisplay() const { return m_progressiveDisplay; }
    247     void setProgressiveDisplay(bool progressiveDisplay) { m_progressiveDisplay = progressiveDisplay; }
    248     bool interlaced() const { return m_interlaced; }
    249     void setInterlaced(bool interlaced) { m_interlaced = interlaced; }
    250 
    251     void clearDecodeState() { m_lzwContext.clear(); }
    252     const GIFColorMap& localColorMap() const { return m_localColorMap; }
    253     GIFColorMap& localColorMap() { return m_localColorMap; }
    254 
    255 private:
    256     int m_frameId;
    257     unsigned m_xOffset;
    258     unsigned m_yOffset; // With respect to "screen" origin.
    259     unsigned m_width;
    260     unsigned m_height;
    261     size_t m_transparentPixel; // Index of transparent pixel. Value is notFound if there is no transparent pixel.
    262     WebCore::ImageFrame::FrameDisposalMethod m_disposalMethod; // Restore to background, leave in place, etc.
    263     int m_dataSize;
    264 
    265     bool m_progressiveDisplay; // If true, do Haeberli interlace hack.
    266     bool m_interlaced; // True, if scanlines arrive interlaced order.
    267 
    268     unsigned m_delayTime; // Display time, in milliseconds, for this image in a multi-image GIF.
    269 
    270     OwnPtr<GIFLZWContext> m_lzwContext;
    271     Vector<GIFLZWBlock> m_lzwBlocks; // LZW blocks for this frame.
    272     GIFColorMap m_localColorMap;
    273 
    274     size_t m_currentLzwBlock;
    275     bool m_isComplete;
    276     bool m_isHeaderDefined;
    277     bool m_isDataSizeDefined;
    278 };
    279 
    280 class GIFImageReader {
    281     WTF_MAKE_FAST_ALLOCATED;
    282 public:
    283     GIFImageReader(WebCore::GIFImageDecoder* client = 0)
    284         : m_client(client)
    285         , m_state(GIFType)
    286         , m_bytesToConsume(6) // Number of bytes for GIF type, either "GIF87a" or "GIF89a".
    287         , m_bytesRead(0)
    288         , m_version(0)
    289         , m_screenWidth(0)
    290         , m_screenHeight(0)
    291         , m_isGlobalColormapDefined(false)
    292         , m_loopCount(cLoopCountNotSeen)
    293         , m_parseCompleted(false)
    294     {
    295     }
    296 
    297     ~GIFImageReader()
    298     {
    299     }
    300 
    301     void setData(PassRefPtr<WebCore::SharedBuffer> data) { m_data = data; }
    302     bool parse(WebCore::GIFImageDecoder::GIFParseQuery);
    303     bool decode(size_t frameIndex);
    304 
    305     size_t imagesCount() const
    306     {
    307         if (m_frames.isEmpty())
    308             return 0;
    309 
    310         // This avoids counting an empty frame when the file is truncated right after
    311         // GIFControlExtension but before GIFImageHeader.
    312         // FIXME: This extra complexity is not necessary and we should just report m_frames.size().
    313         return m_frames.last()->isHeaderDefined() ? m_frames.size() : m_frames.size() - 1;
    314     }
    315     int loopCount() const { return m_loopCount; }
    316 
    317     const GIFColorMap& globalColorMap() const
    318     {
    319         return m_globalColorMap;
    320     }
    321 
    322     const GIFFrameContext* frameContext(size_t index) const
    323     {
    324         return index < m_frames.size() ? m_frames[index].get() : 0;
    325     }
    326 
    327     bool parseCompleted() const { return m_parseCompleted; }
    328 
    329     void clearDecodeState(size_t index) { m_frames[index]->clearDecodeState(); }
    330 
    331 private:
    332     bool parseData(size_t dataPosition, size_t len, WebCore::GIFImageDecoder::GIFParseQuery);
    333     void setRemainingBytes(size_t);
    334 
    335     const unsigned char* data(size_t dataPosition) const
    336     {
    337         return reinterpret_cast<const unsigned char*>(m_data->data()) + dataPosition;
    338     }
    339 
    340     void addFrameIfNecessary();
    341     bool currentFrameIsFirstFrame() const
    342     {
    343         return m_frames.isEmpty() || (m_frames.size() == 1u && !m_frames[0]->isComplete());
    344     }
    345 
    346     WebCore::GIFImageDecoder* m_client;
    347 
    348     // Parsing state machine.
    349     GIFState m_state; // Current decoder master state.
    350     size_t m_bytesToConsume; // Number of bytes to consume for next stage of parsing.
    351     size_t m_bytesRead; // Number of bytes processed.
    352 
    353     // Global (multi-image) state.
    354     int m_version; // Either 89 for GIF89 or 87 for GIF87.
    355     unsigned m_screenWidth; // Logical screen width & height.
    356     unsigned m_screenHeight;
    357     bool m_isGlobalColormapDefined;
    358     GIFColorMap m_globalColorMap;
    359     int m_loopCount; // Netscape specific extension block to control the number of animation loops a GIF renders.
    360 
    361     Vector<OwnPtr<GIFFrameContext> > m_frames;
    362 
    363     RefPtr<WebCore::SharedBuffer> m_data;
    364     bool m_parseCompleted;
    365 };
    366 
    367 #endif
    368