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

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

Issue 2045293002: Add support for multiple frames in SkCodec (Closed) Base URL: https://skia.googlesource.com/skia.git@master
Patch Set: Rebase; new API Created 4 years, 3 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
1 /* 1 /*
2 * Copyright 2015 Google Inc. 2 * Copyright 2015 Google Inc.
3 * 3 *
4 * Use of this source code is governed by a BSD-style license that can be 4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file. 5 * found in the LICENSE file.
6 */ 6 */
7 7
8 #include "SkBitmap.h"
9 #include "SkCanvas.h"
10 #include "SkCodecAnimation.h"
8 #include "SkCodecPriv.h" 11 #include "SkCodecPriv.h"
9 #include "SkColorPriv.h" 12 #include "SkColorPriv.h"
10 #include "SkColorTable.h" 13 #include "SkColorTable.h"
11 #include "SkGifCodec.h" 14 #include "SkGifCodec.h"
12 #include "SkStream.h" 15 #include "SkStream.h"
13 #include "SkSwizzler.h" 16 #include "SkSwizzler.h"
14 #include "SkUtils.h" 17 #include "SkUtils.h"
15 18
16 #include "gif_lib.h" 19 #include "gif_lib.h"
17 20
(...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after
52 */ 55 */
53 static GifFileType* open_gif(SkStream* stream) { 56 static GifFileType* open_gif(SkStream* stream) {
54 #if GIFLIB_MAJOR < 5 57 #if GIFLIB_MAJOR < 5
55 return DGifOpen(stream, read_bytes_callback); 58 return DGifOpen(stream, read_bytes_callback);
56 #else 59 #else
57 return DGifOpen(stream, read_bytes_callback, nullptr); 60 return DGifOpen(stream, read_bytes_callback, nullptr);
58 #endif 61 #endif
59 } 62 }
60 63
61 /* 64 /*
62 * Check if a there is an index of the color table for a transparent pixel 65 * Read the graphics extension and report info from it. Returns false if there i s none.
63 */ 66 */
64 static uint32_t find_trans_index(const SavedImage& image) { 67 static bool read_graphics_extension(const SavedImage& image, uint32_t* transInde x,
68 size_t* duration,
69 SkCodecAnimation::DisposalMethod* disposalMe thod) {
65 // If there is a transparent index specified, it will be contained in an 70 // 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 71 // extension block. We will loop through extension blocks in reverse order
67 // to check the most recent extension blocks first. 72 // to check the most recent extension blocks first.
68 for (int32_t i = image.ExtensionBlockCount - 1; i >= 0; i--) { 73 for (int32_t i = image.ExtensionBlockCount - 1; i >= 0; i--) {
69 // Get an extension block 74 // Get an extension block
70 const ExtensionBlock& extBlock = image.ExtensionBlocks[i]; 75 const ExtensionBlock& extBlock = image.ExtensionBlocks[i];
71 76
72 // Specifically, we need to check for a graphics control extension, 77 // Specifically, we need to check for a graphics control extension,
73 // which may contain transparency information. Also, note that a valid 78 // which may contain transparency information. Also, note that a valid
74 // graphics control extension is always four bytes. The fourth byte 79 // graphics control extension is always four bytes. The fourth byte
75 // is the transparent index (if it exists), so we need at least four 80 // is the transparent index (if it exists), so we need at least four
76 // bytes. 81 // bytes.
77 if (GRAPHICS_EXT_FUNC_CODE == extBlock.Function && extBlock.ByteCount >= 4) { 82 if (GRAPHICS_EXT_FUNC_CODE == extBlock.Function && extBlock.ByteCount >= 4) {
78 // Check the transparent color flag which indicates whether a 83 // Check the transparent color flag which indicates whether a
79 // transparent index exists. It is the least significant bit of 84 // transparent index exists. It is the least significant bit of
80 // the first byte of the extension block. 85 // the first byte of the extension block.
81 if (1 == (extBlock.Bytes[0] & 1)) { 86 if (transIndex) {
82 // Use uint32_t to prevent sign extending 87 if (1 == (extBlock.Bytes[0] & 1)) {
83 return extBlock.Bytes[3]; 88 // Use uint32_t to prevent sign extending
89 *transIndex = extBlock.Bytes[3];
90 } else {
91 // Use maximum unsigned int (surely an invalid index) to ind icate that a valid
92 // index was not found.
93 *transIndex = SK_MaxU32;
94 }
95 }
96
97 // The second and third bytes represent the duration.
98 if (duration) {
99 *duration = extBlock.Bytes[2] << 8 | extBlock.Bytes[1];
100 }
101
102 if (disposalMethod) {
103 int rawDisposalMethod = (extBlock.Bytes[0] >> 2) & 7;
104 switch (rawDisposalMethod) {
105 case 1:
106 case 2:
107 case 3:
108 *disposalMethod = (SkCodecAnimation::DisposalMethod) raw DisposalMethod;
109 break;
110 case 4:
111 *disposalMethod = SkCodecAnimation::RestorePrevious_Disp osalMethod;
112 break;
113 default:
114 *disposalMethod = SkCodecAnimation::Keep_DisposalMethod;
115 break;
116 }
84 } 117 }
85 118
86 // There should only be one graphics control extension for the image frame 119 // There should only be one graphics control extension for the image frame
87 break; 120 return true;
88 } 121 }
89 } 122 }
90 123
91 // Use maximum unsigned int (surely an invalid index) to indicate that a val id 124 return false;
92 // index was not found.
93 return SK_MaxU32;
94 }
95
96 inline uint32_t ceil_div(uint32_t a, uint32_t b) {
97 return (a + b - 1) / b;
98 } 125 }
99 126
100 /* 127 /*
101 * Gets the output row corresponding to the encoded row for interlaced gifs
102 */
103 inline uint32_t get_output_row_interlaced(uint32_t encodedRow, uint32_t height) {
104 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
121 /*
122 * This function cleans up the gif object after the decode completes 128 * This function cleans up the gif object after the decode completes
123 * It is used in a SkAutoTCallIProc template 129 * It is used in a SkAutoTCallIProc template
124 */ 130 */
125 void SkGifCodec::CloseGif(GifFileType* gif) { 131 void SkGifCodec::CloseGif(GifFileType* gif) {
126 #if GIFLIB_MAJOR < 5 || (GIFLIB_MAJOR == 5 && GIFLIB_MINOR == 0) 132 #if GIFLIB_MAJOR < 5 || (GIFLIB_MAJOR == 5 && GIFLIB_MINOR == 0)
127 DGifCloseFile(gif); 133 DGifCloseFile(gif);
128 #else 134 #else
129 DGifCloseFile(gif, nullptr); 135 DGifCloseFile(gif, nullptr);
130 #endif 136 #endif
131 } 137 }
(...skipping 35 matching lines...) Expand 10 before | Expand all | Expand 10 after
167 SkAutoTDelete<SkStream> streamDeleter(stream); 173 SkAutoTDelete<SkStream> streamDeleter(stream);
168 174
169 // Read gif header, logical screen descriptor, and global color table 175 // Read gif header, logical screen descriptor, and global color table
170 SkAutoTCallVProc<GifFileType, CloseGif> gif(open_gif(stream)); 176 SkAutoTCallVProc<GifFileType, CloseGif> gif(open_gif(stream));
171 177
172 if (nullptr == gif) { 178 if (nullptr == gif) {
173 gif_error("DGifOpen failed.\n"); 179 gif_error("DGifOpen failed.\n");
174 return false; 180 return false;
175 } 181 }
176 182
177 // Read through gif extensions to get to the image data. Set the 183 // Read the whole file.
178 // transparent index based on the extension data. 184 if (GIF_ERROR == DGifSlurp(gif) || gif->ImageCount == 0) {
179 uint32_t transIndex;
180 SkCodec::Result result = ReadUpToFirstImage(gif, &transIndex);
181 if (kSuccess != result){
182 return false; 185 return false;
183 } 186 }
184 187
185 // Read the image descriptor 188 SkISize size;
186 if (GIF_ERROR == DGifGetImageDesc(gif)) { 189 if (!GetDimensions(gif, &size)) {
190 gif_error("Invalid gif size.\n");
187 return false; 191 return false;
188 } 192 }
189 // If reading the image descriptor is successful, the image count will be 193
190 // incremented. 194 uint32_t transIndex = SK_MaxU32;
191 SkASSERT(gif->ImageCount >= 1); 195 read_graphics_extension(gif->SavedImages[0], &transIndex, nullptr, nullptr);
192 196
193 if (nullptr != codecOut) { 197 if (nullptr != codecOut) {
194 SkISize size;
195 SkIRect frameRect;
196 if (!GetDimensions(gif, &size, &frameRect)) {
197 gif_error("Invalid gif size.\n");
198 return false;
199 }
200 bool frameIsSubset = (size != frameRect.size());
201
202 // Determine the encoded alpha type. The transIndex might be valid if i t less 198 // Determine the encoded alpha type. The transIndex might be valid if i t less
203 // than 256. We are not certain that the index is valid until we proces s the color 199 // than 256. We are not certain that the index is valid until we proces s the color
204 // table, since some gifs have color tables with less than 256 colors. If 200 // 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 i mage has 201 // there might be a valid transparent index, we must indicate that the i mage has
206 // alpha. 202 // alpha.
207 // In the case where we must support alpha, we indicate kBinary, since e very 203 // In the case where we must support alpha, we indicate kBinary, since e very
208 // pixel will either be fully opaque or fully transparent. 204 // pixel will either be fully opaque or fully transparent.
209 SkEncodedInfo::Alpha alpha = (transIndex < 256) ? SkEncodedInfo::kBinary _Alpha : 205 SkEncodedInfo::Alpha alpha = (transIndex < 256) ? SkEncodedInfo::kBinary _Alpha :
210 SkEncodedInfo::kOpaque_Alpha; 206 SkEncodedInfo::kOpaque_Alpha;
211 207
212 // Return the codec 208 // Return the codec
213 // Use kPalette since Gifs are encoded with a color table. 209 // Use kPalette since Gifs are encoded with a color table.
214 // Use 8-bits per component, since this is the output we get from giflib . 210 // Use 8-bits per component, since this is the output we get from giflib .
215 // FIXME: Gifs can actually be encoded with 4-bits per pixel. Can we su pport this? 211 // FIXME: Gifs can actually be encoded with 4-bits per pixel. Can we su pport this?
216 SkEncodedInfo info = SkEncodedInfo::Make(SkEncodedInfo::kPalette_Color, alpha, 8); 212 SkEncodedInfo info = SkEncodedInfo::Make(SkEncodedInfo::kPalette_Color, alpha, 8);
217 *codecOut = new SkGifCodec(size.width(), size.height(), info, streamDele ter.release(), 213 *codecOut = new SkGifCodec(size.width(), size.height(), info, streamDele ter.release(),
218 gif.release(), transIndex, frameRect, frameIsSubset); 214 gif.release(), transIndex);
219 } else { 215 } else {
220 SkASSERT(nullptr != gifOut); 216 SkASSERT(nullptr != gifOut);
221 streamDeleter.release(); 217 streamDeleter.release();
222 *gifOut = gif.release(); 218 *gifOut = gif.release();
223 } 219 }
224 return true; 220 return true;
225 } 221 }
226 222
227 /* 223 /*
228 * Assumes IsGif was called and returned true 224 * Assumes IsGif was called and returned true
229 * Creates a gif decoder 225 * Creates a gif decoder
230 * Reads enough of the stream to determine the image format 226 * Reads enough of the stream to determine the image format
231 */ 227 */
232 SkCodec* SkGifCodec::NewFromStream(SkStream* stream) { 228 SkCodec* SkGifCodec::NewFromStream(SkStream* stream) {
233 SkCodec* codec = nullptr; 229 SkCodec* codec = nullptr;
234 if (ReadHeader(stream, &codec, nullptr)) { 230 if (ReadHeader(stream, &codec, nullptr)) {
231 SkASSERT(codec);
235 return codec; 232 return codec;
236 } 233 }
237 return nullptr; 234 return nullptr;
238 } 235 }
239 236
237 static SkColorTable* create_color_table(const ColorMapObject& colorMap, uint32_t transIndex,
238 uint32_t backgroundIndex);
240 SkGifCodec::SkGifCodec(int width, int height, const SkEncodedInfo& info, SkStrea m* stream, 239 SkGifCodec::SkGifCodec(int width, int height, const SkEncodedInfo& info, SkStrea m* stream,
241 GifFileType* gif, uint32_t transIndex, const SkIRect& frameRect, bool fr ameIsSubset) 240 GifFileType* gif, uint32_t transIndex)
242 : INHERITED(width, height, info, stream) 241 : INHERITED(width, height, info, stream)
243 , fGif(gif) 242 , fGif(gif)
244 , fSrcBuffer(new uint8_t[this->getInfo().width()]) 243 , fSrcBuffer(new uint8_t[this->getInfo().width()])
245 , fFrameRect(frameRect)
246 // If it is valid, fTransIndex will be used to set fFillIndex. We don't kno w if
247 // fTransIndex is valid until we process the color table, since fTransIndex may
248 // be greater than the size of the color table.
249 , fTransIndex(transIndex)
250 // Default fFillIndex is 0. We will overwrite this if fTransIndex is valid, or if
251 // there is a valid background color.
252 , fFillIndex(0) 244 , fFillIndex(0)
253 , fFrameIsSubset(frameIsSubset)
254 , fSwizzler(NULL) 245 , fSwizzler(NULL)
255 , fColorTable(NULL) 246 , fColorTable(NULL)
256 {} 247 , fFrameInfos(gif->ImageCount)
248 {
249 if (gif->SColorMap) {
250 // FIXME: Note - this is the global color table.
251 fColorTable.reset(create_color_table(*gif->SColorMap, transIndex, gif->S BackGroundColor));
252 } else {
253 // Read the first image's local color table, for now.
254 const SavedImage* image = &gif->SavedImages[0];
255 const GifImageDesc& desc = image->ImageDesc;
257 256
258 bool SkGifCodec::onRewind() { 257 if (desc.ColorMap) {
259 GifFileType* gifOut = nullptr; 258 // I'm guessing the background index only makes sense for the global color table.
260 if (!ReadHeader(this->stream(), nullptr, &gifOut)) { 259 // A lot of users (including Chromium!) ignore the background color, but we (currently)
261 return false; 260 // use it to fill in the color table if it's less than 256 colors.
261 fColorTable.reset(create_color_table(*desc.ColorMap, transIndex, SK_ MaxU32));
262 }
262 } 263 }
263 264
264 SkASSERT(nullptr != gifOut); 265 for (int i = 0; i < gif->ImageCount; i++) {
265 fGif.reset(gifOut); 266 const SavedImage* image = &gif->SavedImages[i];
266 return true; 267 const GifImageDesc& desc = image->ImageDesc;
268
269 auto& frame = fFrameInfos.push_back();
270 // FIXME: Probably want to intersect this with the bounds, just in case.
271 // But then we'll need to make sure we draw the right thing...
272 // i.e. if the top is cut off (desc.Top < 0), we want to start off drawi ng line -desc.Top
273 // (probably?)
274 // Or if we're cut off width-wise, we need to ensure we use the original row bytes
275 // (desc.Width) but the corrected width.
276 frame.fFrameRect = SkIRect::MakeXYWH(desc.Left, desc.Top, desc.Width, de sc.Height);
277 if (!read_graphics_extension(*image, &frame.fTransIndex, &frame.fDuratio n,
278 &frame.fDisposalMethod)) {
279 frame.fDisposalMethod = SkCodecAnimation::Keep_DisposalMethod;
280 frame.fDuration = 0;
281 frame.fTransIndex = SK_MaxU32;
282 }
283
284 if (0 == i) {
285 frame.fRequiredFrame = kIndependentFrame;
286 } else {
287 // FIXME: We could correct these after decoding (i.e. some frames ma y turn out to be
288 // independent although we did not determine that here).
289 const SkCodecAnimation::FrameInfo& prevFrame = fFrameInfos[i-1];
290 switch (prevFrame.fDisposalMethod) {
291 case SkCodecAnimation::Keep_DisposalMethod:
292 frame.fRequiredFrame = i - 1;
293 break;
294 case SkCodecAnimation::RestorePrevious_DisposalMethod:
295 frame.fRequiredFrame = prevFrame.fRequiredFrame;
296 break;
297 case SkCodecAnimation::RestoreBGColor_DisposalMethod:
298 if (prevFrame.fFrameRect == SkIRect::MakeWH(width, height)
299 || prevFrame.fRequiredFrame == kIndependentFrame) {
300 frame.fRequiredFrame = kIndependentFrame;
301 } else {
302 frame.fRequiredFrame = i - 1;
303 }
304 break;
305 }
306 }
307 }
267 } 308 }
268 309
269 SkCodec::Result SkGifCodec::ReadUpToFirstImage(GifFileType* gif, uint32_t* trans Index) { 310 size_t SkGifCodec::onGetRequiredFrame(size_t index) {
270 // Use this as a container to hold information about any gif extension 311 if ((int) index >= fFrameInfos.count()) {
271 // blocks. This generally stores transparency and animation instructions. 312 return kIndependentFrame;
272 SavedImage saveExt; 313 }
273 SkAutoTCallVProc<SavedImage, FreeExtension> autoFreeExt(&saveExt);
274 saveExt.ExtensionBlocks = nullptr;
275 saveExt.ExtensionBlockCount = 0;
276 GifByteType* extData;
277 int32_t extFunction;
278 314
279 // We will loop over components of gif images until we find an image. Once 315 return fFrameInfos[index].fRequiredFrame;
280 // we find an image, we will decode and return it. While many gif files
281 // contain more than one image, we will simply decode the first image.
282 GifRecordType recordType;
283 do {
284 // Get the current record type
285 if (GIF_ERROR == DGifGetRecordType(gif, &recordType)) {
286 return gif_error("DGifGetRecordType failed.\n", kInvalidInput);
287 }
288 switch (recordType) {
289 case IMAGE_DESC_RECORD_TYPE: {
290 *transIndex = find_trans_index(saveExt);
291
292 // FIXME: Gif files may have multiple images stored in a single
293 // file. This is most commonly used to enable
294 // animations. Since we are leaving animated gifs as a
295 // TODO, we will return kSuccess after decoding the
296 // first image in the file. This is the same behavior
297 // as SkImageDecoder_libgif.
298 //
299 // Most times this works pretty well, but sometimes it
300 // doesn't. For example, I have an animated test image
301 // where the first image in the file is 1x1, but the
302 // subsequent images are meaningful. This currently
303 // displays the 1x1 image, which is not ideal. Right
304 // now I am leaving this as an issue that will be
305 // addressed when we implement animated gifs.
306 //
307 // It is also possible (not explicitly disallowed in the
308 // specification) that gif files provide multiple
309 // images in a single file that are all meant to be
310 // displayed in the same frame together. I will
311 // currently leave this unimplemented until I find a
312 // test case that expects this behavior.
313 return kSuccess;
314 }
315 // Extensions are used to specify special properties of the image
316 // such as transparency or animation.
317 case EXTENSION_RECORD_TYPE:
318 // Read extension data
319 if (GIF_ERROR == DGifGetExtension(gif, &extFunction, &extData)) {
320 return gif_error("Could not get extension.\n", kIncompleteIn put);
321 }
322
323 // Create an extension block with our data
324 while (nullptr != extData) {
325 // Add a single block
326
327 #if GIFLIB_MAJOR < 5
328 if (AddExtensionBlock(&saveExt, extData[0],
329 &extData[1]) == GIF_ERROR) {
330 #else
331 if (GIF_ERROR == GifAddExtensionBlock(&saveExt.ExtensionBloc kCount,
332 &saveExt.ExtensionBloc ks,
333 extFunction, extData[0 ], &extData[1])) {
334 #endif
335 return gif_error("Could not add extension block.\n", kIn completeInput);
336 }
337 // Move to the next block
338 if (GIF_ERROR == DGifGetExtensionNext(gif, &extData)) {
339 return gif_error("Could not get next extension.\n", kInc ompleteInput);
340 }
341 }
342 break;
343
344 // Signals the end of the gif file
345 case TERMINATE_RECORD_TYPE:
346 break;
347
348 default:
349 // DGifGetRecordType returns an error if the record type does
350 // not match one of the above cases. This should not be
351 // reached.
352 SkASSERT(false);
353 break;
354 }
355 } while (TERMINATE_RECORD_TYPE != recordType);
356
357 return gif_error("Could not find any images to decode in gif file.\n", kInva lidInput);
358 } 316 }
359 317
360 bool SkGifCodec::GetDimensions(GifFileType* gif, SkISize* size, SkIRect* frameRe ct) { 318 size_t SkGifCodec::onGetFrameDuration(size_t index) {
361 // Get the encoded dimension values 319 if ((int) index >= fFrameInfos.count()) {
362 SavedImage* image = &gif->SavedImages[gif->ImageCount - 1]; 320 return 0;
321 }
322
323 return fFrameInfos[index].fDuration;
324 }
325
326 bool SkGifCodec::GetDimensions(GifFileType* gif, SkISize* size) {
327 // Get the encoded dimension values for the first frame. Some GIFs have fram es that are bigger
328 // than the screen width and height. For the first frame only, we will expan d in that case.
329 SavedImage* image = &gif->SavedImages[0];
363 const GifImageDesc& desc = image->ImageDesc; 330 const GifImageDesc& desc = image->ImageDesc;
364 int frameLeft = desc.Left; 331 int frameLeft = desc.Left;
365 int frameTop = desc.Top; 332 int frameTop = desc.Top;
366 int frameWidth = desc.Width; 333 int frameWidth = desc.Width;
367 int frameHeight = desc.Height; 334 int frameHeight = desc.Height;
368 int width = gif->SWidth; 335 int width = gif->SWidth;
369 int height = gif->SHeight; 336 int height = gif->SHeight;
370 337
371 // Ensure that the decode dimensions are large enough to contain the frame 338 // Ensure that the decode dimensions are large enough to contain the frame
372 width = SkTMax(width, frameWidth + frameLeft); 339 width = SkTMax(width, frameWidth + frameLeft);
373 height = SkTMax(height, frameHeight + frameTop); 340 height = SkTMax(height, frameHeight + frameTop);
374 341
375 // All of these dimensions should be positive, as they are encoded as unsign ed 16-bit integers. 342 // All of these dimensions should be positive, as they are encoded as unsign ed 16-bit integers.
376 // It is unclear why giflib casts them to ints. We will go ahead and check that they are 343 // It is unclear why giflib casts them to ints. We will go ahead and check that they are
377 // in fact positive. 344 // in fact positive.
378 if (frameLeft < 0 || frameTop < 0 || frameWidth < 0 || frameHeight < 0 || wi dth <= 0 || 345 if (frameLeft < 0 || frameTop < 0 || frameWidth < 0 || frameHeight < 0 || wi dth <= 0 ||
379 height <= 0) { 346 height <= 0) {
380 return false; 347 return false;
381 } 348 }
382 349
383 frameRect->setXYWH(frameLeft, frameTop, frameWidth, frameHeight);
384 size->set(width, height); 350 size->set(width, height);
385 return true; 351 return true;
386 } 352 }
387 353
354 constexpr uint32_t kMaxColors = 256;
355
388 void SkGifCodec::initializeColorTable(const SkImageInfo& dstInfo, SkPMColor* inp utColorPtr, 356 void SkGifCodec::initializeColorTable(const SkImageInfo& dstInfo, SkPMColor* inp utColorPtr,
389 int* inputColorCount) { 357 int* inputColorCount) {
390 // Set up our own color table 358 // FIXME: Use the correct one for the frame.
391 const uint32_t maxColors = 256; 359 SkASSERT(fColorTable);
392 SkPMColor colorPtr[256]; 360 if (inputColorCount) {
393 if (NULL != inputColorCount) { 361 *inputColorCount = fColorTable->count();
394 // We set the number of colors to maxColors in order to ensure
395 // safe memory accesses. Otherwise, an invalid pixel could
396 // access memory outside of our color table array.
397 *inputColorCount = maxColors;
398 } 362 }
399 363
400 // Get local color table 364 copy_color_table(dstInfo, fColorTable, inputColorPtr, inputColorCount);
401 ColorMapObject* colorMap = fGif->Image.ColorMap; 365 }
402 // If there is no local color table, use the global color table
403 if (NULL == colorMap) {
404 colorMap = fGif->SColorMap;
405 }
406 366
407 uint32_t colorCount = 0; 367 static SkColorTable* create_color_table(const ColorMapObject& colorMap, uint32_t transIndex,
408 if (NULL != colorMap) { 368 uint32_t backgroundIndex) {
409 colorCount = colorMap->ColorCount; 369 SkPMColor colorPtr[kMaxColors];
410 // giflib guarantees these properties 370 const uint32_t colorCount = colorMap.ColorCount;
411 SkASSERT(colorCount == (unsigned) (1 << (colorMap->BitsPerPixel))); 371 // giflib guarantees these properties
412 SkASSERT(colorCount <= 256); 372 SkASSERT(colorCount == (unsigned) (1 << (colorMap.BitsPerPixel)));
413 PackColorProc proc = choose_pack_color_proc(false, dstInfo.colorType()); 373 SkASSERT(colorCount <= 256);
414 for (uint32_t i = 0; i < colorCount; i++) { 374
415 colorPtr[i] = proc(0xFF, colorMap->Colors[i].Red, 375 // FIXME: We may be creating this at the wrong time - we don't know the dst color type.
416 colorMap->Colors[i].Green, colorMap->Colors[i].Blue); 376 PackColorProc proc = choose_pack_color_proc(false, kIndex_8_SkColorType);
417 } 377 for (uint32_t i = 0; i < colorCount; i++) {
378 const GifColorType& color = colorMap.Colors[i];
379 colorPtr[i] = proc(0xFF, color.Red, color.Green, color.Blue);
418 } 380 }
419 381
420 // Fill in the color table for indices greater than color count. 382 // Fill in the color table for indices greater than color count.
421 // This allows for predictable, safe behavior. 383 // This allows for predictable, safe behavior.
422 if (colorCount > 0) { 384 if (colorCount > 0) {
423 // Gifs have the option to specify the color at a single index of the co lor 385 // Gifs have the option to specify the color at a single index of the co lor
424 // table as transparent. If the transparent index is greater than the 386 // table as transparent. If the transparent index is greater than the
425 // colorCount, we know that there is no valid transparent color in the c olor 387 // colorCount, we know that there is no valid transparent color in the c olor
426 // table. If there is not valid transparent index, we will try to use t he 388 // table. If there is not valid transparent index, we will try to use t he
427 // backgroundIndex as the fill index. If the backgroundIndex is also no t 389 // backgroundIndex as the fill index. If the backgroundIndex is also no t
428 // valid, we will let fFillIndex default to 0 (it is set to zero in the 390 // valid, we will let fFillIndex default to 0 (it is set to zero in the
429 // constructor). This behavior is not specified but matches 391 // constructor). This behavior is not specified but matches
430 // SkImageDecoder_libgif. 392 // SkImageDecoder_libgif.
431 uint32_t backgroundIndex = fGif->SBackGroundColor; 393 uint32_t fillIndex;
432 if (fTransIndex < colorCount) { 394 if (transIndex < colorCount) {
433 colorPtr[fTransIndex] = SK_ColorTRANSPARENT; 395 colorPtr[transIndex] = SK_ColorTRANSPARENT;
434 fFillIndex = fTransIndex; 396 fillIndex = transIndex;
435 } else if (backgroundIndex < colorCount) { 397 } else if (backgroundIndex < colorCount) {
436 fFillIndex = backgroundIndex; 398 fillIndex = backgroundIndex;
399 } else {
400 fillIndex = 0;
437 } 401 }
438 402
439 for (uint32_t i = colorCount; i < maxColors; i++) { 403 for (uint32_t i = colorCount; i < kMaxColors; i++) {
440 colorPtr[i] = colorPtr[fFillIndex]; 404 colorPtr[i] = colorPtr[fillIndex];
441 } 405 }
442 } else { 406 } else {
443 sk_memset32(colorPtr, 0xFF000000, maxColors); 407 sk_memset32(colorPtr, 0xFF000000, kMaxColors);
444 } 408 }
445 409
446 fColorTable.reset(new SkColorTable(colorPtr, maxColors)); 410 return new SkColorTable(colorPtr, kMaxColors);
447 copy_color_table(dstInfo, this->fColorTable, inputColorPtr, inputColorCount) ;
448 } 411 }
449 412
450 SkCodec::Result SkGifCodec::prepareToDecode(const SkImageInfo& dstInfo, SkPMColo r* inputColorPtr, 413 SkCodec::Result SkGifCodec::prepareToDecode(const SkImageInfo& dstInfo, SkPMColo r* inputColorPtr,
451 int* inputColorCount, const Options& opts) { 414 int* inputColorCount, const Options& opts) {
452 // Check for valid input parameters 415 // Check for valid input parameters
453 if (!conversion_possible_ignore_color_space(dstInfo, this->getInfo())) { 416 if (!conversion_possible_ignore_color_space(dstInfo, this->getInfo())) {
454 return gif_error("Cannot convert input type to output type.\n", kInvalid Conversion); 417 return gif_error("Cannot convert input type to output type.\n", kInvalid Conversion);
455 } 418 }
456 419
420 if (opts.fFrameIndex > 0 && dstInfo.colorType() == kIndex_8_SkColorType) {
421 // FIXME: It is possible that a later frame can be decoded to index8, if it does one of the
422 // following:
423 // - Covers the entire previous frame
424 // - Shares a color table (and transparent index) with any prior frames that are showing.
425 // We must support index8 for the first frame to be backwards compatible on Android.
426 return gif_error("Cannot decode multiframe gif (except frame 0) as index 8.\n",
427 kInvalidConversion);
428 }
429
430 if ((int) opts.fFrameIndex > fFrameInfos.count()) {
431 return gif_error("frame index out of range!\n", kInvalidParameters);
432 }
433
457 // Initialize color table and copy to the client if necessary 434 // Initialize color table and copy to the client if necessary
458 this->initializeColorTable(dstInfo, inputColorPtr, inputColorCount); 435 this->initializeColorTable(dstInfo, inputColorPtr, inputColorCount);
459
460 this->initializeSwizzler(dstInfo, opts);
461 return kSuccess; 436 return kSuccess;
462 } 437 }
463 438
464 void SkGifCodec::initializeSwizzler(const SkImageInfo& dstInfo, const Options& o pts) {
465 const SkPMColor* colorPtr = get_color_ptr(fColorTable.get());
466 const SkIRect* frameRect = fFrameIsSubset ? &fFrameRect : nullptr;
467 fSwizzler.reset(SkSwizzler::CreateSwizzler(this->getEncodedInfo(), colorPtr, dstInfo, opts,
468 frameRect));
469 SkASSERT(fSwizzler);
470 }
471
472 bool SkGifCodec::readRow() {
473 return GIF_ERROR != DGifGetLine(fGif, fSrcBuffer.get(), fFrameRect.width());
474 }
475
476 /* 439 /*
477 * Initiates the gif decode 440 * Initiates the gif decode
478 */ 441 */
479 SkCodec::Result SkGifCodec::onGetPixels(const SkImageInfo& dstInfo, 442 SkCodec::Result SkGifCodec::onGetPixels(const SkImageInfo& dstInfo,
480 void* dst, size_t dstRowBytes, 443 void* pixels, size_t dstRowBytes,
481 const Options& opts, 444 const Options& opts,
482 SkPMColor* inputColorPtr, 445 SkPMColor* inputColorPtr,
483 int* inputColorCount, 446 int* inputColorCount,
484 int* rowsDecoded) { 447 int* rowsDecoded) {
485 Result result = this->prepareToDecode(dstInfo, inputColorPtr, inputColorCoun t, opts); 448 Result result = this->prepareToDecode(dstInfo, inputColorPtr, inputColorCoun t, opts);
486 if (kSuccess != result) { 449 if (kSuccess != result) {
487 return result; 450 return result;
488 } 451 }
489 452
490 if (dstInfo.dimensions() != this->getInfo().dimensions()) { 453 if (dstInfo.dimensions() != this->getInfo().dimensions()) {
491 return gif_error("Scaling not supported.\n", kInvalidScale); 454 return gif_error("Scaling not supported.\n", kInvalidScale);
492 } 455 }
493 456
494 // Initialize the swizzler 457 this->decodeFrame(dstInfo, pixels, dstRowBytes, opts);
495 if (fFrameIsSubset) { 458 return kSuccess;
496 // Fill the background 459 }
497 SkSampler::Fill(dstInfo, dst, dstRowBytes, this->getFillValue(dstInfo), 460
498 opts.fZeroInitialized); 461 // FIXME: This should be SkCodec::Result, probably?
462 void SkGifCodec::decodeFrame(const SkImageInfo& dstInfo, void* pixels, size_t ds tRowBytes,
463 const Options& opts) {
464 SkBitmap tmpBm;
465 void* dst = pixels;
466
467 SkASSERT((int) opts.fFrameIndex < fFrameInfos.count());
468 const auto& frameInfo = fFrameInfos[opts.fFrameIndex];
469 const SkIRect& frameRect = frameInfo.fFrameRect;
470 const bool independent = frameInfo.fRequiredFrame == kIndependentFrame;
471 if (!independent) {
472 if (!opts.fHasPriorFrame) {
473 // Decode that frame into pixels.
474 Options prevFrameOpts(opts);
475 prevFrameOpts.fFrameIndex = frameInfo.fRequiredFrame;
476 this->decodeFrame(dstInfo, pixels, dstRowBytes, prevFrameOpts);
477 }
478 const auto& prevFrame = fFrameInfos[frameInfo.fRequiredFrame];
479 if (prevFrame.fDisposalMethod == SkCodecAnimation::RestoreBGColor_Dispos alMethod) {
480 const SkIRect& prevRect = prevFrame.fFrameRect;
481 void* const eraseDst = SkTAddOffset<void>(pixels, prevRect.fTop * ds tRowBytes
482 + prevRect.fLeft * SkColorTypeBytesPerPixel(dstInfo.colorTyp e()));
483 // FIXME: Is this the right color?
484 SkSampler::Fill(dstInfo.makeWH(prevRect.width(), prevRect.height()), eraseDst,
485 dstRowBytes, SK_ColorTRANSPARENT, SkCodec::kNo_ZeroI nitialized);
486 }
487
488 // Now we need to swizzle to a temporary bitmap. That way we do not over write pixels
489 // with transparent. Later we'll draw to pixels
490 const int frameWidth = frameRect.width();
491 const int frameHeight = frameRect.height();
492 SkImageInfo tmpInfo = dstInfo.makeWH(frameWidth, frameHeight);
493 // FIXME: Could be more agressive than this (i.e. it could be out of the actual range of
494 // the color map).
495 if (frameInfo.fTransIndex < 256) {
496 // Need alpha to blend with prior frame.
497 tmpInfo = tmpInfo.makeAlphaType(kUnpremul_SkAlphaType);
498 }
499 tmpBm.allocPixels(tmpInfo);
500 dst = tmpBm.getPixels();
501 } else {
502 // This frame is independent
503 if (frameRect != dstInfo.bounds()) {
504 // Fill the background
505 // FIXME: Android may want the BG color, but Chromium wants transpar ent!
506 SkSampler::Fill(dstInfo, pixels, dstRowBytes, SK_ColorTRANSPARENT,
507 opts.fZeroInitialized);
508
509 // Now offset dst to draw the frame:
510 dst = SkTAddOffset<void>(dst, frameRect.fTop * dstRowBytes
511 + frameRect.fLeft * SkColorTypeBytesPerPixel(dstInfo.colorTy pe()));
512 }
499 } 513 }
500 514
515 SkASSERT((int) opts.fFrameIndex < fGif->ImageCount);
516 const SavedImage* image = &fGif->SavedImages[opts.fFrameIndex];
517 const GifImageDesc& desc = image->ImageDesc;
518
519 ColorMapObject* cmap = desc.ColorMap ? desc.ColorMap : fGif->SColorMap;
520 sk_sp<SkColorTable> ct(create_color_table(*cmap, frameInfo.fTransIndex, SK_M axU32));
521
522 std::unique_ptr<SkSwizzler> swizzler(SkSwizzler::CreateSwizzler(this->getEnc odedInfo(),
523 ct->readColors(), dstInfo, opts));
524 SkASSERT(swizzler);
525
501 // Iterate over rows of the input 526 // Iterate over rows of the input
502 for (int y = fFrameRect.top(); y < fFrameRect.bottom(); y++) { 527 void* dstRow = dst;
503 if (!this->readRow()) { 528 GifByteType* src = image->RasterBits;
504 *rowsDecoded = y; 529 for (int y = 0; y < desc.Height; y++) {
505 return gif_error("Could not decode line.\n", kIncompleteInput); 530 swizzler->swizzle(dstRow, src);
506 } 531 dstRow = SkTAddOffset<void>(dstRow, dstRowBytes);
507 void* dstRow = SkTAddOffset<void>(dst, dstRowBytes * this->outputScanlin e(y)); 532 src = SkTAddOffset<GifByteType>(src, desc.Width);
508 fSwizzler->swizzle(dstRow, fSrcBuffer.get());
509 } 533 }
510 return kSuccess; 534
535 if (!independent) {
536 // We drew to a temporary bitmap. Now we need to draw it to pixels.
537 SkASSERT(tmpBm.getPixels() == dst);
538 SkBitmap dstBm;
539 // FIXME: What to do if this fails?
540 dstBm.installPixels(dstInfo, pixels, dstRowBytes, fColorTable, nullptr, nullptr);
541 SkCanvas canvas(dstBm);
542 const SkScalar left = SkIntToScalar(frameRect.left());
543 const SkScalar top = SkIntToScalar(frameRect.top());
544 canvas.drawBitmap(tmpBm, left, top);
545 }
511 } 546 }
512 547
513 // FIXME: This is similar to the implementation for bmp and png. Can we share m ore code or 548 // FIXME: This is similar to the implementation for bmp and png. Can we share m ore code or
514 // possibly make this non-virtual? 549 // possibly make this non-virtual?
515 uint64_t SkGifCodec::onGetFillValue(const SkImageInfo& dstInfo) const { 550 uint64_t SkGifCodec::onGetFillValue(const SkImageInfo& dstInfo) const {
516 const SkPMColor* colorPtr = get_color_ptr(fColorTable.get()); 551 const SkPMColor* colorPtr = get_color_ptr(fColorTable.get());
517 return get_color_table_fill_value(dstInfo.colorType(), dstInfo.alphaType(), colorPtr, 552 return get_color_table_fill_value(dstInfo.colorType(), dstInfo.alphaType(), colorPtr,
518 fFillIndex, nullptr); 553 fFillIndex, nullptr);
519 } 554 }
520
521 SkCodec::Result SkGifCodec::onStartScanlineDecode(const SkImageInfo& dstInfo,
522 const SkCodec::Options& opts, SkPMColor inputColorPtr[], int* inputColor Count) {
523 return this->prepareToDecode(dstInfo, inputColorPtr, inputColorCount, opts);
524 }
525
526 void SkGifCodec::handleScanlineFrame(int count, int* rowsBeforeFrame, int* rowsI nFrame) {
527 if (fFrameIsSubset) {
528 const int currRow = this->currScanline();
529
530 // The number of rows that remain to be skipped before reaching rows tha t we
531 // actually must decode into.
532 // This must be at least zero. We also make sure that it is less than o r
533 // equal to count, since we will skip at most count rows.
534 *rowsBeforeFrame = SkTMin(count, SkTMax(0, fFrameRect.top() - currRow));
535
536 // Rows left to decode once we reach the start of the frame.
537 const int rowsLeft = count - *rowsBeforeFrame;
538
539 // Count the number of that extend beyond the bottom of the frame. We d o not
540 // need to decode into these rows.
541 const int rowsAfterFrame = SkTMax(0, currRow + rowsLeft - fFrameRect.bot tom());
542
543 // Set the actual number of source rows that we need to decode.
544 *rowsInFrame = rowsLeft - rowsAfterFrame;
545 } else {
546 *rowsBeforeFrame = 0;
547 *rowsInFrame = count;
548 }
549 }
550
551 int SkGifCodec::onGetScanlines(void* dst, int count, size_t rowBytes) {
552 int rowsBeforeFrame;
553 int rowsInFrame;
554 this->handleScanlineFrame(count, &rowsBeforeFrame, &rowsInFrame);
555
556 if (fFrameIsSubset) {
557 // Fill the requested rows
558 SkImageInfo fillInfo = this->dstInfo().makeWH(this->dstInfo().width(), c ount);
559 uint64_t fillValue = this->onGetFillValue(this->dstInfo());
560 fSwizzler->fill(fillInfo, dst, rowBytes, fillValue, this->options().fZer oInitialized);
561
562 // Start to write pixels at the start of the image frame
563 dst = SkTAddOffset<void>(dst, rowBytes * rowsBeforeFrame);
564 }
565
566 for (int i = 0; i < rowsInFrame; i++) {
567 if (!this->readRow()) {
568 return i + rowsBeforeFrame;
569 }
570 fSwizzler->swizzle(dst, fSrcBuffer.get());
571 dst = SkTAddOffset<void>(dst, rowBytes);
572 }
573
574 return count;
575 }
576
577 bool SkGifCodec::onSkipScanlines(int count) {
578 int rowsBeforeFrame;
579 int rowsInFrame;
580 this->handleScanlineFrame(count, &rowsBeforeFrame, &rowsInFrame);
581
582 for (int i = 0; i < rowsInFrame; i++) {
583 if (!this->readRow()) {
584 return false;
585 }
586 }
587
588 return true;
589 }
590
591 SkCodec::SkScanlineOrder SkGifCodec::onGetScanlineOrder() const {
592 if (fGif->Image.Interlace) {
593 return kOutOfOrder_SkScanlineOrder;
594 }
595 return kTopDown_SkScanlineOrder;
596 }
597
598 int SkGifCodec::onOutputScanline(int inputScanline) const {
599 if (fGif->Image.Interlace) {
600 if (inputScanline < fFrameRect.top() || inputScanline >= fFrameRect.bott om()) {
601 return inputScanline;
602 }
603 return get_output_row_interlaced(inputScanline - fFrameRect.top(), fFram eRect.height()) +
604 fFrameRect.top();
605 }
606 return inputScanline;
607 }
OLDNEW
« include/codec/SkCodec.h ('K') | « src/codec/SkGifCodec.h ('k') | tests/CodecAnimTest.cpp » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698