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

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: Cache all frames in the GM Created 4 years, 2 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));
msarett 2016/09/22 22:54:35 So if there is a global color table we always use
scroggo 2016/09/23 15:53:15 Not sure. Most of this code is throw-away/proof-of
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.
msarett 2016/09/22 22:54:35 I have no strong feelings about using or not using
scroggo 2016/09/23 15:53:15 My guess would be a lot of them. Even if they fill
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.
msarett 2016/09/22 22:54:35 I think I made a bunch of test gifs to exercise so
scroggo 2016/09/23 15:53:15 Yes, that is what they do. But I didn't want to ha
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
msarett 2016/09/22 22:54:34 Seems like an optimization to consider later...
scroggo 2016/09/23 15:53:16 Yeah, this is what we talked about yesterday (e.g.
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:
msarett 2016/09/22 22:54:34 I'm not sure I completely understand the logic in
scroggo 2016/09/23 15:53:16 Yeah, this is a confusing one. As I understand it,
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()) {
msarett 2016/09/22 22:54:36 Can we assert this? Seems like client should be s
scroggo 2016/09/23 15:53:15 I lean towards returning a failure for a public AP
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()) {
msarett 2016/09/22 22:54:35 Ditto.
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
msarett 2016/09/22 22:54:36 I remember when we decided to do this... But now
scroggo 2016/09/23 15:53:15 I think we should stick with the behavior that Chr
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
msarett 2016/09/22 22:54:35 I know Chrome always fills incomplete images with
scroggo 2016/09/23 15:53:15 Do you mean a transparent pixel that is out of ran
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.fFrameOptions && opts.fFrameOptions->fIndex > 0)
421 && dstInfo.colorType() == kIndex_8_SkColorType) {
422 // FIXME: It is possible that a later frame can be decoded to index8, if it does one of the
msarett 2016/09/22 22:54:35 Good questions, probably a good place to follow up
423 // following:
424 // - Covers the entire previous frame
425 // - Shares a color table (and transparent index) with any prior frames that are showing.
426 // We must support index8 for the first frame to be backwards compatible on Android.
427 return gif_error("Cannot decode multiframe gif (except frame 0) as index 8.\n",
428 kInvalidConversion);
429 }
430
431 if (opts.fFrameOptions && (int) opts.fFrameOptions->fIndex > fFrameInfos.cou nt()) {
432 return gif_error("frame index out of range!\n", kInvalidParameters);
msarett 2016/09/22 22:54:34 Hmmm ok... We are set up to fail nicely here on i
scroggo 2016/09/23 15:53:16 Again I lean towards failing gracefully in public
433 }
434
457 // Initialize color table and copy to the client if necessary 435 // Initialize color table and copy to the client if necessary
458 this->initializeColorTable(dstInfo, inputColorPtr, inputColorCount); 436 this->initializeColorTable(dstInfo, inputColorPtr, inputColorCount);
459
460 this->initializeSwizzler(dstInfo, opts);
461 return kSuccess; 437 return kSuccess;
462 } 438 }
463 439
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 /* 440 /*
477 * Initiates the gif decode 441 * Initiates the gif decode
478 */ 442 */
479 SkCodec::Result SkGifCodec::onGetPixels(const SkImageInfo& dstInfo, 443 SkCodec::Result SkGifCodec::onGetPixels(const SkImageInfo& dstInfo,
480 void* dst, size_t dstRowBytes, 444 void* pixels, size_t dstRowBytes,
481 const Options& opts, 445 const Options& opts,
482 SkPMColor* inputColorPtr, 446 SkPMColor* inputColorPtr,
483 int* inputColorCount, 447 int* inputColorCount,
484 int* rowsDecoded) { 448 int* rowsDecoded) {
485 Result result = this->prepareToDecode(dstInfo, inputColorPtr, inputColorCoun t, opts); 449 Result result = this->prepareToDecode(dstInfo, inputColorPtr, inputColorCoun t, opts);
486 if (kSuccess != result) { 450 if (kSuccess != result) {
487 return result; 451 return result;
488 } 452 }
489 453
490 if (dstInfo.dimensions() != this->getInfo().dimensions()) { 454 if (dstInfo.dimensions() != this->getInfo().dimensions()) {
491 return gif_error("Scaling not supported.\n", kInvalidScale); 455 return gif_error("Scaling not supported.\n", kInvalidScale);
492 } 456 }
493 457
494 // Initialize the swizzler 458 this->decodeFrame(dstInfo, pixels, dstRowBytes, opts);
495 if (fFrameIsSubset) { 459 return kSuccess;
496 // Fill the background 460 }
497 SkSampler::Fill(dstInfo, dst, dstRowBytes, this->getFillValue(dstInfo), 461
498 opts.fZeroInitialized); 462 // FIXME: This should be SkCodec::Result, probably?
463 void SkGifCodec::decodeFrame(const SkImageInfo& dstInfo, void* pixels, size_t ds tRowBytes,
464 const Options& opts) {
465 SkBitmap tmpBm;
466 void* dst = pixels;
467
468 const size_t frameIndex = opts.fFrameOptions ? opts.fFrameOptions->fIndex : 0;
469 SkASSERT((int) frameIndex < fFrameInfos.count());
scroggo 2016/09/23 21:15:00 D'oh! After all my talk about failing gracefully I
470 const auto& frameInfo = fFrameInfos[frameIndex];
471 const SkIRect& frameRect = frameInfo.fFrameRect;
472 const bool independent = frameInfo.fRequiredFrame == kIndependentFrame;
473 if (!independent) {
474 if (opts.fFrameOptions && !opts.fFrameOptions->fHasPriorFrame) {
475 // Decode that frame into pixels.
476 Options prevFrameOpts(opts);
477 MultiFrameOptions prevFrameMultiOpts;
478 prevFrameMultiOpts.fIndex = frameInfo.fRequiredFrame;
479 prevFrameMultiOpts.fHasPriorFrame = false;
480 prevFrameOpts.fFrameOptions = &prevFrameMultiOpts;
481 this->decodeFrame(dstInfo, pixels, dstRowBytes, prevFrameOpts);
482 }
483 const auto& prevFrame = fFrameInfos[frameInfo.fRequiredFrame];
484 if (prevFrame.fDisposalMethod == SkCodecAnimation::RestoreBGColor_Dispos alMethod) {
485 const SkIRect& prevRect = prevFrame.fFrameRect;
486 void* const eraseDst = SkTAddOffset<void>(pixels, prevRect.fTop * ds tRowBytes
487 + prevRect.fLeft * SkColorTypeBytesPerPixel(dstInfo.colorTyp e()));
488 // FIXME: Is this the right color?
msarett 2016/09/22 22:54:34 Is this what Chrome does?
scroggo 2016/09/23 15:53:15 Yes. But my concern is that if we're decoding to i
489 SkSampler::Fill(dstInfo.makeWH(prevRect.width(), prevRect.height()), eraseDst,
490 dstRowBytes, SK_ColorTRANSPARENT, SkCodec::kNo_ZeroI nitialized);
491 }
492
493 // Now we need to swizzle to a temporary bitmap. That way we do not over write pixels
494 // with transparent. Later we'll draw to pixels
495 const int frameWidth = frameRect.width();
496 const int frameHeight = frameRect.height();
497 SkImageInfo tmpInfo = dstInfo.makeWH(frameWidth, frameHeight);
498 // FIXME: Could be more agressive than this (i.e. it could be out of the actual range of
499 // the color map).
500 if (frameInfo.fTransIndex < 256) {
501 // Need alpha to blend with prior frame.
502 tmpInfo = tmpInfo.makeAlphaType(kUnpremul_SkAlphaType);
503 }
504 tmpBm.allocPixels(tmpInfo);
505 dst = tmpBm.getPixels();
506 } else {
507 // This frame is independent
508 if (frameRect != dstInfo.bounds()) {
509 // Fill the background
510 // FIXME: Android may want the BG color, but Chromium wants transpar ent!
511 SkSampler::Fill(dstInfo, pixels, dstRowBytes, SK_ColorTRANSPARENT,
512 opts.fZeroInitialized);
513
514 // Now offset dst to draw the frame:
515 dst = SkTAddOffset<void>(dst, frameRect.fTop * dstRowBytes
516 + frameRect.fLeft * SkColorTypeBytesPerPixel(dstInfo.colorTy pe()));
517 }
499 } 518 }
500 519
520 SkASSERT((int) frameIndex < fGif->ImageCount);
521 const SavedImage* image = &fGif->SavedImages[frameIndex];
522 const GifImageDesc& desc = image->ImageDesc;
523
524 ColorMapObject* cmap = desc.ColorMap ? desc.ColorMap : fGif->SColorMap;
525 sk_sp<SkColorTable> ct(create_color_table(*cmap, frameInfo.fTransIndex, SK_M axU32));
526
527 std::unique_ptr<SkSwizzler> swizzler(SkSwizzler::CreateSwizzler(this->getEnc odedInfo(),
528 ct->readColors(), dstInfo, opts));
529 SkASSERT(swizzler);
530
501 // Iterate over rows of the input 531 // Iterate over rows of the input
502 for (int y = fFrameRect.top(); y < fFrameRect.bottom(); y++) { 532 void* dstRow = dst;
503 if (!this->readRow()) { 533 GifByteType* src = image->RasterBits;
504 *rowsDecoded = y; 534 for (int y = 0; y < desc.Height; y++) {
505 return gif_error("Could not decode line.\n", kIncompleteInput); 535 swizzler->swizzle(dstRow, src);
506 } 536 dstRow = SkTAddOffset<void>(dstRow, dstRowBytes);
507 void* dstRow = SkTAddOffset<void>(dst, dstRowBytes * this->outputScanlin e(y)); 537 src = SkTAddOffset<GifByteType>(src, desc.Width);
508 fSwizzler->swizzle(dstRow, fSrcBuffer.get());
509 } 538 }
510 return kSuccess; 539
540 if (!independent) {
541 // We drew to a temporary bitmap. Now we need to draw it to pixels.
542 SkASSERT(tmpBm.getPixels() == dst);
543 SkBitmap dstBm;
544 // FIXME: What to do if this fails?
545 dstBm.installPixels(dstInfo, pixels, dstRowBytes, fColorTable, nullptr, nullptr);
546 SkCanvas canvas(dstBm);
547 const SkScalar left = SkIntToScalar(frameRect.left());
548 const SkScalar top = SkIntToScalar(frameRect.top());
549 canvas.drawBitmap(tmpBm, left, top);
550 }
511 } 551 }
512 552
513 // FIXME: This is similar to the implementation for bmp and png. Can we share m ore code or 553 // FIXME: This is similar to the implementation for bmp and png. Can we share m ore code or
514 // possibly make this non-virtual? 554 // possibly make this non-virtual?
515 uint64_t SkGifCodec::onGetFillValue(const SkImageInfo& dstInfo) const { 555 uint64_t SkGifCodec::onGetFillValue(const SkImageInfo& dstInfo) const {
516 const SkPMColor* colorPtr = get_color_ptr(fColorTable.get()); 556 const SkPMColor* colorPtr = get_color_ptr(fColorTable.get());
517 return get_color_table_fill_value(dstInfo.colorType(), dstInfo.alphaType(), colorPtr, 557 return get_color_table_fill_value(dstInfo.colorType(), dstInfo.alphaType(), colorPtr,
518 fFillIndex, nullptr); 558 fFillIndex, nullptr);
519 } 559 }
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

Powered by Google App Engine
This is Rietveld 408576698