• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 SkGifImageReader_h
39 #define SkGifImageReader_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 class SkLibGifCodec;
44 
45 #include "include/codec/SkCodec.h"
46 #include "include/codec/SkCodecAnimation.h"
47 #include "include/core/SkData.h"
48 #include "include/core/SkImageInfo.h"
49 #include "include/private/SkTArray.h"
50 #include "src/codec/SkCodecPriv.h"
51 #include "src/codec/SkColorTable.h"
52 #include "src/codec/SkFrameHolder.h"
53 #include "src/codec/SkStreamBuffer.h"
54 
55 #include <array>
56 #include <memory>
57 
58 typedef SkTArray<unsigned char, true> SkGIFRow;
59 
60 
61 #define SK_MAX_DICTIONARY_ENTRY_BITS 12
62 #define SK_MAX_DICTIONARY_ENTRIES    4096 // 2^SK_MAX_DICTIONARY_ENTRY_BITS
63 #define SK_MAX_COLORS                256
64 #define SK_BYTES_PER_COLORMAP_ENTRY  3
65 #define SK_DICTIONARY_WORD_SIZE      8
66 
67 // List of possible parsing states.
68 enum SkGIFState {
69     SkGIFType,
70     SkGIFGlobalHeader,
71     SkGIFGlobalColormap,
72     SkGIFImageStart,
73     SkGIFImageHeader,
74     SkGIFImageColormap,
75     SkGIFImageBody,
76     SkGIFLZWStart,
77     SkGIFLZW,
78     SkGIFSubBlock,
79     SkGIFExtension,
80     SkGIFControlExtension,
81     SkGIFConsumeBlock,
82     SkGIFSkipBlock,
83     SkGIFDone,
84     SkGIFCommentExtension,
85     SkGIFApplicationExtension,
86     SkGIFNetscapeExtensionBlock,
87     SkGIFConsumeNetscapeExtension,
88     SkGIFConsumeComment
89 };
90 
91 class SkGIFFrameContext;
92 class SkGIFColorMap;
93 
94 // LZW decoder state machine.
95 class SkGIFLZWContext final : public SkNoncopyable {
96 public:
SkGIFLZWContext(SkLibGifCodec * client,const SkGIFFrameContext * frameContext)97     SkGIFLZWContext(SkLibGifCodec* client, const SkGIFFrameContext* frameContext)
98         : codesize(0)
99         , codemask(0)
100         , clearCode(0)
101         , avail(0)
102         , oldcode(0)
103         , bits(0)
104         , datum(0)
105         , ipass(0)
106         , irow(0)
107         , rowsRemaining(0)
108         , rowIter(nullptr)
109         , m_client(client)
110         , m_frameContext(frameContext)
111     { }
112 
113     bool prepareToDecode();
114     void outputRow(const unsigned char* rowBegin);
115     bool doLZW(const unsigned char* block, size_t bytesInBlock);
hasRemainingRows()116     bool hasRemainingRows() { return SkToBool(rowsRemaining); }
117 
118 private:
119     // LZW decoding states and output states.
120     int codesize;
121     int codemask;
122     int clearCode; // Codeword used to trigger dictionary reset.
123     int avail; // Index of next available slot in dictionary.
124     int oldcode;
125     int bits; // Number of unread bits in "datum".
126     int datum; // 32-bit input buffer.
127     int ipass; // Interlace pass; Ranges 1-4 if interlaced.
128     size_t irow; // Current output row, starting at zero.
129     size_t rowsRemaining; // Rows remaining to be output.
130 
131     unsigned short prefix[SK_MAX_DICTIONARY_ENTRIES];
132     std::array<std::array<unsigned char, SK_DICTIONARY_WORD_SIZE>,
133                 SK_MAX_DICTIONARY_ENTRIES> suffix;
134     unsigned short suffixLength[SK_MAX_DICTIONARY_ENTRIES];
135     SkGIFRow rowBuffer; // Single scanline temporary buffer.
136     unsigned char* rowIter;
137 
138     SkLibGifCodec* const m_client;
139     const SkGIFFrameContext* m_frameContext;
140 };
141 
142 struct SkGIFLZWBlock {
143  public:
SkGIFLZWBlockSkGIFLZWBlock144   SkGIFLZWBlock(size_t position, size_t size)
145       : blockPosition(position), blockSize(size) {}
146 
147   size_t blockPosition;
148   size_t blockSize;
149 };
150 
151 class SkGIFColorMap final {
152 public:
153     static constexpr int kNotFound = -1;
154 
SkGIFColorMap()155     SkGIFColorMap()
156         : m_isDefined(false)
157         , m_position(0)
158         , m_colors(0)
159         , m_transPixel(kNotFound)
160         , m_packColorProc(nullptr)
161     {
162     }
163 
setNumColors(int colors)164     void setNumColors(int colors) {
165         SkASSERT(!m_colors);
166         SkASSERT(!m_position);
167 
168         m_colors = colors;
169     }
170 
setTablePosition(size_t position)171     void setTablePosition(size_t position) {
172         SkASSERT(!m_isDefined);
173 
174         m_position = position;
175         m_isDefined = true;
176     }
177 
numColors()178     int numColors() const { return m_colors; }
179 
isDefined()180     bool isDefined() const { return m_isDefined; }
181 
182     // Build RGBA table using the data stream.
183     sk_sp<SkColorTable> buildTable(SkStreamBuffer*, SkColorType dstColorType,
184                                    int transparentPixel) const;
185 
186 private:
187     bool m_isDefined;
188     size_t m_position;
189     int m_colors;
190     // Cached values. If these match on a new request, we can reuse m_table.
191     mutable int m_transPixel;
192     mutable PackColorProc m_packColorProc;
193     mutable sk_sp<SkColorTable> m_table;
194 };
195 
196 class SkGifImageReader;
197 
198 // LocalFrame output state machine.
199 class SkGIFFrameContext : public SkFrame {
200 public:
SkGIFFrameContext(int id)201     SkGIFFrameContext(int id)
202         : INHERITED(id)
203         , m_transparentPixel(SkGIFColorMap::kNotFound)
204         , m_dataSize(0)
205         , m_progressiveDisplay(false)
206         , m_interlaced(false)
207         , m_currentLzwBlock(0)
208         , m_isComplete(false)
209         , m_isHeaderDefined(false)
210         , m_isDataSizeDefined(false)
211     {
212     }
213 
~SkGIFFrameContext()214     ~SkGIFFrameContext() override
215     {
216     }
217 
addLzwBlock(size_t position,size_t size)218     void addLzwBlock(size_t position, size_t size)
219     {
220         m_lzwBlocks.emplace_back(position, size);
221     }
222 
223     bool decode(SkStreamBuffer*, SkLibGifCodec* client, bool* frameDecoded);
224 
transparentPixel()225     int transparentPixel() const { return m_transparentPixel; }
setTransparentPixel(int pixel)226     void setTransparentPixel(int pixel) { m_transparentPixel = pixel; }
227 
isComplete()228     bool isComplete() const { return m_isComplete; }
setComplete()229     void setComplete() { m_isComplete = true; }
isHeaderDefined()230     bool isHeaderDefined() const { return m_isHeaderDefined; }
setHeaderDefined()231     void setHeaderDefined() { m_isHeaderDefined = true; }
isDataSizeDefined()232     bool isDataSizeDefined() const { return m_isDataSizeDefined; }
dataSize()233     int dataSize() const { return m_dataSize; }
setDataSize(int size)234     void setDataSize(int size)
235     {
236         m_dataSize = size;
237         m_isDataSizeDefined = true;
238     }
progressiveDisplay()239     bool progressiveDisplay() const { return m_progressiveDisplay; }
setProgressiveDisplay(bool progressiveDisplay)240     void setProgressiveDisplay(bool progressiveDisplay) { m_progressiveDisplay = progressiveDisplay; }
interlaced()241     bool interlaced() const { return m_interlaced; }
setInterlaced(bool interlaced)242     void setInterlaced(bool interlaced) { m_interlaced = interlaced; }
243 
clearDecodeState()244     void clearDecodeState() { m_lzwContext.reset(); }
localColorMap()245     const SkGIFColorMap& localColorMap() const { return m_localColorMap; }
localColorMap()246     SkGIFColorMap& localColorMap() { return m_localColorMap; }
247 
248 protected:
249     SkEncodedInfo::Alpha onReportedAlpha() const override;
250 
251 private:
252     int m_transparentPixel; // Index of transparent pixel. Value is kNotFound if there is no transparent pixel.
253     int m_dataSize;
254 
255     bool m_progressiveDisplay; // If true, do Haeberli interlace hack.
256     bool m_interlaced; // True, if scanlines arrive interlaced order.
257 
258     std::unique_ptr<SkGIFLZWContext> m_lzwContext;
259     // LZW blocks for this frame.
260     SkTArray<SkGIFLZWBlock> m_lzwBlocks;
261 
262     SkGIFColorMap m_localColorMap;
263 
264     int m_currentLzwBlock;
265     bool m_isComplete;
266     bool m_isHeaderDefined;
267     bool m_isDataSizeDefined;
268 
269     typedef SkFrame INHERITED;
270 };
271 
272 class SkGifImageReader final : public SkFrameHolder {
273 public:
274     // This takes ownership of stream.
SkGifImageReader(std::unique_ptr<SkStream> stream)275     SkGifImageReader(std::unique_ptr<SkStream> stream)
276         : m_client(nullptr)
277         , m_state(SkGIFType)
278         , m_bytesToConsume(6) // Number of bytes for GIF type, either "GIF87a" or "GIF89a".
279         , m_version(0)
280         , m_loopCount(cLoopCountNotSeen)
281         , m_streamBuffer(std::move(stream))
282         , m_parseCompleted(false)
283         , m_firstFrameHasAlpha(false)
284     {
285     }
286 
~SkGifImageReader()287     ~SkGifImageReader() override
288     {
289     }
290 
setClient(SkLibGifCodec * client)291     void setClient(SkLibGifCodec* client) { m_client = client; }
292 
293     // Option to pass to parse(). All enums are negative, because a non-negative value is used to
294     // indicate that the Reader should parse up to and including the frame indicated.
295     enum SkGIFParseQuery {
296         // Parse enough to determine the size. Note that this parses the first frame's header,
297         // since we may decide to expand based on the frame's dimensions.
298         SkGIFSizeQuery        = -1,
299         // Parse to the end, so we know about all frames.
300         SkGIFFrameCountQuery  = -2,
301         // Parse until we see the loop count.
302         SkGIFLoopCountQuery   = -3,
303     };
304 
305     // Parse incoming GIF data stream into internal data structures.
306     // Non-negative values are used to indicate to parse through that frame.
307     SkCodec::Result parse(int);
308 
309     // Decode the frame indicated by frameIndex.
310     // frameComplete will be set to true if the frame is completely decoded.
311     // The method returns false if there is an error.
312     bool decode(int frameIndex, bool* frameComplete);
313 
imagesCount()314     int imagesCount() const
315     {
316         const int frames = m_frames.count();
317         if (!frames) {
318             return 0;
319         }
320 
321         // This avoids counting an empty frame when the file is truncated (or
322         // simply not yet complete) after receiving SkGIFControlExtension (and
323         // possibly SkGIFImageHeader) but before reading the color table. This
324         // ensures that we do not count a frame before we know its required
325         // frame.
326         return m_frames.back()->reachedStartOfData() ? frames : frames - 1;
327     }
loopCount()328     int loopCount() const {
329         if (cLoopCountNotSeen == m_loopCount) {
330             return 0;
331         }
332         return m_loopCount;
333     }
334 
globalColorMap()335     const SkGIFColorMap& globalColorMap() const
336     {
337         return m_globalColorMap;
338     }
339 
frameContext(int index)340     const SkGIFFrameContext* frameContext(int index) const
341     {
342         return index >= 0 && index < m_frames.count()
343                 ? m_frames[index].get() : nullptr;
344     }
345 
clearDecodeState()346     void clearDecodeState() {
347         for (int index = 0; index < m_frames.count(); index++) {
348             m_frames[index]->clearDecodeState();
349         }
350     }
351 
352     // Return the color table for frame index (which may be the global color table).
353     sk_sp<SkColorTable> getColorTable(SkColorType dstColorType, int index);
354 
firstFrameHasAlpha()355     bool firstFrameHasAlpha() const { return m_firstFrameHasAlpha; }
356 
357 protected:
onGetFrame(int i)358     const SkFrame* onGetFrame(int i) const override {
359         return static_cast<const SkFrame*>(this->frameContext(i));
360     }
361 
362 private:
363     // Requires that one byte has been buffered into m_streamBuffer.
getOneByte()364     unsigned char getOneByte() const {
365         return reinterpret_cast<const unsigned char*>(m_streamBuffer.get())[0];
366     }
367 
368     void addFrameIfNecessary();
currentFrameIsFirstFrame()369     bool currentFrameIsFirstFrame() const
370     {
371         return m_frames.empty() || (m_frames.count() == 1 && !m_frames[0]->isComplete());
372     }
373 
374     // Unowned pointer
375     SkLibGifCodec* m_client;
376 
377     // Parsing state machine.
378     SkGIFState m_state; // Current decoder master state.
379     size_t m_bytesToConsume; // Number of bytes to consume for next stage of parsing.
380 
381     // Global (multi-image) state.
382     int m_version; // Either 89 for GIF89 or 87 for GIF87.
383     SkGIFColorMap m_globalColorMap;
384 
385     static constexpr int cLoopCountNotSeen = -2;
386     int m_loopCount; // Netscape specific extension block to control the number of animation loops a GIF renders.
387 
388     SkTArray<std::unique_ptr<SkGIFFrameContext>> m_frames;
389 
390     SkStreamBuffer m_streamBuffer;
391     bool m_parseCompleted;
392 
393     // This value can be computed before we create a SkGIFFrameContext, so we
394     // store it here instead of on m_frames[0].
395     bool m_firstFrameHasAlpha;
396 };
397 
398 #endif
399