blob: 3c57f2d7092476ea9a7bf9eb54d565ef9797676b [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;
101 // FIXME: GIF should default to SkColorSpace::NewNamed(SkColorSpace::kSRGB_Named).
102 const auto imageInfo = SkImageInfo::Make(reader->screenWidth(), reader->screenHeight(),
103 colorType, alphaType);
104 return new SkGifCodec(encodedInfo, imageInfo, reader.release());
105}
msarett8c8f22a2015-04-01 06:58:48 -0700106
scroggob427db12015-08-12 07:24:13 -0700107bool SkGifCodec::onRewind() {
scroggo19b91532016-10-24 09:03:26 -0700108 fReader->clearDecodeState();
scroggob427db12015-08-12 07:24:13 -0700109 return true;
110}
111
scroggo19b91532016-10-24 09:03:26 -0700112SkGifCodec::SkGifCodec(const SkEncodedInfo& encodedInfo, const SkImageInfo& imageInfo,
scroggo3d3a65c2016-10-24 12:28:30 -0700113 SkGifImageReader* reader)
scroggo19b91532016-10-24 09:03:26 -0700114 : INHERITED(encodedInfo, imageInfo, nullptr)
115 , fReader(reader)
116 , fTmpBuffer(nullptr)
117 , fSwizzler(nullptr)
118 , fCurrColorTable(nullptr)
119 , fCurrColorTableIsReal(false)
120 , fFilledBackground(false)
121 , fFirstCallToIncrementalDecode(false)
122 , fDst(nullptr)
123 , fDstRowBytes(0)
124 , fRowsDecoded(0)
125{
126 reader->setClient(this);
msarett8c8f22a2015-04-01 06:58:48 -0700127}
msarett10522ff2015-09-07 08:54:01 -0700128
scroggo19b91532016-10-24 09:03:26 -0700129std::vector<SkCodec::FrameInfo> SkGifCodec::onGetFrameInfo() {
scroggof9acbe22016-10-25 12:43:21 -0700130 fReader->parse(SkGifImageReader::SkGIFFrameCountQuery);
scroggo19b91532016-10-24 09:03:26 -0700131 const size_t size = fReader->imagesCount();
132 std::vector<FrameInfo> result(size);
133 for (size_t i = 0; i < size; i++) {
scroggof9acbe22016-10-25 12:43:21 -0700134 const SkGIFFrameContext* frameContext = fReader->frameContext(i);
scroggo19b91532016-10-24 09:03:26 -0700135 result[i].fDuration = frameContext->delayTime();
136 result[i].fRequiredFrame = frameContext->getRequiredFrame();
msarett10522ff2015-09-07 08:54:01 -0700137 }
scroggo19b91532016-10-24 09:03:26 -0700138 return result;
msarett10522ff2015-09-07 08:54:01 -0700139}
140
scroggo19b91532016-10-24 09:03:26 -0700141void SkGifCodec::initializeColorTable(const SkImageInfo& dstInfo, size_t frameIndex,
142 SkPMColor* inputColorPtr, int* inputColorCount) {
143 fCurrColorTable = fReader->getColorTable(dstInfo.colorType(), frameIndex);
144 fCurrColorTableIsReal = fCurrColorTable;
145 if (!fCurrColorTable) {
Leon Scroggins IIIa049ac42016-10-27 11:16:11 -0400146 // This is possible for an empty frame. Create a dummy with one value (transparent).
147 SkPMColor color = SK_ColorTRANSPARENT;
148 fCurrColorTable.reset(new SkColorTable(&color, 1));
msarett10522ff2015-09-07 08:54:01 -0700149 }
150
scroggo19b91532016-10-24 09:03:26 -0700151 if (inputColorCount) {
152 *inputColorCount = fCurrColorTable->count();
msarett10522ff2015-09-07 08:54:01 -0700153 }
154
scroggo19b91532016-10-24 09:03:26 -0700155 copy_color_table(dstInfo, fCurrColorTable.get(), inputColorPtr, inputColorCount);
msarett10522ff2015-09-07 08:54:01 -0700156}
157
scroggo19b91532016-10-24 09:03:26 -0700158
msarett10522ff2015-09-07 08:54:01 -0700159SkCodec::Result SkGifCodec::prepareToDecode(const SkImageInfo& dstInfo, SkPMColor* inputColorPtr,
160 int* inputColorCount, const Options& opts) {
msarett10522ff2015-09-07 08:54:01 -0700161 // Check for valid input parameters
msarett2ecc35f2016-09-08 11:55:16 -0700162 if (!conversion_possible_ignore_color_space(dstInfo, this->getInfo())) {
163 return gif_error("Cannot convert input type to output type.\n", kInvalidConversion);
msarett10522ff2015-09-07 08:54:01 -0700164 }
165
scroggo19b91532016-10-24 09:03:26 -0700166 if (dstInfo.colorType() == kRGBA_F16_SkColorType) {
167 // FIXME: This should be supported.
168 return gif_error("GIF does not yet support F16.\n", kInvalidConversion);
169 }
msarett5af4e0b2015-11-17 11:18:03 -0800170
scroggo19b91532016-10-24 09:03:26 -0700171 if (opts.fSubset) {
172 return gif_error("Subsets not supported.\n", kUnimplemented);
173 }
174
175 const size_t frameIndex = opts.fFrameIndex;
scroggo53f63b62016-10-27 08:29:13 -0700176 if (frameIndex > 0) {
177 switch (dstInfo.colorType()) {
178 case kIndex_8_SkColorType:
179 // FIXME: It is possible that a later frame can be decoded to index8, if it does one
180 // of the following:
181 // - Covers the entire previous frame
182 // - Shares a color table (and transparent index) with any prior frames that are
183 // showing.
184 // We must support index8 for the first frame to be backwards compatible on Android,
185 // but we do not (currently) need to support later frames as index8.
186 return gif_error("Cannot decode multiframe gif (except frame 0) as index 8.\n",
187 kInvalidConversion);
188 case kRGB_565_SkColorType:
189 // FIXME: In theory, we might be able to support this, but it's not clear that it
190 // is necessary (Chromium does not decode to 565, and Android does not decode
191 // frames beyond the first). Disabling it because it is somewhat difficult:
192 // - If there is a transparent pixel, and this frame draws on top of another frame
193 // (if the frame is independent with a transparent pixel, we should not decode to
194 // 565 anyway, since it is not opaque), we need to skip drawing the transparent
195 // pixels (see writeTransparentPixels in haveDecodedRow). We currently do this by
196 // first swizzling into temporary memory, then copying into the destination. (We
197 // let the swizzler handle it first because it may need to sample.) After
198 // swizzling to 565, we do not know which pixels in our temporary memory
199 // correspond to the transparent pixel, so we do not know what to skip. We could
200 // special case the non-sampled case (no need to swizzle), but as this is
201 // currently unused we can just not support it.
202 return gif_error("Cannot decode multiframe gif (except frame 0) as 565.\n",
203 kInvalidConversion);
204 default:
205 break;
206 }
scroggo19b91532016-10-24 09:03:26 -0700207 }
208
scroggof9acbe22016-10-25 12:43:21 -0700209 fReader->parse((SkGifImageReader::SkGIFParseQuery) frameIndex);
scroggo19b91532016-10-24 09:03:26 -0700210
211 if (frameIndex >= fReader->imagesCount()) {
212 return gif_error("frame index out of range!\n", kIncompleteInput);
213 }
214
215 fTmpBuffer.reset(new uint8_t[dstInfo.minRowBytes()]);
216
217 // Initialize color table and copy to the client if necessary
218 this->initializeColorTable(dstInfo, frameIndex, inputColorPtr, inputColorCount);
219 this->initializeSwizzler(dstInfo, frameIndex);
msarettb30d6982016-02-15 10:18:45 -0800220 return kSuccess;
msarett10522ff2015-09-07 08:54:01 -0700221}
222
scroggo19b91532016-10-24 09:03:26 -0700223void SkGifCodec::initializeSwizzler(const SkImageInfo& dstInfo, size_t frameIndex) {
scroggof9acbe22016-10-25 12:43:21 -0700224 const SkGIFFrameContext* frame = fReader->frameContext(frameIndex);
scroggo19b91532016-10-24 09:03:26 -0700225 // This is only called by prepareToDecode, which ensures frameIndex is in range.
226 SkASSERT(frame);
msarett10522ff2015-09-07 08:54:01 -0700227
scroggo19b91532016-10-24 09:03:26 -0700228 const int xBegin = frame->xOffset();
229 const int xEnd = std::min(static_cast<int>(frame->xOffset() + frame->width()),
230 static_cast<int>(fReader->screenWidth()));
231
232 // CreateSwizzler only reads left and right of the frame. We cannot use the frame's raw
233 // frameRect, since it might extend beyond the edge of the frame.
234 SkIRect swizzleRect = SkIRect::MakeLTRB(xBegin, 0, xEnd, 0);
235
236 // The default Options should be fine:
237 // - we'll ignore if the memory is zero initialized - unless we're the first frame, this won't
238 // matter anyway.
239 // - subsets are not supported for gif
240 // - the swizzler does not need to know about the frame.
241 // We may not be able to use the real Options anyway, since getPixels does not store it (due to
242 // a bug).
243 fSwizzler.reset(SkSwizzler::CreateSwizzler(this->getEncodedInfo(),
244 fCurrColorTable->readColors(), dstInfo, Options(), &swizzleRect));
245 SkASSERT(fSwizzler.get());
msarett10522ff2015-09-07 08:54:01 -0700246}
247
248/*
249 * Initiates the gif decode
250 */
251SkCodec::Result SkGifCodec::onGetPixels(const SkImageInfo& dstInfo,
scroggo19b91532016-10-24 09:03:26 -0700252 void* pixels, size_t dstRowBytes,
msarett10522ff2015-09-07 08:54:01 -0700253 const Options& opts,
254 SkPMColor* inputColorPtr,
msarette6dd0042015-10-09 11:07:34 -0700255 int* inputColorCount,
256 int* rowsDecoded) {
msarett10522ff2015-09-07 08:54:01 -0700257 Result result = this->prepareToDecode(dstInfo, inputColorPtr, inputColorCount, opts);
258 if (kSuccess != result) {
259 return result;
260 }
261
262 if (dstInfo.dimensions() != this->getInfo().dimensions()) {
263 return gif_error("Scaling not supported.\n", kInvalidScale);
264 }
265
scroggo19b91532016-10-24 09:03:26 -0700266 fDst = pixels;
267 fDstRowBytes = dstRowBytes;
268
269 return this->decodeFrame(true, opts, rowsDecoded);
270}
271
272SkCodec::Result SkGifCodec::onStartIncrementalDecode(const SkImageInfo& dstInfo,
273 void* pixels, size_t dstRowBytes,
274 const SkCodec::Options& opts,
275 SkPMColor* inputColorPtr,
276 int* inputColorCount) {
277 Result result = this->prepareToDecode(dstInfo, inputColorPtr, inputColorCount, opts);
278 if (result != kSuccess) {
279 return result;
msarett10522ff2015-09-07 08:54:01 -0700280 }
281
scroggo19b91532016-10-24 09:03:26 -0700282 fDst = pixels;
283 fDstRowBytes = dstRowBytes;
284
285 fFirstCallToIncrementalDecode = true;
286
msarett10522ff2015-09-07 08:54:01 -0700287 return kSuccess;
288}
289
scroggo19b91532016-10-24 09:03:26 -0700290SkCodec::Result SkGifCodec::onIncrementalDecode(int* rowsDecoded) {
291 // It is possible the client has appended more data. Parse, if needed.
292 const auto& options = this->options();
293 const size_t frameIndex = options.fFrameIndex;
scroggof9acbe22016-10-25 12:43:21 -0700294 fReader->parse((SkGifImageReader::SkGIFParseQuery) frameIndex);
scroggo19b91532016-10-24 09:03:26 -0700295
296 const bool firstCallToIncrementalDecode = fFirstCallToIncrementalDecode;
297 fFirstCallToIncrementalDecode = false;
298 return this->decodeFrame(firstCallToIncrementalDecode, options, rowsDecoded);
msarette6dd0042015-10-09 11:07:34 -0700299}
300
scroggo19b91532016-10-24 09:03:26 -0700301SkCodec::Result SkGifCodec::decodeFrame(bool firstAttempt, const Options& opts, int* rowsDecoded) {
302 const SkImageInfo& dstInfo = this->dstInfo();
303 const size_t frameIndex = opts.fFrameIndex;
304 SkASSERT(frameIndex < fReader->imagesCount());
scroggof9acbe22016-10-25 12:43:21 -0700305 const SkGIFFrameContext* frameContext = fReader->frameContext(frameIndex);
scroggo19b91532016-10-24 09:03:26 -0700306 if (firstAttempt) {
307 // rowsDecoded reports how many rows have been initialized, so a layer above
308 // can fill the rest. In some cases, we fill the background before decoding
309 // (or it is already filled for us), so we report rowsDecoded to be the full
310 // height.
311 bool filledBackground = false;
312 if (frameContext->getRequiredFrame() == kNone) {
313 // We may need to clear to transparent for one of the following reasons:
314 // - The frameRect does not cover the full bounds. haveDecodedRow will
315 // only draw inside the frameRect, so we need to clear the rest.
scroggo19b91532016-10-24 09:03:26 -0700316 // - The frame is interlaced. There is no obvious way to fill
317 // afterwards for an incomplete image. (FIXME: Does the first pass
318 // cover all rows? If so, we do not have to fill here.)
scroggo8bce1172016-10-25 13:08:40 -0700319 // - There is no color table for this frame. In that case will not
320 // draw anything, so we need to fill.
scroggo19b91532016-10-24 09:03:26 -0700321 if (frameContext->frameRect() != this->getInfo().bounds()
scroggo8bce1172016-10-25 13:08:40 -0700322 || frameContext->interlaced() || !fCurrColorTableIsReal) {
scroggo19b91532016-10-24 09:03:26 -0700323 // fill ignores the width (replaces it with the actual, scaled width).
324 // But we need to scale in Y.
325 const int scaledHeight = get_scaled_dimension(dstInfo.height(),
326 fSwizzler->sampleY());
327 auto fillInfo = dstInfo.makeWH(0, scaledHeight);
328 fSwizzler->fill(fillInfo, fDst, fDstRowBytes, this->getFillValue(dstInfo),
329 opts.fZeroInitialized);
330 filledBackground = true;
331 }
332 } else {
333 // Not independent
334 if (!opts.fHasPriorFrame) {
335 // Decode that frame into pixels.
336 Options prevFrameOpts(opts);
337 prevFrameOpts.fFrameIndex = frameContext->getRequiredFrame();
338 prevFrameOpts.fHasPriorFrame = false;
339 const Result prevResult = this->decodeFrame(true, prevFrameOpts, nullptr);
340 switch (prevResult) {
341 case kSuccess:
342 // Prior frame succeeded. Carry on.
343 break;
344 case kIncompleteInput:
345 // Prior frame was incomplete. So this frame cannot be decoded.
346 return kInvalidInput;
347 default:
348 return prevResult;
349 }
350 }
351 const auto* prevFrame = fReader->frameContext(frameContext->getRequiredFrame());
352 if (prevFrame->getDisposalMethod() == SkCodecAnimation::RestoreBGColor_DisposalMethod) {
353 const SkIRect prevRect = prevFrame->frameRect();
354 auto left = get_scaled_dimension(prevRect.fLeft, fSwizzler->sampleX());
355 auto top = get_scaled_dimension(prevRect.fTop, fSwizzler->sampleY());
356 void* const eraseDst = SkTAddOffset<void>(fDst, top * fDstRowBytes
357 + left * SkColorTypeBytesPerPixel(dstInfo.colorType()));
358 auto width = get_scaled_dimension(prevRect.width(), fSwizzler->sampleX());
359 auto height = get_scaled_dimension(prevRect.height(), fSwizzler->sampleY());
360 // fSwizzler->fill() would fill to the scaled width of the frame, but we want to
361 // fill to the scaled with of the width of the PRIOR frame, so we do all the scaling
362 // ourselves and call the static version.
363 SkSampler::Fill(dstInfo.makeWH(width, height), eraseDst,
364 fDstRowBytes, this->getFillValue(dstInfo), kNo_ZeroInitialized);
365 }
366 filledBackground = true;
msarett10522ff2015-09-07 08:54:01 -0700367 }
scroggo19b91532016-10-24 09:03:26 -0700368
369 fFilledBackground = filledBackground;
370 if (filledBackground) {
371 // Report the full (scaled) height, since the client will never need to fill.
372 fRowsDecoded = get_scaled_dimension(dstInfo.height(), fSwizzler->sampleY());
373 } else {
374 // This will be updated by haveDecodedRow.
375 fRowsDecoded = 0;
376 }
msarett10522ff2015-09-07 08:54:01 -0700377 }
msarette6dd0042015-10-09 11:07:34 -0700378
scroggo3d3a65c2016-10-24 12:28:30 -0700379 // Note: there is a difference between the following call to SkGifImageReader::decode
scroggo19b91532016-10-24 09:03:26 -0700380 // returning false and leaving frameDecoded false:
381 // - If the method returns false, there was an error in the stream. We still treat this as
382 // incomplete, since we have already decoded some rows.
383 // - If frameDecoded is false, that just means that we do not have enough data. If more data
384 // is supplied, we may be able to continue decoding this frame. We also treat this as
385 // incomplete.
386 // FIXME: Ensure that we do not attempt to continue decoding if the method returns false and
387 // more data is supplied.
388 bool frameDecoded = false;
389 if (!fReader->decode(frameIndex, &frameDecoded) || !frameDecoded) {
390 if (rowsDecoded) {
391 *rowsDecoded = fRowsDecoded;
392 }
393 return kIncompleteInput;
394 }
395
396 return kSuccess;
msarett10522ff2015-09-07 08:54:01 -0700397}
scroggo46c57472015-09-30 08:57:13 -0700398
scroggo19b91532016-10-24 09:03:26 -0700399uint64_t SkGifCodec::onGetFillValue(const SkImageInfo& dstInfo) const {
400 // Note: Using fCurrColorTable relies on having called initializeColorTable already.
401 // This is (currently) safe because this method is only called when filling, after
402 // initializeColorTable has been called.
403 // FIXME: Is there a way to make this less fragile?
404 if (dstInfo.colorType() == kIndex_8_SkColorType && fCurrColorTableIsReal) {
405 // We only support index 8 for the first frame, for backwards
406 // compatibity on Android, so we are using the color table for the first frame.
407 SkASSERT(this->options().fFrameIndex == 0);
408 // Use the transparent index for the first frame.
409 const size_t transPixel = fReader->frameContext(0)->transparentPixel();
410 if (transPixel < (size_t) fCurrColorTable->count()) {
411 return transPixel;
412 }
413 // Fall through to return SK_ColorTRANSPARENT (i.e. 0). This choice is arbitrary,
414 // but we have to pick something inside the color table, and this one is as good
415 // as any.
416 }
417 // Using transparent as the fill value matches the behavior in Chromium,
418 // which ignores the background color.
419 // If the colorType is kIndex_8, and there was no color table (i.e.
420 // fCurrColorTableIsReal is false), this value (zero) corresponds to the
421 // only entry in the dummy color table provided to the client.
422 return SK_ColorTRANSPARENT;
423}
msarett72261c02015-11-19 15:29:26 -0800424
scroggo19b91532016-10-24 09:03:26 -0700425bool SkGifCodec::haveDecodedRow(size_t frameIndex, const unsigned char* rowBegin,
426 size_t rowNumber, unsigned repeatCount, bool writeTransparentPixels)
427{
scroggof9acbe22016-10-25 12:43:21 -0700428 const SkGIFFrameContext* frameContext = fReader->frameContext(frameIndex);
scroggo19b91532016-10-24 09:03:26 -0700429 // The pixel data and coordinates supplied to us are relative to the frame's
430 // origin within the entire image size, i.e.
431 // (frameContext->xOffset, frameContext->yOffset). There is no guarantee
432 // that width == (size().width() - frameContext->xOffset), so
433 // we must ensure we don't run off the end of either the source data or the
434 // row's X-coordinates.
435 const size_t width = frameContext->width();
436 const int xBegin = frameContext->xOffset();
437 const int yBegin = frameContext->yOffset() + rowNumber;
438 const int xEnd = std::min(static_cast<int>(frameContext->xOffset() + width),
439 this->getInfo().width());
440 const int yEnd = std::min(static_cast<int>(frameContext->yOffset() + rowNumber + repeatCount),
441 this->getInfo().height());
442 // FIXME: No need to make the checks on width/xBegin/xEnd for every row. We could instead do
443 // this once in prepareToDecode.
444 if (!width || (xBegin < 0) || (yBegin < 0) || (xEnd <= xBegin) || (yEnd <= yBegin))
445 return true;
446
447 // yBegin is the first row in the non-sampled image. dstRow will be the row in the output,
448 // after potentially scaling it.
449 int dstRow = yBegin;
450
451 const int sampleY = fSwizzler->sampleY();
452 if (sampleY > 1) {
453 // Check to see whether this row or one that falls in the repeatCount is needed in the
454 // output.
455 bool foundNecessaryRow = false;
456 for (unsigned i = 0; i < repeatCount; i++) {
457 const int potentialRow = yBegin + i;
458 if (fSwizzler->rowNeeded(potentialRow)) {
459 dstRow = potentialRow / sampleY;
460 const int scaledHeight = get_scaled_dimension(this->dstInfo().height(), sampleY);
461 if (dstRow >= scaledHeight) {
462 return true;
463 }
464
465 foundNecessaryRow = true;
466 repeatCount -= i;
467
468 repeatCount = (repeatCount - 1) / sampleY + 1;
469
470 // Make sure the repeatCount does not take us beyond the end of the dst
471 if (dstRow + (int) repeatCount > scaledHeight) {
472 repeatCount = scaledHeight - dstRow;
473 SkASSERT(repeatCount >= 1);
474 }
475 break;
476 }
477 }
478
479 if (!foundNecessaryRow) {
480 return true;
481 }
Matt Sarett8a4e9c52016-10-25 14:24:50 -0400482 } else {
483 // Make sure the repeatCount does not take us beyond the end of the dst
484 SkASSERT(this->dstInfo().height() >= yBegin);
485 repeatCount = SkTMin(repeatCount, (unsigned) (this->dstInfo().height() - yBegin));
scroggo19b91532016-10-24 09:03:26 -0700486 }
487
488 if (!fFilledBackground) {
489 // At this point, we are definitely going to write the row, so count it towards the number
490 // of rows decoded.
491 // We do not consider the repeatCount, which only happens for interlaced, in which case we
492 // have already set fRowsDecoded to the proper value (reflecting that we have filled the
493 // background).
494 fRowsDecoded++;
495 }
496
497 if (!fCurrColorTableIsReal) {
498 // No color table, so nothing to draw this frame.
499 // FIXME: We can abort even earlier - no need to decode this frame.
500 return true;
501 }
502
503 // The swizzler takes care of offsetting into the dst width-wise.
504 void* dstLine = SkTAddOffset<void>(fDst, dstRow * fDstRowBytes);
505
506 // We may or may not need to write transparent pixels to the buffer.
scroggo1285f412016-10-26 13:48:03 -0700507 // If we're compositing against a previous image, it's wrong, but if
508 // we're decoding an interlaced gif and displaying it "Haeberli"-style,
509 // we must write these for passes beyond the first, or the initial passes
510 // will "show through" the later ones.
scroggo19b91532016-10-24 09:03:26 -0700511 const auto dstInfo = this->dstInfo();
scroggo53f63b62016-10-27 08:29:13 -0700512 if (writeTransparentPixels) {
scroggo19b91532016-10-24 09:03:26 -0700513 fSwizzler->swizzle(dstLine, rowBegin);
514 } else {
515 // We cannot swizzle directly into the dst, since that will write the transparent pixels.
516 // Instead, swizzle into a temporary buffer, and copy that into the dst.
517 {
518 void* const memsetDst = fTmpBuffer.get();
519 // Although onGetFillValue returns a uint64_t, we only use the low eight bits. The
520 // return value is either an 8 bit index (for index8) or SK_ColorTRANSPARENT, which is
521 // all zeroes.
522 const int fillValue = (uint8_t) this->onGetFillValue(dstInfo);
523 const size_t rb = dstInfo.minRowBytes();
524 if (fillValue == 0) {
525 // FIXME: This special case should be unnecessary, and in fact sk_bzero just calls
526 // memset. But without it, the compiler thinks this is trying to pass a zero length
527 // to memset, causing an error.
528 sk_bzero(memsetDst, rb);
529 } else {
530 memset(memsetDst, fillValue, rb);
531 }
532 }
533 fSwizzler->swizzle(fTmpBuffer.get(), rowBegin);
534
535 const size_t offsetBytes = fSwizzler->swizzleOffsetBytes();
536 switch (dstInfo.colorType()) {
537 case kBGRA_8888_SkColorType:
538 case kRGBA_8888_SkColorType: {
539 uint32_t* dstPixel = SkTAddOffset<uint32_t>(dstLine, offsetBytes);
540 uint32_t* srcPixel = SkTAddOffset<uint32_t>(fTmpBuffer.get(), offsetBytes);
541 for (int i = 0; i < fSwizzler->swizzleWidth(); i++) {
542 // Technically SK_ColorTRANSPARENT is an SkPMColor, and srcPixel would have
543 // the opposite swizzle for the non-native swizzle, but TRANSPARENT is all
544 // zeroes, which is the same either way.
545 if (*srcPixel != SK_ColorTRANSPARENT) {
546 *dstPixel = *srcPixel;
547 }
548 dstPixel++;
549 srcPixel++;
550 }
551 break;
552 }
553 case kIndex_8_SkColorType: {
554 uint8_t* dstPixel = SkTAddOffset<uint8_t>(dstLine, offsetBytes);
555 uint8_t* srcPixel = SkTAddOffset<uint8_t>(fTmpBuffer.get(), offsetBytes);
556 for (int i = 0; i < fSwizzler->swizzleWidth(); i++) {
557 if (*srcPixel != frameContext->transparentPixel()) {
558 *dstPixel = *srcPixel;
559 }
560 dstPixel++;
561 srcPixel++;
562 }
563 break;
564 }
565 default:
566 SkASSERT(false);
567 break;
568 }
569 }
570
571 // Tell the frame to copy the row data if need be.
572 if (repeatCount > 1) {
573 const size_t bytesPerPixel = SkColorTypeBytesPerPixel(this->dstInfo().colorType());
574 const size_t bytesToCopy = fSwizzler->swizzleWidth() * bytesPerPixel;
575 void* copiedLine = SkTAddOffset<void>(dstLine, fSwizzler->swizzleOffsetBytes());
576 void* dst = copiedLine;
577 for (unsigned i = 1; i < repeatCount; i++) {
578 dst = SkTAddOffset<void>(dst, fDstRowBytes);
579 memcpy(dst, copiedLine, bytesToCopy);
msarett72261c02015-11-19 15:29:26 -0800580 }
581 }
582
583 return true;
584}