blob: 9b15151f1066d876500cd980caad2f936af2980f [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
8#include "SkCodec_libgif.h"
9#include "SkCodecPriv.h"
10#include "SkColorPriv.h"
11#include "SkColorTable.h"
12#include "SkGifInterlaceIter.h"
13#include "SkStream.h"
14#include "SkSwizzler.h"
15#include "SkUtils.h"
16
17/*
18 * Checks the start of the stream to see if the image is a gif
19 */
20bool SkGifCodec::IsGif(SkStream* stream) {
21 char buf[GIF_STAMP_LEN];
22 if (stream->read(buf, GIF_STAMP_LEN) == GIF_STAMP_LEN) {
23 if (memcmp(GIF_STAMP, buf, GIF_STAMP_LEN) == 0 ||
24 memcmp(GIF87_STAMP, buf, GIF_STAMP_LEN) == 0 ||
25 memcmp(GIF89_STAMP, buf, GIF_STAMP_LEN) == 0) {
26 return true;
27 }
28 }
29 return false;
30}
31
32/*
33 * Warning reporting function
34 */
35static void gif_warning(const char* msg) {
36 SkCodecPrintf("Gif Warning: %s\n", msg);
37}
38
39/*
40 * Error function
41 */
42static SkCodec::Result gif_error(const char* msg,
43 SkCodec::Result result = SkCodec::kInvalidInput) {
44 SkCodecPrintf("Gif Error: %s\n", msg);
45 return result;
46}
47
48
49/*
50 * Read function that will be passed to gif_lib
51 */
52static int32_t read_bytes_callback(GifFileType* fileType, GifByteType* out,
53 int32_t size) {
54 SkStream* stream = (SkStream*) fileType->UserData;
55 return (int32_t) stream->read(out, size);
56}
57
58/*
59 * Open the gif file
60 */
61static GifFileType* open_gif(SkStream* stream) {
62#if GIFLIB_MAJOR < 5
63 return DGifOpen(stream, read_bytes_callback);
64#else
65 return DGifOpen(stream, read_bytes_callback, NULL);
66#endif
67}
68
69 /*
70 * This function cleans up the gif object after the decode completes
71 * It is used in a SkAutoTCallIProc template
72 */
msarett438b2ad2015-04-09 12:43:10 -070073void SkGifCodec::CloseGif(GifFileType* gif) {
msarett8c8f22a2015-04-01 06:58:48 -070074#if GIFLIB_MAJOR < 5 || (GIFLIB_MAJOR == 5 && GIFLIB_MINOR == 0)
msarett438b2ad2015-04-09 12:43:10 -070075 DGifCloseFile(gif);
msarett8c8f22a2015-04-01 06:58:48 -070076#else
msarett438b2ad2015-04-09 12:43:10 -070077 DGifCloseFile(gif, NULL);
msarett8c8f22a2015-04-01 06:58:48 -070078#endif
79}
80
81/*
82 * This function free extension data that has been saved to assist the image
83 * decoder
84 */
85void SkGifCodec::FreeExtension(SavedImage* image) {
86 if (NULL != image->ExtensionBlocks) {
87#if GIFLIB_MAJOR < 5
88 FreeExtension(image);
89#else
90 GifFreeExtensions(&image->ExtensionBlockCount, &image->ExtensionBlocks);
91#endif
92 }
93}
94
95/*
96 * Check if a there is an index of the color table for a transparent pixel
97 */
98static uint32_t find_trans_index(const SavedImage& image) {
99 // If there is a transparent index specified, it will be contained in an
100 // extension block. We will loop through extension blocks in reverse order
101 // to check the most recent extension blocks first.
102 for (int32_t i = image.ExtensionBlockCount - 1; i >= 0; i--) {
103 // Get an extension block
104 const ExtensionBlock& extBlock = image.ExtensionBlocks[i];
105
106 // Specifically, we need to check for a graphics control extension,
107 // which may contain transparency information. Also, note that a valid
108 // graphics control extension is always four bytes. The fourth byte
109 // is the transparent index (if it exists), so we need at least four
110 // bytes.
111 if (GRAPHICS_EXT_FUNC_CODE == extBlock.Function &&
112 extBlock.ByteCount >= 4) {
113
114 // Check the transparent color flag which indicates whether a
115 // transparent index exists. It is the least significant bit of
116 // the first byte of the extension block.
117 if (1 == (extBlock.Bytes[0] & 1)) {
118
119 // Use uint32_t to prevent sign extending
120 return extBlock.Bytes[3];
121 }
122
123 // There should only be one graphics control extension for the image frame
124 break;
125 }
126 }
127
128 // Use maximum unsigned int (surely an invalid index) to indicate that a valid
129 // index was not found.
130 return SK_MaxU32;
131}
132
133/*
msarett438b2ad2015-04-09 12:43:10 -0700134 * Read enough of the stream to initialize the SkGifCodec.
135 * Returns a bool representing success or failure.
136 *
137 * @param codecOut
138 * If it returned true, and codecOut was not NULL,
139 * codecOut will be set to a new SkGifCodec.
140 *
141 * @param gifOut
142 * If it returned true, and codecOut was NULL,
143 * gifOut must be non-NULL and gifOut will be set to a new
144 * GifFileType pointer.
145 *
146 * @param stream
147 * Deleted on failure.
148 * codecOut will take ownership of it in the case where we created a codec.
149 * Ownership is unchanged when we returned a gifOut.
150 *
151 */
152bool SkGifCodec::ReadHeader(SkStream* stream, SkCodec** codecOut, GifFileType** gifOut) {
153 SkAutoTDelete<SkStream> streamDeleter(stream);
154
155 // Read gif header, logical screen descriptor, and global color table
156 SkAutoTCallVProc<GifFileType, CloseGif> gif(open_gif(stream));
157
158 if (NULL == gif) {
159 gif_error("DGifOpen failed.\n");
160 return false;
161 }
162
163 if (NULL != codecOut) {
164 // Get fields from header
165 const int32_t width = gif->SWidth;
166 const int32_t height = gif->SHeight;
167 if (width <= 0 || height <= 0) {
168 gif_error("Invalid dimensions.\n");
169 return false;
170 }
171
172 // Return the codec
173 // kIndex is the most natural color type for gifs, so we set this as
174 // the default.
175 // Many gifs specify a color table index for transparent pixels. Every
176 // other pixel is guaranteed to be opaque. Despite this, because of the
177 // possiblity of transparent pixels, we cannot assume that the image is
178 // opaque. We have the option to set the alpha type as kPremul or
179 // kUnpremul. Both are valid since the alpha component will always be
180 // 0xFF or the entire 32-bit pixel will be set to zero. We prefer
181 // kPremul because we support kPremul, and it is more efficient to
182 // use kPremul directly even when kUnpremul is supported.
183 const SkImageInfo& imageInfo = SkImageInfo::Make(width, height,
184 kIndex_8_SkColorType, kPremul_SkAlphaType);
185 *codecOut = SkNEW_ARGS(SkGifCodec, (imageInfo, streamDeleter.detach(), gif.detach()));
186 } else {
187 SkASSERT(NULL != gifOut);
188 streamDeleter.detach();
189 *gifOut = gif.detach();
190 }
191 return true;
192}
193
194/*
msarett8c8f22a2015-04-01 06:58:48 -0700195 * Assumes IsGif was called and returned true
196 * Creates a gif decoder
197 * Reads enough of the stream to determine the image format
198 */
199SkCodec* SkGifCodec::NewFromStream(SkStream* stream) {
msarett438b2ad2015-04-09 12:43:10 -0700200 SkCodec* codec = NULL;
201 if (ReadHeader(stream, &codec, NULL)) {
202 return codec;
msarett8c8f22a2015-04-01 06:58:48 -0700203 }
msarett438b2ad2015-04-09 12:43:10 -0700204 return NULL;
msarett8c8f22a2015-04-01 06:58:48 -0700205}
206
207SkGifCodec::SkGifCodec(const SkImageInfo& srcInfo, SkStream* stream,
208 GifFileType* gif)
209 : INHERITED(srcInfo, stream)
210 , fGif(gif)
211{}
212
213/*
214 * Checks if the conversion between the input image and the requested output
215 * image has been implemented
216 */
217static bool conversion_possible(const SkImageInfo& dst,
218 const SkImageInfo& src) {
219 // Ensure that the profile type is unchanged
220 if (dst.profileType() != src.profileType()) {
221 return false;
222 }
223
224 // Check for supported color and alpha types
225 switch (dst.colorType()) {
226 case kN32_SkColorType:
227 return kPremul_SkAlphaType == dst.alphaType() ||
228 kUnpremul_SkAlphaType == dst.alphaType();
msarett438b2ad2015-04-09 12:43:10 -0700229 case kIndex_8_SkColorType:
230 return kPremul_SkAlphaType == dst.alphaType() ||
231 kUnpremul_SkAlphaType == dst.alphaType();
msarett8c8f22a2015-04-01 06:58:48 -0700232 default:
233 return false;
234 }
235}
236
237/*
238 * Initiates the gif decode
239 */
240SkCodec::Result SkGifCodec::onGetPixels(const SkImageInfo& dstInfo,
241 void* dst, size_t dstRowBytes,
msarett438b2ad2015-04-09 12:43:10 -0700242 const Options& opts,
243 SkPMColor* inputColorPtr,
244 int* inputColorCount) {
245 // Rewind if necessary
246 SkCodec::RewindState rewindState = this->rewindIfNeeded();
247 if (rewindState == kCouldNotRewind_RewindState) {
msarett8c8f22a2015-04-01 06:58:48 -0700248 return kCouldNotRewind;
msarett438b2ad2015-04-09 12:43:10 -0700249 } else if (rewindState == kRewound_RewindState) {
250 GifFileType* gifOut = NULL;
251 if (!ReadHeader(this->stream(), NULL, &gifOut)) {
252 return kCouldNotRewind;
253 } else {
254 SkASSERT(NULL != gifOut);
255 fGif.reset(gifOut);
256 }
msarett8c8f22a2015-04-01 06:58:48 -0700257 }
msarett438b2ad2015-04-09 12:43:10 -0700258
259 // Check for valid input parameters
scroggob636b452015-07-22 07:16:20 -0700260 if (opts.fSubset) {
261 // Subsets are not supported.
262 return kUnimplemented;
263 }
msarett8c8f22a2015-04-01 06:58:48 -0700264 if (dstInfo.dimensions() != this->getInfo().dimensions()) {
265 return gif_error("Scaling not supported.\n", kInvalidScale);
266 }
267 if (!conversion_possible(dstInfo, this->getInfo())) {
268 return gif_error("Cannot convert input type to output type.\n",
269 kInvalidConversion);
270 }
271
272 // 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);
276 saveExt.ExtensionBlocks = NULL;
277 saveExt.ExtensionBlockCount = 0;
278 GifByteType* extData;
279#if GIFLIB_MAJOR >= 5
280 int32_t extFunction;
281#endif
282
283 // We will loop over components of gif images until we find an image. Once
284 // we find an image, we will decode and return it. While many gif files
285 // contain more than one image, we will simply decode the first image.
286 const int32_t width = dstInfo.width();
287 const int32_t height = dstInfo.height();
288 GifRecordType recordType;
289 do {
290 // Get the current record type
291 if (GIF_ERROR == DGifGetRecordType(fGif, &recordType)) {
292 return gif_error("DGifGetRecordType failed.\n", kInvalidInput);
293 }
294
295 switch (recordType) {
296 case IMAGE_DESC_RECORD_TYPE: {
297 // Read the image descriptor
298 if (GIF_ERROR == DGifGetImageDesc(fGif)) {
299 return gif_error("DGifGetImageDesc failed.\n",
300 kInvalidInput);
301 }
302
303 // If reading the image descriptor is successful, the image
304 // count will be incremented
305 SkASSERT(fGif->ImageCount >= 1);
306 SavedImage* image = &fGif->SavedImages[fGif->ImageCount - 1];
307
308 // Process the descriptor
309 const GifImageDesc& desc = image->ImageDesc;
310 int32_t imageLeft = desc.Left;
311 int32_t imageTop = desc.Top;
312 int32_t innerWidth = desc.Width;
313 int32_t innerHeight = desc.Height;
314 // Fail on non-positive dimensions
315 if (innerWidth <= 0 || innerHeight <= 0) {
316 return gif_error("Invalid dimensions for inner image.\n",
317 kInvalidInput);
318 }
319 // Treat the following cases as warnings and try to fix
320 if (innerWidth > width) {
321 gif_warning("Inner image too wide, shrinking.\n");
322 innerWidth = width;
323 imageLeft = 0;
324 } else if (imageLeft + innerWidth > width) {
325 gif_warning("Shifting inner image to left to fit.\n");
326 imageLeft = width - innerWidth;
327 } else if (imageLeft < 0) {
328 gif_warning("Shifting image to right to fit\n");
329 imageLeft = 0;
330 }
331 if (innerHeight > height) {
332 gif_warning("Inner image too tall, shrinking.\n");
333 innerHeight = height;
334 imageTop = 0;
335 } else if (imageTop + innerHeight > height) {
336 gif_warning("Shifting inner image up to fit.\n");
337 imageTop = height - innerHeight;
338 } else if (imageTop < 0) {
339 gif_warning("Shifting image down to fit\n");
340 imageTop = 0;
341 }
342
msarett438b2ad2015-04-09 12:43:10 -0700343 // Create a color table to store colors the giflib colorMap
344 SkPMColor alternateColorPtr[256];
345 SkPMColor* colorTable;
346 SkColorType dstColorType = dstInfo.colorType();
347 if (kIndex_8_SkColorType == dstColorType) {
348 SkASSERT(NULL != inputColorPtr);
349 SkASSERT(NULL != inputColorCount);
msarett438b2ad2015-04-09 12:43:10 -0700350 colorTable = inputColorPtr;
351 } else {
352 colorTable = alternateColorPtr;
353 }
354
msarett8c8f22a2015-04-01 06:58:48 -0700355 // Set up the color table
356 uint32_t colorCount = 0;
357 // Allocate maximum storage to deal with invalid indices safely
358 const uint32_t maxColors = 256;
msarett8c8f22a2015-04-01 06:58:48 -0700359 ColorMapObject* colorMap = fGif->Image.ColorMap;
360 // If there is no local color table, use the global color table
361 if (NULL == colorMap) {
362 colorMap = fGif->SColorMap;
363 }
364 if (NULL != colorMap) {
365 colorCount = colorMap->ColorCount;
366 SkASSERT(colorCount ==
367 (unsigned) (1 << (colorMap->BitsPerPixel)));
368 SkASSERT(colorCount <= 256);
369 for (uint32_t i = 0; i < colorCount; i++) {
370 colorTable[i] = SkPackARGB32(0xFF,
371 colorMap->Colors[i].Red,
372 colorMap->Colors[i].Green,
373 colorMap->Colors[i].Blue);
374 }
375 }
376
377 // This is used to fill unspecified pixels in the image data.
378 uint32_t fillIndex = fGif->SBackGroundColor;
msarett8c8f22a2015-04-01 06:58:48 -0700379 ZeroInitialized zeroInit = opts.fZeroInitialized;
380
381 // Gifs have the option to specify the color at a single
382 // index of the color table as transparent.
383 {
384 // Get the transparent index. If the return value of this
385 // function is greater than the colorCount, we know that
386 // there is no valid transparent color in the color table.
387 // This occurs if there is no graphics control extension or
388 // if the index specified by the graphics control extension
389 // is out of range.
390 uint32_t transIndex = find_trans_index(saveExt);
391
msarett8c8f22a2015-04-01 06:58:48 -0700392 if (transIndex < colorCount) {
393 colorTable[transIndex] = SK_ColorTRANSPARENT;
394 // If there is a transparent index, we also use this as
395 // the fill index.
396 fillIndex = transIndex;
msarett8c8f22a2015-04-01 06:58:48 -0700397 } else if (fillIndex >= colorCount) {
398 // If the fill index is invalid, we default to 0. This
399 // behavior is unspecified but matches SkImageDecoder.
400 fillIndex = 0;
401 }
402 }
403
msarett438b2ad2015-04-09 12:43:10 -0700404 // Check if we can skip filling the background of the image. We
405 // may be able to if the memory is zero initialized.
406 bool skipBackground =
407 ((kN32_SkColorType == dstColorType && colorTable[fillIndex] == 0) ||
408 (kIndex_8_SkColorType == dstColorType && fillIndex == 0)) &&
409 kYes_ZeroInitialized == zeroInit;
410
411
msarett8c8f22a2015-04-01 06:58:48 -0700412 // Fill in the color table for indices greater than color count.
413 // This allows for predictable, safe behavior.
414 for (uint32_t i = colorCount; i < maxColors; i++) {
415 colorTable[i] = colorTable[fillIndex];
416 }
417
418 // Check if image is only a subset of the image frame
419 SkAutoTDelete<SkSwizzler> swizzler(NULL);
420 if (innerWidth < width || innerHeight < height) {
421
422 // Modify the destination info
423 const SkImageInfo subsetDstInfo =
424 dstInfo.makeWH(innerWidth, innerHeight);
425
426 // Fill the destination with the fill color
427 // FIXME: This may not be the behavior that we want for
428 // animated gifs where we draw on top of the
429 // previous frame.
msarett438b2ad2015-04-09 12:43:10 -0700430 if (!skipBackground) {
msarett3c309db2015-04-10 14:36:48 -0700431 SkSwizzler::Fill(dst, dstInfo, dstRowBytes, height, fillIndex, colorTable);
msarett8c8f22a2015-04-01 06:58:48 -0700432 }
433
434 // Modify the dst pointer
435 const int32_t dstBytesPerPixel =
436 SkColorTypeBytesPerPixel(dstColorType);
437 void* subsetDst = SkTAddOffset<void*>(dst,
438 dstRowBytes * imageTop +
439 dstBytesPerPixel * imageLeft);
440
441 // Create the subset swizzler
442 swizzler.reset(SkSwizzler::CreateSwizzler(
443 SkSwizzler::kIndex, colorTable, subsetDstInfo,
444 subsetDst, dstRowBytes, zeroInit));
445 } else {
446 // Create the fully dimensional swizzler
447 swizzler.reset(SkSwizzler::CreateSwizzler(
448 SkSwizzler::kIndex, colorTable, dstInfo, dst,
449 dstRowBytes, zeroInit));
450 }
451
452 // Stores output from dgiflib and input to the swizzler
453 SkAutoTDeleteArray<uint8_t>
454 buffer(SkNEW_ARRAY(uint8_t, innerWidth));
455
456 // Check the interlace flag and iterate over rows of the input
457 if (fGif->Image.Interlace) {
458 // In interlace mode, the rows of input are rearranged in
459 // the output image. We use an iterator to take care of
460 // the rearranging.
461 SkGifInterlaceIter iter(innerHeight);
462 for (int32_t y = 0; y < innerHeight; y++) {
463 if (GIF_ERROR == DGifGetLine(fGif, buffer.get(),
464 innerWidth)) {
465 // Recover from error by filling remainder of image
msarett438b2ad2015-04-09 12:43:10 -0700466 if (!skipBackground) {
msarett8c8f22a2015-04-01 06:58:48 -0700467 memset(buffer.get(), fillIndex, innerWidth);
468 for (; y < innerHeight; y++) {
469 swizzler->next(buffer.get(), iter.nextY());
470 }
471 }
472 return gif_error(SkStringPrintf(
473 "Could not decode line %d of %d.\n",
474 y, height - 1).c_str(), kIncompleteInput);
475 }
476 swizzler->next(buffer.get(), iter.nextY());
477 }
478 } else {
479 // Standard mode
480 for (int32_t y = 0; y < innerHeight; y++) {
481 if (GIF_ERROR == DGifGetLine(fGif, buffer.get(),
482 innerWidth)) {
msarett438b2ad2015-04-09 12:43:10 -0700483 if (!skipBackground) {
msarett3c309db2015-04-10 14:36:48 -0700484 SkSwizzler::Fill(swizzler->getDstRow(), dstInfo, dstRowBytes,
485 innerHeight - y, fillIndex, colorTable);
msarett8c8f22a2015-04-01 06:58:48 -0700486 }
487 return gif_error(SkStringPrintf(
488 "Could not decode line %d of %d.\n",
489 y, height - 1).c_str(), kIncompleteInput);
490 }
491 swizzler->next(buffer.get());
492 }
493 }
494
495 // FIXME: Gif files may have multiple images stored in a single
496 // file. This is most commonly used to enable
497 // animations. Since we are leaving animated gifs as a
498 // TODO, we will return kSuccess after decoding the
499 // first image in the file. This is the same behavior
500 // as SkImageDecoder_libgif.
501 //
502 // Most times this works pretty well, but sometimes it
503 // doesn't. For example, I have an animated test image
504 // where the first image in the file is 1x1, but the
505 // subsequent images are meaningful. This currently
506 // displays the 1x1 image, which is not ideal. Right
507 // now I am leaving this as an issue that will be
508 // addressed when we implement animated gifs.
509 //
510 // It is also possible (not explicitly disallowed in the
511 // specification) that gif files provide multiple
512 // images in a single file that are all meant to be
513 // displayed in the same frame together. I will
514 // currently leave this unimplemented until I find a
515 // test case that expects this behavior.
516 return kSuccess;
517 }
518
519 // Extensions are used to specify special properties of the image
520 // such as transparency or animation.
521 case EXTENSION_RECORD_TYPE:
522 // Read extension data
523#if GIFLIB_MAJOR < 5
524 if (GIF_ERROR ==
525 DGifGetExtension(fGif, &saveExt.Function, &extData)) {
526#else
527 if (GIF_ERROR ==
528 DGifGetExtension(fGif, &extFunction, &extData)) {
529#endif
530 return gif_error("Could not get extension.\n",
531 kIncompleteInput);
532 }
533
534 // Create an extension block with our data
535 while (NULL != extData) {
536 // Add a single block
537#if GIFLIB_MAJOR < 5
538 if (GIF_ERROR == AddExtensionBlock(&saveExt, extData[0],
539 &extData[1])) {
540#else
541 if (GIF_ERROR ==
542 GifAddExtensionBlock(&saveExt.ExtensionBlockCount,
543 &saveExt.ExtensionBlocks, extFunction, extData[0],
544 &extData[1])) {
545#endif
546 return gif_error("Could not add extension block.\n",
547 kIncompleteInput);
548 }
549 // Move to the next block
550 if (GIF_ERROR == DGifGetExtensionNext(fGif, &extData)) {
551 return gif_error("Could not get next extension.\n",
552 kIncompleteInput);
553 }
554#if GIFLIB_MAJOR < 5
555 saveExt.Function = 0;
556#endif
557 }
558 break;
559
560 // Signals the end of the gif file
561 case TERMINATE_RECORD_TYPE:
562 break;
563
564 default:
565 // giflib returns an error code if the record type is not known.
566 // We should catch this error immediately.
567 SkASSERT(false);
568 break;
569 }
570 } while (TERMINATE_RECORD_TYPE != recordType);
571
572 return gif_error("Could not find any images to decode in gif file.\n",
573 kInvalidInput);
574}