blob: 56d20e927c5033e011fb8c20345dc90b1c2a9ace [file] [log] [blame]
msarett8c8f22a2015-04-01 06:58:48 -07001/*
2 * Copyright 2015 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
msarett8c8f22a2015-04-01 06:58:48 -07008#include "SkCodecPriv.h"
9#include "SkColorPriv.h"
10#include "SkColorTable.h"
msarett1a464672016-01-07 13:17:19 -080011#include "SkGifCodec.h"
msarett8c8f22a2015-04-01 06:58:48 -070012#include "SkStream.h"
13#include "SkSwizzler.h"
14#include "SkUtils.h"
15
msarett39b2d5a2016-02-17 08:26:31 -080016#include "gif_lib.h"
17
msarett8c8f22a2015-04-01 06:58:48 -070018/*
19 * Checks the start of the stream to see if the image is a gif
20 */
scroggodb30be22015-12-08 18:54:13 -080021bool SkGifCodec::IsGif(const void* buf, size_t bytesRead) {
22 if (bytesRead >= GIF_STAMP_LEN) {
msarett8c8f22a2015-04-01 06:58:48 -070023 if (memcmp(GIF_STAMP, buf, GIF_STAMP_LEN) == 0 ||
bungeman0153dea2015-08-27 16:43:42 -070024 memcmp(GIF87_STAMP, buf, GIF_STAMP_LEN) == 0 ||
25 memcmp(GIF89_STAMP, buf, GIF_STAMP_LEN) == 0)
26 {
msarett8c8f22a2015-04-01 06:58:48 -070027 return true;
28 }
29 }
30 return false;
31}
32
33/*
msarett8c8f22a2015-04-01 06:58:48 -070034 * Error function
35 */
bungeman0153dea2015-08-27 16:43:42 -070036static SkCodec::Result gif_error(const char* msg, SkCodec::Result result = SkCodec::kInvalidInput) {
msarett8c8f22a2015-04-01 06:58:48 -070037 SkCodecPrintf("Gif Error: %s\n", msg);
38 return result;
39}
40
41
42/*
43 * Read function that will be passed to gif_lib
44 */
bungeman0153dea2015-08-27 16:43:42 -070045static int32_t read_bytes_callback(GifFileType* fileType, GifByteType* out, int32_t size) {
msarett8c8f22a2015-04-01 06:58:48 -070046 SkStream* stream = (SkStream*) fileType->UserData;
47 return (int32_t) stream->read(out, size);
48}
49
50/*
51 * Open the gif file
52 */
53static GifFileType* open_gif(SkStream* stream) {
msarett4691d992016-02-16 13:16:39 -080054#if GIFLIB_MAJOR < 5
55 return DGifOpen(stream, read_bytes_callback);
56#else
halcanary96fcdcc2015-08-27 07:41:13 -070057 return DGifOpen(stream, read_bytes_callback, nullptr);
msarett4691d992016-02-16 13:16:39 -080058#endif
msarett8c8f22a2015-04-01 06:58:48 -070059}
60
msarett8c8f22a2015-04-01 06:58:48 -070061/*
62 * Check if a there is an index of the color table for a transparent pixel
63 */
64static uint32_t find_trans_index(const SavedImage& image) {
65 // If there is a transparent index specified, it will be contained in an
66 // extension block. We will loop through extension blocks in reverse order
67 // to check the most recent extension blocks first.
68 for (int32_t i = image.ExtensionBlockCount - 1; i >= 0; i--) {
69 // Get an extension block
70 const ExtensionBlock& extBlock = image.ExtensionBlocks[i];
71
72 // Specifically, we need to check for a graphics control extension,
73 // which may contain transparency information. Also, note that a valid
74 // graphics control extension is always four bytes. The fourth byte
75 // is the transparent index (if it exists), so we need at least four
76 // bytes.
bungeman0153dea2015-08-27 16:43:42 -070077 if (GRAPHICS_EXT_FUNC_CODE == extBlock.Function && extBlock.ByteCount >= 4) {
msarett8c8f22a2015-04-01 06:58:48 -070078 // Check the transparent color flag which indicates whether a
79 // transparent index exists. It is the least significant bit of
80 // the first byte of the extension block.
81 if (1 == (extBlock.Bytes[0] & 1)) {
msarett8c8f22a2015-04-01 06:58:48 -070082 // Use uint32_t to prevent sign extending
83 return extBlock.Bytes[3];
84 }
85
86 // There should only be one graphics control extension for the image frame
87 break;
88 }
89 }
90
91 // Use maximum unsigned int (surely an invalid index) to indicate that a valid
92 // index was not found.
93 return SK_MaxU32;
94}
95
msarette6dd0042015-10-09 11:07:34 -070096inline uint32_t ceil_div(uint32_t a, uint32_t b) {
msarettd02b99f2015-08-28 07:36:55 -070097 return (a + b - 1) / b;
98}
99
100/*
101 * Gets the output row corresponding to the encoded row for interlaced gifs
102 */
msarette6dd0042015-10-09 11:07:34 -0700103inline uint32_t get_output_row_interlaced(uint32_t encodedRow, uint32_t height) {
msarettd02b99f2015-08-28 07:36:55 -0700104 SkASSERT(encodedRow < height);
105 // First pass
106 if (encodedRow * 8 < height) {
107 return encodedRow * 8;
108 }
109 // Second pass
110 if (encodedRow * 4 < height) {
111 return 4 + 8 * (encodedRow - ceil_div(height, 8));
112 }
113 // Third pass
114 if (encodedRow * 2 < height) {
115 return 2 + 4 * (encodedRow - ceil_div(height, 4));
116 }
117 // Fourth pass
118 return 1 + 2 * (encodedRow - ceil_div(height, 2));
119}
120
msarett8c8f22a2015-04-01 06:58:48 -0700121/*
msarett10522ff2015-09-07 08:54:01 -0700122 * This function cleans up the gif object after the decode completes
123 * It is used in a SkAutoTCallIProc template
124 */
125void SkGifCodec::CloseGif(GifFileType* gif) {
msarett4691d992016-02-16 13:16:39 -0800126#if GIFLIB_MAJOR < 5 || (GIFLIB_MAJOR == 5 && GIFLIB_MINOR == 0)
127 DGifCloseFile(gif);
128#else
129 DGifCloseFile(gif, nullptr);
130#endif
msarett10522ff2015-09-07 08:54:01 -0700131}
132
133/*
134 * This function free extension data that has been saved to assist the image
135 * decoder
136 */
137void SkGifCodec::FreeExtension(SavedImage* image) {
138 if (NULL != image->ExtensionBlocks) {
msarett4691d992016-02-16 13:16:39 -0800139#if GIFLIB_MAJOR < 5
140 FreeExtension(image);
141#else
msarett10522ff2015-09-07 08:54:01 -0700142 GifFreeExtensions(&image->ExtensionBlockCount, &image->ExtensionBlocks);
msarett4691d992016-02-16 13:16:39 -0800143#endif
msarett10522ff2015-09-07 08:54:01 -0700144 }
145}
146
147/*
msarett438b2ad2015-04-09 12:43:10 -0700148 * Read enough of the stream to initialize the SkGifCodec.
149 * Returns a bool representing success or failure.
150 *
151 * @param codecOut
halcanary96fcdcc2015-08-27 07:41:13 -0700152 * If it returned true, and codecOut was not nullptr,
msarett438b2ad2015-04-09 12:43:10 -0700153 * codecOut will be set to a new SkGifCodec.
154 *
155 * @param gifOut
halcanary96fcdcc2015-08-27 07:41:13 -0700156 * If it returned true, and codecOut was nullptr,
157 * gifOut must be non-nullptr and gifOut will be set to a new
msarett438b2ad2015-04-09 12:43:10 -0700158 * GifFileType pointer.
159 *
160 * @param stream
161 * Deleted on failure.
162 * codecOut will take ownership of it in the case where we created a codec.
163 * Ownership is unchanged when we returned a gifOut.
164 *
165 */
166bool SkGifCodec::ReadHeader(SkStream* stream, SkCodec** codecOut, GifFileType** gifOut) {
167 SkAutoTDelete<SkStream> streamDeleter(stream);
168
169 // Read gif header, logical screen descriptor, and global color table
170 SkAutoTCallVProc<GifFileType, CloseGif> gif(open_gif(stream));
171
halcanary96fcdcc2015-08-27 07:41:13 -0700172 if (nullptr == gif) {
msarett438b2ad2015-04-09 12:43:10 -0700173 gif_error("DGifOpen failed.\n");
174 return false;
175 }
176
msarett10522ff2015-09-07 08:54:01 -0700177 // Read through gif extensions to get to the image data. Set the
178 // transparent index based on the extension data.
179 uint32_t transIndex;
180 SkCodec::Result result = ReadUpToFirstImage(gif, &transIndex);
181 if (kSuccess != result){
182 return false;
183 }
184
185 // Read the image descriptor
186 if (GIF_ERROR == DGifGetImageDesc(gif)) {
187 return false;
188 }
189 // If reading the image descriptor is successful, the image count will be
190 // incremented.
191 SkASSERT(gif->ImageCount >= 1);
192
halcanary96fcdcc2015-08-27 07:41:13 -0700193 if (nullptr != codecOut) {
msarett4aa02d82015-10-06 07:46:02 -0700194 SkISize size;
195 SkIRect frameRect;
196 if (!GetDimensions(gif, &size, &frameRect)) {
197 gif_error("Invalid gif size.\n");
msarettf724b992015-10-15 06:41:06 -0700198 return false;
msarett438b2ad2015-04-09 12:43:10 -0700199 }
msarett4aa02d82015-10-06 07:46:02 -0700200 bool frameIsSubset = (size != frameRect.size());
msarett438b2ad2015-04-09 12:43:10 -0700201
msarett10522ff2015-09-07 08:54:01 -0700202 // Determine the recommended alpha type. The transIndex might be valid if it less
203 // than 256. We are not certain that the index is valid until we process the color
204 // table, since some gifs have color tables with less than 256 colors. If
205 // there might be a valid transparent index, we must indicate that the image has
206 // alpha.
207 // In the case where we must support alpha, we have the option to set the
208 // suggested alpha type to kPremul or kUnpremul. Both are valid since the alpha
209 // component will always be 0xFF or the entire 32-bit pixel will be set to zero.
210 // We prefer kPremul because we support kPremul, and it is more efficient to use
211 // kPremul directly even when kUnpremul is supported.
212 SkAlphaType alphaType = (transIndex < 256) ? kPremul_SkAlphaType : kOpaque_SkAlphaType;
213
msarett438b2ad2015-04-09 12:43:10 -0700214 // Return the codec
215 // kIndex is the most natural color type for gifs, so we set this as
216 // the default.
msarett4aa02d82015-10-06 07:46:02 -0700217 SkImageInfo imageInfo = SkImageInfo::Make(size.width(), size.height(), kIndex_8_SkColorType,
218 alphaType);
219 *codecOut = new SkGifCodec(imageInfo, streamDeleter.detach(), gif.detach(), transIndex,
220 frameRect, frameIsSubset);
msarett438b2ad2015-04-09 12:43:10 -0700221 } else {
halcanary96fcdcc2015-08-27 07:41:13 -0700222 SkASSERT(nullptr != gifOut);
msarett438b2ad2015-04-09 12:43:10 -0700223 streamDeleter.detach();
224 *gifOut = gif.detach();
225 }
226 return true;
227}
228
229/*
msarett8c8f22a2015-04-01 06:58:48 -0700230 * Assumes IsGif was called and returned true
231 * Creates a gif decoder
232 * Reads enough of the stream to determine the image format
233 */
234SkCodec* SkGifCodec::NewFromStream(SkStream* stream) {
halcanary96fcdcc2015-08-27 07:41:13 -0700235 SkCodec* codec = nullptr;
236 if (ReadHeader(stream, &codec, nullptr)) {
msarett438b2ad2015-04-09 12:43:10 -0700237 return codec;
msarett8c8f22a2015-04-01 06:58:48 -0700238 }
halcanary96fcdcc2015-08-27 07:41:13 -0700239 return nullptr;
msarett8c8f22a2015-04-01 06:58:48 -0700240}
241
msarett10522ff2015-09-07 08:54:01 -0700242SkGifCodec::SkGifCodec(const SkImageInfo& srcInfo, SkStream* stream, GifFileType* gif,
msarett4aa02d82015-10-06 07:46:02 -0700243 uint32_t transIndex, const SkIRect& frameRect, bool frameIsSubset)
msarett8c8f22a2015-04-01 06:58:48 -0700244 : INHERITED(srcInfo, stream)
245 , fGif(gif)
msarett10522ff2015-09-07 08:54:01 -0700246 , fSrcBuffer(new uint8_t[this->getInfo().width()])
msarettf724b992015-10-15 06:41:06 -0700247 , fFrameRect(frameRect)
msarett10522ff2015-09-07 08:54:01 -0700248 // If it is valid, fTransIndex will be used to set fFillIndex. We don't know if
249 // fTransIndex is valid until we process the color table, since fTransIndex may
250 // be greater than the size of the color table.
251 , fTransIndex(transIndex)
252 // Default fFillIndex is 0. We will overwrite this if fTransIndex is valid, or if
253 // there is a valid background color.
254 , fFillIndex(0)
msarett4aa02d82015-10-06 07:46:02 -0700255 , fFrameIsSubset(frameIsSubset)
msarett10522ff2015-09-07 08:54:01 -0700256 , fSwizzler(NULL)
msarettf724b992015-10-15 06:41:06 -0700257 , fColorTable(NULL)
msarett8c8f22a2015-04-01 06:58:48 -0700258{}
259
scroggob427db12015-08-12 07:24:13 -0700260bool SkGifCodec::onRewind() {
halcanary96fcdcc2015-08-27 07:41:13 -0700261 GifFileType* gifOut = nullptr;
262 if (!ReadHeader(this->stream(), nullptr, &gifOut)) {
scroggob427db12015-08-12 07:24:13 -0700263 return false;
264 }
265
halcanary96fcdcc2015-08-27 07:41:13 -0700266 SkASSERT(nullptr != gifOut);
scroggob427db12015-08-12 07:24:13 -0700267 fGif.reset(gifOut);
268 return true;
269}
270
msarett10522ff2015-09-07 08:54:01 -0700271SkCodec::Result SkGifCodec::ReadUpToFirstImage(GifFileType* gif, uint32_t* transIndex) {
msarett8c8f22a2015-04-01 06:58:48 -0700272 // Use this as a container to hold information about any gif extension
273 // blocks. This generally stores transparency and animation instructions.
274 SavedImage saveExt;
275 SkAutoTCallVProc<SavedImage, FreeExtension> autoFreeExt(&saveExt);
halcanary96fcdcc2015-08-27 07:41:13 -0700276 saveExt.ExtensionBlocks = nullptr;
msarett8c8f22a2015-04-01 06:58:48 -0700277 saveExt.ExtensionBlockCount = 0;
278 GifByteType* extData;
msarett8c8f22a2015-04-01 06:58:48 -0700279 int32_t extFunction;
msarett8c8f22a2015-04-01 06:58:48 -0700280
281 // We will loop over components of gif images until we find an image. Once
282 // we find an image, we will decode and return it. While many gif files
283 // contain more than one image, we will simply decode the first image.
msarett8c8f22a2015-04-01 06:58:48 -0700284 GifRecordType recordType;
285 do {
286 // Get the current record type
msarett10522ff2015-09-07 08:54:01 -0700287 if (GIF_ERROR == DGifGetRecordType(gif, &recordType)) {
msarett8c8f22a2015-04-01 06:58:48 -0700288 return gif_error("DGifGetRecordType failed.\n", kInvalidInput);
289 }
msarett8c8f22a2015-04-01 06:58:48 -0700290 switch (recordType) {
291 case IMAGE_DESC_RECORD_TYPE: {
msarett10522ff2015-09-07 08:54:01 -0700292 *transIndex = find_trans_index(saveExt);
msarett4aa02d82015-10-06 07:46:02 -0700293
msarett8c8f22a2015-04-01 06:58:48 -0700294 // FIXME: Gif files may have multiple images stored in a single
295 // file. This is most commonly used to enable
296 // animations. Since we are leaving animated gifs as a
297 // TODO, we will return kSuccess after decoding the
298 // first image in the file. This is the same behavior
299 // as SkImageDecoder_libgif.
300 //
301 // Most times this works pretty well, but sometimes it
302 // doesn't. For example, I have an animated test image
303 // where the first image in the file is 1x1, but the
304 // subsequent images are meaningful. This currently
305 // displays the 1x1 image, which is not ideal. Right
306 // now I am leaving this as an issue that will be
307 // addressed when we implement animated gifs.
308 //
309 // It is also possible (not explicitly disallowed in the
310 // specification) that gif files provide multiple
311 // images in a single file that are all meant to be
312 // displayed in the same frame together. I will
313 // currently leave this unimplemented until I find a
314 // test case that expects this behavior.
315 return kSuccess;
316 }
msarett8c8f22a2015-04-01 06:58:48 -0700317 // Extensions are used to specify special properties of the image
318 // such as transparency or animation.
319 case EXTENSION_RECORD_TYPE:
320 // Read extension data
msarett10522ff2015-09-07 08:54:01 -0700321 if (GIF_ERROR == DGifGetExtension(gif, &extFunction, &extData)) {
bungeman0153dea2015-08-27 16:43:42 -0700322 return gif_error("Could not get extension.\n", kIncompleteInput);
msarett8c8f22a2015-04-01 06:58:48 -0700323 }
324
325 // Create an extension block with our data
halcanary96fcdcc2015-08-27 07:41:13 -0700326 while (nullptr != extData) {
msarett8c8f22a2015-04-01 06:58:48 -0700327 // Add a single block
msarett4691d992016-02-16 13:16:39 -0800328
329#if GIFLIB_MAJOR < 5
330 if (AddExtensionBlock(&saveExt, extData[0],
331 &extData[1]) == GIF_ERROR) {
332#else
bungeman0153dea2015-08-27 16:43:42 -0700333 if (GIF_ERROR == GifAddExtensionBlock(&saveExt.ExtensionBlockCount,
334 &saveExt.ExtensionBlocks,
msarett4691d992016-02-16 13:16:39 -0800335 extFunction, extData[0], &extData[1])) {
336#endif
bungeman0153dea2015-08-27 16:43:42 -0700337 return gif_error("Could not add extension block.\n", kIncompleteInput);
msarett8c8f22a2015-04-01 06:58:48 -0700338 }
339 // Move to the next block
msarett10522ff2015-09-07 08:54:01 -0700340 if (GIF_ERROR == DGifGetExtensionNext(gif, &extData)) {
bungeman0153dea2015-08-27 16:43:42 -0700341 return gif_error("Could not get next extension.\n", kIncompleteInput);
msarett8c8f22a2015-04-01 06:58:48 -0700342 }
msarett8c8f22a2015-04-01 06:58:48 -0700343 }
344 break;
345
346 // Signals the end of the gif file
347 case TERMINATE_RECORD_TYPE:
348 break;
349
350 default:
msarett10522ff2015-09-07 08:54:01 -0700351 // DGifGetRecordType returns an error if the record type does
352 // not match one of the above cases. This should not be
353 // reached.
msarett8c8f22a2015-04-01 06:58:48 -0700354 SkASSERT(false);
355 break;
356 }
357 } while (TERMINATE_RECORD_TYPE != recordType);
358
bungeman0153dea2015-08-27 16:43:42 -0700359 return gif_error("Could not find any images to decode in gif file.\n", kInvalidInput);
msarett8c8f22a2015-04-01 06:58:48 -0700360}
msarett10522ff2015-09-07 08:54:01 -0700361
msarett4aa02d82015-10-06 07:46:02 -0700362bool SkGifCodec::GetDimensions(GifFileType* gif, SkISize* size, SkIRect* frameRect) {
363 // Get the encoded dimension values
364 SavedImage* image = &gif->SavedImages[gif->ImageCount - 1];
365 const GifImageDesc& desc = image->ImageDesc;
366 int frameLeft = desc.Left;
367 int frameTop = desc.Top;
368 int frameWidth = desc.Width;
369 int frameHeight = desc.Height;
370 int width = gif->SWidth;
371 int height = gif->SHeight;
372
373 // Ensure that the decode dimensions are large enough to contain the frame
374 width = SkTMax(width, frameWidth + frameLeft);
375 height = SkTMax(height, frameHeight + frameTop);
376
377 // All of these dimensions should be positive, as they are encoded as unsigned 16-bit integers.
378 // It is unclear why giflib casts them to ints. We will go ahead and check that they are
379 // in fact positive.
380 if (frameLeft < 0 || frameTop < 0 || frameWidth < 0 || frameHeight < 0 || width <= 0 ||
381 height <= 0) {
msarett10522ff2015-09-07 08:54:01 -0700382 return false;
383 }
384
msarett4aa02d82015-10-06 07:46:02 -0700385 frameRect->setXYWH(frameLeft, frameTop, frameWidth, frameHeight);
386 size->set(width, height);
msarett10522ff2015-09-07 08:54:01 -0700387 return true;
388}
389
390void SkGifCodec::initializeColorTable(const SkImageInfo& dstInfo, SkPMColor* inputColorPtr,
391 int* inputColorCount) {
392 // Set up our own color table
393 const uint32_t maxColors = 256;
394 SkPMColor colorPtr[256];
395 if (NULL != inputColorCount) {
396 // We set the number of colors to maxColors in order to ensure
397 // safe memory accesses. Otherwise, an invalid pixel could
398 // access memory outside of our color table array.
399 *inputColorCount = maxColors;
400 }
401
402 // Get local color table
403 ColorMapObject* colorMap = fGif->Image.ColorMap;
404 // If there is no local color table, use the global color table
405 if (NULL == colorMap) {
406 colorMap = fGif->SColorMap;
407 }
408
409 uint32_t colorCount = 0;
410 if (NULL != colorMap) {
411 colorCount = colorMap->ColorCount;
412 // giflib guarantees these properties
413 SkASSERT(colorCount == (unsigned) (1 << (colorMap->BitsPerPixel)));
414 SkASSERT(colorCount <= 256);
415 for (uint32_t i = 0; i < colorCount; i++) {
416 colorPtr[i] = SkPackARGB32(0xFF, colorMap->Colors[i].Red,
417 colorMap->Colors[i].Green, colorMap->Colors[i].Blue);
418 }
419 }
420
msarett10522ff2015-09-07 08:54:01 -0700421 // Fill in the color table for indices greater than color count.
422 // This allows for predictable, safe behavior.
msarett7f7ec202016-03-01 12:12:27 -0800423 if (colorCount > 0) {
424 // Gifs have the option to specify the color at a single index of the color
425 // table as transparent. If the transparent index is greater than the
426 // colorCount, we know that there is no valid transparent color in the color
427 // table. If there is not valid transparent index, we will try to use the
428 // backgroundIndex as the fill index. If the backgroundIndex is also not
429 // valid, we will let fFillIndex default to 0 (it is set to zero in the
430 // constructor). This behavior is not specified but matches
431 // SkImageDecoder_libgif.
432 uint32_t backgroundIndex = fGif->SBackGroundColor;
433 if (fTransIndex < colorCount) {
434 colorPtr[fTransIndex] = SK_ColorTRANSPARENT;
435 fFillIndex = fTransIndex;
436 } else if (backgroundIndex < colorCount) {
437 fFillIndex = backgroundIndex;
438 }
439
440 for (uint32_t i = colorCount; i < maxColors; i++) {
441 colorPtr[i] = colorPtr[fFillIndex];
442 }
443 } else {
444 sk_memset32(colorPtr, 0xFF000000, maxColors);
msarett10522ff2015-09-07 08:54:01 -0700445 }
446
447 fColorTable.reset(new SkColorTable(colorPtr, maxColors));
448 copy_color_table(dstInfo, this->fColorTable, inputColorPtr, inputColorCount);
449}
450
451SkCodec::Result SkGifCodec::prepareToDecode(const SkImageInfo& dstInfo, SkPMColor* inputColorPtr,
452 int* inputColorCount, const Options& opts) {
msarett10522ff2015-09-07 08:54:01 -0700453 // Check for valid input parameters
msarett10522ff2015-09-07 08:54:01 -0700454 if (!conversion_possible(dstInfo, this->getInfo())) {
455 return gif_error("Cannot convert input type to output type.\n",
456 kInvalidConversion);
457 }
458
msarett10522ff2015-09-07 08:54:01 -0700459 // Initialize color table and copy to the client if necessary
460 this->initializeColorTable(dstInfo, inputColorPtr, inputColorCount);
msarett5af4e0b2015-11-17 11:18:03 -0800461
msarettb30d6982016-02-15 10:18:45 -0800462 this->initializeSwizzler(dstInfo, opts);
463 return kSuccess;
msarett10522ff2015-09-07 08:54:01 -0700464}
465
msarettb30d6982016-02-15 10:18:45 -0800466void SkGifCodec::initializeSwizzler(const SkImageInfo& dstInfo, const Options& opts) {
msarett10522ff2015-09-07 08:54:01 -0700467 const SkPMColor* colorPtr = get_color_ptr(fColorTable.get());
msarett5af4e0b2015-11-17 11:18:03 -0800468 const SkIRect* frameRect = fFrameIsSubset ? &fFrameRect : nullptr;
469 fSwizzler.reset(SkSwizzler::CreateSwizzler(SkSwizzler::kIndex, colorPtr, dstInfo, opts,
470 frameRect));
msarettb30d6982016-02-15 10:18:45 -0800471 SkASSERT(fSwizzler);
msarett10522ff2015-09-07 08:54:01 -0700472}
473
msarette6dd0042015-10-09 11:07:34 -0700474bool SkGifCodec::readRow() {
475 return GIF_ERROR != DGifGetLine(fGif, fSrcBuffer.get(), fFrameRect.width());
msarett10522ff2015-09-07 08:54:01 -0700476}
477
478/*
479 * Initiates the gif decode
480 */
481SkCodec::Result SkGifCodec::onGetPixels(const SkImageInfo& dstInfo,
482 void* dst, size_t dstRowBytes,
483 const Options& opts,
484 SkPMColor* inputColorPtr,
msarette6dd0042015-10-09 11:07:34 -0700485 int* inputColorCount,
486 int* rowsDecoded) {
msarett10522ff2015-09-07 08:54:01 -0700487 Result result = this->prepareToDecode(dstInfo, inputColorPtr, inputColorCount, opts);
488 if (kSuccess != result) {
489 return result;
490 }
491
492 if (dstInfo.dimensions() != this->getInfo().dimensions()) {
493 return gif_error("Scaling not supported.\n", kInvalidScale);
494 }
495
496 // Initialize the swizzler
497 if (fFrameIsSubset) {
msarett10522ff2015-09-07 08:54:01 -0700498 // Fill the background
scroggoc5560be2016-02-03 09:42:42 -0800499 SkSampler::Fill(dstInfo, dst, dstRowBytes, this->getFillValue(dstInfo.colorType()),
msarette6dd0042015-10-09 11:07:34 -0700500 opts.fZeroInitialized);
msarett10522ff2015-09-07 08:54:01 -0700501 }
502
msarette6dd0042015-10-09 11:07:34 -0700503 // Iterate over rows of the input
msarett5af4e0b2015-11-17 11:18:03 -0800504 for (int y = fFrameRect.top(); y < fFrameRect.bottom(); y++) {
msarette6dd0042015-10-09 11:07:34 -0700505 if (!this->readRow()) {
506 *rowsDecoded = y;
507 return gif_error("Could not decode line.\n", kIncompleteInput);
msarett10522ff2015-09-07 08:54:01 -0700508 }
msarette6dd0042015-10-09 11:07:34 -0700509 void* dstRow = SkTAddOffset<void>(dst, dstRowBytes * this->outputScanline(y));
510 fSwizzler->swizzle(dstRow, fSrcBuffer.get());
msarett10522ff2015-09-07 08:54:01 -0700511 }
512 return kSuccess;
513}
514
msarette6dd0042015-10-09 11:07:34 -0700515// FIXME: This is similar to the implementation for bmp and png. Can we share more code or
516// possibly make this non-virtual?
scroggoc5560be2016-02-03 09:42:42 -0800517uint32_t SkGifCodec::onGetFillValue(SkColorType colorType) const {
msarette6dd0042015-10-09 11:07:34 -0700518 const SkPMColor* colorPtr = get_color_ptr(fColorTable.get());
519 return get_color_table_fill_value(colorType, colorPtr, fFillIndex);
520}
521
scroggo46c57472015-09-30 08:57:13 -0700522SkCodec::Result SkGifCodec::onStartScanlineDecode(const SkImageInfo& dstInfo,
523 const SkCodec::Options& opts, SkPMColor inputColorPtr[], int* inputColorCount) {
msarett5af4e0b2015-11-17 11:18:03 -0800524 return this->prepareToDecode(dstInfo, inputColorPtr, inputColorCount, this->options());
scroggo46c57472015-09-30 08:57:13 -0700525}
msarett10522ff2015-09-07 08:54:01 -0700526
msarett72261c02015-11-19 15:29:26 -0800527void SkGifCodec::handleScanlineFrame(int count, int* rowsBeforeFrame, int* rowsInFrame) {
528 if (fFrameIsSubset) {
msarettcb0d5c92015-12-03 12:23:43 -0800529 const int currRow = this->currScanline();
msarett72261c02015-11-19 15:29:26 -0800530
531 // The number of rows that remain to be skipped before reaching rows that we
532 // actually must decode into.
533 // This must be at least zero. We also make sure that it is less than or
534 // equal to count, since we will skip at most count rows.
535 *rowsBeforeFrame = SkTMin(count, SkTMax(0, fFrameRect.top() - currRow));
536
537 // Rows left to decode once we reach the start of the frame.
538 const int rowsLeft = count - *rowsBeforeFrame;
539
540 // Count the number of that extend beyond the bottom of the frame. We do not
541 // need to decode into these rows.
542 const int rowsAfterFrame = SkTMax(0, currRow + rowsLeft - fFrameRect.bottom());
543
544 // Set the actual number of source rows that we need to decode.
545 *rowsInFrame = rowsLeft - rowsAfterFrame;
546 } else {
547 *rowsBeforeFrame = 0;
548 *rowsInFrame = count;
549 }
550}
551
msarette6dd0042015-10-09 11:07:34 -0700552int SkGifCodec::onGetScanlines(void* dst, int count, size_t rowBytes) {
msarett72261c02015-11-19 15:29:26 -0800553 int rowsBeforeFrame;
554 int rowsInFrame;
555 this->handleScanlineFrame(count, &rowsBeforeFrame, &rowsInFrame);
556
scroggo46c57472015-09-30 08:57:13 -0700557 if (fFrameIsSubset) {
558 // Fill the requested rows
msarette6dd0042015-10-09 11:07:34 -0700559 SkImageInfo fillInfo = this->dstInfo().makeWH(this->dstInfo().width(), count);
scroggoc5560be2016-02-03 09:42:42 -0800560 uint32_t fillValue = this->onGetFillValue(this->dstInfo().colorType());
msarett5af4e0b2015-11-17 11:18:03 -0800561 fSwizzler->fill(fillInfo, dst, rowBytes, fillValue, this->options().fZeroInitialized);
scroggo46c57472015-09-30 08:57:13 -0700562
msarett72261c02015-11-19 15:29:26 -0800563 // Start to write pixels at the start of the image frame
msarett4aa02d82015-10-06 07:46:02 -0700564 dst = SkTAddOffset<void>(dst, rowBytes * rowsBeforeFrame);
msarett10522ff2015-09-07 08:54:01 -0700565 }
566
msarette6dd0042015-10-09 11:07:34 -0700567 for (int i = 0; i < rowsInFrame; i++) {
568 if (!this->readRow()) {
569 return i + rowsBeforeFrame;
msarett10522ff2015-09-07 08:54:01 -0700570 }
scroggo46c57472015-09-30 08:57:13 -0700571 fSwizzler->swizzle(dst, fSrcBuffer.get());
572 dst = SkTAddOffset<void>(dst, rowBytes);
msarett10522ff2015-09-07 08:54:01 -0700573 }
msarette6dd0042015-10-09 11:07:34 -0700574
575 return count;
msarett10522ff2015-09-07 08:54:01 -0700576}
scroggo46c57472015-09-30 08:57:13 -0700577
msarett72261c02015-11-19 15:29:26 -0800578bool SkGifCodec::onSkipScanlines(int count) {
579 int rowsBeforeFrame;
580 int rowsInFrame;
581 this->handleScanlineFrame(count, &rowsBeforeFrame, &rowsInFrame);
582
583 for (int i = 0; i < rowsInFrame; i++) {
584 if (!this->readRow()) {
585 return false;
586 }
587 }
588
589 return true;
590}
591
scroggo46c57472015-09-30 08:57:13 -0700592SkCodec::SkScanlineOrder SkGifCodec::onGetScanlineOrder() const {
593 if (fGif->Image.Interlace) {
594 return kOutOfOrder_SkScanlineOrder;
scroggo46c57472015-09-30 08:57:13 -0700595 }
msarette6dd0042015-10-09 11:07:34 -0700596 return kTopDown_SkScanlineOrder;
scroggo46c57472015-09-30 08:57:13 -0700597}
598
msarette6dd0042015-10-09 11:07:34 -0700599int SkGifCodec::onOutputScanline(int inputScanline) const {
scroggo46c57472015-09-30 08:57:13 -0700600 if (fGif->Image.Interlace) {
msarette6dd0042015-10-09 11:07:34 -0700601 if (inputScanline < fFrameRect.top() || inputScanline >= fFrameRect.bottom()) {
602 return inputScanline;
msarett4aa02d82015-10-06 07:46:02 -0700603 }
msarett5af4e0b2015-11-17 11:18:03 -0800604 return get_output_row_interlaced(inputScanline - fFrameRect.top(), fFrameRect.height()) +
605 fFrameRect.top();
scroggo46c57472015-09-30 08:57:13 -0700606 }
msarette6dd0042015-10-09 11:07:34 -0700607 return inputScanline;
scroggo46c57472015-09-30 08:57:13 -0700608}