blob: 876d71f553a1a45ed3b1f04a08468aacd02a37a5 [file] [log] [blame]
msarett8c8f22a2015-04-01 06:58:48 -07001/*
2 * Copyright 2015 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
scroggo19b91532016-10-24 09:03:26 -07008/*
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"
msarett8c8f22a2015-04-01 06:58:48 -070034#include "SkCodecPriv.h"
35#include "SkColorPriv.h"
36#include "SkColorTable.h"
msarett1a464672016-01-07 13:17:19 -080037#include "SkGifCodec.h"
msarett8c8f22a2015-04-01 06:58:48 -070038#include "SkStream.h"
39#include "SkSwizzler.h"
scroggo0057ac12016-10-25 12:48:25 -070040#include "SkUtils.h"
msarett8c8f22a2015-04-01 06:58:48 -070041
scroggo19b91532016-10-24 09:03:26 -070042#include <algorithm>
43
44#define GIF87_STAMP "GIF87a"
45#define GIF89_STAMP "GIF89a"
46#define GIF_STAMP_LEN 6
msarett39b2d5a2016-02-17 08:26:31 -080047
msarett8c8f22a2015-04-01 06:58:48 -070048/*
49 * Checks the start of the stream to see if the image is a gif
50 */
scroggodb30be22015-12-08 18:54:13 -080051bool SkGifCodec::IsGif(const void* buf, size_t bytesRead) {
52 if (bytesRead >= GIF_STAMP_LEN) {
scroggo19b91532016-10-24 09:03:26 -070053 if (memcmp(GIF87_STAMP, buf, GIF_STAMP_LEN) == 0 ||
bungeman0153dea2015-08-27 16:43:42 -070054 memcmp(GIF89_STAMP, buf, GIF_STAMP_LEN) == 0)
55 {
msarett8c8f22a2015-04-01 06:58:48 -070056 return true;
57 }
58 }
59 return false;
60}
61
62/*
msarett8c8f22a2015-04-01 06:58:48 -070063 * Error function
64 */
bungeman0153dea2015-08-27 16:43:42 -070065static SkCodec::Result gif_error(const char* msg, SkCodec::Result result = SkCodec::kInvalidInput) {
msarett8c8f22a2015-04-01 06:58:48 -070066 SkCodecPrintf("Gif Error: %s\n", msg);
67 return result;
68}
69
msarett438b2ad2015-04-09 12:43:10 -070070/*
msarett8c8f22a2015-04-01 06:58:48 -070071 * Assumes IsGif was called and returned true
72 * Creates a gif decoder
73 * Reads enough of the stream to determine the image format
74 */
75SkCodec* SkGifCodec::NewFromStream(SkStream* stream) {
scroggo3d3a65c2016-10-24 12:28:30 -070076 std::unique_ptr<SkGifImageReader> reader(new SkGifImageReader(stream));
scroggof9acbe22016-10-25 12:43:21 -070077 if (!reader->parse(SkGifImageReader::SkGIFSizeQuery)) {
scroggo19b91532016-10-24 09:03:26 -070078 // Not enough data to determine the size.
79 return nullptr;
msarett8c8f22a2015-04-01 06:58:48 -070080 }
msarett8c8f22a2015-04-01 06:58:48 -070081
scroggo19b91532016-10-24 09:03:26 -070082 if (0 == reader->screenWidth() || 0 == reader->screenHeight()) {
83 return nullptr;
84 }
85
86 const auto alpha = reader->firstFrameHasAlpha() ? SkEncodedInfo::kBinary_Alpha
87 : SkEncodedInfo::kOpaque_Alpha;
88 // Use kPalette since Gifs are encoded with a color table.
89 // FIXME: Gifs can actually be encoded with 4-bits per pixel. Using 8 works, but we could skip
90 // expanding to 8 bits and take advantage of the SkSwizzler to work from 4.
91 const auto encodedInfo = SkEncodedInfo::Make(SkEncodedInfo::kPalette_Color, alpha, 8);
92
93 // Although the encodedInfo is always kPalette_Color, it is possible that kIndex_8 is
94 // unsupported if the frame is subset and there is no transparent pixel.
95 const auto colorType = reader->firstFrameSupportsIndex8() ? kIndex_8_SkColorType
96 : kN32_SkColorType;
97 // The choice of unpremul versus premul is arbitrary, since all colors are either fully
98 // opaque or fully transparent (i.e. kBinary), but we stored the transparent colors as all
99 // zeroes, which is arguably premultiplied.
100 const auto alphaType = reader->firstFrameHasAlpha() ? kUnpremul_SkAlphaType
101 : kOpaque_SkAlphaType;
102 // FIXME: GIF should default to SkColorSpace::NewNamed(SkColorSpace::kSRGB_Named).
103 const auto imageInfo = SkImageInfo::Make(reader->screenWidth(), reader->screenHeight(),
104 colorType, alphaType);
105 return new SkGifCodec(encodedInfo, imageInfo, reader.release());
106}
msarett8c8f22a2015-04-01 06:58:48 -0700107
scroggob427db12015-08-12 07:24:13 -0700108bool SkGifCodec::onRewind() {
scroggo19b91532016-10-24 09:03:26 -0700109 fReader->clearDecodeState();
scroggob427db12015-08-12 07:24:13 -0700110 return true;
111}
112
scroggo19b91532016-10-24 09:03:26 -0700113SkGifCodec::SkGifCodec(const SkEncodedInfo& encodedInfo, const SkImageInfo& imageInfo,
scroggo3d3a65c2016-10-24 12:28:30 -0700114 SkGifImageReader* reader)
scroggo19b91532016-10-24 09:03:26 -0700115 : INHERITED(encodedInfo, imageInfo, nullptr)
116 , fReader(reader)
117 , fTmpBuffer(nullptr)
118 , fSwizzler(nullptr)
119 , fCurrColorTable(nullptr)
120 , fCurrColorTableIsReal(false)
121 , fFilledBackground(false)
122 , fFirstCallToIncrementalDecode(false)
123 , fDst(nullptr)
124 , fDstRowBytes(0)
125 , fRowsDecoded(0)
126{
127 reader->setClient(this);
msarett8c8f22a2015-04-01 06:58:48 -0700128}
msarett10522ff2015-09-07 08:54:01 -0700129
scroggo19b91532016-10-24 09:03:26 -0700130std::vector<SkCodec::FrameInfo> SkGifCodec::onGetFrameInfo() {
scroggof9acbe22016-10-25 12:43:21 -0700131 fReader->parse(SkGifImageReader::SkGIFFrameCountQuery);
scroggo19b91532016-10-24 09:03:26 -0700132 const size_t size = fReader->imagesCount();
133 std::vector<FrameInfo> result(size);
134 for (size_t i = 0; i < size; i++) {
scroggof9acbe22016-10-25 12:43:21 -0700135 const SkGIFFrameContext* frameContext = fReader->frameContext(i);
scroggo19b91532016-10-24 09:03:26 -0700136 result[i].fDuration = frameContext->delayTime();
137 result[i].fRequiredFrame = frameContext->getRequiredFrame();
msarett10522ff2015-09-07 08:54:01 -0700138 }
scroggo19b91532016-10-24 09:03:26 -0700139 return result;
msarett10522ff2015-09-07 08:54:01 -0700140}
141
scroggo19b91532016-10-24 09:03:26 -0700142void SkGifCodec::initializeColorTable(const SkImageInfo& dstInfo, size_t frameIndex,
143 SkPMColor* inputColorPtr, int* inputColorCount) {
144 fCurrColorTable = fReader->getColorTable(dstInfo.colorType(), frameIndex);
145 fCurrColorTableIsReal = fCurrColorTable;
146 if (!fCurrColorTable) {
scroggo0057ac12016-10-25 12:48:25 -0700147 // This is possible for an empty frame. Create a dummy with all transparent.
scroggoc85b9702016-10-25 12:53:59 -0700148 SkPMColor colors[SK_MAX_COLORS];
149 sk_memset32(colors, SK_ColorTRANSPARENT, SK_MAX_COLORS);
scroggo0057ac12016-10-25 12:48:25 -0700150 fCurrColorTable.reset(new SkColorTable(colors, 256));
msarett10522ff2015-09-07 08:54:01 -0700151 }
152
scroggo19b91532016-10-24 09:03:26 -0700153 if (inputColorCount) {
154 *inputColorCount = fCurrColorTable->count();
msarett10522ff2015-09-07 08:54:01 -0700155 }
156
scroggo19b91532016-10-24 09:03:26 -0700157 copy_color_table(dstInfo, fCurrColorTable.get(), inputColorPtr, inputColorCount);
msarett10522ff2015-09-07 08:54:01 -0700158}
159
scroggo19b91532016-10-24 09:03:26 -0700160
msarett10522ff2015-09-07 08:54:01 -0700161SkCodec::Result SkGifCodec::prepareToDecode(const SkImageInfo& dstInfo, SkPMColor* inputColorPtr,
162 int* inputColorCount, const Options& opts) {
msarett10522ff2015-09-07 08:54:01 -0700163 // Check for valid input parameters
msarett2ecc35f2016-09-08 11:55:16 -0700164 if (!conversion_possible_ignore_color_space(dstInfo, this->getInfo())) {
165 return gif_error("Cannot convert input type to output type.\n", kInvalidConversion);
msarett10522ff2015-09-07 08:54:01 -0700166 }
167
scroggo19b91532016-10-24 09:03:26 -0700168 if (dstInfo.colorType() == kRGBA_F16_SkColorType) {
169 // FIXME: This should be supported.
170 return gif_error("GIF does not yet support F16.\n", kInvalidConversion);
171 }
msarett5af4e0b2015-11-17 11:18:03 -0800172
scroggo19b91532016-10-24 09:03:26 -0700173 if (opts.fSubset) {
174 return gif_error("Subsets not supported.\n", kUnimplemented);
175 }
176
177 const size_t frameIndex = opts.fFrameIndex;
178 if (frameIndex > 0 && dstInfo.colorType() == kIndex_8_SkColorType) {
179 // FIXME: It is possible that a later frame can be decoded to index8, if it does one of the
180 // following:
181 // - Covers the entire previous frame
182 // - Shares a color table (and transparent index) with any prior frames that are showing.
183 // We must support index8 for the first frame to be backwards compatible on Android, but
184 // we do not (currently) need to support later frames as index8.
185 return gif_error("Cannot decode multiframe gif (except frame 0) as index 8.\n",
186 kInvalidConversion);
187 }
188
scroggof9acbe22016-10-25 12:43:21 -0700189 fReader->parse((SkGifImageReader::SkGIFParseQuery) frameIndex);
scroggo19b91532016-10-24 09:03:26 -0700190
191 if (frameIndex >= fReader->imagesCount()) {
192 return gif_error("frame index out of range!\n", kIncompleteInput);
193 }
194
195 fTmpBuffer.reset(new uint8_t[dstInfo.minRowBytes()]);
196
197 // Initialize color table and copy to the client if necessary
198 this->initializeColorTable(dstInfo, frameIndex, inputColorPtr, inputColorCount);
199 this->initializeSwizzler(dstInfo, frameIndex);
msarettb30d6982016-02-15 10:18:45 -0800200 return kSuccess;
msarett10522ff2015-09-07 08:54:01 -0700201}
202
scroggo19b91532016-10-24 09:03:26 -0700203void SkGifCodec::initializeSwizzler(const SkImageInfo& dstInfo, size_t frameIndex) {
scroggof9acbe22016-10-25 12:43:21 -0700204 const SkGIFFrameContext* frame = fReader->frameContext(frameIndex);
scroggo19b91532016-10-24 09:03:26 -0700205 // This is only called by prepareToDecode, which ensures frameIndex is in range.
206 SkASSERT(frame);
msarett10522ff2015-09-07 08:54:01 -0700207
scroggo19b91532016-10-24 09:03:26 -0700208 const int xBegin = frame->xOffset();
209 const int xEnd = std::min(static_cast<int>(frame->xOffset() + frame->width()),
210 static_cast<int>(fReader->screenWidth()));
211
212 // CreateSwizzler only reads left and right of the frame. We cannot use the frame's raw
213 // frameRect, since it might extend beyond the edge of the frame.
214 SkIRect swizzleRect = SkIRect::MakeLTRB(xBegin, 0, xEnd, 0);
215
216 // The default Options should be fine:
217 // - we'll ignore if the memory is zero initialized - unless we're the first frame, this won't
218 // matter anyway.
219 // - subsets are not supported for gif
220 // - the swizzler does not need to know about the frame.
221 // We may not be able to use the real Options anyway, since getPixels does not store it (due to
222 // a bug).
223 fSwizzler.reset(SkSwizzler::CreateSwizzler(this->getEncodedInfo(),
224 fCurrColorTable->readColors(), dstInfo, Options(), &swizzleRect));
225 SkASSERT(fSwizzler.get());
msarett10522ff2015-09-07 08:54:01 -0700226}
227
228/*
229 * Initiates the gif decode
230 */
231SkCodec::Result SkGifCodec::onGetPixels(const SkImageInfo& dstInfo,
scroggo19b91532016-10-24 09:03:26 -0700232 void* pixels, size_t dstRowBytes,
msarett10522ff2015-09-07 08:54:01 -0700233 const Options& opts,
234 SkPMColor* inputColorPtr,
msarette6dd0042015-10-09 11:07:34 -0700235 int* inputColorCount,
236 int* rowsDecoded) {
msarett10522ff2015-09-07 08:54:01 -0700237 Result result = this->prepareToDecode(dstInfo, inputColorPtr, inputColorCount, opts);
238 if (kSuccess != result) {
239 return result;
240 }
241
242 if (dstInfo.dimensions() != this->getInfo().dimensions()) {
243 return gif_error("Scaling not supported.\n", kInvalidScale);
244 }
245
scroggo19b91532016-10-24 09:03:26 -0700246 fDst = pixels;
247 fDstRowBytes = dstRowBytes;
248
249 return this->decodeFrame(true, opts, rowsDecoded);
250}
251
252SkCodec::Result SkGifCodec::onStartIncrementalDecode(const SkImageInfo& dstInfo,
253 void* pixels, size_t dstRowBytes,
254 const SkCodec::Options& opts,
255 SkPMColor* inputColorPtr,
256 int* inputColorCount) {
257 Result result = this->prepareToDecode(dstInfo, inputColorPtr, inputColorCount, opts);
258 if (result != kSuccess) {
259 return result;
msarett10522ff2015-09-07 08:54:01 -0700260 }
261
scroggo19b91532016-10-24 09:03:26 -0700262 fDst = pixels;
263 fDstRowBytes = dstRowBytes;
264
265 fFirstCallToIncrementalDecode = true;
266
msarett10522ff2015-09-07 08:54:01 -0700267 return kSuccess;
268}
269
scroggo19b91532016-10-24 09:03:26 -0700270SkCodec::Result SkGifCodec::onIncrementalDecode(int* rowsDecoded) {
271 // It is possible the client has appended more data. Parse, if needed.
272 const auto& options = this->options();
273 const size_t frameIndex = options.fFrameIndex;
scroggof9acbe22016-10-25 12:43:21 -0700274 fReader->parse((SkGifImageReader::SkGIFParseQuery) frameIndex);
scroggo19b91532016-10-24 09:03:26 -0700275
276 const bool firstCallToIncrementalDecode = fFirstCallToIncrementalDecode;
277 fFirstCallToIncrementalDecode = false;
278 return this->decodeFrame(firstCallToIncrementalDecode, options, rowsDecoded);
msarette6dd0042015-10-09 11:07:34 -0700279}
280
scroggo19b91532016-10-24 09:03:26 -0700281SkCodec::Result SkGifCodec::decodeFrame(bool firstAttempt, const Options& opts, int* rowsDecoded) {
282 const SkImageInfo& dstInfo = this->dstInfo();
283 const size_t frameIndex = opts.fFrameIndex;
284 SkASSERT(frameIndex < fReader->imagesCount());
scroggof9acbe22016-10-25 12:43:21 -0700285 const SkGIFFrameContext* frameContext = fReader->frameContext(frameIndex);
scroggo19b91532016-10-24 09:03:26 -0700286 if (firstAttempt) {
287 // rowsDecoded reports how many rows have been initialized, so a layer above
288 // can fill the rest. In some cases, we fill the background before decoding
289 // (or it is already filled for us), so we report rowsDecoded to be the full
290 // height.
291 bool filledBackground = false;
292 if (frameContext->getRequiredFrame() == kNone) {
293 // We may need to clear to transparent for one of the following reasons:
294 // - The frameRect does not cover the full bounds. haveDecodedRow will
295 // only draw inside the frameRect, so we need to clear the rest.
scroggo19b91532016-10-24 09:03:26 -0700296 // - The frame is interlaced. There is no obvious way to fill
297 // afterwards for an incomplete image. (FIXME: Does the first pass
298 // cover all rows? If so, we do not have to fill here.)
scroggo8bce1172016-10-25 13:08:40 -0700299 // - There is no color table for this frame. In that case will not
300 // draw anything, so we need to fill.
scroggo19b91532016-10-24 09:03:26 -0700301 if (frameContext->frameRect() != this->getInfo().bounds()
scroggo8bce1172016-10-25 13:08:40 -0700302 || frameContext->interlaced() || !fCurrColorTableIsReal) {
scroggo19b91532016-10-24 09:03:26 -0700303 // fill ignores the width (replaces it with the actual, scaled width).
304 // But we need to scale in Y.
305 const int scaledHeight = get_scaled_dimension(dstInfo.height(),
306 fSwizzler->sampleY());
307 auto fillInfo = dstInfo.makeWH(0, scaledHeight);
308 fSwizzler->fill(fillInfo, fDst, fDstRowBytes, this->getFillValue(dstInfo),
309 opts.fZeroInitialized);
310 filledBackground = true;
311 }
312 } else {
313 // Not independent
314 if (!opts.fHasPriorFrame) {
315 // Decode that frame into pixels.
316 Options prevFrameOpts(opts);
317 prevFrameOpts.fFrameIndex = frameContext->getRequiredFrame();
318 prevFrameOpts.fHasPriorFrame = false;
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 decoded.
326 return kInvalidInput;
327 default:
328 return prevResult;
329 }
330 }
331 const auto* prevFrame = fReader->frameContext(frameContext->getRequiredFrame());
332 if (prevFrame->getDisposalMethod() == SkCodecAnimation::RestoreBGColor_DisposalMethod) {
333 const SkIRect prevRect = prevFrame->frameRect();
334 auto left = get_scaled_dimension(prevRect.fLeft, fSwizzler->sampleX());
335 auto top = get_scaled_dimension(prevRect.fTop, fSwizzler->sampleY());
336 void* const eraseDst = SkTAddOffset<void>(fDst, top * fDstRowBytes
337 + left * SkColorTypeBytesPerPixel(dstInfo.colorType()));
338 auto width = get_scaled_dimension(prevRect.width(), fSwizzler->sampleX());
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 we 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_ZeroInitialized);
345 }
346 filledBackground = true;
msarett10522ff2015-09-07 08:54:01 -0700347 }
scroggo19b91532016-10-24 09:03:26 -0700348
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->sampleY());
353 } else {
354 // This will be updated by haveDecodedRow.
355 fRowsDecoded = 0;
356 }
msarett10522ff2015-09-07 08:54:01 -0700357 }
msarette6dd0042015-10-09 11:07:34 -0700358
scroggo3d3a65c2016-10-24 12:28:30 -0700359 // Note: there is a difference between the following call to SkGifImageReader::decode
scroggo19b91532016-10-24 09:03:26 -0700360 // 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 data. If more data
364 // is supplied, we may be able to continue decoding this frame. We also treat this as
365 // incomplete.
366 // FIXME: Ensure that we do not attempt to continue decoding if the method returns 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;
msarett10522ff2015-09-07 08:54:01 -0700377}
scroggo46c57472015-09-30 08:57:13 -0700378
scroggo19b91532016-10-24 09:03:26 -0700379uint64_t SkGifCodec::onGetFillValue(const SkImageInfo& dstInfo) const {
380 // Note: Using fCurrColorTable relies on having called initializeColorTable already.
381 // This is (currently) safe because this method is only called when filling, after
382 // initializeColorTable has been called.
383 // FIXME: Is there a way to make this less fragile?
384 if (dstInfo.colorType() == kIndex_8_SkColorType && fCurrColorTableIsReal) {
385 // We only support index 8 for the first frame, for backwards
386 // compatibity on Android, so we are using the color table for the first frame.
387 SkASSERT(this->options().fFrameIndex == 0);
388 // Use the transparent index for the first frame.
389 const size_t transPixel = fReader->frameContext(0)->transparentPixel();
390 if (transPixel < (size_t) fCurrColorTable->count()) {
391 return transPixel;
392 }
393 // Fall through to return SK_ColorTRANSPARENT (i.e. 0). This choice is arbitrary,
394 // but we have to pick something inside the color table, and this one is as good
395 // as any.
396 }
397 // Using transparent as the fill value matches the behavior in Chromium,
398 // which ignores the background color.
399 // If the colorType is kIndex_8, and there was no color table (i.e.
400 // fCurrColorTableIsReal is false), this value (zero) corresponds to the
401 // only entry in the dummy color table provided to the client.
402 return SK_ColorTRANSPARENT;
403}
msarett72261c02015-11-19 15:29:26 -0800404
scroggo19b91532016-10-24 09:03:26 -0700405bool SkGifCodec::haveDecodedRow(size_t frameIndex, const unsigned char* rowBegin,
406 size_t rowNumber, unsigned repeatCount, bool writeTransparentPixels)
407{
scroggof9acbe22016-10-25 12:43:21 -0700408 const SkGIFFrameContext* frameContext = fReader->frameContext(frameIndex);
scroggo19b91532016-10-24 09:03:26 -0700409 // 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() + rowNumber + 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 <= yBegin))
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().height(), 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 }
Matt Sarett8a4e9c52016-10-25 14:24:50 -0400462 } else {
463 // Make sure the repeatCount does not take us beyond the end of the dst
464 SkASSERT(this->dstInfo().height() >= yBegin);
465 repeatCount = SkTMin(repeatCount, (unsigned) (this->dstInfo().height() - yBegin));
scroggo19b91532016-10-24 09:03:26 -0700466 }
467
468 if (!fFilledBackground) {
469 // At this point, we are definitely going to write the row, so count it towards the number
470 // of rows decoded.
471 // We do not consider the repeatCount, which only happens for interlaced, in which case we
472 // have already set fRowsDecoded to the proper value (reflecting that we have filled the
473 // background).
474 fRowsDecoded++;
475 }
476
477 if (!fCurrColorTableIsReal) {
478 // No color table, so nothing to draw this frame.
479 // FIXME: We can abort even earlier - no need to decode this frame.
480 return true;
481 }
482
483 // The swizzler takes care of offsetting into the dst width-wise.
484 void* dstLine = SkTAddOffset<void>(fDst, dstRow * fDstRowBytes);
485
486 // We may or may not need to write transparent pixels to the buffer.
scroggo1285f412016-10-26 13:48:03 -0700487 // If we're compositing against a previous image, it's wrong, but if
488 // we're decoding an interlaced gif and displaying it "Haeberli"-style,
489 // we must write these for passes beyond the first, or the initial passes
490 // will "show through" the later ones.
scroggo19b91532016-10-24 09:03:26 -0700491 const auto dstInfo = this->dstInfo();
492 if (writeTransparentPixels || dstInfo.colorType() == kRGB_565_SkColorType) {
493 fSwizzler->swizzle(dstLine, rowBegin);
494 } else {
495 // We cannot swizzle directly into the dst, since that will write the transparent pixels.
496 // Instead, swizzle into a temporary buffer, and copy that into the dst.
497 {
498 void* const memsetDst = fTmpBuffer.get();
499 // Although onGetFillValue returns a uint64_t, we only use the low eight bits. The
500 // return value is either an 8 bit index (for index8) or SK_ColorTRANSPARENT, which is
501 // all zeroes.
502 const int fillValue = (uint8_t) this->onGetFillValue(dstInfo);
503 const size_t rb = dstInfo.minRowBytes();
504 if (fillValue == 0) {
505 // FIXME: This special case should be unnecessary, and in fact sk_bzero just calls
506 // memset. But without it, the compiler thinks this is trying to pass a zero length
507 // to memset, causing an error.
508 sk_bzero(memsetDst, rb);
509 } else {
510 memset(memsetDst, fillValue, rb);
511 }
512 }
513 fSwizzler->swizzle(fTmpBuffer.get(), rowBegin);
514
515 const size_t offsetBytes = fSwizzler->swizzleOffsetBytes();
516 switch (dstInfo.colorType()) {
517 case kBGRA_8888_SkColorType:
518 case kRGBA_8888_SkColorType: {
519 uint32_t* dstPixel = SkTAddOffset<uint32_t>(dstLine, offsetBytes);
520 uint32_t* srcPixel = SkTAddOffset<uint32_t>(fTmpBuffer.get(), offsetBytes);
521 for (int i = 0; i < fSwizzler->swizzleWidth(); i++) {
522 // Technically SK_ColorTRANSPARENT is an SkPMColor, and srcPixel would have
523 // the opposite swizzle for the non-native swizzle, but TRANSPARENT is all
524 // zeroes, which is the same either way.
525 if (*srcPixel != SK_ColorTRANSPARENT) {
526 *dstPixel = *srcPixel;
527 }
528 dstPixel++;
529 srcPixel++;
530 }
531 break;
532 }
533 case kIndex_8_SkColorType: {
534 uint8_t* dstPixel = SkTAddOffset<uint8_t>(dstLine, offsetBytes);
535 uint8_t* srcPixel = SkTAddOffset<uint8_t>(fTmpBuffer.get(), offsetBytes);
536 for (int i = 0; i < fSwizzler->swizzleWidth(); i++) {
537 if (*srcPixel != frameContext->transparentPixel()) {
538 *dstPixel = *srcPixel;
539 }
540 dstPixel++;
541 srcPixel++;
542 }
543 break;
544 }
545 default:
546 SkASSERT(false);
547 break;
548 }
549 }
550
551 // Tell the frame to copy the row data if need be.
552 if (repeatCount > 1) {
553 const size_t bytesPerPixel = SkColorTypeBytesPerPixel(this->dstInfo().colorType());
554 const size_t bytesToCopy = fSwizzler->swizzleWidth() * bytesPerPixel;
555 void* copiedLine = SkTAddOffset<void>(dstLine, fSwizzler->swizzleOffsetBytes());
556 void* dst = copiedLine;
557 for (unsigned i = 1; i < repeatCount; i++) {
558 dst = SkTAddOffset<void>(dst, fDstRowBytes);
559 memcpy(dst, copiedLine, bytesToCopy);
msarett72261c02015-11-19 15:29:26 -0800560 }
561 }
562
563 return true;
564}