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

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: Disable DNG if Raw is disabled 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
« no previous file with comments | « src/codec/SkGifCodec.h ('k') | src/codec/SkSampledCodec.cpp » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
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 /*
9 * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 *
20 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
21 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
24 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
25 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
26 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
27 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
28 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 */
32
33 #include "SkCodecAnimation.h"
8 #include "SkCodecPriv.h" 34 #include "SkCodecPriv.h"
9 #include "SkColorPriv.h" 35 #include "SkColorPriv.h"
10 #include "SkColorTable.h" 36 #include "SkColorTable.h"
11 #include "SkGifCodec.h" 37 #include "SkGifCodec.h"
12 #include "SkStream.h" 38 #include "SkStream.h"
13 #include "SkSwizzler.h" 39 #include "SkSwizzler.h"
14 #include "SkUtils.h"
15 40
16 #include "gif_lib.h" 41 #define GIF87_STAMP "GIF87a"
42 #define GIF89_STAMP "GIF89a"
43 #define GIF_STAMP_LEN 6
17 44
18 /* 45 /*
19 * Checks the start of the stream to see if the image is a gif 46 * Checks the start of the stream to see if the image is a gif
20 */ 47 */
21 bool SkGifCodec::IsGif(const void* buf, size_t bytesRead) { 48 bool SkGifCodec::IsGif(const void* buf, size_t bytesRead) {
22 if (bytesRead >= GIF_STAMP_LEN) { 49 if (bytesRead >= GIF_STAMP_LEN) {
23 if (memcmp(GIF_STAMP, buf, GIF_STAMP_LEN) == 0 || 50 if (memcmp(GIF87_STAMP, buf, GIF_STAMP_LEN) == 0 ||
24 memcmp(GIF87_STAMP, buf, GIF_STAMP_LEN) == 0 ||
25 memcmp(GIF89_STAMP, buf, GIF_STAMP_LEN) == 0) 51 memcmp(GIF89_STAMP, buf, GIF_STAMP_LEN) == 0)
26 { 52 {
27 return true; 53 return true;
28 } 54 }
29 } 55 }
30 return false; 56 return false;
31 } 57 }
32 58
33 /* 59 /*
34 * Error function 60 * Error function
35 */ 61 */
36 static SkCodec::Result gif_error(const char* msg, SkCodec::Result result = SkCod ec::kInvalidInput) { 62 static SkCodec::Result gif_error(const char* msg, SkCodec::Result result = SkCod ec::kInvalidInput) {
37 SkCodecPrintf("Gif Error: %s\n", msg); 63 SkCodecPrintf("Gif Error: %s\n", msg);
38 return result; 64 return result;
39 } 65 }
40 66
41
42 /*
43 * Read function that will be passed to gif_lib
44 */
45 static int32_t read_bytes_callback(GifFileType* fileType, GifByteType* out, int3 2_t size) {
46 SkStream* stream = (SkStream*) fileType->UserData;
47 return (int32_t) stream->read(out, size);
48 }
49
50 /*
51 * Open the gif file
52 */
53 static GifFileType* open_gif(SkStream* stream) {
54 #if GIFLIB_MAJOR < 5
55 return DGifOpen(stream, read_bytes_callback);
56 #else
57 return DGifOpen(stream, read_bytes_callback, nullptr);
58 #endif
59 }
60
61 /*
62 * Check if a there is an index of the color table for a transparent pixel
63 */
64 static uint32_t find_trans_index(const SavedImage& image) {
65 // 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
67 // to check the most recent extension blocks first.
68 for (int32_t i = image.ExtensionBlockCount - 1; i >= 0; i--) {
69 // Get an extension block
70 const ExtensionBlock& extBlock = image.ExtensionBlocks[i];
71
72 // Specifically, we need to check for a graphics control extension,
73 // which may contain transparency information. Also, note that a valid
74 // graphics control extension is always four bytes. The fourth byte
75 // is the transparent index (if it exists), so we need at least four
76 // bytes.
77 if (GRAPHICS_EXT_FUNC_CODE == extBlock.Function && extBlock.ByteCount >= 4) {
78 // Check the transparent color flag which indicates whether a
79 // transparent index exists. It is the least significant bit of
80 // the first byte of the extension block.
81 if (1 == (extBlock.Bytes[0] & 1)) {
82 // Use uint32_t to prevent sign extending
83 return extBlock.Bytes[3];
84 }
85
86 // There should only be one graphics control extension for the image frame
87 break;
88 }
89 }
90
91 // Use maximum unsigned int (surely an invalid index) to indicate that a val id
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 }
99
100 /*
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
123 * It is used in a SkAutoTCallIProc template
124 */
125 void SkGifCodec::CloseGif(GifFileType* gif) {
126 #if GIFLIB_MAJOR < 5 || (GIFLIB_MAJOR == 5 && GIFLIB_MINOR == 0)
127 DGifCloseFile(gif);
128 #else
129 DGifCloseFile(gif, nullptr);
130 #endif
131 }
132
133 /*
134 * This function free extension data that has been saved to assist the image
135 * decoder
136 */
137 void SkGifCodec::FreeExtension(SavedImage* image) {
138 if (NULL != image->ExtensionBlocks) {
139 #if GIFLIB_MAJOR < 5
140 FreeExtension(image);
141 #else
142 GifFreeExtensions(&image->ExtensionBlockCount, &image->ExtensionBlocks);
143 #endif
144 }
145 }
146
147 /*
148 * Read enough of the stream to initialize the SkGifCodec.
149 * Returns a bool representing success or failure.
150 *
151 * @param codecOut
152 * If it returned true, and codecOut was not nullptr,
153 * codecOut will be set to a new SkGifCodec.
154 *
155 * @param gifOut
156 * If it returned true, and codecOut was nullptr,
157 * gifOut must be non-nullptr and gifOut will be set to a new
158 * GifFileType pointer.
159 *
160 * @param stream
161 * Deleted on failure.
162 * codecOut will take ownership of it in the case where we created a codec.
163 * Ownership is unchanged when we returned a gifOut.
164 *
165 */
166 bool SkGifCodec::ReadHeader(SkStream* stream, SkCodec** codecOut, GifFileType** gifOut) {
167 SkAutoTDelete<SkStream> streamDeleter(stream);
168
169 // Read gif header, logical screen descriptor, and global color table
170 SkAutoTCallVProc<GifFileType, CloseGif> gif(open_gif(stream));
171
172 if (nullptr == gif) {
173 gif_error("DGifOpen failed.\n");
174 return false;
175 }
176
177 // Read through gif extensions to get to the image data. Set the
178 // transparent index based on the extension data.
179 uint32_t transIndex;
180 SkCodec::Result result = ReadUpToFirstImage(gif, &transIndex);
181 if (kSuccess != result){
182 return false;
183 }
184
185 // Read the image descriptor
186 if (GIF_ERROR == DGifGetImageDesc(gif)) {
187 return false;
188 }
189 // If reading the image descriptor is successful, the image count will be
190 // incremented.
191 SkASSERT(gif->ImageCount >= 1);
192
193 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
203 // 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
205 // there might be a valid transparent index, we must indicate that the i mage has
206 // alpha.
207 // In the case where we must support alpha, we indicate kBinary, since e very
208 // pixel will either be fully opaque or fully transparent.
209 SkEncodedInfo::Alpha alpha = (transIndex < 256) ? SkEncodedInfo::kBinary _Alpha :
210 SkEncodedInfo::kOpaque_Alpha;
211
212 // Return the codec
213 // 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 .
215 // 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);
217 *codecOut = new SkGifCodec(size.width(), size.height(), info, streamDele ter.release(),
218 gif.release(), transIndex, frameRect, frameIsSubset);
219 } else {
220 SkASSERT(nullptr != gifOut);
221 streamDeleter.release();
222 *gifOut = gif.release();
223 }
224 return true;
225 }
226
227 /* 67 /*
228 * Assumes IsGif was called and returned true 68 * Assumes IsGif was called and returned true
229 * Creates a gif decoder 69 * Creates a gif decoder
230 * Reads enough of the stream to determine the image format 70 * Reads enough of the stream to determine the image format
231 */ 71 */
232 SkCodec* SkGifCodec::NewFromStream(SkStream* stream) { 72 SkCodec* SkGifCodec::NewFromStream(SkStream* stream) {
233 SkCodec* codec = nullptr; 73 std::unique_ptr<GIFImageReader> reader(new GIFImageReader(stream));
234 if (ReadHeader(stream, &codec, nullptr)) { 74 if (!reader->parse(GIFImageReader::GIFSizeQuery)) {
235 return codec; 75 // Not enough data to determine the size.
76 return nullptr;
236 } 77 }
237 return nullptr; 78
79 if (0 == reader->screenWidth() || 0 == reader->screenHeight()) {
80 return nullptr;
81 }
82
83 const auto alpha = reader->firstFrameHasAlpha() ? SkEncodedInfo::kBinary_Alp ha
84 : SkEncodedInfo::kOpaque_Alp ha;
85 // Use kPalette since Gifs are encoded with a color table.
86 // FIXME: Gifs can actually be encoded with 4-bits per pixel. Using 8 works, but we could skip
87 // expanding to 8 bits and take advantage of the SkSwizzler to work f rom 4.
88 const auto encodedInfo = SkEncodedInfo::Make(SkEncodedInfo::kPalette_Color, alpha, 8);
89
90 // Although the encodedInfo is always kPalette_Color, it is possible that kI ndex_8 is
91 // unsupported if the frame is subset and there is no transparent pixel.
92 const auto colorType = reader->firstFrameSupportsIndex8() ? kIndex_8_SkColor Type
93 : kN32_SkColorType ;
94 // The choice of unpremul versus premul is arbitrary, since all colors are e ither fully
95 // opaque or fully transparent (i.e. kBinary), but we stored the transparent colors as all
96 // zeroes, which is arguably premultiplied.
97 const auto alphaType = reader->firstFrameHasAlpha() ? kPremul_SkAlphaType
msarett 2016/10/20 18:20:37 Can we recommend kUnpremul here? I *think* we wan
scroggo 2016/10/20 18:34:11 Done.
98 : kOpaque_SkAlphaType;
99 const auto imageInfo = SkImageInfo::Make(reader->screenWidth(), reader->scre enHeight(),
msarett 2016/10/20 18:20:37 I missed this in the earlier patch sets, but we sh
scroggo 2016/10/20 18:34:11 As discussed in person, it looks like we previousl
100 colorType, alphaType);
101 return new SkGifCodec(encodedInfo, imageInfo, reader.release());
238 } 102 }
239 103
240 SkGifCodec::SkGifCodec(int width, int height, const SkEncodedInfo& info, SkStrea m* stream,
241 GifFileType* gif, uint32_t transIndex, const SkIRect& frameRect, bool fr ameIsSubset)
242 : INHERITED(width, height, info, stream)
243 , fGif(gif)
244 , 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)
253 , fFrameIsSubset(frameIsSubset)
254 , fSwizzler(NULL)
255 , fColorTable(NULL)
256 {}
257
258 bool SkGifCodec::onRewind() { 104 bool SkGifCodec::onRewind() {
259 GifFileType* gifOut = nullptr; 105 fReader->clearDecodeState();
260 if (!ReadHeader(this->stream(), nullptr, &gifOut)) {
261 return false;
262 }
263
264 SkASSERT(nullptr != gifOut);
265 fGif.reset(gifOut);
266 return true; 106 return true;
267 } 107 }
268 108
269 SkCodec::Result SkGifCodec::ReadUpToFirstImage(GifFileType* gif, uint32_t* trans Index) { 109 SkGifCodec::SkGifCodec(const SkEncodedInfo& encodedInfo, const SkImageInfo& imag eInfo,
270 // Use this as a container to hold information about any gif extension 110 GIFImageReader* reader)
271 // blocks. This generally stores transparency and animation instructions. 111 : INHERITED(encodedInfo, imageInfo, nullptr)
272 SavedImage saveExt; 112 , fReader(reader)
273 SkAutoTCallVProc<SavedImage, FreeExtension> autoFreeExt(&saveExt); 113 , fTmpBuffer(nullptr)
274 saveExt.ExtensionBlocks = nullptr; 114 , fSwizzler(nullptr)
275 saveExt.ExtensionBlockCount = 0; 115 , fCurrColorTable(nullptr)
276 GifByteType* extData; 116 , fCurrColorTableIsReal(false)
277 int32_t extFunction; 117 , fFilledBackground(false)
278 118 , fFirstCallToIncrementalDecode(false)
279 // We will loop over components of gif images until we find an image. Once 119 , fDst(nullptr)
280 // we find an image, we will decode and return it. While many gif files 120 , fDstRowBytes(0)
281 // contain more than one image, we will simply decode the first image. 121 , fRowsDecoded(0)
282 GifRecordType recordType; 122 {
283 do { 123 reader->setClient(this);
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 } 124 }
359 125
360 bool SkGifCodec::GetDimensions(GifFileType* gif, SkISize* size, SkIRect* frameRe ct) { 126 std::vector<SkCodec::FrameInfo> SkGifCodec::onGetFrameInfo() {
361 // Get the encoded dimension values 127 fReader->parse(GIFImageReader::GIFFrameCountQuery);
362 SavedImage* image = &gif->SavedImages[gif->ImageCount - 1]; 128 const size_t size = fReader->imagesCount();
363 const GifImageDesc& desc = image->ImageDesc; 129 std::vector<FrameInfo> result(size);
364 int frameLeft = desc.Left; 130 for (size_t i = 0; i < size; i++) {
365 int frameTop = desc.Top; 131 const GIFFrameContext* frameContext = fReader->frameContext(i);
366 int frameWidth = desc.Width; 132 result[i].fDuration = frameContext->delayTime();
367 int frameHeight = desc.Height; 133 result[i].fRequiredFrame = frameContext->getRequiredFrame();
368 int width = gif->SWidth; 134 }
369 int height = gif->SHeight; 135 return result;
136 }
370 137
371 // Ensure that the decode dimensions are large enough to contain the frame 138 void SkGifCodec::initializeColorTable(const SkImageInfo& dstInfo, size_t frameIn dex,
372 width = SkTMax(width, frameWidth + frameLeft); 139 SkPMColor* inputColorPtr, int* inputColorCount) {
373 height = SkTMax(height, frameHeight + frameTop); 140 fCurrColorTable = std::move(fReader->getColorTable(dstInfo.colorType(), fram eIndex));
374 141 fCurrColorTableIsReal = fCurrColorTable;
375 // All of these dimensions should be positive, as they are encoded as unsign ed 16-bit integers. 142 if (!fCurrColorTable) {
376 // It is unclear why giflib casts them to ints. We will go ahead and check that they are 143 // This is possible for an empty frame. Create a dummy with one value (t ransparent).
377 // in fact positive. 144 SkPMColor color = SK_ColorTRANSPARENT;
378 if (frameLeft < 0 || frameTop < 0 || frameWidth < 0 || frameHeight < 0 || wi dth <= 0 || 145 fCurrColorTable.reset(new SkColorTable(&color, 1));
379 height <= 0) {
380 return false;
381 } 146 }
382 147
383 frameRect->setXYWH(frameLeft, frameTop, frameWidth, frameHeight); 148 if (inputColorCount) {
384 size->set(width, height); 149 *inputColorCount = fCurrColorTable->count();
385 return true; 150 }
151
152 copy_color_table(dstInfo, fCurrColorTable.get(), inputColorPtr, inputColorCo unt);
386 } 153 }
387 154
388 void SkGifCodec::initializeColorTable(const SkImageInfo& dstInfo, SkPMColor* inp utColorPtr,
389 int* inputColorCount) {
390 // Set up our own color table
391 const uint32_t maxColors = 256;
392 SkPMColor colorPtr[256];
393 if (NULL != inputColorCount) {
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 }
399
400 // Get local color table
401 ColorMapObject* colorMap = fGif->Image.ColorMap;
402 // If there is no local color table, use the global color table
403 if (NULL == colorMap) {
404 colorMap = fGif->SColorMap;
405 }
406
407 uint32_t colorCount = 0;
408 if (NULL != colorMap) {
409 colorCount = colorMap->ColorCount;
410 // giflib guarantees these properties
411 SkASSERT(colorCount == (unsigned) (1 << (colorMap->BitsPerPixel)));
412 SkASSERT(colorCount <= 256);
413 PackColorProc proc = choose_pack_color_proc(false, dstInfo.colorType());
414 for (uint32_t i = 0; i < colorCount; i++) {
415 colorPtr[i] = proc(0xFF, colorMap->Colors[i].Red,
416 colorMap->Colors[i].Green, colorMap->Colors[i].Blue);
417 }
418 }
419
420 // Fill in the color table for indices greater than color count.
421 // This allows for predictable, safe behavior.
422 if (colorCount > 0) {
423 // 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
425 // 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
427 // 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
429 // constructor). This behavior is not specified but matches
430 // SkImageDecoder_libgif.
431 uint32_t backgroundIndex = fGif->SBackGroundColor;
432 if (fTransIndex < colorCount) {
433 colorPtr[fTransIndex] = SK_ColorTRANSPARENT;
434 fFillIndex = fTransIndex;
435 } else if (backgroundIndex < colorCount) {
436 fFillIndex = backgroundIndex;
437 }
438
439 for (uint32_t i = colorCount; i < maxColors; i++) {
440 colorPtr[i] = colorPtr[fFillIndex];
441 }
442 } else {
443 sk_memset32(colorPtr, 0xFF000000, maxColors);
444 }
445
446 fColorTable.reset(new SkColorTable(colorPtr, maxColors));
447 copy_color_table(dstInfo, this->fColorTable, inputColorPtr, inputColorCount) ;
448 }
449 155
450 SkCodec::Result SkGifCodec::prepareToDecode(const SkImageInfo& dstInfo, SkPMColo r* inputColorPtr, 156 SkCodec::Result SkGifCodec::prepareToDecode(const SkImageInfo& dstInfo, SkPMColo r* inputColorPtr,
451 int* inputColorCount, const Options& opts) { 157 int* inputColorCount, const Options& opts) {
452 // Check for valid input parameters 158 // Check for valid input parameters
453 if (!conversion_possible_ignore_color_space(dstInfo, this->getInfo())) { 159 if (!conversion_possible_ignore_color_space(dstInfo, this->getInfo())) {
454 return gif_error("Cannot convert input type to output type.\n", kInvalid Conversion); 160 return gif_error("Cannot convert input type to output type.\n", kInvalid Conversion);
455 } 161 }
456 162
163 if (dstInfo.colorType() == kRGBA_F16_SkColorType) {
164 // FIXME: This should be supported.
165 return gif_error("GIF does not yet support F16.\n", kInvalidConversion);
166 }
167
168 if (opts.fSubset) {
169 return gif_error("Subsets not supported.\n", kUnimplemented);
170 }
171
172 const size_t frameIndex = opts.fFrameOptions ? opts.fFrameOptions->fIndex : 0;
173 if (frameIndex > 0 && dstInfo.colorType() == kIndex_8_SkColorType) {
174 // FIXME: It is possible that a later frame can be decoded to index8, if it does one of the
175 // following:
176 // - Covers the entire previous frame
177 // - Shares a color table (and transparent index) with any prior frames that are showing.
178 // We must support index8 for the first frame to be backwards compatible on Android, but
179 // we do not (currently) need to support later frames as index8.
180 return gif_error("Cannot decode multiframe gif (except frame 0) as index 8.\n",
181 kInvalidConversion);
182 }
183
184 fReader->parse((GIFImageReader::GIFParseQuery) frameIndex);
185
186 if (frameIndex >= fReader->imagesCount()) {
187 return gif_error("frame index out of range!\n", kIncompleteInput);
188 }
189
190 fTmpBuffer.reset(new uint8_t[dstInfo.minRowBytes()]);
191
457 // Initialize color table and copy to the client if necessary 192 // Initialize color table and copy to the client if necessary
458 this->initializeColorTable(dstInfo, inputColorPtr, inputColorCount); 193 this->initializeColorTable(dstInfo, frameIndex, inputColorPtr, inputColorCou nt);
459 194 this->initializeSwizzler(dstInfo, frameIndex);
460 this->initializeSwizzler(dstInfo, opts);
461 return kSuccess; 195 return kSuccess;
462 } 196 }
463 197
464 void SkGifCodec::initializeSwizzler(const SkImageInfo& dstInfo, const Options& o pts) { 198 void SkGifCodec::initializeSwizzler(const SkImageInfo& dstInfo, size_t frameInde x) {
465 const SkPMColor* colorPtr = get_color_ptr(fColorTable.get()); 199 const GIFFrameContext* frame = fReader->frameContext(frameIndex);
466 const SkIRect* frameRect = fFrameIsSubset ? &fFrameRect : nullptr; 200 // This is only called by prepareToDecode, which ensures frameIndex is in ra nge.
467 fSwizzler.reset(SkSwizzler::CreateSwizzler(this->getEncodedInfo(), colorPtr, dstInfo, opts, 201 SkASSERT(frame);
468 frameRect));
469 SkASSERT(fSwizzler);
470 }
471 202
472 bool SkGifCodec::readRow() { 203 const int xBegin = frame->xOffset();
473 return GIF_ERROR != DGifGetLine(fGif, fSrcBuffer.get(), fFrameRect.width()); 204 const int xEnd = std::min(static_cast<int>(frame->xOffset() + frame->width() ),
205 static_cast<int>(fReader->screenWidth()));
206
207 // CreateSwizzler only reads left and right of the frame. We cannot use the frame's raw
208 // frameRect, since it might extend beyond the edge of the frame.
209 SkIRect swizzleRect = SkIRect::MakeLTRB(xBegin, 0, xEnd, 0);
210
211 // The default Options should be fine:
212 // - we'll ignore if the memory is zero initialized - unless we're the first frame, this won't
213 // matter anyway.
214 // - subsets are not supported for gif
215 // - the swizzler does not need to know about the frame.
216 // We may not be able to use the real Options anyway, since getPixels does n ot store it (due to
217 // a bug).
218 fSwizzler.reset(SkSwizzler::CreateSwizzler(this->getEncodedInfo(),
219 fCurrColorTable->readColors(), dstInfo, Options(), &swizzleR ect));
220 SkASSERT(fSwizzler.get());
474 } 221 }
475 222
476 /* 223 /*
477 * Initiates the gif decode 224 * Initiates the gif decode
478 */ 225 */
479 SkCodec::Result SkGifCodec::onGetPixels(const SkImageInfo& dstInfo, 226 SkCodec::Result SkGifCodec::onGetPixels(const SkImageInfo& dstInfo,
480 void* dst, size_t dstRowBytes, 227 void* pixels, size_t dstRowBytes,
481 const Options& opts, 228 const Options& opts,
482 SkPMColor* inputColorPtr, 229 SkPMColor* inputColorPtr,
483 int* inputColorCount, 230 int* inputColorCount,
484 int* rowsDecoded) { 231 int* rowsDecoded) {
485 Result result = this->prepareToDecode(dstInfo, inputColorPtr, inputColorCoun t, opts); 232 Result result = this->prepareToDecode(dstInfo, inputColorPtr, inputColorCoun t, opts);
486 if (kSuccess != result) { 233 if (kSuccess != result) {
487 return result; 234 return result;
488 } 235 }
489 236
490 if (dstInfo.dimensions() != this->getInfo().dimensions()) { 237 if (dstInfo.dimensions() != this->getInfo().dimensions()) {
491 return gif_error("Scaling not supported.\n", kInvalidScale); 238 return gif_error("Scaling not supported.\n", kInvalidScale);
492 } 239 }
493 240
494 // Initialize the swizzler 241 fDst = pixels;
495 if (fFrameIsSubset) { 242 fDstRowBytes = dstRowBytes;
496 // Fill the background 243
497 SkSampler::Fill(dstInfo, dst, dstRowBytes, this->getFillValue(dstInfo), 244 return this->decodeFrame(true, opts, rowsDecoded);
498 opts.fZeroInitialized); 245 }
499 } 246
500 247 SkCodec::Result SkGifCodec::onStartIncrementalDecode(const SkImageInfo& dstInfo,
501 // Iterate over rows of the input 248 void* pixels, size_t dstRow Bytes,
502 for (int y = fFrameRect.top(); y < fFrameRect.bottom(); y++) { 249 const SkCodec::Options& opt s,
503 if (!this->readRow()) { 250 SkPMColor* inputColorPtr,
504 *rowsDecoded = y; 251 int* inputColorCount) {
505 return gif_error("Could not decode line.\n", kIncompleteInput); 252 Result result = this->prepareToDecode(dstInfo, inputColorPtr, inputColorCoun t, opts);
506 } 253 if (result != kSuccess) {
507 void* dstRow = SkTAddOffset<void>(dst, dstRowBytes * this->outputScanlin e(y)); 254 return result;
508 fSwizzler->swizzle(dstRow, fSrcBuffer.get()); 255 }
509 } 256
257 fDst = pixels;
258 fDstRowBytes = dstRowBytes;
259
260 fFirstCallToIncrementalDecode = true;
261
510 return kSuccess; 262 return kSuccess;
511 } 263 }
512 264
513 // FIXME: This is similar to the implementation for bmp and png. Can we share m ore code or 265 SkCodec::Result SkGifCodec::onIncrementalDecode(int* rowsDecoded) {
514 // possibly make this non-virtual? 266 // It is possible the client has appended more data. Parse, if needed.
267 const auto& options = this->options();
268 const size_t frameIndex = options.fFrameOptions ? options.fFrameOptions->fIn dex : 0;
269 fReader->parse((GIFImageReader::GIFParseQuery) frameIndex);
270
271 const bool firstCallToIncrementalDecode = fFirstCallToIncrementalDecode;
272 fFirstCallToIncrementalDecode = false;
273 return this->decodeFrame(firstCallToIncrementalDecode, options, rowsDecoded) ;
274 }
275
276 SkCodec::Result SkGifCodec::decodeFrame(bool firstAttempt, const Options& opts, int* rowsDecoded) {
277 const SkImageInfo& dstInfo = this->dstInfo();
278 const size_t frameIndex = opts.fFrameOptions ? opts.fFrameOptions->fIndex : 0;
279 SkASSERT(frameIndex < fReader->imagesCount());
280 const GIFFrameContext* frameContext = fReader->frameContext(frameIndex);
281 if (firstAttempt) {
282 // rowsDecoded reports how many rows have been initialized, so a layer a bove
283 // can fill the rest. In some cases, we fill the background before decod ing
284 // (or it is already filled for us), so we report rowsDecoded to be the full
285 // height.
286 bool filledBackground = false;
287 if (frameContext->getRequiredFrame() == kNone) {
288 // We may need to clear to transparent for one of the following reas ons:
289 // - The frameRect does not cover the full bounds. haveDecodedRow wi ll
290 // only draw inside the frameRect, so we need to clear the rest.
291 // - There is a valid transparent pixel value. (FIXME: I'm assuming
292 // writeTransparentPixels will be false in this case, based on
293 // Chromium's assumption that it would already be zeroed. If we
294 // change that behavior, could we skip Filling here?)
295 // - The frame is interlaced. There is no obvious way to fill
296 // afterwards for an incomplete image. (FIXME: Does the first pass
297 // cover all rows? If so, we do not have to fill here.)
298 if (frameContext->frameRect() != this->getInfo().bounds()
299 || frameContext->transparentPixel() < MAX_COLORS
300 || frameContext->interlaced()) {
301 // fill ignores the width (replaces it with the actual, scaled w idth).
302 // But we need to scale in Y.
303 const int scaledHeight = get_scaled_dimension(dstInfo.height(),
304 fSwizzler->sampleY ());
305 auto fillInfo = dstInfo.makeWH(0, scaledHeight);
306 fSwizzler->fill(fillInfo, fDst, fDstRowBytes, this->getFillValue (dstInfo),
307 opts.fZeroInitialized);
308 filledBackground = true;
309 }
310 } else {
311 // Not independent
312 if (opts.fFrameOptions && !opts.fFrameOptions->fHasPriorFrame) {
313 // Decode that frame into pixels.
314 Options prevFrameOpts(opts);
315 MultiFrameOptions prevFrameMultiOpts;
316 prevFrameMultiOpts.fIndex = frameContext->getRequiredFrame();
317 prevFrameMultiOpts.fHasPriorFrame = false;
318 prevFrameOpts.fFrameOptions = &prevFrameMultiOpts;
319 const Result prevResult = this->decodeFrame(true, prevFrameOpts, nullptr);
320 switch (prevResult) {
321 case kSuccess:
322 // Prior frame succeeded. Carry on.
323 break;
324 case kIncompleteInput:
325 // Prior frame was incomplete. So this frame cannot be d ecoded.
326 return kInvalidInput;
327 default:
328 return prevResult;
329 }
330 }
331 const auto* prevFrame = fReader->frameContext(frameContext->getRequi redFrame());
332 if (prevFrame->getDisposalMethod() == SkCodecAnimation::RestoreBGCol or_DisposalMethod) {
333 const SkIRect prevRect = prevFrame->frameRect();
334 auto left = get_scaled_dimension(prevRect.fLeft, fSwizzler->samp leX());
335 auto top = get_scaled_dimension(prevRect.fTop, fSwizzler->sample Y());
336 void* const eraseDst = SkTAddOffset<void>(fDst, top * fDstRowByt es
337 + left * SkColorTypeBytesPerPixel(dstInfo.colorType()));
338 auto width = get_scaled_dimension(prevRect.width(), fSwizzler->s ampleX());
339 auto height = get_scaled_dimension(prevRect.height(), fSwizzler- >sampleY());
340 // fSwizzler->fill() would fill to the scaled width of the frame , but we want to
341 // fill to the scaled with of the width of the PRIOR frame, so w e do all the scaling
342 // ourselves and call the static version.
343 SkSampler::Fill(dstInfo.makeWH(width, height), eraseDst,
344 fDstRowBytes, this->getFillValue(dstInfo), kNo_Z eroInitialized);
345 }
346 filledBackground = true;
347 }
348
349 fFilledBackground = filledBackground;
350 if (filledBackground) {
351 // Report the full (scaled) height, since the client will never need to fill.
352 fRowsDecoded = get_scaled_dimension(dstInfo.height(), fSwizzler->sam pleY());
353 } else {
354 // This will be updated by haveDecodedRow.
355 fRowsDecoded = 0;
356 }
357 }
358
359 // Note: there is a difference between the following call to GIFImageReader: :decode
360 // returning false and leaving frameDecoded false:
361 // - If the method returns false, there was an error in the stream. We still treat this as
362 // incomplete, since we have already decoded some rows.
363 // - If frameDecoded is false, that just means that we do not have enough da ta. If more data
364 // is supplied, we may be able to continue decoding this frame. We also tr eat this as
365 // incomplete.
366 // FIXME: Ensure that we do not attempt to continue decoding if the method r eturns false and
367 // more data is supplied.
368 bool frameDecoded = false;
369 if (!fReader->decode(frameIndex, &frameDecoded) || !frameDecoded) {
370 if (rowsDecoded) {
371 *rowsDecoded = fRowsDecoded;
372 }
373 return kIncompleteInput;
374 }
375
376 return kSuccess;
377 }
378
515 uint64_t SkGifCodec::onGetFillValue(const SkImageInfo& dstInfo) const { 379 uint64_t SkGifCodec::onGetFillValue(const SkImageInfo& dstInfo) const {
516 const SkPMColor* colorPtr = get_color_ptr(fColorTable.get()); 380 // Note: Using fCurrColorTable relies on having called initializeColorTable already.
517 return get_color_table_fill_value(dstInfo.colorType(), dstInfo.alphaType(), colorPtr, 381 // This is (currently) safe because this method is only called when filling, after
518 fFillIndex, nullptr); 382 // initializeColorTable has been called.
519 } 383 // FIXME: Is there a way to make this less fragile?
520 384 if (dstInfo.colorType() == kIndex_8_SkColorType && fCurrColorTableIsReal) {
521 SkCodec::Result SkGifCodec::onStartScanlineDecode(const SkImageInfo& dstInfo, 385 // We only support index 8 for the first frame, for backwards
522 const SkCodec::Options& opts, SkPMColor inputColorPtr[], int* inputColor Count) { 386 // compatibity on Android, so we are using the color table for the first frame.
523 return this->prepareToDecode(dstInfo, inputColorPtr, inputColorCount, opts); 387 SkASSERT(!this->options().fFrameOptions || this->options().fFrameOptions ->fIndex == 0);
524 } 388 // Use the transparent index for the first frame.
525 389 const size_t transPixel = fReader->frameContext(0)->transparentPixel();
526 void SkGifCodec::handleScanlineFrame(int count, int* rowsBeforeFrame, int* rowsI nFrame) { 390 if (transPixel < (size_t) fCurrColorTable->count()) {
527 if (fFrameIsSubset) { 391 return transPixel;
528 const int currRow = this->currScanline(); 392 }
529 393 // Fall through to return SK_ColorTRANSPARENT (i.e. 0). This choice is a rbitrary,
530 // The number of rows that remain to be skipped before reaching rows tha t we 394 // but we have to pick something inside the color table, and this one is as good
531 // actually must decode into. 395 // as any.
532 // This must be at least zero. We also make sure that it is less than o r 396 }
533 // equal to count, since we will skip at most count rows. 397 // Using transparent as the fill value matches the behavior in Chromium,
534 *rowsBeforeFrame = SkTMin(count, SkTMax(0, fFrameRect.top() - currRow)); 398 // which ignores the background color.
535 399 // If the colorType is kIndex_8, and there was no color table (i.e.
536 // Rows left to decode once we reach the start of the frame. 400 // fCurrColorTableIsReal is false), this value (zero) corresponds to the
537 const int rowsLeft = count - *rowsBeforeFrame; 401 // only entry in the dummy color table provided to the client.
538 402 return SK_ColorTRANSPARENT;
539 // Count the number of that extend beyond the bottom of the frame. We d o not 403 }
540 // need to decode into these rows. 404
541 const int rowsAfterFrame = SkTMax(0, currRow + rowsLeft - fFrameRect.bot tom()); 405 bool SkGifCodec::haveDecodedRow(size_t frameIndex, const unsigned char* rowBegin ,
542 406 size_t rowNumber, unsigned repeatCount, bool wri teTransparentPixels)
543 // Set the actual number of source rows that we need to decode. 407 {
544 *rowsInFrame = rowsLeft - rowsAfterFrame; 408 const GIFFrameContext* frameContext = fReader->frameContext(frameIndex);
409 // The pixel data and coordinates supplied to us are relative to the frame's
410 // origin within the entire image size, i.e.
411 // (frameContext->xOffset, frameContext->yOffset). There is no guarantee
412 // that width == (size().width() - frameContext->xOffset), so
413 // we must ensure we don't run off the end of either the source data or the
414 // row's X-coordinates.
415 const size_t width = frameContext->width();
416 const int xBegin = frameContext->xOffset();
417 const int yBegin = frameContext->yOffset() + rowNumber;
418 const int xEnd = std::min(static_cast<int>(frameContext->xOffset() + width),
419 this->getInfo().width());
420 const int yEnd = std::min(static_cast<int>(frameContext->yOffset() + rowNumb er + repeatCount),
421 this->getInfo().height());
422 // FIXME: No need to make the checks on width/xBegin/xEnd for every row. We could instead do
423 // this once in prepareToDecode.
424 if (!width || (xBegin < 0) || (yBegin < 0) || (xEnd <= xBegin) || (yEnd <= y Begin))
425 return true;
426
427 // yBegin is the first row in the non-sampled image. dstRow will be the row in the output,
428 // after potentially scaling it.
429 int dstRow = yBegin;
430
431 const int sampleY = fSwizzler->sampleY();
432 if (sampleY > 1) {
433 // Check to see whether this row or one that falls in the repeatCount is needed in the
434 // output.
435 bool foundNecessaryRow = false;
436 for (unsigned i = 0; i < repeatCount; i++) {
437 const int potentialRow = yBegin + i;
438 if (fSwizzler->rowNeeded(potentialRow)) {
439 dstRow = potentialRow / sampleY;
440 const int scaledHeight = get_scaled_dimension(this->dstInfo().he ight(), sampleY);
441 if (dstRow >= scaledHeight) {
442 return true;
443 }
444
445 foundNecessaryRow = true;
446 repeatCount -= i;
447
448 repeatCount = (repeatCount - 1) / sampleY + 1;
449
450 // Make sure the repeatCount does not take us beyond the end of the dst
451 if (dstRow + (int) repeatCount > scaledHeight) {
452 repeatCount = scaledHeight - dstRow;
453 SkASSERT(repeatCount >= 1);
454 }
455 break;
456 }
457 }
458
459 if (!foundNecessaryRow) {
460 return true;
461 }
462 }
463
464 if (!fFilledBackground) {
465 // At this point, we are definitely going to write the row, so count it towards the number
466 // of rows decoded.
467 // We do not consider the repeatCount, which only happens for interlaced , in which case we
468 // have already set fRowsDecoded to the proper value (reflecting that we have filled the
469 // background).
470 fRowsDecoded++;
471 }
472
473 if (!fCurrColorTableIsReal) {
474 // No color table, so nothing to draw this frame.
475 // FIXME: We can abort even earlier - no need to decode this frame.
476 return true;
477 }
478
479 // The swizzler takes care of offsetting into the dst width-wise.
480 void* dstLine = SkTAddOffset<void>(fDst, dstRow * fDstRowBytes);
481
482 // We may or may not need to write transparent pixels to the buffer.
483 // If we're compositing against a previous image, it's wrong, and if
484 // we're writing atop a cleared, fully transparent buffer, it's
485 // unnecessary; but if we're decoding an interlaced gif and
486 // displaying it "Haeberli"-style, we must write these for passes
487 // beyond the first, or the initial passes will "show through" the
488 // later ones.
489 const auto dstInfo = this->dstInfo();
490 if (writeTransparentPixels || dstInfo.colorType() == kRGB_565_SkColorType) {
491 fSwizzler->swizzle(dstLine, rowBegin);
545 } else { 492 } else {
546 *rowsBeforeFrame = 0; 493 // We cannot swizzle directly into the dst, since that will write the tr ansparent pixels.
547 *rowsInFrame = count; 494 // Instead, swizzle into a temporary buffer, and copy that into the dst.
548 } 495 {
549 } 496 void* const memsetDst = fTmpBuffer.get();
550 497 // Although onGetFillValue returns a uint64_t, we only use the low e ight bits. The
551 int SkGifCodec::onGetScanlines(void* dst, int count, size_t rowBytes) { 498 // return value is either an 8 bit index (for index8) or SK_ColorTRA NSPARENT, which is
552 int rowsBeforeFrame; 499 // all zeroes.
553 int rowsInFrame; 500 const int fillValue = (uint8_t) this->onGetFillValue(dstInfo);
554 this->handleScanlineFrame(count, &rowsBeforeFrame, &rowsInFrame); 501 const size_t rb = dstInfo.minRowBytes();
555 502 if (fillValue == 0) {
556 if (fFrameIsSubset) { 503 // FIXME: This special case should be unnecessary, and in fact s k_bzero just calls
557 // Fill the requested rows 504 // memset. But without it, the compiler thinks this is trying to pass a zero length
558 SkImageInfo fillInfo = this->dstInfo().makeWH(this->dstInfo().width(), c ount); 505 // to memset, causing an error.
559 uint64_t fillValue = this->onGetFillValue(this->dstInfo()); 506 sk_bzero(memsetDst, rb);
560 fSwizzler->fill(fillInfo, dst, rowBytes, fillValue, this->options().fZer oInitialized); 507 } else {
561 508 memset(memsetDst, fillValue, rb);
562 // Start to write pixels at the start of the image frame 509 }
563 dst = SkTAddOffset<void>(dst, rowBytes * rowsBeforeFrame); 510 }
564 } 511 fSwizzler->swizzle(fTmpBuffer.get(), rowBegin);
565 512
566 for (int i = 0; i < rowsInFrame; i++) { 513 const size_t offsetBytes = fSwizzler->swizzleOffsetBytes();
567 if (!this->readRow()) { 514 switch (dstInfo.colorType()) {
568 return i + rowsBeforeFrame; 515 case kBGRA_8888_SkColorType:
569 } 516 case kRGBA_8888_SkColorType: {
570 fSwizzler->swizzle(dst, fSrcBuffer.get()); 517 uint32_t* dstPixel = SkTAddOffset<uint32_t>(dstLine, offsetBytes );
571 dst = SkTAddOffset<void>(dst, rowBytes); 518 uint32_t* srcPixel = SkTAddOffset<uint32_t>(fTmpBuffer.get(), of fsetBytes);
572 } 519 for (int i = 0; i < fSwizzler->swizzleWidth(); i++) {
573 520 // Technically SK_ColorTRANSPARENT is an SkPMColor, and srcP ixel would have
574 return count; 521 // the opposite swizzle for the non-native swizzle, but TRAN SPARENT is all
575 } 522 // zeroes, which is the same either way.
576 523 if (*srcPixel != SK_ColorTRANSPARENT) {
577 bool SkGifCodec::onSkipScanlines(int count) { 524 *dstPixel = *srcPixel;
578 int rowsBeforeFrame; 525 }
579 int rowsInFrame; 526 dstPixel++;
580 this->handleScanlineFrame(count, &rowsBeforeFrame, &rowsInFrame); 527 srcPixel++;
581 528 }
582 for (int i = 0; i < rowsInFrame; i++) { 529 break;
583 if (!this->readRow()) { 530 }
584 return false; 531 case kIndex_8_SkColorType: {
532 uint8_t* dstPixel = SkTAddOffset<uint8_t>(dstLine, offsetBytes);
533 uint8_t* srcPixel = SkTAddOffset<uint8_t>(fTmpBuffer.get(), offs etBytes);
534 for (int i = 0; i < fSwizzler->swizzleWidth(); i++) {
535 if (*srcPixel != frameContext->transparentPixel()) {
536 *dstPixel = *srcPixel;
537 }
538 dstPixel++;
539 srcPixel++;
540 }
541 break;
542 }
543 default:
544 SkASSERT(false);
545 break;
546 }
547 }
548
549 // Tell the frame to copy the row data if need be.
550 if (repeatCount > 1) {
551 const size_t bytesPerPixel = SkColorTypeBytesPerPixel(this->dstInfo().co lorType());
552 const size_t bytesToCopy = fSwizzler->swizzleWidth() * bytesPerPixel;
553 void* copiedLine = SkTAddOffset<void>(dstLine, fSwizzler->swizzleOffsetB ytes());
554 void* dst = copiedLine;
555 for (unsigned i = 1; i < repeatCount; i++) {
556 dst = SkTAddOffset<void>(dst, fDstRowBytes);
557 memcpy(dst, copiedLine, bytesToCopy);
585 } 558 }
586 } 559 }
587 560
588 return true; 561 return true;
589 } 562 }
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
« no previous file with comments | « src/codec/SkGifCodec.h ('k') | src/codec/SkSampledCodec.cpp » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698