blob: a70f7be14eb55721b431711cd3592af6309befad [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)) {
Leon Scroggins III4993b952016-12-08 11:54:04 -050077 // Fatal error occurred.
scroggo19b91532016-10-24 09:03:26 -070078 return nullptr;
msarett8c8f22a2015-04-01 06:58:48 -070079 }
msarett8c8f22a2015-04-01 06:58:48 -070080
Leon Scroggins III4993b952016-12-08 11:54:04 -050081 // If no images are in the data, or the first header is not yet defined, we cannot
82 // create a codec. In either case, the width and height are not yet known.
83 if (0 == reader->imagesCount() || !reader->frameContext(0)->isHeaderDefined()) {
scroggo19b91532016-10-24 09:03:26 -070084 return nullptr;
85 }
86
Leon Scroggins III4993b952016-12-08 11:54:04 -050087 // isHeaderDefined() will not return true if the screen size is empty.
88 SkASSERT(reader->screenHeight() > 0 && reader->screenWidth() > 0);
89
scroggo19b91532016-10-24 09:03:26 -070090 const auto alpha = reader->firstFrameHasAlpha() ? SkEncodedInfo::kBinary_Alpha
91 : SkEncodedInfo::kOpaque_Alpha;
92 // Use kPalette since Gifs are encoded with a color table.
93 // FIXME: Gifs can actually be encoded with 4-bits per pixel. Using 8 works, but we could skip
94 // expanding to 8 bits and take advantage of the SkSwizzler to work from 4.
95 const auto encodedInfo = SkEncodedInfo::Make(SkEncodedInfo::kPalette_Color, alpha, 8);
96
97 // Although the encodedInfo is always kPalette_Color, it is possible that kIndex_8 is
98 // unsupported if the frame is subset and there is no transparent pixel.
99 const auto colorType = reader->firstFrameSupportsIndex8() ? kIndex_8_SkColorType
100 : kN32_SkColorType;
101 // The choice of unpremul versus premul is arbitrary, since all colors are either fully
102 // opaque or fully transparent (i.e. kBinary), but we stored the transparent colors as all
103 // zeroes, which is arguably premultiplied.
104 const auto alphaType = reader->firstFrameHasAlpha() ? kUnpremul_SkAlphaType
105 : kOpaque_SkAlphaType;
Matt Sarett7f650bd2016-10-30 21:25:34 -0400106
scroggo19b91532016-10-24 09:03:26 -0700107 const auto imageInfo = SkImageInfo::Make(reader->screenWidth(), reader->screenHeight(),
Matt Sarett7f650bd2016-10-30 21:25:34 -0400108 colorType, alphaType,
Matt Sarett77a7a1b2017-02-07 13:56:11 -0500109 SkColorSpace::MakeSRGB());
scroggo19b91532016-10-24 09:03:26 -0700110 return new SkGifCodec(encodedInfo, imageInfo, reader.release());
111}
msarett8c8f22a2015-04-01 06:58:48 -0700112
scroggob427db12015-08-12 07:24:13 -0700113bool SkGifCodec::onRewind() {
scroggo19b91532016-10-24 09:03:26 -0700114 fReader->clearDecodeState();
scroggob427db12015-08-12 07:24:13 -0700115 return true;
116}
117
scroggo19b91532016-10-24 09:03:26 -0700118SkGifCodec::SkGifCodec(const SkEncodedInfo& encodedInfo, const SkImageInfo& imageInfo,
scroggo3d3a65c2016-10-24 12:28:30 -0700119 SkGifImageReader* reader)
scroggo19b91532016-10-24 09:03:26 -0700120 : INHERITED(encodedInfo, imageInfo, nullptr)
121 , fReader(reader)
122 , fTmpBuffer(nullptr)
123 , fSwizzler(nullptr)
124 , fCurrColorTable(nullptr)
125 , fCurrColorTableIsReal(false)
126 , fFilledBackground(false)
127 , fFirstCallToIncrementalDecode(false)
128 , fDst(nullptr)
129 , fDstRowBytes(0)
130 , fRowsDecoded(0)
131{
132 reader->setClient(this);
msarett8c8f22a2015-04-01 06:58:48 -0700133}
msarett10522ff2015-09-07 08:54:01 -0700134
scroggo19b91532016-10-24 09:03:26 -0700135std::vector<SkCodec::FrameInfo> SkGifCodec::onGetFrameInfo() {
scroggof9acbe22016-10-25 12:43:21 -0700136 fReader->parse(SkGifImageReader::SkGIFFrameCountQuery);
scroggo19b91532016-10-24 09:03:26 -0700137 const size_t size = fReader->imagesCount();
138 std::vector<FrameInfo> result(size);
139 for (size_t i = 0; i < size; i++) {
scroggof9acbe22016-10-25 12:43:21 -0700140 const SkGIFFrameContext* frameContext = fReader->frameContext(i);
scroggo19b91532016-10-24 09:03:26 -0700141 result[i].fDuration = frameContext->delayTime();
142 result[i].fRequiredFrame = frameContext->getRequiredFrame();
Leon Scroggins III3639faa2016-12-08 11:38:58 -0500143 result[i].fFullyReceived = frameContext->isComplete();
msarett10522ff2015-09-07 08:54:01 -0700144 }
scroggo19b91532016-10-24 09:03:26 -0700145 return result;
msarett10522ff2015-09-07 08:54:01 -0700146}
147
scroggoe71b1a12016-11-01 08:28:28 -0700148int SkGifCodec::onGetRepetitionCount() {
149 fReader->parse(SkGifImageReader::SkGIFLoopCountQuery);
150 return fReader->loopCount();
151}
152
Matt Sarett562e6812016-11-08 16:13:43 -0500153static const SkColorType kXformSrcColorType = kRGBA_8888_SkColorType;
154
Leon Scroggins IIIfc49b402016-10-31 14:08:56 -0400155void SkGifCodec::initializeColorTable(const SkImageInfo& dstInfo, size_t frameIndex) {
Matt Sarett61eedeb2016-11-04 13:19:48 -0400156 SkColorType colorTableColorType = dstInfo.colorType();
157 if (this->colorXform()) {
Matt Sarett562e6812016-11-08 16:13:43 -0500158 colorTableColorType = kXformSrcColorType;
Matt Sarett61eedeb2016-11-04 13:19:48 -0400159 }
160
161 sk_sp<SkColorTable> currColorTable = fReader->getColorTable(colorTableColorType, frameIndex);
162 fCurrColorTableIsReal = currColorTable;
163 if (!fCurrColorTableIsReal) {
Leon Scroggins IIIa049ac42016-10-27 11:16:11 -0400164 // This is possible for an empty frame. Create a dummy with one value (transparent).
165 SkPMColor color = SK_ColorTRANSPARENT;
166 fCurrColorTable.reset(new SkColorTable(&color, 1));
Matt Sarett61eedeb2016-11-04 13:19:48 -0400167 } else if (this->colorXform() && !fXformOnDecode) {
168 SkPMColor dstColors[256];
Matt Sarett562e6812016-11-08 16:13:43 -0500169 const SkColorSpaceXform::ColorFormat dstFormat = select_xform_format(dstInfo.colorType());
170 const SkColorSpaceXform::ColorFormat srcFormat = select_xform_format(kXformSrcColorType);
171 const SkAlphaType xformAlphaType = select_xform_alpha(dstInfo.alphaType(),
172 this->getInfo().alphaType());
Matt Sarett61eedeb2016-11-04 13:19:48 -0400173 SkAssertResult(this->colorXform()->apply(dstFormat, dstColors, srcFormat,
174 currColorTable->readColors(),
175 currColorTable->count(), xformAlphaType));
176 fCurrColorTable.reset(new SkColorTable(dstColors, currColorTable->count()));
177 } else {
178 fCurrColorTable = std::move(currColorTable);
msarett10522ff2015-09-07 08:54:01 -0700179 }
msarett10522ff2015-09-07 08:54:01 -0700180}
181
scroggo19b91532016-10-24 09:03:26 -0700182
msarett10522ff2015-09-07 08:54:01 -0700183SkCodec::Result SkGifCodec::prepareToDecode(const SkImageInfo& dstInfo, SkPMColor* inputColorPtr,
184 int* inputColorCount, const Options& opts) {
msarett10522ff2015-09-07 08:54:01 -0700185 // Check for valid input parameters
Matt Sarettcf3f2342017-03-23 15:32:25 -0400186 if (!conversion_possible(dstInfo, this->getInfo()) ||
187 !this->initializeColorXform(dstInfo, opts.fPremulBehavior))
188 {
msarett2ecc35f2016-09-08 11:55:16 -0700189 return gif_error("Cannot convert input type to output type.\n", kInvalidConversion);
msarett10522ff2015-09-07 08:54:01 -0700190 }
191
Matt Sarett61eedeb2016-11-04 13:19:48 -0400192 fXformOnDecode = false;
193 if (this->colorXform()) {
194 fXformOnDecode = apply_xform_on_decode(dstInfo.colorType(), this->getEncodedInfo().color());
195 if (fXformOnDecode) {
196 fXformBuffer.reset(new uint32_t[dstInfo.width()]);
197 sk_bzero(fXformBuffer.get(), dstInfo.width() * sizeof(uint32_t));
198 }
scroggo19b91532016-10-24 09:03:26 -0700199 }
msarett5af4e0b2015-11-17 11:18:03 -0800200
scroggo19b91532016-10-24 09:03:26 -0700201 if (opts.fSubset) {
202 return gif_error("Subsets not supported.\n", kUnimplemented);
203 }
204
205 const size_t frameIndex = opts.fFrameIndex;
scroggo53f63b62016-10-27 08:29:13 -0700206 if (frameIndex > 0) {
207 switch (dstInfo.colorType()) {
208 case kIndex_8_SkColorType:
209 // FIXME: It is possible that a later frame can be decoded to index8, if it does one
210 // of the following:
211 // - Covers the entire previous frame
212 // - Shares a color table (and transparent index) with any prior frames that are
213 // showing.
214 // We must support index8 for the first frame to be backwards compatible on Android,
215 // but we do not (currently) need to support later frames as index8.
216 return gif_error("Cannot decode multiframe gif (except frame 0) as index 8.\n",
217 kInvalidConversion);
218 case kRGB_565_SkColorType:
219 // FIXME: In theory, we might be able to support this, but it's not clear that it
220 // is necessary (Chromium does not decode to 565, and Android does not decode
221 // frames beyond the first). Disabling it because it is somewhat difficult:
222 // - If there is a transparent pixel, and this frame draws on top of another frame
223 // (if the frame is independent with a transparent pixel, we should not decode to
224 // 565 anyway, since it is not opaque), we need to skip drawing the transparent
225 // pixels (see writeTransparentPixels in haveDecodedRow). We currently do this by
226 // first swizzling into temporary memory, then copying into the destination. (We
227 // let the swizzler handle it first because it may need to sample.) After
228 // swizzling to 565, we do not know which pixels in our temporary memory
229 // correspond to the transparent pixel, so we do not know what to skip. We could
230 // special case the non-sampled case (no need to swizzle), but as this is
231 // currently unused we can just not support it.
232 return gif_error("Cannot decode multiframe gif (except frame 0) as 565.\n",
233 kInvalidConversion);
234 default:
235 break;
236 }
scroggo19b91532016-10-24 09:03:26 -0700237 }
238
scroggof9acbe22016-10-25 12:43:21 -0700239 fReader->parse((SkGifImageReader::SkGIFParseQuery) frameIndex);
scroggo19b91532016-10-24 09:03:26 -0700240
241 if (frameIndex >= fReader->imagesCount()) {
242 return gif_error("frame index out of range!\n", kIncompleteInput);
243 }
244
Leon Scroggins IIIe4ba1052017-01-30 13:55:14 -0500245 if (!fReader->frameContext(frameIndex)->reachedStartOfData()) {
Leon Scroggins III3fc97d72016-12-09 16:39:33 -0500246 // We have parsed enough to know that there is a color map, but cannot
247 // parse the map itself yet. Exit now, so we do not build an incorrect
248 // table.
249 return gif_error("color map not available yet\n", kIncompleteInput);
250 }
251
scroggo19b91532016-10-24 09:03:26 -0700252 fTmpBuffer.reset(new uint8_t[dstInfo.minRowBytes()]);
253
Leon Scroggins IIIfc49b402016-10-31 14:08:56 -0400254 this->initializeColorTable(dstInfo, frameIndex);
scroggo19b91532016-10-24 09:03:26 -0700255 this->initializeSwizzler(dstInfo, frameIndex);
Leon Scroggins IIIfc49b402016-10-31 14:08:56 -0400256
257 SkASSERT(fCurrColorTable);
258 if (inputColorCount) {
259 *inputColorCount = fCurrColorTable->count();
260 }
261 copy_color_table(dstInfo, fCurrColorTable.get(), inputColorPtr, inputColorCount);
262
msarettb30d6982016-02-15 10:18:45 -0800263 return kSuccess;
msarett10522ff2015-09-07 08:54:01 -0700264}
265
scroggo19b91532016-10-24 09:03:26 -0700266void SkGifCodec::initializeSwizzler(const SkImageInfo& dstInfo, size_t frameIndex) {
scroggof9acbe22016-10-25 12:43:21 -0700267 const SkGIFFrameContext* frame = fReader->frameContext(frameIndex);
scroggo19b91532016-10-24 09:03:26 -0700268 // This is only called by prepareToDecode, which ensures frameIndex is in range.
269 SkASSERT(frame);
msarett10522ff2015-09-07 08:54:01 -0700270
scroggo19b91532016-10-24 09:03:26 -0700271 const int xBegin = frame->xOffset();
272 const int xEnd = std::min(static_cast<int>(frame->xOffset() + frame->width()),
273 static_cast<int>(fReader->screenWidth()));
274
275 // CreateSwizzler only reads left and right of the frame. We cannot use the frame's raw
276 // frameRect, since it might extend beyond the edge of the frame.
277 SkIRect swizzleRect = SkIRect::MakeLTRB(xBegin, 0, xEnd, 0);
278
Matt Sarett61eedeb2016-11-04 13:19:48 -0400279 SkImageInfo swizzlerInfo = dstInfo;
280 if (this->colorXform()) {
Matt Sarett562e6812016-11-08 16:13:43 -0500281 swizzlerInfo = swizzlerInfo.makeColorType(kXformSrcColorType);
Matt Sarett61eedeb2016-11-04 13:19:48 -0400282 if (kPremul_SkAlphaType == dstInfo.alphaType()) {
283 swizzlerInfo = swizzlerInfo.makeAlphaType(kUnpremul_SkAlphaType);
284 }
285 }
286
scroggo19b91532016-10-24 09:03:26 -0700287 // The default Options should be fine:
288 // - we'll ignore if the memory is zero initialized - unless we're the first frame, this won't
289 // matter anyway.
290 // - subsets are not supported for gif
291 // - the swizzler does not need to know about the frame.
292 // We may not be able to use the real Options anyway, since getPixels does not store it (due to
293 // a bug).
294 fSwizzler.reset(SkSwizzler::CreateSwizzler(this->getEncodedInfo(),
Matt Sarett61eedeb2016-11-04 13:19:48 -0400295 fCurrColorTable->readColors(), swizzlerInfo, Options(), &swizzleRect));
scroggo19b91532016-10-24 09:03:26 -0700296 SkASSERT(fSwizzler.get());
msarett10522ff2015-09-07 08:54:01 -0700297}
298
299/*
300 * Initiates the gif decode
301 */
302SkCodec::Result SkGifCodec::onGetPixels(const SkImageInfo& dstInfo,
scroggo19b91532016-10-24 09:03:26 -0700303 void* pixels, size_t dstRowBytes,
msarett10522ff2015-09-07 08:54:01 -0700304 const Options& opts,
305 SkPMColor* inputColorPtr,
msarette6dd0042015-10-09 11:07:34 -0700306 int* inputColorCount,
307 int* rowsDecoded) {
msarett10522ff2015-09-07 08:54:01 -0700308 Result result = this->prepareToDecode(dstInfo, inputColorPtr, inputColorCount, opts);
Leon Scroggins III3fc97d72016-12-09 16:39:33 -0500309 switch (result) {
310 case kSuccess:
311 break;
312 case kIncompleteInput:
313 // onStartIncrementalDecode treats this as incomplete, since it may
314 // provide more data later, but in this case, no more data will be
315 // provided, and there is nothing to draw. We also cannot return
316 // kIncompleteInput, which will make SkCodec attempt to fill
317 // remaining rows, but that requires an SkSwizzler, which we have
318 // not created.
319 return kInvalidInput;
320 default:
321 return result;
msarett10522ff2015-09-07 08:54:01 -0700322 }
323
324 if (dstInfo.dimensions() != this->getInfo().dimensions()) {
325 return gif_error("Scaling not supported.\n", kInvalidScale);
326 }
327
scroggo19b91532016-10-24 09:03:26 -0700328 fDst = pixels;
329 fDstRowBytes = dstRowBytes;
330
331 return this->decodeFrame(true, opts, rowsDecoded);
332}
333
334SkCodec::Result SkGifCodec::onStartIncrementalDecode(const SkImageInfo& dstInfo,
335 void* pixels, size_t dstRowBytes,
336 const SkCodec::Options& opts,
337 SkPMColor* inputColorPtr,
338 int* inputColorCount) {
339 Result result = this->prepareToDecode(dstInfo, inputColorPtr, inputColorCount, opts);
340 if (result != kSuccess) {
341 return result;
msarett10522ff2015-09-07 08:54:01 -0700342 }
343
scroggo19b91532016-10-24 09:03:26 -0700344 fDst = pixels;
345 fDstRowBytes = dstRowBytes;
346
347 fFirstCallToIncrementalDecode = true;
348
msarett10522ff2015-09-07 08:54:01 -0700349 return kSuccess;
350}
351
scroggo19b91532016-10-24 09:03:26 -0700352SkCodec::Result SkGifCodec::onIncrementalDecode(int* rowsDecoded) {
353 // It is possible the client has appended more data. Parse, if needed.
354 const auto& options = this->options();
355 const size_t frameIndex = options.fFrameIndex;
scroggof9acbe22016-10-25 12:43:21 -0700356 fReader->parse((SkGifImageReader::SkGIFParseQuery) frameIndex);
scroggo19b91532016-10-24 09:03:26 -0700357
358 const bool firstCallToIncrementalDecode = fFirstCallToIncrementalDecode;
359 fFirstCallToIncrementalDecode = false;
360 return this->decodeFrame(firstCallToIncrementalDecode, options, rowsDecoded);
msarette6dd0042015-10-09 11:07:34 -0700361}
362
scroggo19b91532016-10-24 09:03:26 -0700363SkCodec::Result SkGifCodec::decodeFrame(bool firstAttempt, const Options& opts, int* rowsDecoded) {
364 const SkImageInfo& dstInfo = this->dstInfo();
365 const size_t frameIndex = opts.fFrameIndex;
366 SkASSERT(frameIndex < fReader->imagesCount());
scroggof9acbe22016-10-25 12:43:21 -0700367 const SkGIFFrameContext* frameContext = fReader->frameContext(frameIndex);
scroggo19b91532016-10-24 09:03:26 -0700368 if (firstAttempt) {
369 // rowsDecoded reports how many rows have been initialized, so a layer above
370 // can fill the rest. In some cases, we fill the background before decoding
371 // (or it is already filled for us), so we report rowsDecoded to be the full
372 // height.
373 bool filledBackground = false;
374 if (frameContext->getRequiredFrame() == kNone) {
375 // We may need to clear to transparent for one of the following reasons:
376 // - The frameRect does not cover the full bounds. haveDecodedRow will
377 // only draw inside the frameRect, so we need to clear the rest.
scroggo19b91532016-10-24 09:03:26 -0700378 // - The frame is interlaced. There is no obvious way to fill
379 // afterwards for an incomplete image. (FIXME: Does the first pass
380 // cover all rows? If so, we do not have to fill here.)
scroggo8bce1172016-10-25 13:08:40 -0700381 // - There is no color table for this frame. In that case will not
382 // draw anything, so we need to fill.
scroggo19b91532016-10-24 09:03:26 -0700383 if (frameContext->frameRect() != this->getInfo().bounds()
scroggo8bce1172016-10-25 13:08:40 -0700384 || frameContext->interlaced() || !fCurrColorTableIsReal) {
scroggo19b91532016-10-24 09:03:26 -0700385 // fill ignores the width (replaces it with the actual, scaled width).
386 // But we need to scale in Y.
387 const int scaledHeight = get_scaled_dimension(dstInfo.height(),
388 fSwizzler->sampleY());
389 auto fillInfo = dstInfo.makeWH(0, scaledHeight);
390 fSwizzler->fill(fillInfo, fDst, fDstRowBytes, this->getFillValue(dstInfo),
391 opts.fZeroInitialized);
392 filledBackground = true;
393 }
394 } else {
395 // Not independent
396 if (!opts.fHasPriorFrame) {
397 // Decode that frame into pixels.
398 Options prevFrameOpts(opts);
399 prevFrameOpts.fFrameIndex = frameContext->getRequiredFrame();
400 prevFrameOpts.fHasPriorFrame = false;
Leon Scroggins IIIfc49b402016-10-31 14:08:56 -0400401 // The prior frame may have a different color table, so update it and the
402 // swizzler.
403 this->initializeColorTable(dstInfo, prevFrameOpts.fFrameIndex);
404 this->initializeSwizzler(dstInfo, prevFrameOpts.fFrameIndex);
405
scroggo19b91532016-10-24 09:03:26 -0700406 const Result prevResult = this->decodeFrame(true, prevFrameOpts, nullptr);
407 switch (prevResult) {
408 case kSuccess:
409 // Prior frame succeeded. Carry on.
410 break;
411 case kIncompleteInput:
412 // Prior frame was incomplete. So this frame cannot be decoded.
413 return kInvalidInput;
414 default:
415 return prevResult;
416 }
Leon Scroggins IIIfc49b402016-10-31 14:08:56 -0400417
418 // Go back to using the correct color table for this frame.
419 this->initializeColorTable(dstInfo, frameIndex);
420 this->initializeSwizzler(dstInfo, frameIndex);
scroggo19b91532016-10-24 09:03:26 -0700421 }
422 const auto* prevFrame = fReader->frameContext(frameContext->getRequiredFrame());
423 if (prevFrame->getDisposalMethod() == SkCodecAnimation::RestoreBGColor_DisposalMethod) {
Leon Scroggins III56e32092016-12-12 17:10:46 -0500424 SkIRect prevRect = prevFrame->frameRect();
425 if (prevRect.intersect(this->getInfo().bounds())) {
Leon Scroggins III49f5da72016-12-13 10:57:43 -0500426 // Do the divide ourselves for left and top, since we do not want
427 // get_scaled_dimension to upgrade 0 to 1. (This is similar to SkSampledCodec's
428 // sampling of the subset.)
429 auto left = prevRect.fLeft / fSwizzler->sampleX();
430 auto top = prevRect.fTop / fSwizzler->sampleY();
Leon Scroggins III56e32092016-12-12 17:10:46 -0500431 void* const eraseDst = SkTAddOffset<void>(fDst, top * fDstRowBytes
432 + left * SkColorTypeBytesPerPixel(dstInfo.colorType()));
433 auto width = get_scaled_dimension(prevRect.width(), fSwizzler->sampleX());
434 auto height = get_scaled_dimension(prevRect.height(), fSwizzler->sampleY());
435 // fSwizzler->fill() would fill to the scaled width of the frame, but we want to
436 // fill to the scaled with of the width of the PRIOR frame, so we do all the
437 // scaling ourselves and call the static version.
438 SkSampler::Fill(dstInfo.makeWH(width, height), eraseDst,
439 fDstRowBytes, this->getFillValue(dstInfo), kNo_ZeroInitialized);
440 }
scroggo19b91532016-10-24 09:03:26 -0700441 }
442 filledBackground = true;
msarett10522ff2015-09-07 08:54:01 -0700443 }
scroggo19b91532016-10-24 09:03:26 -0700444
445 fFilledBackground = filledBackground;
446 if (filledBackground) {
447 // Report the full (scaled) height, since the client will never need to fill.
448 fRowsDecoded = get_scaled_dimension(dstInfo.height(), fSwizzler->sampleY());
449 } else {
450 // This will be updated by haveDecodedRow.
451 fRowsDecoded = 0;
452 }
msarett10522ff2015-09-07 08:54:01 -0700453 }
msarette6dd0042015-10-09 11:07:34 -0700454
Leon Scroggins III3fc97d72016-12-09 16:39:33 -0500455 if (!fCurrColorTableIsReal) {
456 // Nothing to draw this frame.
457 return kSuccess;
458 }
459
scroggo3d3a65c2016-10-24 12:28:30 -0700460 // Note: there is a difference between the following call to SkGifImageReader::decode
scroggo19b91532016-10-24 09:03:26 -0700461 // returning false and leaving frameDecoded false:
462 // - If the method returns false, there was an error in the stream. We still treat this as
463 // incomplete, since we have already decoded some rows.
464 // - If frameDecoded is false, that just means that we do not have enough data. If more data
465 // is supplied, we may be able to continue decoding this frame. We also treat this as
466 // incomplete.
467 // FIXME: Ensure that we do not attempt to continue decoding if the method returns false and
468 // more data is supplied.
469 bool frameDecoded = false;
470 if (!fReader->decode(frameIndex, &frameDecoded) || !frameDecoded) {
471 if (rowsDecoded) {
472 *rowsDecoded = fRowsDecoded;
473 }
474 return kIncompleteInput;
475 }
476
477 return kSuccess;
msarett10522ff2015-09-07 08:54:01 -0700478}
scroggo46c57472015-09-30 08:57:13 -0700479
scroggo19b91532016-10-24 09:03:26 -0700480uint64_t SkGifCodec::onGetFillValue(const SkImageInfo& dstInfo) const {
481 // Note: Using fCurrColorTable relies on having called initializeColorTable already.
482 // This is (currently) safe because this method is only called when filling, after
483 // initializeColorTable has been called.
484 // FIXME: Is there a way to make this less fragile?
485 if (dstInfo.colorType() == kIndex_8_SkColorType && fCurrColorTableIsReal) {
486 // We only support index 8 for the first frame, for backwards
487 // compatibity on Android, so we are using the color table for the first frame.
488 SkASSERT(this->options().fFrameIndex == 0);
489 // Use the transparent index for the first frame.
490 const size_t transPixel = fReader->frameContext(0)->transparentPixel();
491 if (transPixel < (size_t) fCurrColorTable->count()) {
492 return transPixel;
493 }
494 // Fall through to return SK_ColorTRANSPARENT (i.e. 0). This choice is arbitrary,
495 // but we have to pick something inside the color table, and this one is as good
496 // as any.
497 }
498 // Using transparent as the fill value matches the behavior in Chromium,
499 // which ignores the background color.
500 // If the colorType is kIndex_8, and there was no color table (i.e.
501 // fCurrColorTableIsReal is false), this value (zero) corresponds to the
502 // only entry in the dummy color table provided to the client.
503 return SK_ColorTRANSPARENT;
504}
msarett72261c02015-11-19 15:29:26 -0800505
Matt Sarett61eedeb2016-11-04 13:19:48 -0400506void SkGifCodec::applyXformRow(const SkImageInfo& dstInfo, void* dst, const uint8_t* src) const {
507 if (this->colorXform() && fXformOnDecode) {
508 fSwizzler->swizzle(fXformBuffer.get(), src);
509
510 const SkColorSpaceXform::ColorFormat dstFormat = select_xform_format(dstInfo.colorType());
Matt Sarett562e6812016-11-08 16:13:43 -0500511 const SkColorSpaceXform::ColorFormat srcFormat = select_xform_format(kXformSrcColorType);
Matt Sarett61eedeb2016-11-04 13:19:48 -0400512 const SkAlphaType xformAlphaType = select_xform_alpha(dstInfo.alphaType(),
513 this->getInfo().alphaType());
514 const int xformWidth = get_scaled_dimension(dstInfo.width(), fSwizzler->sampleX());
515 SkAssertResult(this->colorXform()->apply(dstFormat, dst, srcFormat, fXformBuffer.get(),
516 xformWidth, xformAlphaType));
517 } else {
518 fSwizzler->swizzle(dst, src);
519 }
520}
521
scroggo19b91532016-10-24 09:03:26 -0700522bool SkGifCodec::haveDecodedRow(size_t frameIndex, const unsigned char* rowBegin,
523 size_t rowNumber, unsigned repeatCount, bool writeTransparentPixels)
524{
scroggof9acbe22016-10-25 12:43:21 -0700525 const SkGIFFrameContext* frameContext = fReader->frameContext(frameIndex);
scroggo19b91532016-10-24 09:03:26 -0700526 // The pixel data and coordinates supplied to us are relative to the frame's
527 // origin within the entire image size, i.e.
528 // (frameContext->xOffset, frameContext->yOffset). There is no guarantee
529 // that width == (size().width() - frameContext->xOffset), so
530 // we must ensure we don't run off the end of either the source data or the
531 // row's X-coordinates.
532 const size_t width = frameContext->width();
533 const int xBegin = frameContext->xOffset();
534 const int yBegin = frameContext->yOffset() + rowNumber;
535 const int xEnd = std::min(static_cast<int>(frameContext->xOffset() + width),
536 this->getInfo().width());
537 const int yEnd = std::min(static_cast<int>(frameContext->yOffset() + rowNumber + repeatCount),
538 this->getInfo().height());
539 // FIXME: No need to make the checks on width/xBegin/xEnd for every row. We could instead do
540 // this once in prepareToDecode.
541 if (!width || (xBegin < 0) || (yBegin < 0) || (xEnd <= xBegin) || (yEnd <= yBegin))
542 return true;
543
544 // yBegin is the first row in the non-sampled image. dstRow will be the row in the output,
545 // after potentially scaling it.
546 int dstRow = yBegin;
547
548 const int sampleY = fSwizzler->sampleY();
549 if (sampleY > 1) {
550 // Check to see whether this row or one that falls in the repeatCount is needed in the
551 // output.
552 bool foundNecessaryRow = false;
553 for (unsigned i = 0; i < repeatCount; i++) {
554 const int potentialRow = yBegin + i;
555 if (fSwizzler->rowNeeded(potentialRow)) {
556 dstRow = potentialRow / sampleY;
557 const int scaledHeight = get_scaled_dimension(this->dstInfo().height(), sampleY);
558 if (dstRow >= scaledHeight) {
559 return true;
560 }
561
562 foundNecessaryRow = true;
563 repeatCount -= i;
564
565 repeatCount = (repeatCount - 1) / sampleY + 1;
566
567 // Make sure the repeatCount does not take us beyond the end of the dst
568 if (dstRow + (int) repeatCount > scaledHeight) {
569 repeatCount = scaledHeight - dstRow;
570 SkASSERT(repeatCount >= 1);
571 }
572 break;
573 }
574 }
575
576 if (!foundNecessaryRow) {
577 return true;
578 }
Matt Sarett8a4e9c52016-10-25 14:24:50 -0400579 } else {
580 // Make sure the repeatCount does not take us beyond the end of the dst
581 SkASSERT(this->dstInfo().height() >= yBegin);
582 repeatCount = SkTMin(repeatCount, (unsigned) (this->dstInfo().height() - yBegin));
scroggo19b91532016-10-24 09:03:26 -0700583 }
584
585 if (!fFilledBackground) {
586 // At this point, we are definitely going to write the row, so count it towards the number
587 // of rows decoded.
588 // We do not consider the repeatCount, which only happens for interlaced, in which case we
589 // have already set fRowsDecoded to the proper value (reflecting that we have filled the
590 // background).
591 fRowsDecoded++;
592 }
593
Leon Scroggins III3fc97d72016-12-09 16:39:33 -0500594 // decodeFrame will early exit if this is false, so this method will not be
595 // called.
596 SkASSERT(fCurrColorTableIsReal);
scroggo19b91532016-10-24 09:03:26 -0700597
598 // The swizzler takes care of offsetting into the dst width-wise.
599 void* dstLine = SkTAddOffset<void>(fDst, dstRow * fDstRowBytes);
600
601 // We may or may not need to write transparent pixels to the buffer.
scroggo1285f412016-10-26 13:48:03 -0700602 // If we're compositing against a previous image, it's wrong, but if
603 // we're decoding an interlaced gif and displaying it "Haeberli"-style,
604 // we must write these for passes beyond the first, or the initial passes
605 // will "show through" the later ones.
scroggo19b91532016-10-24 09:03:26 -0700606 const auto dstInfo = this->dstInfo();
scroggo53f63b62016-10-27 08:29:13 -0700607 if (writeTransparentPixels) {
Matt Sarett61eedeb2016-11-04 13:19:48 -0400608 this->applyXformRow(dstInfo, dstLine, rowBegin);
scroggo19b91532016-10-24 09:03:26 -0700609 } else {
Matt Sarett61eedeb2016-11-04 13:19:48 -0400610 sk_bzero(fTmpBuffer.get(), dstInfo.minRowBytes());
611 this->applyXformRow(dstInfo, fTmpBuffer.get(), rowBegin);
scroggo19b91532016-10-24 09:03:26 -0700612
613 const size_t offsetBytes = fSwizzler->swizzleOffsetBytes();
614 switch (dstInfo.colorType()) {
615 case kBGRA_8888_SkColorType:
616 case kRGBA_8888_SkColorType: {
617 uint32_t* dstPixel = SkTAddOffset<uint32_t>(dstLine, offsetBytes);
618 uint32_t* srcPixel = SkTAddOffset<uint32_t>(fTmpBuffer.get(), offsetBytes);
619 for (int i = 0; i < fSwizzler->swizzleWidth(); i++) {
620 // Technically SK_ColorTRANSPARENT is an SkPMColor, and srcPixel would have
621 // the opposite swizzle for the non-native swizzle, but TRANSPARENT is all
622 // zeroes, which is the same either way.
623 if (*srcPixel != SK_ColorTRANSPARENT) {
624 *dstPixel = *srcPixel;
625 }
626 dstPixel++;
627 srcPixel++;
628 }
629 break;
630 }
Matt Sarett61eedeb2016-11-04 13:19:48 -0400631 case kRGBA_F16_SkColorType: {
632 uint64_t* dstPixel = SkTAddOffset<uint64_t>(dstLine, offsetBytes);
633 uint64_t* srcPixel = SkTAddOffset<uint64_t>(fTmpBuffer.get(), offsetBytes);
scroggo19b91532016-10-24 09:03:26 -0700634 for (int i = 0; i < fSwizzler->swizzleWidth(); i++) {
Matt Sarett61eedeb2016-11-04 13:19:48 -0400635 if (*srcPixel != 0) {
scroggo19b91532016-10-24 09:03:26 -0700636 *dstPixel = *srcPixel;
637 }
638 dstPixel++;
639 srcPixel++;
640 }
641 break;
642 }
643 default:
644 SkASSERT(false);
645 break;
646 }
647 }
648
649 // Tell the frame to copy the row data if need be.
650 if (repeatCount > 1) {
651 const size_t bytesPerPixel = SkColorTypeBytesPerPixel(this->dstInfo().colorType());
652 const size_t bytesToCopy = fSwizzler->swizzleWidth() * bytesPerPixel;
653 void* copiedLine = SkTAddOffset<void>(dstLine, fSwizzler->swizzleOffsetBytes());
654 void* dst = copiedLine;
655 for (unsigned i = 1; i < repeatCount; i++) {
656 dst = SkTAddOffset<void>(dst, fDstRowBytes);
657 memcpy(dst, copiedLine, bytesToCopy);
msarett72261c02015-11-19 15:29:26 -0800658 }
659 }
660
661 return true;
662}