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

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: Small cleanups 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));
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[i];
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 std::vector<SkCodec::FrameInfo> SkGifCodec::onGetFrameInfo() {
270 // Use this as a container to hold information about any gif extension 311 const size_t size = fFrameInfos.size();
271 // blocks. This generally stores transparency and animation instructions. 312 if (1 == size) {
272 SavedImage saveExt; 313 // As with other formats, return empty set for non-animated
273 SkAutoTCallVProc<SavedImage, FreeExtension> autoFreeExt(&saveExt); 314 // FIXME: But it might be animated, we just haven't received the second frame?
274 saveExt.ExtensionBlocks = nullptr; 315 // I suppose we could check the duration? But even that might not be per fect...
275 saveExt.ExtensionBlockCount = 0; 316 return {};
276 GifByteType* extData; 317 }
277 int32_t extFunction; 318 std::vector<FrameInfo> result(size);
278 319 for (size_t i = 0; i < size; i++) {
279 // We will loop over components of gif images until we find an image. Once 320 result[i] = (FrameInfo) fFrameInfos[i];
280 // we find an image, we will decode and return it. While many gif files 321 }
281 // contain more than one image, we will simply decode the first image. 322 return result;
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 } 323 }
359 324
360 bool SkGifCodec::GetDimensions(GifFileType* gif, SkISize* size, SkIRect* frameRe ct) { 325 bool SkGifCodec::GetDimensions(GifFileType* gif, SkISize* size) {
361 // Get the encoded dimension values 326 // Get the encoded dimension values for the first frame. Some GIFs have fram es that are bigger
362 SavedImage* image = &gif->SavedImages[gif->ImageCount - 1]; 327 // than the screen width and height. For the first frame only, we will expan d in that case.
328 SavedImage* image = &gif->SavedImages[0];
363 const GifImageDesc& desc = image->ImageDesc; 329 const GifImageDesc& desc = image->ImageDesc;
364 int frameLeft = desc.Left; 330 int frameLeft = desc.Left;
365 int frameTop = desc.Top; 331 int frameTop = desc.Top;
366 int frameWidth = desc.Width; 332 int frameWidth = desc.Width;
367 int frameHeight = desc.Height; 333 int frameHeight = desc.Height;
368 int width = gif->SWidth; 334 int width = gif->SWidth;
369 int height = gif->SHeight; 335 int height = gif->SHeight;
370 336
371 // Ensure that the decode dimensions are large enough to contain the frame 337 // Ensure that the decode dimensions are large enough to contain the frame
372 width = SkTMax(width, frameWidth + frameLeft); 338 width = SkTMax(width, frameWidth + frameLeft);
373 height = SkTMax(height, frameHeight + frameTop); 339 height = SkTMax(height, frameHeight + frameTop);
374 340
375 // All of these dimensions should be positive, as they are encoded as unsign ed 16-bit integers. 341 // 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 342 // It is unclear why giflib casts them to ints. We will go ahead and check that they are
377 // in fact positive. 343 // in fact positive.
378 if (frameLeft < 0 || frameTop < 0 || frameWidth < 0 || frameHeight < 0 || wi dth <= 0 || 344 if (frameLeft < 0 || frameTop < 0 || frameWidth < 0 || frameHeight < 0 || wi dth <= 0 ||
379 height <= 0) { 345 height <= 0) {
380 return false; 346 return false;
381 } 347 }
382 348
383 frameRect->setXYWH(frameLeft, frameTop, frameWidth, frameHeight);
384 size->set(width, height); 349 size->set(width, height);
385 return true; 350 return true;
386 } 351 }
387 352
388 void SkGifCodec::initializeColorTable(const SkImageInfo& dstInfo, SkPMColor* inp utColorPtr, 353 constexpr uint32_t kMaxColors = 256;
354
355 bool SkGifCodec::initializeColorTable(const SkImageInfo& dstInfo, SkPMColor* inp utColorPtr,
389 int* inputColorCount) { 356 int* inputColorCount) {
390 // Set up our own color table 357 // FIXME: Use the correct one for the frame.
391 const uint32_t maxColors = 256; 358 if (!fColorTable) {
392 SkPMColor colorPtr[256]; 359 return false;
393 if (NULL != inputColorCount) { 360 }
394 // We set the number of colors to maxColors in order to ensure 361 if (inputColorCount) {
395 // safe memory accesses. Otherwise, an invalid pixel could 362 *inputColorCount = fColorTable->count();
396 // access memory outside of our color table array.
397 *inputColorCount = maxColors;
398 } 363 }
399 364
400 // Get local color table 365 copy_color_table(dstInfo, fColorTable, inputColorPtr, inputColorCount);
401 ColorMapObject* colorMap = fGif->Image.ColorMap; 366 return true;
402 // If there is no local color table, use the global color table 367 }
403 if (NULL == colorMap) {
404 colorMap = fGif->SColorMap;
405 }
406 368
407 uint32_t colorCount = 0; 369 static SkColorTable* create_color_table(const ColorMapObject& colorMap, uint32_t transIndex,
408 if (NULL != colorMap) { 370 uint32_t backgroundIndex) {
409 colorCount = colorMap->ColorCount; 371 SkPMColor colorPtr[kMaxColors];
410 // giflib guarantees these properties 372 const uint32_t colorCount = colorMap.ColorCount;
411 SkASSERT(colorCount == (unsigned) (1 << (colorMap->BitsPerPixel))); 373 // giflib guarantees these properties
412 SkASSERT(colorCount <= 256); 374 SkASSERT(colorCount == (unsigned) (1 << (colorMap.BitsPerPixel)));
413 PackColorProc proc = choose_pack_color_proc(false, dstInfo.colorType()); 375 SkASSERT(colorCount <= 256);
414 for (uint32_t i = 0; i < colorCount; i++) { 376
415 colorPtr[i] = proc(0xFF, colorMap->Colors[i].Red, 377 // 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); 378 PackColorProc proc = choose_pack_color_proc(false, kIndex_8_SkColorType);
417 } 379 for (uint32_t i = 0; i < colorCount; i++) {
380 const GifColorType& color = colorMap.Colors[i];
381 colorPtr[i] = proc(0xFF, color.Red, color.Green, color.Blue);
418 } 382 }
419 383
420 // Fill in the color table for indices greater than color count. 384 // Fill in the color table for indices greater than color count.
421 // This allows for predictable, safe behavior. 385 // This allows for predictable, safe behavior.
422 if (colorCount > 0) { 386 if (colorCount > 0) {
423 // Gifs have the option to specify the color at a single index of the co lor 387 // 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 388 // 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 389 // 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 390 // 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 391 // 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 392 // valid, we will let fFillIndex default to 0 (it is set to zero in the
429 // constructor). This behavior is not specified but matches 393 // constructor). This behavior is not specified but matches
430 // SkImageDecoder_libgif. 394 // SkImageDecoder_libgif.
431 uint32_t backgroundIndex = fGif->SBackGroundColor; 395 uint32_t fillIndex;
432 if (fTransIndex < colorCount) { 396 if (transIndex < colorCount) {
433 colorPtr[fTransIndex] = SK_ColorTRANSPARENT; 397 colorPtr[transIndex] = SK_ColorTRANSPARENT;
434 fFillIndex = fTransIndex; 398 fillIndex = transIndex;
435 } else if (backgroundIndex < colorCount) { 399 } else if (backgroundIndex < colorCount) {
436 fFillIndex = backgroundIndex; 400 fillIndex = backgroundIndex;
401 } else {
402 fillIndex = 0;
437 } 403 }
438 404
439 for (uint32_t i = colorCount; i < maxColors; i++) { 405 for (uint32_t i = colorCount; i < kMaxColors; i++) {
440 colorPtr[i] = colorPtr[fFillIndex]; 406 colorPtr[i] = colorPtr[fillIndex];
441 } 407 }
442 } else { 408 } else {
443 sk_memset32(colorPtr, 0xFF000000, maxColors); 409 sk_memset32(colorPtr, 0xFF000000, kMaxColors);
444 } 410 }
445 411
446 fColorTable.reset(new SkColorTable(colorPtr, maxColors)); 412 return new SkColorTable(colorPtr, kMaxColors);
447 copy_color_table(dstInfo, this->fColorTable, inputColorPtr, inputColorCount) ;
448 } 413 }
449 414
450 SkCodec::Result SkGifCodec::prepareToDecode(const SkImageInfo& dstInfo, SkPMColo r* inputColorPtr, 415 SkCodec::Result SkGifCodec::prepareToDecode(const SkImageInfo& dstInfo, SkPMColo r* inputColorPtr,
451 int* inputColorCount, const Options& opts) { 416 int* inputColorCount, const Options& opts) {
452 // Check for valid input parameters 417 // Check for valid input parameters
453 if (!conversion_possible_ignore_color_space(dstInfo, this->getInfo())) { 418 if (!conversion_possible_ignore_color_space(dstInfo, this->getInfo())) {
454 return gif_error("Cannot convert input type to output type.\n", kInvalid Conversion); 419 return gif_error("Cannot convert input type to output type.\n", kInvalid Conversion);
455 } 420 }
456 421
422 if ((opts.fFrameOptions && opts.fFrameOptions->fIndex > 0)
423 && dstInfo.colorType() == kIndex_8_SkColorType) {
424 // FIXME: It is possible that a later frame can be decoded to index8, if it does one of the
425 // following:
426 // - Covers the entire previous frame
427 // - Shares a color table (and transparent index) with any prior frames that are showing.
428 // We must support index8 for the first frame to be backwards compatible on Android.
429 return gif_error("Cannot decode multiframe gif (except frame 0) as index 8.\n",
430 kInvalidConversion);
431 }
432
433 if (opts.fFrameOptions && opts.fFrameOptions->fIndex > fFrameInfos.size()) {
434 return gif_error("frame index out of range!\n", kInvalidParameters);
435 }
436
457 // Initialize color table and copy to the client if necessary 437 // Initialize color table and copy to the client if necessary
458 this->initializeColorTable(dstInfo, inputColorPtr, inputColorCount); 438 if (!this->initializeColorTable(dstInfo, inputColorPtr, inputColorCount)) {
459 439 // FIXME: Should have figured this out sooner...
460 this->initializeSwizzler(dstInfo, opts); 440 return gif_error("no color table!\n", kInvalidInput);
441 }
461 return kSuccess; 442 return kSuccess;
462 } 443 }
463 444
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 /* 445 /*
477 * Initiates the gif decode 446 * Initiates the gif decode
478 */ 447 */
479 SkCodec::Result SkGifCodec::onGetPixels(const SkImageInfo& dstInfo, 448 SkCodec::Result SkGifCodec::onGetPixels(const SkImageInfo& dstInfo,
480 void* dst, size_t dstRowBytes, 449 void* pixels, size_t dstRowBytes,
481 const Options& opts, 450 const Options& opts,
482 SkPMColor* inputColorPtr, 451 SkPMColor* inputColorPtr,
483 int* inputColorCount, 452 int* inputColorCount,
484 int* rowsDecoded) { 453 int* rowsDecoded) {
485 Result result = this->prepareToDecode(dstInfo, inputColorPtr, inputColorCoun t, opts); 454 Result result = this->prepareToDecode(dstInfo, inputColorPtr, inputColorCoun t, opts);
486 if (kSuccess != result) { 455 if (kSuccess != result) {
487 return result; 456 return result;
488 } 457 }
489 458
490 if (dstInfo.dimensions() != this->getInfo().dimensions()) { 459 if (dstInfo.dimensions() != this->getInfo().dimensions()) {
491 return gif_error("Scaling not supported.\n", kInvalidScale); 460 return gif_error("Scaling not supported.\n", kInvalidScale);
492 } 461 }
493 462
494 // Initialize the swizzler 463 this->decodeFrame(dstInfo, pixels, dstRowBytes, opts);
495 if (fFrameIsSubset) { 464 return kSuccess;
496 // Fill the background 465 }
497 SkSampler::Fill(dstInfo, dst, dstRowBytes, this->getFillValue(dstInfo), 466
498 opts.fZeroInitialized); 467 // FIXME: This should be SkCodec::Result, probably?
468 void SkGifCodec::decodeFrame(const SkImageInfo& dstInfo, void* pixels, size_t ds tRowBytes,
469 const Options& opts) {
470 SkBitmap tmpBm;
471 void* dst = pixels;
472
473 const size_t frameIndex = opts.fFrameOptions ? opts.fFrameOptions->fIndex : 0;
474 SkASSERT(frameIndex < fFrameInfos.size());
475 const auto& frameInfo = fFrameInfos[frameIndex];
476 const SkIRect& frameRect = frameInfo.fFrameRect;
477 const bool independent = frameInfo.fRequiredFrame == kIndependentFrame;
478 if (!independent) {
479 if (opts.fFrameOptions && !opts.fFrameOptions->fHasPriorFrame) {
480 // Decode that frame into pixels.
481 Options prevFrameOpts(opts);
482 MultiFrameOptions prevFrameMultiOpts;
483 prevFrameMultiOpts.fIndex = frameInfo.fRequiredFrame;
484 prevFrameMultiOpts.fHasPriorFrame = false;
485 prevFrameOpts.fFrameOptions = &prevFrameMultiOpts;
486 this->decodeFrame(dstInfo, pixels, dstRowBytes, prevFrameOpts);
487 }
488 const auto& prevFrame = fFrameInfos[frameInfo.fRequiredFrame];
489 if (prevFrame.fDisposalMethod == SkCodecAnimation::RestoreBGColor_Dispos alMethod) {
490 const SkIRect& prevRect = prevFrame.fFrameRect;
491 void* const eraseDst = SkTAddOffset<void>(pixels, prevRect.fTop * ds tRowBytes
492 + prevRect.fLeft * SkColorTypeBytesPerPixel(dstInfo.colorTyp e()));
493 // FIXME: Is this the right color?
494 SkSampler::Fill(dstInfo.makeWH(prevRect.width(), prevRect.height()), eraseDst,
495 dstRowBytes, SK_ColorTRANSPARENT, SkCodec::kNo_ZeroI nitialized);
496 }
497
498 // Now we need to swizzle to a temporary bitmap. That way we do not over write pixels
499 // with transparent. Later we'll draw to pixels
500 const int frameWidth = frameRect.width();
501 const int frameHeight = frameRect.height();
502 SkImageInfo tmpInfo = dstInfo.makeWH(frameWidth, frameHeight);
503 // FIXME: Could be more agressive than this (i.e. it could be out of the actual range of
504 // the color map).
505 if (frameInfo.fTransIndex < 256) {
506 // Need alpha to blend with prior frame.
507 tmpInfo = tmpInfo.makeAlphaType(kUnpremul_SkAlphaType);
508 }
509 tmpBm.allocPixels(tmpInfo);
510 dst = tmpBm.getPixels();
511 } else {
512 // This frame is independent
513 if (frameRect != dstInfo.bounds()) {
514 // Fill the background
515 // FIXME: Android may want the BG color, but Chromium wants transpar ent!
516 SkSampler::Fill(dstInfo, pixels, dstRowBytes, SK_ColorTRANSPARENT,
517 opts.fZeroInitialized);
518
519 // Now offset dst to draw the frame:
520 dst = SkTAddOffset<void>(dst, frameRect.fTop * dstRowBytes
521 + frameRect.fLeft * SkColorTypeBytesPerPixel(dstInfo.colorTy pe()));
522 }
499 } 523 }
500 524
525 SkASSERT((int) frameIndex < fGif->ImageCount);
526 const SavedImage* image = &fGif->SavedImages[frameIndex];
527 const GifImageDesc& desc = image->ImageDesc;
528
529 ColorMapObject* cmap = desc.ColorMap ? desc.ColorMap : fGif->SColorMap;
530 sk_sp<SkColorTable> ct(create_color_table(*cmap, frameInfo.fTransIndex, SK_M axU32));
531
532 std::unique_ptr<SkSwizzler> swizzler(SkSwizzler::CreateSwizzler(this->getEnc odedInfo(),
533 ct->readColors(), dstInfo, opts));
534 SkASSERT(swizzler);
535
501 // Iterate over rows of the input 536 // Iterate over rows of the input
502 for (int y = fFrameRect.top(); y < fFrameRect.bottom(); y++) { 537 void* dstRow = dst;
503 if (!this->readRow()) { 538 GifByteType* src = image->RasterBits;
504 *rowsDecoded = y; 539 for (int y = 0; y < desc.Height; y++) {
505 return gif_error("Could not decode line.\n", kIncompleteInput); 540 swizzler->swizzle(dstRow, src);
506 } 541 dstRow = SkTAddOffset<void>(dstRow, dstRowBytes);
507 void* dstRow = SkTAddOffset<void>(dst, dstRowBytes * this->outputScanlin e(y)); 542 src = SkTAddOffset<GifByteType>(src, desc.Width);
508 fSwizzler->swizzle(dstRow, fSrcBuffer.get());
509 } 543 }
510 return kSuccess; 544
545 if (!independent) {
546 // We drew to a temporary bitmap. Now we need to draw it to pixels.
547 SkASSERT(tmpBm.getPixels() == dst);
548 SkBitmap dstBm;
549 // FIXME: What to do if this fails?
550 dstBm.installPixels(dstInfo, pixels, dstRowBytes, fColorTable, nullptr, nullptr);
551 SkCanvas canvas(dstBm);
552 const SkScalar left = SkIntToScalar(frameRect.left());
553 const SkScalar top = SkIntToScalar(frameRect.top());
554 canvas.drawBitmap(tmpBm, left, top);
555 }
511 } 556 }
512 557
513 // FIXME: This is similar to the implementation for bmp and png. Can we share m ore code or 558 // FIXME: This is similar to the implementation for bmp and png. Can we share m ore code or
514 // possibly make this non-virtual? 559 // possibly make this non-virtual?
515 uint64_t SkGifCodec::onGetFillValue(const SkImageInfo& dstInfo) const { 560 uint64_t SkGifCodec::onGetFillValue(const SkImageInfo& dstInfo) const {
516 const SkPMColor* colorPtr = get_color_ptr(fColorTable.get()); 561 const SkPMColor* colorPtr = get_color_ptr(fColorTable.get());
517 return get_color_table_fill_value(dstInfo.colorType(), dstInfo.alphaType(), colorPtr, 562 return get_color_table_fill_value(dstInfo.colorType(), dstInfo.alphaType(), colorPtr,
518 fFillIndex, nullptr); 563 fFillIndex, nullptr);
519 } 564 }
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