Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(404)

Side by Side Diff: src/codec/SkCodec_libgif.cpp

Issue 1022673011: Creating a new wrapper for gif decoder (Closed) Base URL: https://skia.googlesource.com/skia.git@ico-real
Patch Set: First round of gif improvements Created 5 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(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 * Error reporting function
34 * TODO: Add option to turn off printing of error
scroggo 2015/03/26 20:03:54 This is done by using SkCodecPrintf
msarett 2015/03/26 22:26:37 Done.
35 */
36 static void gif_message(const char* msg) {
37 SkCodecPrintf("Gif Warning: %s\n", msg);
scroggo 2015/03/26 20:03:53 We might want two different functions: one for err
msarett 2015/03/26 22:26:37 Agreed. This is better.
38 }
39
40 /*
41 * This function cleans up the gif object after the decode completes
42 * It is used in a SkAutoTCallIProc template
43 */
44 int32_t close_gif(GifFileType* gif) {
45 #if GIFLIB_MAJOR < 5 || (GIFLIB_MAJOR == 5 && GIFLIB_MINOR == 0)
46 return DGifCloseFile(gif);
47 #else
48 return DGifCloseFile(gif, NULL);
49 #endif
50 }
51
52 /*
53 * This function free extension data that has been saved to assist the image
54 * decoder
55 */
56 void free_extension(SavedImage* image) {
57 if (NULL != image->ExtensionBlocks) {
58 #if GIFLIB_MAJOR < 5
59 FreeExtension(image);
60 #else
61 GifFreeExtensions(&image->ExtensionBlockCount, &image->ExtensionBlocks);
62 #endif
63 }
64 }
65
66 /*
67 * Read function that will be passed to gif_lib
68 */
69 static int32_t read_bytes_callback(GifFileType* fileType, GifByteType* out,
scroggo 2015/03/26 20:03:53 What does gif_lib expect? size_t seems most approp
msarett 2015/03/26 22:26:37 Agreed, but it expects an int return type.
70 int32_t size) {
71 SkStream* stream = (SkStream*) fileType->UserData;
72 return (int32_t) stream->read(out, size);
73 }
74
75 /*
76 * Check if a there is an index of the color table for a transparent pixel
77 */
78 static int32_t find_trans_index(const SavedImage& image, uint32_t colorCount) {
79 // If there is a transparent index specified, it will be contained in an
80 // extension block.
81 for (int32_t i = 0; i < image.ExtensionBlockCount; i++) {
82 // Get an extension block
83 const ExtensionBlock& extBlock = image.ExtensionBlocks[i];
84
85 // Most of the extension blocks contained in gif images are useless.
scroggo 2015/03/26 20:03:53 Really? Any idea why they are there? Or are they j
msarett 2015/03/26 22:26:37 They are really in fact useless. But I don't thin
86 // Specifically, we need to check for a graphics control extension,
87 // which may contain transparency information. Also, note that a valid
88 // graphics control extension is always four bytes. The fourth byte
89 // is the transparent index (if it exists), so we need at least four
90 // bytes.
91 if (GRAPHICS_EXT_FUNC_CODE == extBlock.Function &&
92 extBlock.ByteCount >= 4) {
93
94 // Check the "transparent color flag" which indicates whether a
scroggo 2015/03/26 20:03:53 Is there a constant/macro for "transparent color f
msarett 2015/03/26 22:26:37 The library actually doesn't have one. It makes a
95 // transparent index exists.
96 if (1 == (extBlock.Bytes[0] & 1)) {
97
98 // Use unsigned int32_t to prevent sign extending
99 uint32_t transIndex = extBlock.Bytes[3];
100 if (transIndex < colorCount) {
101 return transIndex;
102 }
103 }
104 }
105 }
106
107 // Flag indicating that a valid index was not found
108 return -1;
109 }
110
111 /*
112 * Assumes IsGif was called and returned true
113 * Creates a gif decoder
114 * Reads enough of the stream to determine the image format
115 */
116 SkCodec* SkGifCodec::NewFromStream(SkStream* stream) {
117 // Read gif header, logical screen descriptor, and global color table
118 #if GIFLIB_MAJOR < 5
119 SkAutoTCallIProc<GifFileType, close_gif> autoCloseGif(
scroggo 2015/03/26 20:03:53 Just like when we call an SkAutoTDeleteArray "buff
msarett 2015/03/26 22:26:37 Done.
120 DGifOpen(stream, read_bytes_callback));
121 #else
122 SkAutoTCallIProc<GifFileType, close_gif> autoCloseGif(
123 DGifOpen(stream, read_bytes_callback, NULL));
scroggo 2015/03/26 20:03:53 Can we factor out the two different versions like
msarett 2015/03/26 22:26:37 Done.
124 #endif
125 if (NULL == (GifFileType*) autoCloseGif) {
scroggo 2015/03/26 20:03:53 Do you need to explicitly cast here for it to work
msarett 2015/03/26 22:26:37 Apparently not :)
126 gif_message("DGifOpen failed.\n");
127 return NULL;
128 }
129
130 // Get fields from header
131 const int32_t width = autoCloseGif->SWidth;
132 const int32_t height = autoCloseGif->SHeight;
133 if (width <= 0 || height <= 0) {
134 gif_message("Invalid dimensions.\n");
135 return NULL;
136 }
137
138 // Return the codec
139 // kIndex is the most natural color type for gifs, so we set this as
140 // the default.
141 // Many gifs specify a color table index for transparent pixels. Every
142 // other pixel is guaranteed to be opaque. Despite this, because of the
143 // possiblity of transparent pixels, we cannot assume that the image is
144 // opaque. However, we can at least mark it as kPremul, since pixels will
145 // either have a 0xFF alpha component or be completely zeroed.
146 const SkImageInfo& imageInfo = SkImageInfo::Make(width, height,
147 kIndex_8_SkColorType, kPremul_SkAlphaType);
148 return SkNEW_ARGS(SkGifCodec, (imageInfo, stream, autoCloseGif.detach()));
149 }
150
151 SkGifCodec::SkGifCodec(const SkImageInfo& srcInfo, SkStream* stream,
152 GifFileType* gif)
153 : INHERITED(srcInfo, stream)
154 , fGif(gif)
155 {}
156
157 /*
158 * Checks if the conversion between the input image and the requested output
159 * image has been implemented
160 */
161 static bool conversion_possible(const SkImageInfo& dst,
162 const SkImageInfo& src) {
163 // Ensure that the profile type is unchanged
164 if (dst.profileType() != src.profileType()) {
165 return false;
166 }
167
168 // Check for supported color and alpha types
169 switch (dst.colorType()) {
170 case kN32_SkColorType:
171 return src.alphaType() == dst.alphaType() ||
172 (kPremul_SkAlphaType == dst.alphaType() &&
173 kUnpremul_SkAlphaType == src.alphaType());
174 default:
175 return false;
176 }
177 }
178
179 /*
180 * Initiates the gif decode
181 */
182 SkCodec::Result SkGifCodec::onGetPixels(const SkImageInfo& dstInfo,
183 void* dst, size_t dstRowBytes,
184 const Options& opts, SkPMColor*, int*) {
185 // Use auto call procedures to ensure memory is cleaned up
186 SkAutoTCallIProc<GifFileType, close_gif> autoClose(fGif);
187 SavedImage saveExt;
188 SkAutoTCallVProc<SavedImage, free_extension> autoFreeExt(&saveExt);
189
190 // Check for valid input parameters
191 if (!this->rewindIfNeeded()) {
192 return kCouldNotRewind;
193 }
194 if (dstInfo.dimensions() != this->getInfo().dimensions()) {
195 gif_message("Scaling not supported.\n");
196 return kInvalidScale;
197 }
198 if (!conversion_possible(dstInfo, this->getInfo())) {
199 gif_message("Cannot convert input type to output type.\n");
200 return kInvalidConversion;
201 }
202
203 // Use this as a container to hold information about any gif extension
204 // blocks. This generally stores transparency and animation instructions.
205 saveExt.ExtensionBlocks = NULL;
206 saveExt.ExtensionBlockCount = 0;
207 GifByteType* extData;
208 #if GIFLIB_MAJOR >= 5
209 int32_t extFunction;
210 #endif
211
212 // We will loop over components of gif images until we find an image. Once
213 // we find an image, we will decode and return it. While many gif files
214 // contain more than one image, we will simply decode the first image.
215 const int32_t width = dstInfo.width();
216 const int32_t height = dstInfo.height();
217 GifRecordType recordType = UNDEFINED_RECORD_TYPE;
218 while (TERMINATE_RECORD_TYPE != recordType) {
219 // Get the current record type
220 if (GIF_ERROR == DGifGetRecordType(fGif, &recordType)) {
221 gif_message("DGifGetRecordType failed.\n");
222 return kInvalidInput;
223 }
224
225 switch (recordType) {
226 case IMAGE_DESC_RECORD_TYPE: {
227 // Read the image descriptor
228 if (GIF_ERROR == DGifGetImageDesc(fGif)) {
229 gif_message("DGifGetImageDesc failed.\n");
230 return kInvalidInput;
231 }
232
233 // If reading the image descriptor is successful, the image
234 // count will be incremented
235 SkASSERT(fGif->ImageCount >= 1);
236 SavedImage* image = &fGif->SavedImages[fGif->ImageCount - 1];
237
238 // Process the descriptor
239 const GifImageDesc& desc = image->ImageDesc;
240 int32_t imageLeft = desc.Left;
241 int32_t imageTop = desc.Top;
242 int32_t innerWidth = desc.Width;
243 int32_t innerHeight = desc.Height;
244 // Fail on non-positive dimensions
245 if (innerWidth <= 0 || innerHeight <= 0) {
246 gif_message("Invalid dimensions for inner image.\n");
247 return kInvalidInput;
248 }
249 // Treat the following cases as warnings and try to fix
250 if (innerWidth > width) {
251 gif_message("Inner image too wide, shrinking.\n");
252 innerWidth = width;
253 imageLeft = 0;
254 } else if (imageLeft + innerWidth > width) {
255 gif_message("Shifting inner image to left to fit.\n");
256 imageLeft = width - innerWidth;
257 } else if (imageLeft < 0) {
258 gif_message("Shifting image to right to fit\n");
259 imageLeft = 0;
260 }
261 if (innerHeight > height) {
262 gif_message("Inner image too tall, shrinking.\n");
263 innerHeight = height;
264 imageTop = 0;
265 } else if (imageTop + innerHeight > height) {
266 gif_message("Shifting inner image up to fit.\n");
267 imageTop = height - innerHeight;
268 } else if (imageTop < 0) {
269 gif_message("Shifting image down to fit\n");
270 imageTop = 0;
271 }
272
273 // Set up the color table
274 uint32_t colorCount = 0;
275 // Allocate maximum storage to deal with invalid indices safely
276 const uint32_t maxColors = 256;
277 SkAutoTDeleteArray<SkPMColor> colorTable(
scroggo 2015/03/26 20:03:53 This is better as SkPMColor colorPtr[maxColors];
msarett 2015/03/26 22:26:37 Done.
278 SkNEW_ARRAY(SkPMColor, maxColors));
279 ColorMapObject* colorMap = fGif->Image.ColorMap;
280 // If there is no local color table, use the global color table
281 if (NULL == colorMap) {
282 colorMap = fGif->SColorMap;
283 }
284 if (NULL != colorMap) {
285 colorCount = colorMap->ColorCount;
286 SkASSERT(colorCount ==
287 (unsigned) (1 << (colorMap->BitsPerPixel)));
288 SkASSERT(colorCount <= 256);
289 for (uint32_t i = 0; i < colorCount; i++) {
290 colorTable.get()[i] = SkPackARGB32(0xFF,
291 colorMap->Colors[i].Red,
292 colorMap->Colors[i].Green,
293 colorMap->Colors[i].Blue);
294 }
295 }
296
297 // This is used to fill unspecified pixels in the image data.
298 uint32_t fillIndex = fGif->SBackGroundColor;
299 bool fillBackground = true;
300 ZeroInitialized zeroInit = opts.fZeroInitialized;
301
302 // Gifs have the option to specify the color at a single
303 // index of the color table as transparent.
304 {
305 int32_t transIndex = find_trans_index(saveExt, colorCount);
306
307 // If the background is already zeroed and we have a valid
308 // transparent index, we do not need to fill the background.
309 if (transIndex >= 0) {
310 colorTable.get()[transIndex] = SK_ColorTRANSPARENT;
311 // If there is a transparent index, we also use this as
312 // the fill index.
313 fillIndex = transIndex;
314 fillBackground = (kYes_ZeroInitialized != zeroInit);
scroggo 2015/03/26 20:03:53 Is it possible that the fillIndex, either as speci
msarett 2015/03/26 22:26:37 Hmm yeah it will add complexity when we care about
scroggo 2015/03/27 13:09:36 Really? There aren't any images with invalid entri
msarett 2015/03/27 14:23:19 Yeah this is an actual guarantee. The gif color t
scroggo 2015/03/27 14:36:11 Oh yeah, of course!
315 } else if (fillIndex >= colorCount) {
316 // If the fill index is invalid, we default to 0. This
317 // behavior is unspecified but matches SkImageDecoder.
318 fillIndex = 0;
319 }
320 }
321
322 // Fill in the color table for indices greater than color count.
323 // This allows for predictable, safe behavior.
324 for (uint32_t i = colorCount; i < maxColors; i++) {
325 colorTable.get()[i] = colorTable.get()[fillIndex];
326 }
327
328 // Check if image is only a subset of the image frame
329 SkAutoTDelete<SkSwizzler> swizzler(NULL);
330 if (innerWidth < width || innerHeight < height) {
331
332 // Modify the destination info
333 const SkImageInfo subsetDstInfo =
334 dstInfo.makeWH(innerWidth, innerHeight);
335
336 // Fill the destination with the fill color
337 // FIXME: This may not be the behavior that we want for
338 // animated gifs where we draw on top of the
339 // previous frame.
340 SkColorType dstColorType = dstInfo.colorType();
341 if (fillBackground) {
342 switch (dstColorType) {
343 case kN32_SkColorType:
344 sk_memset32((SkPMColor*) dst,
345 colorTable.get()[fillIndex],
346 dstRowBytes * height / sizeof(SkPMColor));
347 break;
348 default:
349 SkASSERT(false);
350 break;
351 }
352 }
353
354 // Modify the dst pointer
355 const int32_t dstBytesPerPixel =
356 SkColorTypeBytesPerPixel(dstColorType);
357 void* subsetDst = SkTAddOffset<void*>(dst,
358 dstRowBytes * imageTop +
359 dstBytesPerPixel * imageLeft);
360
361 // Create the subset swizzler
362 swizzler.reset(SkSwizzler::CreateSwizzler(
363 SkSwizzler::kIndex, colorTable.get(),
364 subsetDstInfo, subsetDst, dstRowBytes, zeroInit));
365 } else {
366 // Create the fully dimensional swizzler
367 swizzler.reset(SkSwizzler::CreateSwizzler(
368 SkSwizzler::kIndex, colorTable.get(), dstInfo, dst,
369 dstRowBytes, zeroInit));
370 }
371
372 // Stores output from dgiflib and input to the swizzler
373 SkAutoTDeleteArray<uint8_t>
374 buffer(SkNEW_ARRAY(uint8_t, innerWidth));
375
376 // Check the interlace flag and iterate over rows of the input
377 if (fGif->Image.Interlace) {
378 // In interlace mode, the rows of input are rearranged in
379 // the output image. We use an iterator to take care of
380 // the rearranging.
381 SkGifInterlaceIter iter(innerHeight);
382 for (int32_t y = 0; y < innerHeight; y++) {
383 if (GIF_ERROR == DGifGetLine(fGif, buffer.get(),
384 innerWidth)) {
385 gif_message(SkStringPrintf(
386 "Could not decode line %d of %d.\n",
387 y, height - 1).c_str());
388 // Recover from error by filling remainder of image
389 if (fillBackground) {
390 memset(buffer.get(), fillIndex, innerWidth);
391 for (; y < innerHeight; y++) {
392 swizzler->next(buffer.get(), iter.nextY());
393 }
394 }
395 return kIncompleteInput;
396 }
397 swizzler->next(buffer.get(), iter.nextY());
398 }
399 } else {
400 // Standard mode
401 for (int32_t y = 0; y < innerHeight; y++) {
402 if (GIF_ERROR == DGifGetLine(fGif, buffer.get(),
403 innerWidth)) {
404 gif_message(SkStringPrintf(
405 "Could not decode line %d of %d.\n",
406 y, height - 1).c_str());
407 if (fillBackground) {
408 void* dstPtr = SkTAddOffset<void*>(
409 dst, y * dstRowBytes);
410 memset(dstPtr, fillIndex,
scroggo 2015/03/26 20:03:54 For N32, we need to memset32 with the colorPtr[fil
msarett 2015/03/26 22:26:37 Wow yeah, I messed that up. This makes me wonder
scroggo 2015/03/27 13:09:36 Possibly. It would make this code much simpler, fo
411 (height - y) * dstRowBytes);
412 }
413 return kIncompleteInput;
414 }
415 swizzler->next(buffer.get());
416 }
417 }
418
419 // FIXME: Gif files may have multiple images stored in a single
420 // file. This is most commonly used to enable
421 // animations. Since we are leaving animated gifs as a
422 // TODO, we will return kSuccess after decoding the
423 // first image in the file. This is the same behavior
424 // as SkImageDecoder_libgif.
425 //
426 // Most times this works pretty well, but sometimes it
427 // doesn't. For example, I have an animated test image
428 // where the first image in the file is 1x1, but the
429 // subsequent images are meaningful. This currently
430 // displays the 1x1 image, which is not ideal. Right
431 // now I am leaving this as an issue that will be
432 // addressed when we implement animated gifs.
433 //
434 // It is also possible (not explicitly disallowed in the
435 // specification) that gif files provide multiple
436 // images in a single file that are all meant to be
437 // displayed in the same frame together. I will
438 // currently leave this unimplemented until I find a
439 // test case that expects this behavior.
440 return kSuccess;
441 }
442
443 // Extensions are used to specify special properties of the image
444 // such as transparency or animation.
445 case EXTENSION_RECORD_TYPE:
446 // Read extension data
447 #if GIFLIB_MAJOR < 5
448 if (GIF_ERROR ==
449 DGifGetExtension(fGif, &saveExt.Function, &extData)) {
450 #else
451 if (GIF_ERROR ==
452 DGifGetExtension(fGif, &extFunction, &extData)) {
453 #endif
454 gif_message("Could not get extension.\n");
455 return kInvalidInput;
456 }
457
458 // Create an extension block with our data
459 while (NULL != extData) {
460 // Add a single block
461 #if GIFLIB_MAJOR < 5
462 if (GIF_ERROR == AddExtensionBlock(&saveExt, extData[0],
463 &extData[1])) {
464 #else
465 if (GIF_ERROR ==
466 GifAddExtensionBlock(&saveExt.ExtensionBlockCount,
467 &saveExt.ExtensionBlocks, extFunction, extData[0],
468 &extData[1])) {
469 #endif
470 gif_message("Could not add extension block.\n");
471 return kInvalidInput;
472 }
473 // Move to the next block
474 if (GIF_ERROR == DGifGetExtensionNext(fGif, &extData)) {
475 gif_message("Could not get next extension.\n");
476 return kInvalidInput;
477 }
478 #if GIFLIB_MAJOR < 5
479 saveExt.Function = 0;
480 #endif
481 }
482 break;
483
484 // Signals the end of the gif file
485 case TERMINATE_RECORD_TYPE:
486 break;
487
488 default:
489 break;
490 }
491 }
492
493 gif_message("Could not find any images to decode in gif file.\n");
494 return kInvalidInput;
495 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698