1// Copyright 2015 Google Inc.
2// Use of this source code is governed by the BSD-3-Clause license that can be
3// found in the LICENSE.md file.
4
5/*
6 * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
21 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
25 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
30#include "SkGifCodec.h"
31#include "SkLibGifCodec.h"
32
33#include "include/codec/SkCodecAnimation.h"
34#include "include/core/SkStream.h"
35#include "include/private/SkColorData.h"
36#include "src/codec/SkCodecPriv.h"
37#include "src/codec/SkColorTable.h"
38#include "src/codec/SkSwizzler.h"
39
40#include <algorithm>
41
42#define GIF87_STAMP "GIF87a"
43#define GIF89_STAMP "GIF89a"
44#define GIF_STAMP_LEN 6
45
46/*
47 * Checks the start of the stream to see if the image is a gif
48 */
49bool SkGifCodec::IsGif(const void* buf, size_t bytesRead) {
50 if (bytesRead >= GIF_STAMP_LEN) {
51 if (memcmp(GIF87_STAMP, buf, GIF_STAMP_LEN) == 0 ||
52 memcmp(GIF89_STAMP, buf, GIF_STAMP_LEN) == 0)
53 {
54 return true;
55 }
56 }
57 return false;
58}
59
60/*
61 * Error function
62 */
63static SkCodec::Result gif_error(const char* msg, SkCodec::Result result = SkCodec::kInvalidInput) {
64 SkCodecPrintf("Gif Error: %s\n", msg);
65 return result;
66}
67
68std::unique_ptr<SkCodec> SkGifCodec::MakeFromStream(std::unique_ptr<SkStream> stream,
69 SkCodec::Result* result) {
70 std::unique_ptr<SkGifImageReader> reader(new SkGifImageReader(std::move(stream)));
71 *result = reader->parse(SkGifImageReader::SkGIFSizeQuery);
72 if (*result != SkCodec::kSuccess) {
73 return nullptr;
74 }
75
76 // If no images are in the data, or the first header is not yet defined, we cannot
77 // create a codec. In either case, the width and height are not yet known.
78 auto* frame = reader->frameContext(0);
79 if (!frame || !frame->isHeaderDefined()) {
80 *result = SkCodec::kInvalidInput;
81 return nullptr;
82 }
83
84 // isHeaderDefined() will not return true if the screen size is empty.
85 SkASSERT(reader->screenHeight() > 0 && reader->screenWidth() > 0);
86
87 const auto alpha = reader->firstFrameHasAlpha() ? SkEncodedInfo::kBinary_Alpha
88 : SkEncodedInfo::kOpaque_Alpha;
89 // Use kPalette since Gifs are encoded with a color table.
90 // FIXME: Gifs can actually be encoded with 4-bits per pixel. Using 8 works, but we could skip
91 // expanding to 8 bits and take advantage of the SkSwizzler to work from 4.
92 auto encodedInfo = SkEncodedInfo::Make(reader->screenWidth(), reader->screenHeight(),
93 SkEncodedInfo::kPalette_Color, alpha, 8);
94 return std::unique_ptr<SkCodec>(new SkLibGifCodec(std::move(encodedInfo), reader.release()));
95}
96
97bool SkLibGifCodec::onRewind() {
98 fReader->clearDecodeState();
99 return true;
100}
101
102SkLibGifCodec::SkLibGifCodec(SkEncodedInfo&& encodedInfo, SkGifImageReader* reader)
103 : INHERITED(std::move(encodedInfo), skcms_PixelFormat_RGBA_8888, nullptr)
104 , fReader(reader)
105 , fTmpBuffer(nullptr)
106 , fSwizzler(nullptr)
107 , fCurrColorTable(nullptr)
108 , fCurrColorTableIsReal(false)
109 , fFilledBackground(false)
110 , fFirstCallToIncrementalDecode(false)
111 , fDst(nullptr)
112 , fDstRowBytes(0)
113 , fRowsDecoded(0)
114{
115 reader->setClient(this);
116}
117
118int SkLibGifCodec::onGetFrameCount() {
119 fReader->parse(SkGifImageReader::SkGIFFrameCountQuery);
120 return fReader->imagesCount();
121}
122
123bool SkLibGifCodec::onGetFrameInfo(int i, SkCodec::FrameInfo* frameInfo) const {
124 if (i >= fReader->imagesCount()) {
125 return false;
126 }
127
128 const SkGIFFrameContext* frameContext = fReader->frameContext(i);
129 SkASSERT(frameContext->reachedStartOfData());
130
131 if (frameInfo) {
132 frameInfo->fDuration = frameContext->getDuration();
133 frameInfo->fRequiredFrame = frameContext->getRequiredFrame();
134 frameInfo->fFullyReceived = frameContext->isComplete();
135 frameInfo->fAlphaType = frameContext->hasAlpha() ? kUnpremul_SkAlphaType
136 : kOpaque_SkAlphaType;
137 frameInfo->fDisposalMethod = frameContext->getDisposalMethod();
138 }
139 return true;
140}
141
142int SkLibGifCodec::onGetRepetitionCount() {
143 fReader->parse(SkGifImageReader::SkGIFLoopCountQuery);
144 return fReader->loopCount();
145}
146
147static constexpr SkColorType kXformSrcColorType = kRGBA_8888_SkColorType;
148
149void SkLibGifCodec::initializeColorTable(const SkImageInfo& dstInfo, int frameIndex) {
150 SkColorType colorTableColorType = dstInfo.colorType();
151 if (this->colorXform()) {
152 colorTableColorType = kXformSrcColorType;
153 }
154
155 sk_sp<SkColorTable> currColorTable = fReader->getColorTable(colorTableColorType, frameIndex);
156 fCurrColorTableIsReal = static_cast<bool>(currColorTable);
157 if (!fCurrColorTableIsReal) {
158 // 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));
161 } else if (this->colorXform() && !this->xformOnDecode()) {
162 SkPMColor dstColors[256];
163 this->applyColorXform(dstColors, currColorTable->readColors(),
164 currColorTable->count());
165 fCurrColorTable.reset(new SkColorTable(dstColors, currColorTable->count()));
166 } else {
167 fCurrColorTable = std::move(currColorTable);
168 }
169}
170
171
172SkCodec::Result SkLibGifCodec::prepareToDecode(const SkImageInfo& dstInfo, const Options& opts) {
173 if (opts.fSubset) {
174 return gif_error("Subsets not supported.\n", kUnimplemented);
175 }
176
177 const int frameIndex = opts.fFrameIndex;
178 if (frameIndex > 0 && kRGB_565_SkColorType == dstInfo.colorType()) {
179 // FIXME: In theory, we might be able to support this, but it's not clear that it
180 // is necessary (Chromium does not decode to 565, and Android does not decode
181 // frames beyond the first). Disabling it because it is somewhat difficult:
182 // - If there is a transparent pixel, and this frame draws on top of another frame
183 // (if the frame is independent with a transparent pixel, we should not decode to
184 // 565 anyway, since it is not opaque), we need to skip drawing the transparent
185 // pixels (see writeTransparentPixels in haveDecodedRow). We currently do this by
186 // first swizzling into temporary memory, then copying into the destination. (We
187 // let the swizzler handle it first because it may need to sample.) After
188 // swizzling to 565, we do not know which pixels in our temporary memory
189 // correspond to the transparent pixel, so we do not know what to skip. We could
190 // special case the non-sampled case (no need to swizzle), but as this is
191 // currently unused we can just not support it.
192 return gif_error("Cannot decode multiframe gif (except frame 0) as 565.\n",
193 kInvalidConversion);
194 }
195
196 const auto* frame = fReader->frameContext(frameIndex);
197 SkASSERT(frame);
198 if (0 == frameIndex) {
199 // SkCodec does not have a way to just parse through frame 0, so we
200 // have to do so manually, here.
201 fReader->parse((SkGifImageReader::SkGIFParseQuery) 0);
202 if (!frame->reachedStartOfData()) {
203 // We have parsed enough to know that there is a color map, but cannot
204 // parse the map itself yet. Exit now, so we do not build an incorrect
205 // table.
206 return gif_error("color map not available yet\n", kIncompleteInput);
207 }
208 } else {
209 // Parsing happened in SkCodec::getPixels.
210 SkASSERT(frameIndex < fReader->imagesCount());
211 SkASSERT(frame->reachedStartOfData());
212 }
213
214 if (this->xformOnDecode()) {
215 fXformBuffer.reset(new uint32_t[dstInfo.width()]);
216 sk_bzero(fXformBuffer.get(), dstInfo.width() * sizeof(uint32_t));
217 }
218
219 fTmpBuffer.reset(new uint8_t[dstInfo.minRowBytes()]);
220
221 this->initializeColorTable(dstInfo, frameIndex);
222 this->initializeSwizzler(dstInfo, frameIndex);
223
224 SkASSERT(fCurrColorTable);
225 return kSuccess;
226}
227
228void SkLibGifCodec::initializeSwizzler(const SkImageInfo& dstInfo, int frameIndex) {
229 const SkGIFFrameContext* frame = fReader->frameContext(frameIndex);
230 // This is only called by prepareToDecode, which ensures frameIndex is in range.
231 SkASSERT(frame);
232
233 const int xBegin = frame->xOffset();
234 const int xEnd = std::min(frame->frameRect().right(), fReader->screenWidth());
235
236 // CreateSwizzler only reads left and right of the frame. We cannot use the frame's raw
237 // frameRect, since it might extend beyond the edge of the frame.
238 SkIRect swizzleRect = SkIRect::MakeLTRB(xBegin, 0, xEnd, 0);
239
240 SkImageInfo swizzlerInfo = dstInfo;
241 if (this->colorXform()) {
242 swizzlerInfo = swizzlerInfo.makeColorType(kXformSrcColorType);
243 if (kPremul_SkAlphaType == dstInfo.alphaType()) {
244 swizzlerInfo = swizzlerInfo.makeAlphaType(kUnpremul_SkAlphaType);
245 }
246 }
247
248 // The default Options should be fine:
249 // - we'll ignore if the memory is zero initialized - unless we're the first frame, this won't
250 // matter anyway.
251 // - subsets are not supported for gif
252 // - the swizzler does not need to know about the frame.
253 // We may not be able to use the real Options anyway, since getPixels does not store it (due to
254 // a bug).
255 fSwizzler = SkSwizzler::Make(this->getEncodedInfo(), fCurrColorTable->readColors(),
256 swizzlerInfo, Options(), &swizzleRect);
257 SkASSERT(fSwizzler.get());
258}
259
260/*
261 * Initiates the gif decode
262 */
263SkCodec::Result SkLibGifCodec::onGetPixels(const SkImageInfo& dstInfo,
264 void* pixels, size_t dstRowBytes,
265 const Options& opts,
266 int* rowsDecoded) {
267 Result result = this->prepareToDecode(dstInfo, opts);
268 switch (result) {
269 case kSuccess:
270 break;
271 case kIncompleteInput:
272 // onStartIncrementalDecode treats this as incomplete, since it may
273 // provide more data later, but in this case, no more data will be
274 // provided, and there is nothing to draw. We also cannot return
275 // kIncompleteInput, which will make SkCodec attempt to fill
276 // remaining rows, but that requires an SkSwizzler, which we have
277 // not created.
278 return kInvalidInput;
279 default:
280 return result;
281 }
282
283 if (dstInfo.dimensions() != this->dimensions()) {
284 return gif_error("Scaling not supported.\n", kInvalidScale);
285 }
286
287 fDst = pixels;
288 fDstRowBytes = dstRowBytes;
289
290 return this->decodeFrame(true, opts, rowsDecoded);
291}
292
293SkCodec::Result SkLibGifCodec::onStartIncrementalDecode(const SkImageInfo& dstInfo,
294 void* pixels, size_t dstRowBytes,
295 const SkCodec::Options& opts) {
296 Result result = this->prepareToDecode(dstInfo, opts);
297 if (result != kSuccess) {
298 return result;
299 }
300
301 fDst = pixels;
302 fDstRowBytes = dstRowBytes;
303
304 fFirstCallToIncrementalDecode = true;
305
306 return kSuccess;
307}
308
309SkCodec::Result SkLibGifCodec::onIncrementalDecode(int* rowsDecoded) {
310 // It is possible the client has appended more data. Parse, if needed.
311 const auto& options = this->options();
312 const int frameIndex = options.fFrameIndex;
313 fReader->parse((SkGifImageReader::SkGIFParseQuery) frameIndex);
314
315 const bool firstCallToIncrementalDecode = fFirstCallToIncrementalDecode;
316 fFirstCallToIncrementalDecode = false;
317 return this->decodeFrame(firstCallToIncrementalDecode, options, rowsDecoded);
318}
319
320SkCodec::Result SkLibGifCodec::decodeFrame(bool firstAttempt, const Options& opts, int* rowsDecoded) {
321 const SkImageInfo& dstInfo = this->dstInfo();
322 const int scaledHeight = get_scaled_dimension(dstInfo.height(), fSwizzler->sampleY());
323
324 const int frameIndex = opts.fFrameIndex;
325 SkASSERT(frameIndex < fReader->imagesCount());
326 const SkGIFFrameContext* frameContext = fReader->frameContext(frameIndex);
327 if (firstAttempt) {
328 // rowsDecoded reports how many rows have been initialized, so a layer above
329 // can fill the rest. In some cases, we fill the background before decoding
330 // (or it is already filled for us), so we report rowsDecoded to be the full
331 // height.
332 bool filledBackground = false;
333 if (frameContext->getRequiredFrame() == kNoFrame) {
334 // We may need to clear to transparent for one of the following reasons:
335 // - The frameRect does not cover the full bounds. haveDecodedRow will
336 // only draw inside the frameRect, so we need to clear the rest.
337 // - The frame is interlaced. There is no obvious way to fill
338 // afterwards for an incomplete image. (FIXME: Does the first pass
339 // cover all rows? If so, we do not have to fill here.)
340 // - There is no color table for this frame. In that case will not
341 // draw anything, so we need to fill.
342 if (frameContext->frameRect() != this->bounds()
343 || frameContext->interlaced() || !fCurrColorTableIsReal) {
344 auto fillInfo = dstInfo.makeWH(fSwizzler->fillWidth(), scaledHeight);
345 SkSampler::Fill(fillInfo, fDst, fDstRowBytes, opts.fZeroInitialized);
346 filledBackground = true;
347 }
348 } else {
349 // Not independent.
350 // SkCodec ensured that the prior frame has been decoded.
351 filledBackground = true;
352 }
353
354 fFilledBackground = filledBackground;
355 if (filledBackground) {
356 // Report the full (scaled) height, since the client will never need to fill.
357 fRowsDecoded = scaledHeight;
358 } else {
359 // This will be updated by haveDecodedRow.
360 fRowsDecoded = 0;
361 }
362 }
363
364 if (!fCurrColorTableIsReal) {
365 // Nothing to draw this frame.
366 return kSuccess;
367 }
368
369 bool frameDecoded = false;
370 const bool fatalError = !fReader->decode(frameIndex, &frameDecoded);
371 if (fatalError || !frameDecoded || fRowsDecoded != scaledHeight) {
372 if (rowsDecoded) {
373 *rowsDecoded = fRowsDecoded;
374 }
375 if (fatalError) {
376 return kErrorInInput;
377 }
378 return kIncompleteInput;
379 }
380
381 return kSuccess;
382}
383
384void SkLibGifCodec::applyXformRow(const SkImageInfo& dstInfo, void* dst, const uint8_t* src) const {
385 if (this->xformOnDecode()) {
386 SkASSERT(this->colorXform());
387 fSwizzler->swizzle(fXformBuffer.get(), src);
388
389 const int xformWidth = get_scaled_dimension(dstInfo.width(), fSwizzler->sampleX());
390 this->applyColorXform(dst, fXformBuffer.get(), xformWidth);
391 } else {
392 fSwizzler->swizzle(dst, src);
393 }
394}
395
396template <typename T>
397static void blend_line(void* dstAsVoid, const void* srcAsVoid, int width) {
398 T* dst = reinterpret_cast<T*>(dstAsVoid);
399 const T* src = reinterpret_cast<const T*>(srcAsVoid);
400 while (width --> 0) {
401 if (*src != 0) { // GIF pixels are either transparent (== 0) or opaque (!= 0).
402 *dst = *src;
403 }
404 src++;
405 dst++;
406 }
407}
408
409void SkLibGifCodec::haveDecodedRow(int frameIndex, const unsigned char* rowBegin,
410 int rowNumber, int repeatCount, bool writeTransparentPixels)
411{
412 const SkGIFFrameContext* frameContext = fReader->frameContext(frameIndex);
413 // The pixel data and coordinates supplied to us are relative to the frame's
414 // origin within the entire image size, i.e.
415 // (frameContext->xOffset, frameContext->yOffset). There is no guarantee
416 // that width == (size().width() - frameContext->xOffset), so
417 // we must ensure we don't run off the end of either the source data or the
418 // row's X-coordinates.
419 const int width = frameContext->width();
420 const int xBegin = frameContext->xOffset();
421 const int yBegin = frameContext->yOffset() + rowNumber;
422 const int xEnd = std::min(xBegin + width, this->dimensions().width());
423 const int yEnd = std::min(yBegin + rowNumber + repeatCount, this->dimensions().height());
424 // FIXME: No need to make the checks on width/xBegin/xEnd for every row. We could instead do
425 // this once in prepareToDecode.
426 if (!width || (xBegin < 0) || (yBegin < 0) || (xEnd <= xBegin) || (yEnd <= yBegin))
427 return;
428
429 // yBegin is the first row in the non-sampled image. dstRow will be the row in the output,
430 // after potentially scaling it.
431 int dstRow = yBegin;
432
433 const int sampleY = fSwizzler->sampleY();
434 if (sampleY > 1) {
435 // Check to see whether this row or one that falls in the repeatCount is needed in the
436 // output.
437 bool foundNecessaryRow = false;
438 for (int i = 0; i < repeatCount; i++) {
439 const int potentialRow = yBegin + i;
440 if (fSwizzler->rowNeeded(potentialRow)) {
441 dstRow = potentialRow / sampleY;
442 const int scaledHeight = get_scaled_dimension(this->dstInfo().height(), sampleY);
443 if (dstRow >= scaledHeight) {
444 return;
445 }
446
447 foundNecessaryRow = true;
448 repeatCount -= i;
449
450 repeatCount = (repeatCount - 1) / sampleY + 1;
451
452 // Make sure the repeatCount does not take us beyond the end of the dst
453 if (dstRow + repeatCount > scaledHeight) {
454 repeatCount = scaledHeight - dstRow;
455 SkASSERT(repeatCount >= 1);
456 }
457 break;
458 }
459 }
460
461 if (!foundNecessaryRow) {
462 return;
463 }
464 } else {
465 // Make sure the repeatCount does not take us beyond the end of the dst
466 SkASSERT(this->dstInfo().height() >= yBegin);
467 repeatCount = std::min(repeatCount, this->dstInfo().height() - yBegin);
468 }
469
470 if (!fFilledBackground) {
471 // At this point, we are definitely going to write the row, so count it towards the number
472 // of rows decoded.
473 // We do not consider the repeatCount, which only happens for interlaced, in which case we
474 // have already set fRowsDecoded to the proper value (reflecting that we have filled the
475 // background).
476 fRowsDecoded++;
477 }
478
479 // decodeFrame will early exit if this is false, so this method will not be
480 // called.
481 SkASSERT(fCurrColorTableIsReal);
482
483 // The swizzler takes care of offsetting into the dst width-wise.
484 void* dstLine = SkTAddOffset<void>(fDst, dstRow * fDstRowBytes);
485
486 // We may or may not need to write transparent pixels to the buffer.
487 // If we're compositing against a previous image, it's wrong, but if
488 // we're decoding an interlaced gif and displaying it "Haeberli"-style,
489 // we must write these for passes beyond the first, or the initial passes
490 // will "show through" the later ones.
491 const auto dstInfo = this->dstInfo();
492 if (writeTransparentPixels) {
493 this->applyXformRow(dstInfo, dstLine, rowBegin);
494 } else {
495 this->applyXformRow(dstInfo, fTmpBuffer.get(), rowBegin);
496
497 size_t offsetBytes = fSwizzler->swizzleOffsetBytes();
498 if (dstInfo.colorType() == kRGBA_F16_SkColorType) {
499 // Account for the fact that post-swizzling we converted to F16,
500 // which is twice as wide.
501 offsetBytes *= 2;
502 }
503 const void* src = SkTAddOffset<void>(fTmpBuffer.get(), offsetBytes);
504 void* dst = SkTAddOffset<void>(dstLine, offsetBytes);
505
506 switch (dstInfo.colorType()) {
507 case kBGRA_8888_SkColorType:
508 case kRGBA_8888_SkColorType:
509 blend_line<uint32_t>(dst, src, fSwizzler->swizzleWidth());
510 break;
511 case kRGBA_F16_SkColorType:
512 blend_line<uint64_t>(dst, src, fSwizzler->swizzleWidth());
513 break;
514 default:
515 SkASSERT(false);
516 return;
517 }
518 }
519
520 // Tell the frame to copy the row data if need be.
521 if (repeatCount > 1) {
522 const size_t bytesPerPixel = this->dstInfo().bytesPerPixel();
523 const size_t bytesToCopy = fSwizzler->swizzleWidth() * bytesPerPixel;
524 void* copiedLine = SkTAddOffset<void>(dstLine, fSwizzler->swizzleOffsetBytes());
525 void* dst = copiedLine;
526 for (int i = 1; i < repeatCount; i++) {
527 dst = SkTAddOffset<void>(dst, fDstRowBytes);
528 memcpy(dst, copiedLine, bytesToCopy);
529 }
530 }
531}
532