blob: 7fc3c9805a4d5e11ac5b0548762e4dae38ee26c7 [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"
msarett8c8f22a2015-04-01 06:58:48 -070040
scroggo19b91532016-10-24 09:03:26 -070041#include <algorithm>
42
43#define GIF87_STAMP "GIF87a"
44#define GIF89_STAMP "GIF89a"
45#define GIF_STAMP_LEN 6
msarett39b2d5a2016-02-17 08:26:31 -080046
msarett8c8f22a2015-04-01 06:58:48 -070047/*
48 * Checks the start of the stream to see if the image is a gif
49 */
scroggodb30be22015-12-08 18:54:13 -080050bool SkGifCodec::IsGif(const void* buf, size_t bytesRead) {
51 if (bytesRead >= GIF_STAMP_LEN) {
scroggo19b91532016-10-24 09:03:26 -070052 if (memcmp(GIF87_STAMP, buf, GIF_STAMP_LEN) == 0 ||
bungeman0153dea2015-08-27 16:43:42 -070053 memcmp(GIF89_STAMP, buf, GIF_STAMP_LEN) == 0)
54 {
msarett8c8f22a2015-04-01 06:58:48 -070055 return true;
56 }
57 }
58 return false;
59}
60
61/*
msarett8c8f22a2015-04-01 06:58:48 -070062 * Error function
63 */
bungeman0153dea2015-08-27 16:43:42 -070064static SkCodec::Result gif_error(const char* msg, SkCodec::Result result = SkCodec::kInvalidInput) {
msarett8c8f22a2015-04-01 06:58:48 -070065 SkCodecPrintf("Gif Error: %s\n", msg);
66 return result;
67}
68
msarett438b2ad2015-04-09 12:43:10 -070069/*
msarett8c8f22a2015-04-01 06:58:48 -070070 * Assumes IsGif was called and returned true
71 * Creates a gif decoder
72 * Reads enough of the stream to determine the image format
73 */
74SkCodec* SkGifCodec::NewFromStream(SkStream* stream) {
scroggo3d3a65c2016-10-24 12:28:30 -070075 std::unique_ptr<SkGifImageReader> reader(new SkGifImageReader(stream));
scroggof9acbe22016-10-25 12:43:21 -070076 if (!reader->parse(SkGifImageReader::SkGIFSizeQuery)) {
scroggo19b91532016-10-24 09:03:26 -070077 // Not enough data to determine the size.
78 return nullptr;
msarett8c8f22a2015-04-01 06:58:48 -070079 }
msarett8c8f22a2015-04-01 06:58:48 -070080
scroggo19b91532016-10-24 09:03:26 -070081 if (0 == reader->screenWidth() || 0 == reader->screenHeight()) {
82 return nullptr;
83 }
84
85 const auto alpha = reader->firstFrameHasAlpha() ? SkEncodedInfo::kBinary_Alpha
86 : SkEncodedInfo::kOpaque_Alpha;
87 // Use kPalette since Gifs are encoded with a color table.
88 // FIXME: Gifs can actually be encoded with 4-bits per pixel. Using 8 works, but we could skip
89 // expanding to 8 bits and take advantage of the SkSwizzler to work from 4.
90 const auto encodedInfo = SkEncodedInfo::Make(SkEncodedInfo::kPalette_Color, alpha, 8);
91
92 // Although the encodedInfo is always kPalette_Color, it is possible that kIndex_8 is
93 // unsupported if the frame is subset and there is no transparent pixel.
94 const auto colorType = reader->firstFrameSupportsIndex8() ? kIndex_8_SkColorType
95 : kN32_SkColorType;
96 // The choice of unpremul versus premul is arbitrary, since all colors are either fully
97 // opaque or fully transparent (i.e. kBinary), but we stored the transparent colors as all
98 // zeroes, which is arguably premultiplied.
99 const auto alphaType = reader->firstFrameHasAlpha() ? kUnpremul_SkAlphaType
100 : kOpaque_SkAlphaType;
Matt Sarett7f650bd2016-10-30 21:25:34 -0400101
scroggo19b91532016-10-24 09:03:26 -0700102 const auto imageInfo = SkImageInfo::Make(reader->screenWidth(), reader->screenHeight(),
Matt Sarett7f650bd2016-10-30 21:25:34 -0400103 colorType, alphaType,
104 SkColorSpace::MakeNamed(SkColorSpace::kSRGB_Named));
scroggo19b91532016-10-24 09:03:26 -0700105 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
scroggoe71b1a12016-11-01 08:28:28 -0700142int SkGifCodec::onGetRepetitionCount() {
143 fReader->parse(SkGifImageReader::SkGIFLoopCountQuery);
144 return fReader->loopCount();
145}
146
Matt Sarett562e6812016-11-08 16:13:43 -0500147static const SkColorType kXformSrcColorType = kRGBA_8888_SkColorType;
148
Leon Scroggins IIIfc49b402016-10-31 14:08:56 -0400149void SkGifCodec::initializeColorTable(const SkImageInfo& dstInfo, size_t frameIndex) {
Matt Sarett61eedeb2016-11-04 13:19:48 -0400150 SkColorType colorTableColorType = dstInfo.colorType();
151 if (this->colorXform()) {
Matt Sarett562e6812016-11-08 16:13:43 -0500152 colorTableColorType = kXformSrcColorType;
Matt Sarett61eedeb2016-11-04 13:19:48 -0400153 }
154
155 sk_sp<SkColorTable> currColorTable = fReader->getColorTable(colorTableColorType, frameIndex);
156 fCurrColorTableIsReal = currColorTable;
157 if (!fCurrColorTableIsReal) {
Leon Scroggins IIIa049ac42016-10-27 11:16:11 -0400158 // This is possible for an empty frame. Create a dummy with one value (transparent).
159 SkPMColor color = SK_ColorTRANSPARENT;
160 fCurrColorTable.reset(new SkColorTable(&color, 1));
Matt Sarett61eedeb2016-11-04 13:19:48 -0400161 } else if (this->colorXform() && !fXformOnDecode) {
162 SkPMColor dstColors[256];
Matt Sarett562e6812016-11-08 16:13:43 -0500163 const SkColorSpaceXform::ColorFormat dstFormat = select_xform_format(dstInfo.colorType());
164 const SkColorSpaceXform::ColorFormat srcFormat = select_xform_format(kXformSrcColorType);
165 const SkAlphaType xformAlphaType = select_xform_alpha(dstInfo.alphaType(),
166 this->getInfo().alphaType());
Matt Sarett61eedeb2016-11-04 13:19:48 -0400167 SkAssertResult(this->colorXform()->apply(dstFormat, dstColors, srcFormat,
168 currColorTable->readColors(),
169 currColorTable->count(), xformAlphaType));
170 fCurrColorTable.reset(new SkColorTable(dstColors, currColorTable->count()));
171 } else {
172 fCurrColorTable = std::move(currColorTable);
msarett10522ff2015-09-07 08:54:01 -0700173 }
msarett10522ff2015-09-07 08:54:01 -0700174}
175
scroggo19b91532016-10-24 09:03:26 -0700176
msarett10522ff2015-09-07 08:54:01 -0700177SkCodec::Result SkGifCodec::prepareToDecode(const SkImageInfo& dstInfo, SkPMColor* inputColorPtr,
178 int* inputColorCount, const Options& opts) {
msarett10522ff2015-09-07 08:54:01 -0700179 // Check for valid input parameters
Matt Sarett61eedeb2016-11-04 13:19:48 -0400180 if (!conversion_possible(dstInfo, this->getInfo()) || !this->initializeColorXform(dstInfo)) {
msarett2ecc35f2016-09-08 11:55:16 -0700181 return gif_error("Cannot convert input type to output type.\n", kInvalidConversion);
msarett10522ff2015-09-07 08:54:01 -0700182 }
183
Matt Sarett61eedeb2016-11-04 13:19:48 -0400184 fXformOnDecode = false;
185 if (this->colorXform()) {
186 fXformOnDecode = apply_xform_on_decode(dstInfo.colorType(), this->getEncodedInfo().color());
187 if (fXformOnDecode) {
188 fXformBuffer.reset(new uint32_t[dstInfo.width()]);
189 sk_bzero(fXformBuffer.get(), dstInfo.width() * sizeof(uint32_t));
190 }
scroggo19b91532016-10-24 09:03:26 -0700191 }
msarett5af4e0b2015-11-17 11:18:03 -0800192
scroggo19b91532016-10-24 09:03:26 -0700193 if (opts.fSubset) {
194 return gif_error("Subsets not supported.\n", kUnimplemented);
195 }
196
197 const size_t frameIndex = opts.fFrameIndex;
scroggo53f63b62016-10-27 08:29:13 -0700198 if (frameIndex > 0) {
199 switch (dstInfo.colorType()) {
200 case kIndex_8_SkColorType:
201 // FIXME: It is possible that a later frame can be decoded to index8, if it does one
202 // of the following:
203 // - Covers the entire previous frame
204 // - Shares a color table (and transparent index) with any prior frames that are
205 // showing.
206 // We must support index8 for the first frame to be backwards compatible on Android,
207 // but we do not (currently) need to support later frames as index8.
208 return gif_error("Cannot decode multiframe gif (except frame 0) as index 8.\n",
209 kInvalidConversion);
210 case kRGB_565_SkColorType:
211 // FIXME: In theory, we might be able to support this, but it's not clear that it
212 // is necessary (Chromium does not decode to 565, and Android does not decode
213 // frames beyond the first). Disabling it because it is somewhat difficult:
214 // - If there is a transparent pixel, and this frame draws on top of another frame
215 // (if the frame is independent with a transparent pixel, we should not decode to
216 // 565 anyway, since it is not opaque), we need to skip drawing the transparent
217 // pixels (see writeTransparentPixels in haveDecodedRow). We currently do this by
218 // first swizzling into temporary memory, then copying into the destination. (We
219 // let the swizzler handle it first because it may need to sample.) After
220 // swizzling to 565, we do not know which pixels in our temporary memory
221 // correspond to the transparent pixel, so we do not know what to skip. We could
222 // special case the non-sampled case (no need to swizzle), but as this is
223 // currently unused we can just not support it.
224 return gif_error("Cannot decode multiframe gif (except frame 0) as 565.\n",
225 kInvalidConversion);
226 default:
227 break;
228 }
scroggo19b91532016-10-24 09:03:26 -0700229 }
230
scroggof9acbe22016-10-25 12:43:21 -0700231 fReader->parse((SkGifImageReader::SkGIFParseQuery) frameIndex);
scroggo19b91532016-10-24 09:03:26 -0700232
233 if (frameIndex >= fReader->imagesCount()) {
234 return gif_error("frame index out of range!\n", kIncompleteInput);
235 }
236
237 fTmpBuffer.reset(new uint8_t[dstInfo.minRowBytes()]);
238
Leon Scroggins IIIfc49b402016-10-31 14:08:56 -0400239 this->initializeColorTable(dstInfo, frameIndex);
scroggo19b91532016-10-24 09:03:26 -0700240 this->initializeSwizzler(dstInfo, frameIndex);
Leon Scroggins IIIfc49b402016-10-31 14:08:56 -0400241
242 SkASSERT(fCurrColorTable);
243 if (inputColorCount) {
244 *inputColorCount = fCurrColorTable->count();
245 }
246 copy_color_table(dstInfo, fCurrColorTable.get(), inputColorPtr, inputColorCount);
247
msarettb30d6982016-02-15 10:18:45 -0800248 return kSuccess;
msarett10522ff2015-09-07 08:54:01 -0700249}
250
scroggo19b91532016-10-24 09:03:26 -0700251void SkGifCodec::initializeSwizzler(const SkImageInfo& dstInfo, size_t frameIndex) {
scroggof9acbe22016-10-25 12:43:21 -0700252 const SkGIFFrameContext* frame = fReader->frameContext(frameIndex);
scroggo19b91532016-10-24 09:03:26 -0700253 // This is only called by prepareToDecode, which ensures frameIndex is in range.
254 SkASSERT(frame);
msarett10522ff2015-09-07 08:54:01 -0700255
scroggo19b91532016-10-24 09:03:26 -0700256 const int xBegin = frame->xOffset();
257 const int xEnd = std::min(static_cast<int>(frame->xOffset() + frame->width()),
258 static_cast<int>(fReader->screenWidth()));
259
260 // CreateSwizzler only reads left and right of the frame. We cannot use the frame's raw
261 // frameRect, since it might extend beyond the edge of the frame.
262 SkIRect swizzleRect = SkIRect::MakeLTRB(xBegin, 0, xEnd, 0);
263
Matt Sarett61eedeb2016-11-04 13:19:48 -0400264 SkImageInfo swizzlerInfo = dstInfo;
265 if (this->colorXform()) {
Matt Sarett562e6812016-11-08 16:13:43 -0500266 swizzlerInfo = swizzlerInfo.makeColorType(kXformSrcColorType);
Matt Sarett61eedeb2016-11-04 13:19:48 -0400267 if (kPremul_SkAlphaType == dstInfo.alphaType()) {
268 swizzlerInfo = swizzlerInfo.makeAlphaType(kUnpremul_SkAlphaType);
269 }
270 }
271
scroggo19b91532016-10-24 09:03:26 -0700272 // The default Options should be fine:
273 // - we'll ignore if the memory is zero initialized - unless we're the first frame, this won't
274 // matter anyway.
275 // - subsets are not supported for gif
276 // - the swizzler does not need to know about the frame.
277 // We may not be able to use the real Options anyway, since getPixels does not store it (due to
278 // a bug).
279 fSwizzler.reset(SkSwizzler::CreateSwizzler(this->getEncodedInfo(),
Matt Sarett61eedeb2016-11-04 13:19:48 -0400280 fCurrColorTable->readColors(), swizzlerInfo, Options(), &swizzleRect));
scroggo19b91532016-10-24 09:03:26 -0700281 SkASSERT(fSwizzler.get());
msarett10522ff2015-09-07 08:54:01 -0700282}
283
284/*
285 * Initiates the gif decode
286 */
287SkCodec::Result SkGifCodec::onGetPixels(const SkImageInfo& dstInfo,
scroggo19b91532016-10-24 09:03:26 -0700288 void* pixels, size_t dstRowBytes,
msarett10522ff2015-09-07 08:54:01 -0700289 const Options& opts,
290 SkPMColor* inputColorPtr,
msarette6dd0042015-10-09 11:07:34 -0700291 int* inputColorCount,
292 int* rowsDecoded) {
msarett10522ff2015-09-07 08:54:01 -0700293 Result result = this->prepareToDecode(dstInfo, inputColorPtr, inputColorCount, opts);
294 if (kSuccess != result) {
295 return result;
296 }
297
298 if (dstInfo.dimensions() != this->getInfo().dimensions()) {
299 return gif_error("Scaling not supported.\n", kInvalidScale);
300 }
301
scroggo19b91532016-10-24 09:03:26 -0700302 fDst = pixels;
303 fDstRowBytes = dstRowBytes;
304
305 return this->decodeFrame(true, opts, rowsDecoded);
306}
307
308SkCodec::Result SkGifCodec::onStartIncrementalDecode(const SkImageInfo& dstInfo,
309 void* pixels, size_t dstRowBytes,
310 const SkCodec::Options& opts,
311 SkPMColor* inputColorPtr,
312 int* inputColorCount) {
313 Result result = this->prepareToDecode(dstInfo, inputColorPtr, inputColorCount, opts);
314 if (result != kSuccess) {
315 return result;
msarett10522ff2015-09-07 08:54:01 -0700316 }
317
scroggo19b91532016-10-24 09:03:26 -0700318 fDst = pixels;
319 fDstRowBytes = dstRowBytes;
320
321 fFirstCallToIncrementalDecode = true;
322
msarett10522ff2015-09-07 08:54:01 -0700323 return kSuccess;
324}
325
scroggo19b91532016-10-24 09:03:26 -0700326SkCodec::Result SkGifCodec::onIncrementalDecode(int* rowsDecoded) {
327 // It is possible the client has appended more data. Parse, if needed.
328 const auto& options = this->options();
329 const size_t frameIndex = options.fFrameIndex;
scroggof9acbe22016-10-25 12:43:21 -0700330 fReader->parse((SkGifImageReader::SkGIFParseQuery) frameIndex);
scroggo19b91532016-10-24 09:03:26 -0700331
332 const bool firstCallToIncrementalDecode = fFirstCallToIncrementalDecode;
333 fFirstCallToIncrementalDecode = false;
334 return this->decodeFrame(firstCallToIncrementalDecode, options, rowsDecoded);
msarette6dd0042015-10-09 11:07:34 -0700335}
336
scroggo19b91532016-10-24 09:03:26 -0700337SkCodec::Result SkGifCodec::decodeFrame(bool firstAttempt, const Options& opts, int* rowsDecoded) {
338 const SkImageInfo& dstInfo = this->dstInfo();
339 const size_t frameIndex = opts.fFrameIndex;
340 SkASSERT(frameIndex < fReader->imagesCount());
scroggof9acbe22016-10-25 12:43:21 -0700341 const SkGIFFrameContext* frameContext = fReader->frameContext(frameIndex);
scroggo19b91532016-10-24 09:03:26 -0700342 if (firstAttempt) {
343 // rowsDecoded reports how many rows have been initialized, so a layer above
344 // can fill the rest. In some cases, we fill the background before decoding
345 // (or it is already filled for us), so we report rowsDecoded to be the full
346 // height.
347 bool filledBackground = false;
348 if (frameContext->getRequiredFrame() == kNone) {
349 // We may need to clear to transparent for one of the following reasons:
350 // - The frameRect does not cover the full bounds. haveDecodedRow will
351 // only draw inside the frameRect, so we need to clear the rest.
scroggo19b91532016-10-24 09:03:26 -0700352 // - The frame is interlaced. There is no obvious way to fill
353 // afterwards for an incomplete image. (FIXME: Does the first pass
354 // cover all rows? If so, we do not have to fill here.)
scroggo8bce1172016-10-25 13:08:40 -0700355 // - There is no color table for this frame. In that case will not
356 // draw anything, so we need to fill.
scroggo19b91532016-10-24 09:03:26 -0700357 if (frameContext->frameRect() != this->getInfo().bounds()
scroggo8bce1172016-10-25 13:08:40 -0700358 || frameContext->interlaced() || !fCurrColorTableIsReal) {
scroggo19b91532016-10-24 09:03:26 -0700359 // fill ignores the width (replaces it with the actual, scaled width).
360 // But we need to scale in Y.
361 const int scaledHeight = get_scaled_dimension(dstInfo.height(),
362 fSwizzler->sampleY());
363 auto fillInfo = dstInfo.makeWH(0, scaledHeight);
364 fSwizzler->fill(fillInfo, fDst, fDstRowBytes, this->getFillValue(dstInfo),
365 opts.fZeroInitialized);
366 filledBackground = true;
367 }
368 } else {
369 // Not independent
370 if (!opts.fHasPriorFrame) {
371 // Decode that frame into pixels.
372 Options prevFrameOpts(opts);
373 prevFrameOpts.fFrameIndex = frameContext->getRequiredFrame();
374 prevFrameOpts.fHasPriorFrame = false;
Leon Scroggins IIIfc49b402016-10-31 14:08:56 -0400375 // The prior frame may have a different color table, so update it and the
376 // swizzler.
377 this->initializeColorTable(dstInfo, prevFrameOpts.fFrameIndex);
378 this->initializeSwizzler(dstInfo, prevFrameOpts.fFrameIndex);
379
scroggo19b91532016-10-24 09:03:26 -0700380 const Result prevResult = this->decodeFrame(true, prevFrameOpts, nullptr);
381 switch (prevResult) {
382 case kSuccess:
383 // Prior frame succeeded. Carry on.
384 break;
385 case kIncompleteInput:
386 // Prior frame was incomplete. So this frame cannot be decoded.
387 return kInvalidInput;
388 default:
389 return prevResult;
390 }
Leon Scroggins IIIfc49b402016-10-31 14:08:56 -0400391
392 // Go back to using the correct color table for this frame.
393 this->initializeColorTable(dstInfo, frameIndex);
394 this->initializeSwizzler(dstInfo, frameIndex);
scroggo19b91532016-10-24 09:03:26 -0700395 }
396 const auto* prevFrame = fReader->frameContext(frameContext->getRequiredFrame());
397 if (prevFrame->getDisposalMethod() == SkCodecAnimation::RestoreBGColor_DisposalMethod) {
398 const SkIRect prevRect = prevFrame->frameRect();
399 auto left = get_scaled_dimension(prevRect.fLeft, fSwizzler->sampleX());
400 auto top = get_scaled_dimension(prevRect.fTop, fSwizzler->sampleY());
401 void* const eraseDst = SkTAddOffset<void>(fDst, top * fDstRowBytes
402 + left * SkColorTypeBytesPerPixel(dstInfo.colorType()));
403 auto width = get_scaled_dimension(prevRect.width(), fSwizzler->sampleX());
404 auto height = get_scaled_dimension(prevRect.height(), fSwizzler->sampleY());
405 // fSwizzler->fill() would fill to the scaled width of the frame, but we want to
406 // fill to the scaled with of the width of the PRIOR frame, so we do all the scaling
407 // ourselves and call the static version.
408 SkSampler::Fill(dstInfo.makeWH(width, height), eraseDst,
409 fDstRowBytes, this->getFillValue(dstInfo), kNo_ZeroInitialized);
410 }
411 filledBackground = true;
msarett10522ff2015-09-07 08:54:01 -0700412 }
scroggo19b91532016-10-24 09:03:26 -0700413
414 fFilledBackground = filledBackground;
415 if (filledBackground) {
416 // Report the full (scaled) height, since the client will never need to fill.
417 fRowsDecoded = get_scaled_dimension(dstInfo.height(), fSwizzler->sampleY());
418 } else {
419 // This will be updated by haveDecodedRow.
420 fRowsDecoded = 0;
421 }
msarett10522ff2015-09-07 08:54:01 -0700422 }
msarette6dd0042015-10-09 11:07:34 -0700423
scroggo3d3a65c2016-10-24 12:28:30 -0700424 // Note: there is a difference between the following call to SkGifImageReader::decode
scroggo19b91532016-10-24 09:03:26 -0700425 // returning false and leaving frameDecoded false:
426 // - If the method returns false, there was an error in the stream. We still treat this as
427 // incomplete, since we have already decoded some rows.
428 // - If frameDecoded is false, that just means that we do not have enough data. If more data
429 // is supplied, we may be able to continue decoding this frame. We also treat this as
430 // incomplete.
431 // FIXME: Ensure that we do not attempt to continue decoding if the method returns false and
432 // more data is supplied.
433 bool frameDecoded = false;
434 if (!fReader->decode(frameIndex, &frameDecoded) || !frameDecoded) {
435 if (rowsDecoded) {
436 *rowsDecoded = fRowsDecoded;
437 }
438 return kIncompleteInput;
439 }
440
441 return kSuccess;
msarett10522ff2015-09-07 08:54:01 -0700442}
scroggo46c57472015-09-30 08:57:13 -0700443
scroggo19b91532016-10-24 09:03:26 -0700444uint64_t SkGifCodec::onGetFillValue(const SkImageInfo& dstInfo) const {
445 // Note: Using fCurrColorTable relies on having called initializeColorTable already.
446 // This is (currently) safe because this method is only called when filling, after
447 // initializeColorTable has been called.
448 // FIXME: Is there a way to make this less fragile?
449 if (dstInfo.colorType() == kIndex_8_SkColorType && fCurrColorTableIsReal) {
450 // We only support index 8 for the first frame, for backwards
451 // compatibity on Android, so we are using the color table for the first frame.
452 SkASSERT(this->options().fFrameIndex == 0);
453 // Use the transparent index for the first frame.
454 const size_t transPixel = fReader->frameContext(0)->transparentPixel();
455 if (transPixel < (size_t) fCurrColorTable->count()) {
456 return transPixel;
457 }
458 // Fall through to return SK_ColorTRANSPARENT (i.e. 0). This choice is arbitrary,
459 // but we have to pick something inside the color table, and this one is as good
460 // as any.
461 }
462 // Using transparent as the fill value matches the behavior in Chromium,
463 // which ignores the background color.
464 // If the colorType is kIndex_8, and there was no color table (i.e.
465 // fCurrColorTableIsReal is false), this value (zero) corresponds to the
466 // only entry in the dummy color table provided to the client.
467 return SK_ColorTRANSPARENT;
468}
msarett72261c02015-11-19 15:29:26 -0800469
Matt Sarett61eedeb2016-11-04 13:19:48 -0400470void SkGifCodec::applyXformRow(const SkImageInfo& dstInfo, void* dst, const uint8_t* src) const {
471 if (this->colorXform() && fXformOnDecode) {
472 fSwizzler->swizzle(fXformBuffer.get(), src);
473
474 const SkColorSpaceXform::ColorFormat dstFormat = select_xform_format(dstInfo.colorType());
Matt Sarett562e6812016-11-08 16:13:43 -0500475 const SkColorSpaceXform::ColorFormat srcFormat = select_xform_format(kXformSrcColorType);
Matt Sarett61eedeb2016-11-04 13:19:48 -0400476 const SkAlphaType xformAlphaType = select_xform_alpha(dstInfo.alphaType(),
477 this->getInfo().alphaType());
478 const int xformWidth = get_scaled_dimension(dstInfo.width(), fSwizzler->sampleX());
479 SkAssertResult(this->colorXform()->apply(dstFormat, dst, srcFormat, fXformBuffer.get(),
480 xformWidth, xformAlphaType));
481 } else {
482 fSwizzler->swizzle(dst, src);
483 }
484}
485
scroggo19b91532016-10-24 09:03:26 -0700486bool SkGifCodec::haveDecodedRow(size_t frameIndex, const unsigned char* rowBegin,
487 size_t rowNumber, unsigned repeatCount, bool writeTransparentPixels)
488{
scroggof9acbe22016-10-25 12:43:21 -0700489 const SkGIFFrameContext* frameContext = fReader->frameContext(frameIndex);
scroggo19b91532016-10-24 09:03:26 -0700490 // The pixel data and coordinates supplied to us are relative to the frame's
491 // origin within the entire image size, i.e.
492 // (frameContext->xOffset, frameContext->yOffset). There is no guarantee
493 // that width == (size().width() - frameContext->xOffset), so
494 // we must ensure we don't run off the end of either the source data or the
495 // row's X-coordinates.
496 const size_t width = frameContext->width();
497 const int xBegin = frameContext->xOffset();
498 const int yBegin = frameContext->yOffset() + rowNumber;
499 const int xEnd = std::min(static_cast<int>(frameContext->xOffset() + width),
500 this->getInfo().width());
501 const int yEnd = std::min(static_cast<int>(frameContext->yOffset() + rowNumber + repeatCount),
502 this->getInfo().height());
503 // FIXME: No need to make the checks on width/xBegin/xEnd for every row. We could instead do
504 // this once in prepareToDecode.
505 if (!width || (xBegin < 0) || (yBegin < 0) || (xEnd <= xBegin) || (yEnd <= yBegin))
506 return true;
507
508 // yBegin is the first row in the non-sampled image. dstRow will be the row in the output,
509 // after potentially scaling it.
510 int dstRow = yBegin;
511
512 const int sampleY = fSwizzler->sampleY();
513 if (sampleY > 1) {
514 // Check to see whether this row or one that falls in the repeatCount is needed in the
515 // output.
516 bool foundNecessaryRow = false;
517 for (unsigned i = 0; i < repeatCount; i++) {
518 const int potentialRow = yBegin + i;
519 if (fSwizzler->rowNeeded(potentialRow)) {
520 dstRow = potentialRow / sampleY;
521 const int scaledHeight = get_scaled_dimension(this->dstInfo().height(), sampleY);
522 if (dstRow >= scaledHeight) {
523 return true;
524 }
525
526 foundNecessaryRow = true;
527 repeatCount -= i;
528
529 repeatCount = (repeatCount - 1) / sampleY + 1;
530
531 // Make sure the repeatCount does not take us beyond the end of the dst
532 if (dstRow + (int) repeatCount > scaledHeight) {
533 repeatCount = scaledHeight - dstRow;
534 SkASSERT(repeatCount >= 1);
535 }
536 break;
537 }
538 }
539
540 if (!foundNecessaryRow) {
541 return true;
542 }
Matt Sarett8a4e9c52016-10-25 14:24:50 -0400543 } else {
544 // Make sure the repeatCount does not take us beyond the end of the dst
545 SkASSERT(this->dstInfo().height() >= yBegin);
546 repeatCount = SkTMin(repeatCount, (unsigned) (this->dstInfo().height() - yBegin));
scroggo19b91532016-10-24 09:03:26 -0700547 }
548
549 if (!fFilledBackground) {
550 // At this point, we are definitely going to write the row, so count it towards the number
551 // of rows decoded.
552 // We do not consider the repeatCount, which only happens for interlaced, in which case we
553 // have already set fRowsDecoded to the proper value (reflecting that we have filled the
554 // background).
555 fRowsDecoded++;
556 }
557
558 if (!fCurrColorTableIsReal) {
559 // No color table, so nothing to draw this frame.
560 // FIXME: We can abort even earlier - no need to decode this frame.
561 return true;
562 }
563
564 // The swizzler takes care of offsetting into the dst width-wise.
565 void* dstLine = SkTAddOffset<void>(fDst, dstRow * fDstRowBytes);
566
567 // We may or may not need to write transparent pixels to the buffer.
scroggo1285f412016-10-26 13:48:03 -0700568 // If we're compositing against a previous image, it's wrong, but if
569 // we're decoding an interlaced gif and displaying it "Haeberli"-style,
570 // we must write these for passes beyond the first, or the initial passes
571 // will "show through" the later ones.
scroggo19b91532016-10-24 09:03:26 -0700572 const auto dstInfo = this->dstInfo();
scroggo53f63b62016-10-27 08:29:13 -0700573 if (writeTransparentPixels) {
Matt Sarett61eedeb2016-11-04 13:19:48 -0400574 this->applyXformRow(dstInfo, dstLine, rowBegin);
scroggo19b91532016-10-24 09:03:26 -0700575 } else {
Matt Sarett61eedeb2016-11-04 13:19:48 -0400576 sk_bzero(fTmpBuffer.get(), dstInfo.minRowBytes());
577 this->applyXformRow(dstInfo, fTmpBuffer.get(), rowBegin);
scroggo19b91532016-10-24 09:03:26 -0700578
579 const size_t offsetBytes = fSwizzler->swizzleOffsetBytes();
580 switch (dstInfo.colorType()) {
581 case kBGRA_8888_SkColorType:
582 case kRGBA_8888_SkColorType: {
583 uint32_t* dstPixel = SkTAddOffset<uint32_t>(dstLine, offsetBytes);
584 uint32_t* srcPixel = SkTAddOffset<uint32_t>(fTmpBuffer.get(), offsetBytes);
585 for (int i = 0; i < fSwizzler->swizzleWidth(); i++) {
586 // Technically SK_ColorTRANSPARENT is an SkPMColor, and srcPixel would have
587 // the opposite swizzle for the non-native swizzle, but TRANSPARENT is all
588 // zeroes, which is the same either way.
589 if (*srcPixel != SK_ColorTRANSPARENT) {
590 *dstPixel = *srcPixel;
591 }
592 dstPixel++;
593 srcPixel++;
594 }
595 break;
596 }
Matt Sarett61eedeb2016-11-04 13:19:48 -0400597 case kRGBA_F16_SkColorType: {
598 uint64_t* dstPixel = SkTAddOffset<uint64_t>(dstLine, offsetBytes);
599 uint64_t* srcPixel = SkTAddOffset<uint64_t>(fTmpBuffer.get(), offsetBytes);
scroggo19b91532016-10-24 09:03:26 -0700600 for (int i = 0; i < fSwizzler->swizzleWidth(); i++) {
Matt Sarett61eedeb2016-11-04 13:19:48 -0400601 if (*srcPixel != 0) {
scroggo19b91532016-10-24 09:03:26 -0700602 *dstPixel = *srcPixel;
603 }
604 dstPixel++;
605 srcPixel++;
606 }
607 break;
608 }
609 default:
610 SkASSERT(false);
611 break;
612 }
613 }
614
615 // Tell the frame to copy the row data if need be.
616 if (repeatCount > 1) {
617 const size_t bytesPerPixel = SkColorTypeBytesPerPixel(this->dstInfo().colorType());
618 const size_t bytesToCopy = fSwizzler->swizzleWidth() * bytesPerPixel;
619 void* copiedLine = SkTAddOffset<void>(dstLine, fSwizzler->swizzleOffsetBytes());
620 void* dst = copiedLine;
621 for (unsigned i = 1; i < repeatCount; i++) {
622 dst = SkTAddOffset<void>(dst, fDstRowBytes);
623 memcpy(dst, copiedLine, bytesToCopy);
msarett72261c02015-11-19 15:29:26 -0800624 }
625 }
626
627 return true;
628}