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 SkGifCodec;
44 
45 #include "SkCodec.h"
46 #include "SkCodecPriv.h"
47 #include "SkCodecAnimation.h"
48 #include "SkColorTable.h"
49 #include "SkData.h"
50 #include "SkImageInfo.h"
51 #include "SkStreamBuffer.h"
52 #include "../private/SkTArray.h"
53 #include <memory>
54 #include <vector>
55 
56 typedef SkTArray<unsigned char, true> SkGIFRow;
57 
58 
59 #define SK_MAX_DICTIONARY_ENTRY_BITS 12
60 #define SK_MAX_DICTIONARY_ENTRIES    4096 // 2^SK_MAX_DICTIONARY_ENTRY_BITS
61 #define SK_MAX_COLORS                256
62 #define SK_BYTES_PER_COLORMAP_ENTRY  3
63 
64 // List of possible parsing states.
65 enum SkGIFState {
66     SkGIFType,
67     SkGIFGlobalHeader,
68     SkGIFGlobalColormap,
69     SkGIFImageStart,
70     SkGIFImageHeader,
71     SkGIFImageColormap,
72     SkGIFImageBody,
73     SkGIFLZWStart,
74     SkGIFLZW,
75     SkGIFSubBlock,
76     SkGIFExtension,
77     SkGIFControlExtension,
78     SkGIFConsumeBlock,
79     SkGIFSkipBlock,
80     SkGIFDone,
81     SkGIFCommentExtension,
82     SkGIFApplicationExtension,
83     SkGIFNetscapeExtensionBlock,
84     SkGIFConsumeNetscapeExtension,
85     SkGIFConsumeComment
86 };
87 
88 struct SkGIFFrameContext;
89 class SkGIFColorMap;
90 
91 // LZW decoder state machine.
92 class SkGIFLZWContext final : public SkNoncopyable {
93 public:
SkGIFLZWContext(SkGifCodec * client,const SkGIFFrameContext * frameContext)94     SkGIFLZWContext(SkGifCodec* client, const SkGIFFrameContext* frameContext)
95         : codesize(0)
96         , codemask(0)
97         , clearCode(0)
98         , avail(0)
99         , oldcode(0)
100         , firstchar(0)
101         , bits(0)
102         , datum(0)
103         , ipass(0)
104         , irow(0)
105         , rowsRemaining(0)
106         , rowIter(0)
107         , m_client(client)
108         , m_frameContext(frameContext)
109     { }
110 
111     bool prepareToDecode();
112     bool outputRow(const unsigned char* rowBegin);
113     bool doLZW(const unsigned char* block, size_t bytesInBlock);
hasRemainingRows()114     bool hasRemainingRows() { return SkToBool(rowsRemaining); }
115 
116 private:
117     // LZW decoding states and output states.
118     int codesize;
119     int codemask;
120     int clearCode; // Codeword used to trigger dictionary reset.
121     int avail; // Index of next available slot in dictionary.
122     int oldcode;
123     unsigned char firstchar;
124     int bits; // Number of unread bits in "datum".
125     int datum; // 32-bit input buffer.
126     int ipass; // Interlace pass; Ranges 1-4 if interlaced.
127     size_t irow; // Current output row, starting at zero.
128     size_t rowsRemaining; // Rows remaining to be output.
129 
130     unsigned short prefix[SK_MAX_DICTIONARY_ENTRIES];
131     unsigned char suffix[SK_MAX_DICTIONARY_ENTRIES];
132     unsigned short suffixLength[SK_MAX_DICTIONARY_ENTRIES];
133     SkGIFRow rowBuffer; // Single scanline temporary buffer.
134     unsigned char* rowIter;
135 
136     SkGifCodec* const m_client;
137     const SkGIFFrameContext* m_frameContext;
138 };
139 
140 struct SkGIFLZWBlock {
141  public:
SkGIFLZWBlockSkGIFLZWBlock142   SkGIFLZWBlock(size_t position, size_t size)
143       : blockPosition(position), blockSize(size) {}
144 
145   size_t blockPosition;
146   size_t blockSize;
147 };
148 
149 class SkGIFColorMap final {
150 public:
151     static constexpr size_t kNotFound = static_cast<size_t>(-1);
152 
SkGIFColorMap()153     SkGIFColorMap()
154         : m_isDefined(false)
155         , m_position(0)
156         , m_colors(0)
157         , m_transPixel(kNotFound)
158         , m_packColorProc(nullptr)
159     {
160     }
161 
setNumColors(size_t colors)162     void setNumColors(size_t colors) {
163         SkASSERT(!m_colors);
164         SkASSERT(!m_position);
165 
166         m_colors = colors;
167     }
168 
setTablePosition(size_t position)169     void setTablePosition(size_t position) {
170         SkASSERT(!m_isDefined);
171 
172         m_position = position;
173         m_isDefined = true;
174     }
175 
numColors()176     size_t numColors() const { return m_colors; }
177 
isDefined()178     bool isDefined() const { return m_isDefined; }
179 
180     // Build RGBA table using the data stream.
181     sk_sp<SkColorTable> buildTable(SkStreamBuffer*, SkColorType dstColorType,
182                                    size_t transparentPixel) const;
183 
184 private:
185     bool m_isDefined;
186     size_t m_position;
187     size_t m_colors;
188     // Cached values. If these match on a new request, we can reuse m_table.
189     mutable size_t m_transPixel;
190     mutable PackColorProc m_packColorProc;
191     mutable sk_sp<SkColorTable> m_table;
192 };
193 
194 // LocalFrame output state machine.
195 struct SkGIFFrameContext : SkNoncopyable {
196 public:
SkGIFFrameContextSkGIFFrameContext197     SkGIFFrameContext(int id)
198         : m_frameId(id)
199         , m_xOffset(0)
200         , m_yOffset(0)
201         , m_width(0)
202         , m_height(0)
203         , m_transparentPixel(SkGIFColorMap::kNotFound)
204         , m_disposalMethod(SkCodecAnimation::Keep_DisposalMethod)
205         , m_requiredFrame(kUninitialized)
206         , m_dataSize(0)
207         , m_progressiveDisplay(false)
208         , m_interlaced(false)
209         , m_delayTime(0)
210         , m_currentLzwBlock(0)
211         , m_isComplete(false)
212         , m_isHeaderDefined(false)
213         , m_isDataSizeDefined(false)
214     {
215     }
216 
~SkGIFFrameContextSkGIFFrameContext217     ~SkGIFFrameContext()
218     {
219     }
220 
addLzwBlockSkGIFFrameContext221     void addLzwBlock(size_t position, size_t size)
222     {
223         m_lzwBlocks.push_back(SkGIFLZWBlock(position, size));
224     }
225 
226     bool decode(SkStreamBuffer*, SkGifCodec* client, bool* frameDecoded);
227 
frameIdSkGIFFrameContext228     int frameId() const { return m_frameId; }
setRectSkGIFFrameContext229     void setRect(unsigned x, unsigned y, unsigned width, unsigned height)
230     {
231         m_xOffset = x;
232         m_yOffset = y;
233         m_width = width;
234         m_height = height;
235     }
frameRectSkGIFFrameContext236     SkIRect frameRect() const { return SkIRect::MakeXYWH(m_xOffset, m_yOffset, m_width, m_height); }
xOffsetSkGIFFrameContext237     unsigned xOffset() const { return m_xOffset; }
yOffsetSkGIFFrameContext238     unsigned yOffset() const { return m_yOffset; }
widthSkGIFFrameContext239     unsigned width() const { return m_width; }
heightSkGIFFrameContext240     unsigned height() const { return m_height; }
transparentPixelSkGIFFrameContext241     size_t transparentPixel() const { return m_transparentPixel; }
setTransparentPixelSkGIFFrameContext242     void setTransparentPixel(size_t pixel) { m_transparentPixel = pixel; }
getDisposalMethodSkGIFFrameContext243     SkCodecAnimation::DisposalMethod getDisposalMethod() const { return m_disposalMethod; }
setDisposalMethodSkGIFFrameContext244     void setDisposalMethod(SkCodecAnimation::DisposalMethod disposalMethod) { m_disposalMethod = disposalMethod; }
245 
getRequiredFrameSkGIFFrameContext246     size_t getRequiredFrame() const {
247         SkASSERT(this->reachedStartOfData());
248         return m_requiredFrame;
249     }
setRequiredFrameSkGIFFrameContext250     void setRequiredFrame(size_t req) { m_requiredFrame = req; }
251 
delayTimeSkGIFFrameContext252     unsigned delayTime() const { return m_delayTime; }
setDelayTimeSkGIFFrameContext253     void setDelayTime(unsigned delay) { m_delayTime = delay; }
isCompleteSkGIFFrameContext254     bool isComplete() const { return m_isComplete; }
setCompleteSkGIFFrameContext255     void setComplete() { m_isComplete = true; }
isHeaderDefinedSkGIFFrameContext256     bool isHeaderDefined() const { return m_isHeaderDefined; }
setHeaderDefinedSkGIFFrameContext257     void setHeaderDefined() { m_isHeaderDefined = true; }
isDataSizeDefinedSkGIFFrameContext258     bool isDataSizeDefined() const { return m_isDataSizeDefined; }
dataSizeSkGIFFrameContext259     int dataSize() const { return m_dataSize; }
setDataSizeSkGIFFrameContext260     void setDataSize(int size)
261     {
262         m_dataSize = size;
263         m_isDataSizeDefined = true;
264     }
progressiveDisplaySkGIFFrameContext265     bool progressiveDisplay() const { return m_progressiveDisplay; }
setProgressiveDisplaySkGIFFrameContext266     void setProgressiveDisplay(bool progressiveDisplay) { m_progressiveDisplay = progressiveDisplay; }
interlacedSkGIFFrameContext267     bool interlaced() const { return m_interlaced; }
setInterlacedSkGIFFrameContext268     void setInterlaced(bool interlaced) { m_interlaced = interlaced; }
269 
clearDecodeStateSkGIFFrameContext270     void clearDecodeState() { m_lzwContext.reset(); }
localColorMapSkGIFFrameContext271     const SkGIFColorMap& localColorMap() const { return m_localColorMap; }
localColorMapSkGIFFrameContext272     SkGIFColorMap& localColorMap() { return m_localColorMap; }
273 
reachedStartOfDataSkGIFFrameContext274     bool reachedStartOfData() const { return m_requiredFrame != kUninitialized; }
275 
276 private:
277     static constexpr size_t kUninitialized = static_cast<size_t>(-2);
278 
279     int m_frameId;
280     unsigned m_xOffset;
281     unsigned m_yOffset; // With respect to "screen" origin.
282     unsigned m_width;
283     unsigned m_height;
284     size_t m_transparentPixel; // Index of transparent pixel. Value is kNotFound if there is no transparent pixel.
285     SkCodecAnimation::DisposalMethod m_disposalMethod; // Restore to background, leave in place, etc.
286     size_t m_requiredFrame;
287     int m_dataSize;
288 
289     bool m_progressiveDisplay; // If true, do Haeberli interlace hack.
290     bool m_interlaced; // True, if scanlines arrive interlaced order.
291 
292     unsigned m_delayTime; // Display time, in milliseconds, for this image in a multi-image GIF.
293 
294     std::unique_ptr<SkGIFLZWContext> m_lzwContext;
295     // LZW blocks for this frame.
296     std::vector<SkGIFLZWBlock> m_lzwBlocks;
297 
298     SkGIFColorMap m_localColorMap;
299 
300     size_t m_currentLzwBlock;
301     bool m_isComplete;
302     bool m_isHeaderDefined;
303     bool m_isDataSizeDefined;
304 };
305 
306 class SkGifImageReader final : public SkNoncopyable {
307 public:
308     // This takes ownership of stream.
SkGifImageReader(SkStream * stream)309     SkGifImageReader(SkStream* stream)
310         : m_client(nullptr)
311         , m_state(SkGIFType)
312         , m_bytesToConsume(6) // Number of bytes for GIF type, either "GIF87a" or "GIF89a".
313         , m_version(0)
314         , m_screenWidth(0)
315         , m_screenHeight(0)
316         , m_loopCount(cLoopCountNotSeen)
317         , m_streamBuffer(stream)
318         , m_parseCompleted(false)
319         , m_firstFrameHasAlpha(false)
320         , m_firstFrameSupportsIndex8(false)
321     {
322     }
323 
~SkGifImageReader()324     ~SkGifImageReader()
325     {
326     }
327 
setClient(SkGifCodec * client)328     void setClient(SkGifCodec* client) { m_client = client; }
329 
screenWidth()330     unsigned screenWidth() const { return m_screenWidth; }
screenHeight()331     unsigned screenHeight() const { return m_screenHeight; }
332 
333     // Option to pass to parse(). All enums are negative, because a non-negative value is used to
334     // indicate that the Reader should parse up to and including the frame indicated.
335     enum SkGIFParseQuery {
336         // Parse enough to determine the size. Note that this parses the first frame's header,
337         // since we may decide to expand based on the frame's dimensions.
338         SkGIFSizeQuery        = -1,
339         // Parse to the end, so we know about all frames.
340         SkGIFFrameCountQuery  = -2,
341         // Parse until we see the loop count.
342         SkGIFLoopCountQuery   = -3,
343     };
344 
345     // Parse incoming GIF data stream into internal data structures.
346     // Non-negative values are used to indicate to parse through that frame.
347     // Return true if parsing has progressed or there is not enough data.
348     // Return false if a fatal error is encountered.
349     bool parse(SkGIFParseQuery);
350 
351     // Decode the frame indicated by frameIndex.
352     // frameComplete will be set to true if the frame is completely decoded.
353     // The method returns false if there is an error.
354     bool decode(size_t frameIndex, bool* frameComplete);
355 
imagesCount()356     size_t imagesCount() const
357     {
358         // Report the first frame immediately, so the parser can stop when it
359         // sees the size on a SizeQuery.
360         const size_t frames = m_frames.size();
361         if (frames <= 1) {
362             return frames;
363         }
364 
365         // This avoids counting an empty frame when the file is truncated (or
366         // simply not yet complete) after receiving SkGIFControlExtension (and
367         // possibly SkGIFImageHeader) but before reading the color table. This
368         // ensures that we do not count a frame before we know its required
369         // frame.
370         return m_frames.back()->reachedStartOfData() ? frames : frames - 1;
371     }
loopCount()372     int loopCount() const {
373         if (cLoopCountNotSeen == m_loopCount) {
374             return 0;
375         }
376         return m_loopCount;
377     }
378 
globalColorMap()379     const SkGIFColorMap& globalColorMap() const
380     {
381         return m_globalColorMap;
382     }
383 
frameContext(size_t index)384     const SkGIFFrameContext* frameContext(size_t index) const
385     {
386         return index < m_frames.size() ? m_frames[index].get() : 0;
387     }
388 
clearDecodeState()389     void clearDecodeState() {
390         for (size_t index = 0; index < m_frames.size(); index++) {
391             m_frames[index]->clearDecodeState();
392         }
393     }
394 
395     // Return the color table for frame index (which may be the global color table).
396     sk_sp<SkColorTable> getColorTable(SkColorType dstColorType, size_t index);
397 
firstFrameHasAlpha()398     bool firstFrameHasAlpha() const { return m_firstFrameHasAlpha; }
399 
firstFrameSupportsIndex8()400     bool firstFrameSupportsIndex8() const { return m_firstFrameSupportsIndex8; }
401 
402 private:
403     // Requires that one byte has been buffered into m_streamBuffer.
getOneByte()404     unsigned char getOneByte() const {
405         return reinterpret_cast<const unsigned char*>(m_streamBuffer.get())[0];
406     }
407 
408     void addFrameIfNecessary();
409     // Must be called *after* the SkGIFFrameContext's color table (if any) has been parsed.
410     void setRequiredFrame(SkGIFFrameContext*);
411     // This method is sometimes called before creating a SkGIFFrameContext, so it cannot rely
412     // on SkGIFFrameContext::localColorMap().
413     bool hasTransparentPixel(size_t frameIndex, bool hasLocalColorMap, size_t localMapColors);
currentFrameIsFirstFrame()414     bool currentFrameIsFirstFrame() const
415     {
416         return m_frames.empty() || (m_frames.size() == 1u && !m_frames[0]->isComplete());
417     }
418 
419     // Unowned pointer
420     SkGifCodec* m_client;
421 
422     // Parsing state machine.
423     SkGIFState m_state; // Current decoder master state.
424     size_t m_bytesToConsume; // Number of bytes to consume for next stage of parsing.
425 
426     // Global (multi-image) state.
427     int m_version; // Either 89 for GIF89 or 87 for GIF87.
428     unsigned m_screenWidth; // Logical screen width & height.
429     unsigned m_screenHeight;
430     SkGIFColorMap m_globalColorMap;
431 
432     static constexpr int cLoopCountNotSeen = -2;
433     int m_loopCount; // Netscape specific extension block to control the number of animation loops a GIF renders.
434 
435     std::vector<std::unique_ptr<SkGIFFrameContext>> m_frames;
436 
437     SkStreamBuffer m_streamBuffer;
438     bool m_parseCompleted;
439 
440     // These values can be computed before we create a SkGIFFrameContext, so we
441     // store them here instead of on m_frames[0].
442     bool m_firstFrameHasAlpha;
443     bool m_firstFrameSupportsIndex8;
444 };
445 
446 #endif
447