OLD | NEW |
(Empty) | |
| 1 /* |
| 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 */ |
| 20 bool 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 */ |
| 35 static void gif_warning(const char* msg) { |
| 36 SkCodecPrintf("Gif Warning: %s\n", msg); |
| 37 } |
| 38 |
| 39 /* |
| 40 * Error function |
| 41 */ |
| 42 static 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 */ |
| 52 static 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 */ |
| 61 static 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 */ |
| 73 int32_t SkGifCodec::CloseGif(GifFileType* gif) { |
| 74 #if GIFLIB_MAJOR < 5 || (GIFLIB_MAJOR == 5 && GIFLIB_MINOR == 0) |
| 75 return DGifCloseFile(gif); |
| 76 #else |
| 77 return DGifCloseFile(gif, NULL); |
| 78 #endif |
| 79 } |
| 80 |
| 81 /* |
| 82 * This function free extension data that has been saved to assist the image |
| 83 * decoder |
| 84 */ |
| 85 void 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 */ |
| 98 static 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 val
id |
| 129 // index was not found. |
| 130 return SK_MaxU32; |
| 131 } |
| 132 |
| 133 /* |
| 134 * Assumes IsGif was called and returned true |
| 135 * Creates a gif decoder |
| 136 * Reads enough of the stream to determine the image format |
| 137 */ |
| 138 SkCodec* SkGifCodec::NewFromStream(SkStream* stream) { |
| 139 // Read gif header, logical screen descriptor, and global color table |
| 140 SkAutoTCallIProc<GifFileType, CloseGif> gif(open_gif(stream)); |
| 141 |
| 142 if (NULL == gif) { |
| 143 gif_error("DGifOpen failed.\n"); |
| 144 return NULL; |
| 145 } |
| 146 |
| 147 // Get fields from header |
| 148 const int32_t width = gif->SWidth; |
| 149 const int32_t height = gif->SHeight; |
| 150 if (width <= 0 || height <= 0) { |
| 151 gif_error("Invalid dimensions.\n"); |
| 152 return NULL; |
| 153 } |
| 154 |
| 155 // Return the codec |
| 156 // kIndex is the most natural color type for gifs, so we set this as |
| 157 // the default. |
| 158 // Many gifs specify a color table index for transparent pixels. Every |
| 159 // other pixel is guaranteed to be opaque. Despite this, because of the |
| 160 // possiblity of transparent pixels, we cannot assume that the image is |
| 161 // opaque. We have the option to set the alpha type as kPremul or |
| 162 // kUnpremul. Both are valid since the alpha component will always be |
| 163 // 0xFF or the entire 32-bit pixel will be set to zero. We prefer |
| 164 // kPremul because we support kPremul, and it is more efficient to |
| 165 // use kPremul directly even when kUnpremul is supported. |
| 166 const SkImageInfo& imageInfo = SkImageInfo::Make(width, height, |
| 167 kIndex_8_SkColorType, kPremul_SkAlphaType); |
| 168 return SkNEW_ARGS(SkGifCodec, (imageInfo, stream, gif.detach())); |
| 169 } |
| 170 |
| 171 SkGifCodec::SkGifCodec(const SkImageInfo& srcInfo, SkStream* stream, |
| 172 GifFileType* gif) |
| 173 : INHERITED(srcInfo, stream) |
| 174 , fGif(gif) |
| 175 {} |
| 176 |
| 177 /* |
| 178 * Checks if the conversion between the input image and the requested output |
| 179 * image has been implemented |
| 180 */ |
| 181 static bool conversion_possible(const SkImageInfo& dst, |
| 182 const SkImageInfo& src) { |
| 183 // Ensure that the profile type is unchanged |
| 184 if (dst.profileType() != src.profileType()) { |
| 185 return false; |
| 186 } |
| 187 |
| 188 // Check for supported color and alpha types |
| 189 switch (dst.colorType()) { |
| 190 case kN32_SkColorType: |
| 191 return kPremul_SkAlphaType == dst.alphaType() || |
| 192 kUnpremul_SkAlphaType == dst.alphaType(); |
| 193 default: |
| 194 return false; |
| 195 } |
| 196 } |
| 197 |
| 198 /* |
| 199 * Initiates the gif decode |
| 200 */ |
| 201 SkCodec::Result SkGifCodec::onGetPixels(const SkImageInfo& dstInfo, |
| 202 void* dst, size_t dstRowBytes, |
| 203 const Options& opts, SkPMColor*, int*) { |
| 204 // Check for valid input parameters |
| 205 if (!this->rewindIfNeeded()) { |
| 206 return kCouldNotRewind; |
| 207 } |
| 208 if (dstInfo.dimensions() != this->getInfo().dimensions()) { |
| 209 return gif_error("Scaling not supported.\n", kInvalidScale); |
| 210 } |
| 211 if (!conversion_possible(dstInfo, this->getInfo())) { |
| 212 return gif_error("Cannot convert input type to output type.\n", |
| 213 kInvalidConversion); |
| 214 } |
| 215 |
| 216 // Use this as a container to hold information about any gif extension |
| 217 // blocks. This generally stores transparency and animation instructions. |
| 218 SavedImage saveExt; |
| 219 SkAutoTCallVProc<SavedImage, FreeExtension> autoFreeExt(&saveExt); |
| 220 saveExt.ExtensionBlocks = NULL; |
| 221 saveExt.ExtensionBlockCount = 0; |
| 222 GifByteType* extData; |
| 223 #if GIFLIB_MAJOR >= 5 |
| 224 int32_t extFunction; |
| 225 #endif |
| 226 |
| 227 // We will loop over components of gif images until we find an image. Once |
| 228 // we find an image, we will decode and return it. While many gif files |
| 229 // contain more than one image, we will simply decode the first image. |
| 230 const int32_t width = dstInfo.width(); |
| 231 const int32_t height = dstInfo.height(); |
| 232 GifRecordType recordType; |
| 233 do { |
| 234 // Get the current record type |
| 235 if (GIF_ERROR == DGifGetRecordType(fGif, &recordType)) { |
| 236 return gif_error("DGifGetRecordType failed.\n", kInvalidInput); |
| 237 } |
| 238 |
| 239 switch (recordType) { |
| 240 case IMAGE_DESC_RECORD_TYPE: { |
| 241 // Read the image descriptor |
| 242 if (GIF_ERROR == DGifGetImageDesc(fGif)) { |
| 243 return gif_error("DGifGetImageDesc failed.\n", |
| 244 kInvalidInput); |
| 245 } |
| 246 |
| 247 // If reading the image descriptor is successful, the image |
| 248 // count will be incremented |
| 249 SkASSERT(fGif->ImageCount >= 1); |
| 250 SavedImage* image = &fGif->SavedImages[fGif->ImageCount - 1]; |
| 251 |
| 252 // Process the descriptor |
| 253 const GifImageDesc& desc = image->ImageDesc; |
| 254 int32_t imageLeft = desc.Left; |
| 255 int32_t imageTop = desc.Top; |
| 256 int32_t innerWidth = desc.Width; |
| 257 int32_t innerHeight = desc.Height; |
| 258 // Fail on non-positive dimensions |
| 259 if (innerWidth <= 0 || innerHeight <= 0) { |
| 260 return gif_error("Invalid dimensions for inner image.\n", |
| 261 kInvalidInput); |
| 262 } |
| 263 // Treat the following cases as warnings and try to fix |
| 264 if (innerWidth > width) { |
| 265 gif_warning("Inner image too wide, shrinking.\n"); |
| 266 innerWidth = width; |
| 267 imageLeft = 0; |
| 268 } else if (imageLeft + innerWidth > width) { |
| 269 gif_warning("Shifting inner image to left to fit.\n"); |
| 270 imageLeft = width - innerWidth; |
| 271 } else if (imageLeft < 0) { |
| 272 gif_warning("Shifting image to right to fit\n"); |
| 273 imageLeft = 0; |
| 274 } |
| 275 if (innerHeight > height) { |
| 276 gif_warning("Inner image too tall, shrinking.\n"); |
| 277 innerHeight = height; |
| 278 imageTop = 0; |
| 279 } else if (imageTop + innerHeight > height) { |
| 280 gif_warning("Shifting inner image up to fit.\n"); |
| 281 imageTop = height - innerHeight; |
| 282 } else if (imageTop < 0) { |
| 283 gif_warning("Shifting image down to fit\n"); |
| 284 imageTop = 0; |
| 285 } |
| 286 |
| 287 // Set up the color table |
| 288 uint32_t colorCount = 0; |
| 289 // Allocate maximum storage to deal with invalid indices safely |
| 290 const uint32_t maxColors = 256; |
| 291 SkPMColor colorTable[maxColors]; |
| 292 ColorMapObject* colorMap = fGif->Image.ColorMap; |
| 293 // If there is no local color table, use the global color table |
| 294 if (NULL == colorMap) { |
| 295 colorMap = fGif->SColorMap; |
| 296 } |
| 297 if (NULL != colorMap) { |
| 298 colorCount = colorMap->ColorCount; |
| 299 SkASSERT(colorCount == |
| 300 (unsigned) (1 << (colorMap->BitsPerPixel))); |
| 301 SkASSERT(colorCount <= 256); |
| 302 for (uint32_t i = 0; i < colorCount; i++) { |
| 303 colorTable[i] = SkPackARGB32(0xFF, |
| 304 colorMap->Colors[i].Red, |
| 305 colorMap->Colors[i].Green, |
| 306 colorMap->Colors[i].Blue); |
| 307 } |
| 308 } |
| 309 |
| 310 // This is used to fill unspecified pixels in the image data. |
| 311 uint32_t fillIndex = fGif->SBackGroundColor; |
| 312 bool fillBackground = true; |
| 313 ZeroInitialized zeroInit = opts.fZeroInitialized; |
| 314 |
| 315 // Gifs have the option to specify the color at a single |
| 316 // index of the color table as transparent. |
| 317 { |
| 318 // Get the transparent index. If the return value of this |
| 319 // function is greater than the colorCount, we know that |
| 320 // there is no valid transparent color in the color table. |
| 321 // This occurs if there is no graphics control extension or |
| 322 // if the index specified by the graphics control extension |
| 323 // is out of range. |
| 324 uint32_t transIndex = find_trans_index(saveExt); |
| 325 |
| 326 // If the background is already zeroed and we have a valid |
| 327 // transparent index, we do not need to fill the background. |
| 328 if (transIndex < colorCount) { |
| 329 colorTable[transIndex] = SK_ColorTRANSPARENT; |
| 330 // If there is a transparent index, we also use this as |
| 331 // the fill index. |
| 332 fillIndex = transIndex; |
| 333 fillBackground = (kYes_ZeroInitialized != zeroInit); |
| 334 } else if (fillIndex >= colorCount) { |
| 335 // If the fill index is invalid, we default to 0. This |
| 336 // behavior is unspecified but matches SkImageDecoder. |
| 337 fillIndex = 0; |
| 338 } |
| 339 } |
| 340 |
| 341 // Fill in the color table for indices greater than color count. |
| 342 // This allows for predictable, safe behavior. |
| 343 for (uint32_t i = colorCount; i < maxColors; i++) { |
| 344 colorTable[i] = colorTable[fillIndex]; |
| 345 } |
| 346 |
| 347 // Check if image is only a subset of the image frame |
| 348 SkAutoTDelete<SkSwizzler> swizzler(NULL); |
| 349 if (innerWidth < width || innerHeight < height) { |
| 350 |
| 351 // Modify the destination info |
| 352 const SkImageInfo subsetDstInfo = |
| 353 dstInfo.makeWH(innerWidth, innerHeight); |
| 354 |
| 355 // Fill the destination with the fill color |
| 356 // FIXME: This may not be the behavior that we want for |
| 357 // animated gifs where we draw on top of the |
| 358 // previous frame. |
| 359 SkColorType dstColorType = dstInfo.colorType(); |
| 360 if (fillBackground) { |
| 361 switch (dstColorType) { |
| 362 case kN32_SkColorType: |
| 363 sk_memset32((SkPMColor*) dst, |
| 364 colorTable[fillIndex], |
| 365 ((int) dstRowBytes) * height |
| 366 / sizeof(SkPMColor)); |
| 367 break; |
| 368 default: |
| 369 SkASSERT(false); |
| 370 break; |
| 371 } |
| 372 } |
| 373 |
| 374 // Modify the dst pointer |
| 375 const int32_t dstBytesPerPixel = |
| 376 SkColorTypeBytesPerPixel(dstColorType); |
| 377 void* subsetDst = SkTAddOffset<void*>(dst, |
| 378 dstRowBytes * imageTop + |
| 379 dstBytesPerPixel * imageLeft); |
| 380 |
| 381 // Create the subset swizzler |
| 382 swizzler.reset(SkSwizzler::CreateSwizzler( |
| 383 SkSwizzler::kIndex, colorTable, subsetDstInfo, |
| 384 subsetDst, dstRowBytes, zeroInit)); |
| 385 } else { |
| 386 // Create the fully dimensional swizzler |
| 387 swizzler.reset(SkSwizzler::CreateSwizzler( |
| 388 SkSwizzler::kIndex, colorTable, dstInfo, dst, |
| 389 dstRowBytes, zeroInit)); |
| 390 } |
| 391 |
| 392 // Stores output from dgiflib and input to the swizzler |
| 393 SkAutoTDeleteArray<uint8_t> |
| 394 buffer(SkNEW_ARRAY(uint8_t, innerWidth)); |
| 395 |
| 396 // Check the interlace flag and iterate over rows of the input |
| 397 if (fGif->Image.Interlace) { |
| 398 // In interlace mode, the rows of input are rearranged in |
| 399 // the output image. We use an iterator to take care of |
| 400 // the rearranging. |
| 401 SkGifInterlaceIter iter(innerHeight); |
| 402 for (int32_t y = 0; y < innerHeight; y++) { |
| 403 if (GIF_ERROR == DGifGetLine(fGif, buffer.get(), |
| 404 innerWidth)) { |
| 405 // Recover from error by filling remainder of image |
| 406 if (fillBackground) { |
| 407 memset(buffer.get(), fillIndex, innerWidth); |
| 408 for (; y < innerHeight; y++) { |
| 409 swizzler->next(buffer.get(), iter.nextY()); |
| 410 } |
| 411 } |
| 412 return gif_error(SkStringPrintf( |
| 413 "Could not decode line %d of %d.\n", |
| 414 y, height - 1).c_str(), kIncompleteInput); |
| 415 } |
| 416 swizzler->next(buffer.get(), iter.nextY()); |
| 417 } |
| 418 } else { |
| 419 // Standard mode |
| 420 for (int32_t y = 0; y < innerHeight; y++) { |
| 421 if (GIF_ERROR == DGifGetLine(fGif, buffer.get(), |
| 422 innerWidth)) { |
| 423 if (fillBackground) { |
| 424 SkPMColor* dstPtr = (SkPMColor*) SkTAddOffset |
| 425 <void*>(dst, y * dstRowBytes); |
| 426 sk_memset32(dstPtr, colorTable[fillIndex], |
| 427 (height - y) * ((int) dstRowBytes) |
| 428 / sizeof(SkPMColor)); |
| 429 } |
| 430 return gif_error(SkStringPrintf( |
| 431 "Could not decode line %d of %d.\n", |
| 432 y, height - 1).c_str(), kIncompleteInput); |
| 433 } |
| 434 swizzler->next(buffer.get()); |
| 435 } |
| 436 } |
| 437 |
| 438 // FIXME: Gif files may have multiple images stored in a single |
| 439 // file. This is most commonly used to enable |
| 440 // animations. Since we are leaving animated gifs as a |
| 441 // TODO, we will return kSuccess after decoding the |
| 442 // first image in the file. This is the same behavior |
| 443 // as SkImageDecoder_libgif. |
| 444 // |
| 445 // Most times this works pretty well, but sometimes it |
| 446 // doesn't. For example, I have an animated test image |
| 447 // where the first image in the file is 1x1, but the |
| 448 // subsequent images are meaningful. This currently |
| 449 // displays the 1x1 image, which is not ideal. Right |
| 450 // now I am leaving this as an issue that will be |
| 451 // addressed when we implement animated gifs. |
| 452 // |
| 453 // It is also possible (not explicitly disallowed in the |
| 454 // specification) that gif files provide multiple |
| 455 // images in a single file that are all meant to be |
| 456 // displayed in the same frame together. I will |
| 457 // currently leave this unimplemented until I find a |
| 458 // test case that expects this behavior. |
| 459 return kSuccess; |
| 460 } |
| 461 |
| 462 // Extensions are used to specify special properties of the image |
| 463 // such as transparency or animation. |
| 464 case EXTENSION_RECORD_TYPE: |
| 465 // Read extension data |
| 466 #if GIFLIB_MAJOR < 5 |
| 467 if (GIF_ERROR == |
| 468 DGifGetExtension(fGif, &saveExt.Function, &extData)) { |
| 469 #else |
| 470 if (GIF_ERROR == |
| 471 DGifGetExtension(fGif, &extFunction, &extData)) { |
| 472 #endif |
| 473 return gif_error("Could not get extension.\n", |
| 474 kIncompleteInput); |
| 475 } |
| 476 |
| 477 // Create an extension block with our data |
| 478 while (NULL != extData) { |
| 479 // Add a single block |
| 480 #if GIFLIB_MAJOR < 5 |
| 481 if (GIF_ERROR == AddExtensionBlock(&saveExt, extData[0], |
| 482 &extData[1])) { |
| 483 #else |
| 484 if (GIF_ERROR == |
| 485 GifAddExtensionBlock(&saveExt.ExtensionBlockCount, |
| 486 &saveExt.ExtensionBlocks, extFunction, extData[0], |
| 487 &extData[1])) { |
| 488 #endif |
| 489 return gif_error("Could not add extension block.\n", |
| 490 kIncompleteInput); |
| 491 } |
| 492 // Move to the next block |
| 493 if (GIF_ERROR == DGifGetExtensionNext(fGif, &extData)) { |
| 494 return gif_error("Could not get next extension.\n", |
| 495 kIncompleteInput); |
| 496 } |
| 497 #if GIFLIB_MAJOR < 5 |
| 498 saveExt.Function = 0; |
| 499 #endif |
| 500 } |
| 501 break; |
| 502 |
| 503 // Signals the end of the gif file |
| 504 case TERMINATE_RECORD_TYPE: |
| 505 break; |
| 506 |
| 507 default: |
| 508 // giflib returns an error code if the record type is not known. |
| 509 // We should catch this error immediately. |
| 510 SkASSERT(false); |
| 511 break; |
| 512 } |
| 513 } while (TERMINATE_RECORD_TYPE != recordType); |
| 514 |
| 515 return gif_error("Could not find any images to decode in gif file.\n", |
| 516 kInvalidInput); |
| 517 } |
OLD | NEW |