* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/codec/SkCodec.h"
#include "include/codec/SkCodecAnimation.h"
#include "include/codec/SkEncodedImageFormat.h"
#include "include/codec/SkGifDecoder.h"
#include "include/core/SkAlphaType.h"
#include "include/core/SkBitmap.h"
#include "include/core/SkBlendMode.h"
#include "include/core/SkColorType.h"
#include "include/core/SkData.h"
#include "include/core/SkImageInfo.h"
#include "include/core/SkMatrix.h"
#include "include/core/SkPaint.h"
#include "include/core/SkPixmap.h"
#include "include/core/SkRect.h"
#include "include/core/SkRefCnt.h"
#include "include/core/SkSamplingOptions.h"
#include "include/core/SkSize.h"
#include "include/core/SkStream.h"
#include "include/core/SkTypes.h"
#include "include/private/SkEncodedInfo.h"
#include "include/private/base/SkMalloc.h"
#include "include/private/base/SkTo.h"
#include "modules/skcms/skcms.h"
#include "src/codec/SkCodecPriv.h"
#include "src/codec/SkFrameHolder.h"
#include "src/codec/SkSampler.h"
#include "src/codec/SkScalingCodec.h"
#include "src/core/SkDraw.h"
#include "src/core/SkRasterClip.h"
#include "src/core/SkStreamPriv.h"
#include <climits>
#include <cstdint>
#include <cstring>
#include <memory>
#include <utility>
#include <vector>
#if defined(WUFFS_IMPLEMENTATION)
#error "SkWuffsCodec should not #define WUFFS_IMPLEMENTATION"
#endif
#include "wuffs-v0.3.c"
#if WUFFS_VERSION_BUILD_METADATA_COMMIT_COUNT < 2514
#error "Wuffs version is too old. Upgrade to the latest version."
#endif
#define SK_WUFFS_CODEC_BUFFER_SIZE 4096
#if defined(SK_WUFFS_FAVORS_PERFORMANCE_OVER_ADDITIONAL_MEMORY_SAFETY)
#define SK_WUFFS_INITIALIZE_FLAGS WUFFS_INITIALIZE__LEAVE_INTERNAL_BUFFERS_UNINITIALIZED
#else
#define SK_WUFFS_INITIALIZE_FLAGS WUFFS_INITIALIZE__DEFAULT_OPTIONS
#endif
static bool fill_buffer(wuffs_base__io_buffer* b, SkStream* s) {
b->compact();
size_t num_read = s->read(b->data.ptr + b->meta.wi, b->data.len - b->meta.wi);
b->meta.wi += num_read;
b->meta.closed = false;
return num_read > 0;
}
static bool seek_buffer(wuffs_base__io_buffer* b, SkStream* s, uint64_t pos) {
if ((pos >= b->meta.pos) && (pos - b->meta.pos <= b->meta.wi)) {
b->meta.ri = pos - b->meta.pos;
return true;
}
if ((pos > SIZE_MAX) || (!s->seek(pos))) {
return false;
}
b->meta.wi = 0;
b->meta.ri = 0;
b->meta.pos = pos;
b->meta.closed = false;
return true;
}
static SkCodecAnimation::DisposalMethod wuffs_disposal_to_skia_disposal(
wuffs_base__animation_disposal w) {
switch (w) {
case WUFFS_BASE__ANIMATION_DISPOSAL__RESTORE_BACKGROUND:
return SkCodecAnimation::DisposalMethod::kRestoreBGColor;
case WUFFS_BASE__ANIMATION_DISPOSAL__RESTORE_PREVIOUS:
return SkCodecAnimation::DisposalMethod::kRestorePrevious;
default:
return SkCodecAnimation::DisposalMethod::kKeep;
}
}
static SkAlphaType to_alpha_type(bool opaque) {
return opaque ? kOpaque_SkAlphaType : kPremul_SkAlphaType;
}
static SkCodec::Result reset_and_decode_image_config(wuffs_gif__decoder* decoder,
wuffs_base__image_config* imgcfg,
wuffs_base__io_buffer* b,
SkStream* s) {
wuffs_base__status status =
decoder->initialize(sizeof__wuffs_gif__decoder(), WUFFS_VERSION, SK_WUFFS_INITIALIZE_FLAGS);
if (status.repr != nullptr) {
SkCodecPrintf("initialize: %s", status.message());
return SkCodec::kInternalError;
}
decoder->set_quirk_enabled(WUFFS_GIF__QUIRK_IGNORE_TOO_MUCH_PIXEL_DATA, true);
while (true) {
status = decoder->decode_image_config(imgcfg, b);
if (status.repr == nullptr) {
break;
} else if (status.repr != wuffs_base__suspension__short_read) {
SkCodecPrintf("decode_image_config: %s", status.message());
return SkCodec::kErrorInInput;
} else if (!fill_buffer(b, s)) {
return SkCodec::kIncompleteInput;
}
}
uint32_t pixfmt = WUFFS_BASE__PIXEL_FORMAT__INVALID;
switch (kN32_SkColorType) {
case kBGRA_8888_SkColorType:
pixfmt = WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL;
break;
case kRGBA_8888_SkColorType:
pixfmt = WUFFS_BASE__PIXEL_FORMAT__RGBA_NONPREMUL;
break;
default:
return SkCodec::kInternalError;
}
if (imgcfg) {
imgcfg->pixcfg.set(pixfmt, WUFFS_BASE__PIXEL_SUBSAMPLING__NONE, imgcfg->pixcfg.width(),
imgcfg->pixcfg.height());
}
return SkCodec::kSuccess;
}
class SkWuffsCodec;
class SkWuffsFrame final : public SkFrame {
public:
SkWuffsFrame(wuffs_base__frame_config* fc);
uint64_t ioPosition() const;
SkEncodedInfo::Alpha onReportedAlpha() const override;
private:
uint64_t fIOPosition;
SkEncodedInfo::Alpha fReportedAlpha;
using INHERITED = SkFrame;
};
class SkWuffsFrameHolder final : public SkFrameHolder {
public:
SkWuffsFrameHolder() : INHERITED() {}
void init(SkWuffsCodec* codec, int width, int height);
const SkFrame* onGetFrame(int i) const override;
private:
const SkWuffsCodec* fCodec;
using INHERITED = SkFrameHolder;
};
class SkWuffsCodec final : public SkScalingCodec {
public:
SkWuffsCodec(SkEncodedInfo&& encodedInfo,
std::unique_ptr<SkStream> stream,
bool canSeek,
std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> dec,
std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr,
size_t workbuf_len,
wuffs_base__image_config imgcfg,
wuffs_base__io_buffer iobuf);
const SkWuffsFrame* frame(int i) const;
std::unique_ptr<SkStream> getEncodedData() const override;
private:
SkEncodedImageFormat onGetEncodedFormat() const override;
Result onGetPixels(const SkImageInfo&, void*, size_t, const Options&, int*) override;
const SkFrameHolder* getFrameHolder() const override;
Result onStartIncrementalDecode(const SkImageInfo& dstInfo,
void* dst,
size_t rowBytes,
const SkCodec::Options& options) override;
Result onIncrementalDecode(int* rowsDecoded) override;
int onGetFrameCount() override;
bool onGetFrameInfo(int, FrameInfo*) const override;
int onGetRepetitionCount() override;
IsAnimated onIsAnimated() override;
Result onStartIncrementalDecodeOnePass(const SkImageInfo& dstInfo,
uint8_t* dst,
size_t rowBytes,
const SkCodec::Options& options,
uint32_t pixelFormat,
size_t bytesPerPixel);
Result onStartIncrementalDecodeTwoPass();
Result onIncrementalDecodeOnePass();
Result onIncrementalDecodeTwoPass();
void onGetFrameCountInternal();
Result seekFrame(int frameIndex);
Result resetDecoder();
const char* decodeFrameConfig();
const char* decodeFrame();
void updateNumFullyReceivedFrames();
SkWuffsFrameHolder fFrameHolder;
std::unique_ptr<SkStream> fPrivStream;
std::unique_ptr<uint8_t, decltype(&sk_free)> fWorkbufPtr;
size_t fWorkbufLen;
std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> fDecoder;
const uint64_t fFirstFrameIOPosition;
wuffs_base__frame_config fFrameConfig;
wuffs_base__pixel_config fPixelConfig;
wuffs_base__pixel_buffer fPixelBuffer;
wuffs_base__io_buffer fIOBuffer;
uint8_t* fIncrDecDst;
size_t fIncrDecRowBytes;
wuffs_base__pixel_blend fIncrDecPixelBlend;
bool fIncrDecOnePass;
bool fFirstCallToIncrementalDecode;
std::unique_ptr<uint8_t, decltype(&sk_free)> fTwoPassPixbufPtr;
size_t fTwoPassPixbufLen;
uint64_t fNumFullyReceivedFrames;
std::vector<SkWuffsFrame> fFrames;
bool fFramesComplete;
bool fDecoderIsSuspended;
uint8_t fBuffer[SK_WUFFS_CODEC_BUFFER_SIZE];
const bool fCanSeek;
using INHERITED = SkScalingCodec;
};
SkWuffsFrame::SkWuffsFrame(wuffs_base__frame_config* fc)
: INHERITED(fc->index()),
fIOPosition(fc->io_position()),
fReportedAlpha(fc->opaque_within_bounds() ? SkEncodedInfo::kOpaque_Alpha
: SkEncodedInfo::kUnpremul_Alpha) {
wuffs_base__rect_ie_u32 r = fc->bounds();
this->setXYWH(r.min_incl_x, r.min_incl_y, r.width(), r.height());
this->setDisposalMethod(wuffs_disposal_to_skia_disposal(fc->disposal()));
this->setDuration(fc->duration() / WUFFS_BASE__FLICKS_PER_MILLISECOND);
this->setBlend(fc->overwrite_instead_of_blend() ? SkCodecAnimation::Blend::kSrc
: SkCodecAnimation::Blend::kSrcOver);
}
uint64_t SkWuffsFrame::ioPosition() const {
return fIOPosition;
}
SkEncodedInfo::Alpha SkWuffsFrame::onReportedAlpha() const {
return fReportedAlpha;
}
void SkWuffsFrameHolder::init(SkWuffsCodec* codec, int width, int height) {
fCodec = codec;
fScreenWidth = width;
fScreenHeight = height;
}
const SkFrame* SkWuffsFrameHolder::onGetFrame(int i) const {
return fCodec->frame(i);
}
SkWuffsCodec::SkWuffsCodec(SkEncodedInfo&& encodedInfo,
std::unique_ptr<SkStream> stream,
bool canSeek,
std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> dec,
std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr,
size_t workbuf_len,
wuffs_base__image_config imgcfg,
wuffs_base__io_buffer iobuf)
: INHERITED(std::move(encodedInfo),
skcms_PixelFormat_RGBA_8888,
nullptr)
, fFrameHolder()
, fPrivStream(std::move(stream))
, fWorkbufPtr(std::move(workbuf_ptr))
, fWorkbufLen(workbuf_len)
, fDecoder(std::move(dec))
, fFirstFrameIOPosition(imgcfg.first_frame_io_position())
, fFrameConfig(wuffs_base__null_frame_config())
, fPixelConfig(imgcfg.pixcfg)
, fPixelBuffer(wuffs_base__null_pixel_buffer())
, fIOBuffer(wuffs_base__empty_io_buffer())
, fIncrDecDst(nullptr)
, fIncrDecRowBytes(0)
, fIncrDecPixelBlend(WUFFS_BASE__PIXEL_BLEND__SRC)
, fIncrDecOnePass(false)
, fFirstCallToIncrementalDecode(false)
, fTwoPassPixbufPtr(nullptr, &sk_free)
, fTwoPassPixbufLen(0)
, fNumFullyReceivedFrames(0)
, fFramesComplete(false)
, fDecoderIsSuspended(false)
, fCanSeek(canSeek) {
fFrameHolder.init(this, imgcfg.pixcfg.width(), imgcfg.pixcfg.height());
SkASSERT(iobuf.data.len == SK_WUFFS_CODEC_BUFFER_SIZE);
memmove(fBuffer, iobuf.data.ptr, iobuf.meta.wi);
fIOBuffer.data = wuffs_base__make_slice_u8(fBuffer, SK_WUFFS_CODEC_BUFFER_SIZE);
fIOBuffer.meta = iobuf.meta;
}
const SkWuffsFrame* SkWuffsCodec::frame(int i) const {
if ((0 <= i) && (static_cast<size_t>(i) < fFrames.size())) {
return &fFrames[i];
}
return nullptr;
}
SkEncodedImageFormat SkWuffsCodec::onGetEncodedFormat() const {
return SkEncodedImageFormat::kGIF;
}
SkCodec::Result SkWuffsCodec::onGetPixels(const SkImageInfo& dstInfo,
void* dst,
size_t rowBytes,
const Options& options,
int* rowsDecoded) {
SkCodec::Result result = this->onStartIncrementalDecode(dstInfo, dst, rowBytes, options);
if (result != kSuccess) {
return result;
}
return this->onIncrementalDecode(rowsDecoded);
}
const SkFrameHolder* SkWuffsCodec::getFrameHolder() const {
return &fFrameHolder;
}
SkCodec::Result SkWuffsCodec::onStartIncrementalDecode(const SkImageInfo& dstInfo,
void* dst,
size_t rowBytes,
const SkCodec::Options& options) {
if (!dst) {
return SkCodec::kInvalidParameters;
}
if (options.fSubset) {
return SkCodec::kUnimplemented;
}
SkCodec::Result result = this->seekFrame(options.fFrameIndex);
if (result != SkCodec::kSuccess) {
return result;
}
const char* status = this->decodeFrameConfig();
if (status == wuffs_base__suspension__short_read) {
return SkCodec::kIncompleteInput;
} else if (status != nullptr) {
SkCodecPrintf("decodeFrameConfig: %s", status);
return SkCodec::kErrorInInput;
}
uint32_t pixelFormat = WUFFS_BASE__PIXEL_FORMAT__INVALID;
size_t bytesPerPixel = 0;
switch (dstInfo.colorType()) {
case kRGB_565_SkColorType:
pixelFormat = WUFFS_BASE__PIXEL_FORMAT__BGR_565;
bytesPerPixel = 2;
break;
case kBGRA_8888_SkColorType:
pixelFormat = WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL;
bytesPerPixel = 4;
break;
case kRGBA_8888_SkColorType:
pixelFormat = WUFFS_BASE__PIXEL_FORMAT__RGBA_NONPREMUL;
bytesPerPixel = 4;
break;
default:
break;
}
fIncrDecOnePass = (pixelFormat != WUFFS_BASE__PIXEL_FORMAT__INVALID) &&
(!getEncodedInfo().profile()) &&
(this->dimensions() == dstInfo.dimensions());
result = fIncrDecOnePass ? this->onStartIncrementalDecodeOnePass(
dstInfo, static_cast<uint8_t*>(dst), rowBytes, options,
pixelFormat, bytesPerPixel)
: this->onStartIncrementalDecodeTwoPass();
if (result != SkCodec::kSuccess) {
return result;
}
fIncrDecDst = static_cast<uint8_t*>(dst);
fIncrDecRowBytes = rowBytes;
fFirstCallToIncrementalDecode = true;
return SkCodec::kSuccess;
}
SkCodec::Result SkWuffsCodec::onStartIncrementalDecodeOnePass(const SkImageInfo& dstInfo,
uint8_t* dst,
size_t rowBytes,
const SkCodec::Options& options,
uint32_t pixelFormat,
size_t bytesPerPixel) {
wuffs_base__pixel_config pixelConfig;
pixelConfig.set(pixelFormat, WUFFS_BASE__PIXEL_SUBSAMPLING__NONE, dstInfo.width(),
dstInfo.height());
wuffs_base__table_u8 table;
table.ptr = dst;
table.width = static_cast<size_t>(dstInfo.width()) * bytesPerPixel;
table.height = dstInfo.height();
table.stride = rowBytes;
wuffs_base__status status = fPixelBuffer.set_from_table(&pixelConfig, table);
if (status.repr != nullptr) {
SkCodecPrintf("set_from_table: %s", status.message());
return SkCodec::kInternalError;
}
if ((options.fFrameIndex != 0) &&
(this->frame(options.fFrameIndex)->getRequiredFrame() != SkCodec::kNoFrame)) {
fIncrDecPixelBlend = WUFFS_BASE__PIXEL_BLEND__SRC_OVER;
} else {
SkSampler::Fill(dstInfo, dst, rowBytes, options.fZeroInitialized);
fIncrDecPixelBlend = WUFFS_BASE__PIXEL_BLEND__SRC;
}
return SkCodec::kSuccess;
}
SkCodec::Result SkWuffsCodec::onStartIncrementalDecodeTwoPass() {
bool already_zeroed = false;
if (!fTwoPassPixbufPtr) {
uint64_t pixbuf_len = fPixelConfig.pixbuf_len();
void* pixbuf_ptr_raw = (pixbuf_len <= SIZE_MAX)
? sk_malloc_flags(pixbuf_len, SK_MALLOC_ZERO_INITIALIZE)
: nullptr;
if (!pixbuf_ptr_raw) {
return SkCodec::kInternalError;
}
fTwoPassPixbufPtr.reset(reinterpret_cast<uint8_t*>(pixbuf_ptr_raw));
fTwoPassPixbufLen = SkToSizeT(pixbuf_len);
already_zeroed = true;
}
wuffs_base__status status = fPixelBuffer.set_from_slice(
&fPixelConfig, wuffs_base__make_slice_u8(fTwoPassPixbufPtr.get(), fTwoPassPixbufLen));
if (status.repr != nullptr) {
SkCodecPrintf("set_from_slice: %s", status.message());
return SkCodec::kInternalError;
}
if (!already_zeroed) {
uint32_t src_bits_per_pixel = fPixelConfig.pixel_format().bits_per_pixel();
if ((src_bits_per_pixel == 0) || (src_bits_per_pixel % 8 != 0)) {
return SkCodec::kInternalError;
}
size_t src_bytes_per_pixel = src_bits_per_pixel / 8;
wuffs_base__rect_ie_u32 frame_rect = fFrameConfig.bounds();
wuffs_base__table_u8 pixels = fPixelBuffer.plane(0);
uint8_t* ptr = pixels.ptr + (frame_rect.min_incl_y * pixels.stride) +
(frame_rect.min_incl_x * src_bytes_per_pixel);
size_t len = frame_rect.width() * src_bytes_per_pixel;
if ((len == pixels.stride) && (frame_rect.min_incl_y < frame_rect.max_excl_y)) {
sk_bzero(ptr, len * (frame_rect.max_excl_y - frame_rect.min_incl_y));
} else {
for (uint32_t y = frame_rect.min_incl_y; y < frame_rect.max_excl_y; y++) {
sk_bzero(ptr, len);
ptr += pixels.stride;
}
}
}
fIncrDecPixelBlend = WUFFS_BASE__PIXEL_BLEND__SRC;
return SkCodec::kSuccess;
}
SkCodec::Result SkWuffsCodec::onIncrementalDecode(int* rowsDecoded) {
if (!fIncrDecDst) {
return SkCodec::kInternalError;
}
if (rowsDecoded) {
*rowsDecoded = dstInfo().height();
}
SkCodec::Result result =
fIncrDecOnePass ? this->onIncrementalDecodeOnePass() : this->onIncrementalDecodeTwoPass();
if (result == SkCodec::kSuccess) {
fIncrDecDst = nullptr;
fIncrDecRowBytes = 0;
fIncrDecPixelBlend = WUFFS_BASE__PIXEL_BLEND__SRC;
fIncrDecOnePass = false;
}
return result;
}
SkCodec::Result SkWuffsCodec::onIncrementalDecodeOnePass() {
const char* status = this->decodeFrame();
if (status != nullptr) {
if (status == wuffs_base__suspension__short_read) {
return SkCodec::kIncompleteInput;
} else {
SkCodecPrintf("decodeFrame: %s", status);
return SkCodec::kErrorInInput;
}
}
return SkCodec::kSuccess;
}
SkCodec::Result SkWuffsCodec::onIncrementalDecodeTwoPass() {
SkCodec::Result result = SkCodec::kSuccess;
const char* status = this->decodeFrame();
bool independent;
SkAlphaType alphaType;
const int index = options().fFrameIndex;
if (index == 0) {
independent = true;
alphaType = to_alpha_type(getEncodedInfo().opaque());
} else {
const SkWuffsFrame* f = this->frame(index);
independent = f->getRequiredFrame() == SkCodec::kNoFrame;
alphaType = to_alpha_type(f->reportedAlpha() == SkEncodedInfo::kOpaque_Alpha);
}
if (status != nullptr) {
if (status == wuffs_base__suspension__short_read) {
result = SkCodec::kIncompleteInput;
} else {
SkCodecPrintf("decodeFrame: %s", status);
result = SkCodec::kErrorInInput;
}
if (!independent) {
return result;
}
}
uint32_t src_bits_per_pixel = fPixelBuffer.pixcfg.pixel_format().bits_per_pixel();
if ((src_bits_per_pixel == 0) || (src_bits_per_pixel % 8 != 0)) {
return SkCodec::kInternalError;
}
size_t src_bytes_per_pixel = src_bits_per_pixel / 8;
wuffs_base__rect_ie_u32 frame_rect = fFrameConfig.bounds();
if (fFirstCallToIncrementalDecode) {
if (frame_rect.width() > (SIZE_MAX / src_bytes_per_pixel)) {
return SkCodec::kInternalError;
}
auto bounds = SkIRect::MakeLTRB(frame_rect.min_incl_x, frame_rect.min_incl_y,
frame_rect.max_excl_x, frame_rect.max_excl_y);
if (independent && (bounds != this->bounds() || result != kSuccess)) {
SkSampler::Fill(dstInfo(), fIncrDecDst, fIncrDecRowBytes, options().fZeroInitialized);
}
fFirstCallToIncrementalDecode = false;
} else {
SkASSERT(index == 0);
}
wuffs_base__rect_ie_u32 dirty_rect = fDecoder->frame_dirty_rect();
if (!dirty_rect.is_empty()) {
wuffs_base__table_u8 pixels = fPixelBuffer.plane(0);
uint8_t* s = pixels.ptr + (dirty_rect.min_incl_y * pixels.stride) +
(dirty_rect.min_incl_x * src_bytes_per_pixel);
SkASSERT(!getEncodedInfo().profile());
auto srcInfo =
getInfo().makeWH(dirty_rect.width(), dirty_rect.height()).makeAlphaType(alphaType);
SkBitmap src;
src.installPixels(srcInfo, s, pixels.stride);
SkPaint paint;
if (independent) {
paint.setBlendMode(SkBlendMode::kSrc);
}
skcpu::Draw draw;
draw.fDst.reset(dstInfo(), fIncrDecDst, fIncrDecRowBytes);
SkMatrix matrix = SkMatrix::RectToRectOrIdentity(SkRect::Make(this->dimensions()),
SkRect::Make(this->dstInfo().dimensions()));
draw.fCTM = &matrix;
SkRasterClip rc(SkIRect::MakeSize(this->dstInfo().dimensions()));
draw.fRC = &rc;
SkMatrix translate = SkMatrix::Translate(dirty_rect.min_incl_x, dirty_rect.min_incl_y);
draw.drawBitmap(src, translate, nullptr, SkSamplingOptions(), paint);
}
if (result == SkCodec::kSuccess) {
if (fFramesComplete && (static_cast<size_t>(options().fFrameIndex) == fFrames.size() - 1)) {
fTwoPassPixbufPtr.reset(nullptr);
fTwoPassPixbufLen = 0;
}
}
return result;
}
int SkWuffsCodec::onGetFrameCount() {
if (!fCanSeek) {
return 1;
}
bool incrementalDecodeIsInProgress = fIncrDecDst != nullptr;
if (!fFramesComplete && !incrementalDecodeIsInProgress) {
this->onGetFrameCountInternal();
this->updateNumFullyReceivedFrames();
}
return fFrames.size();
}
void SkWuffsCodec::onGetFrameCountInternal() {
size_t n = fFrames.size();
int i = n ? n - 1 : 0;
if (this->seekFrame(i) != SkCodec::kSuccess) {
return;
}
for (; i < INT_MAX; i++) {
const char* status = this->decodeFrameConfig();
if (status == nullptr) {
} else if (status == wuffs_base__note__end_of_data) {
break;
} else {
return;
}
if (static_cast<size_t>(i) < fFrames.size()) {
continue;
}
fFrames.emplace_back(&fFrameConfig);
SkWuffsFrame* f = &fFrames[fFrames.size() - 1];
fFrameHolder.setAlphaAndRequiredFrame(f);
}
fFramesComplete = true;
}
bool SkWuffsCodec::onGetFrameInfo(int i, SkCodec::FrameInfo* frameInfo) const {
if (!fCanSeek) {
return false;
}
const SkWuffsFrame* f = this->frame(i);
if (!f) {
return false;
}
if (frameInfo) {
f->fillIn(frameInfo, static_cast<uint64_t>(i) < this->fNumFullyReceivedFrames);
}
return true;
}
int SkWuffsCodec::onGetRepetitionCount() {
uint32_t n = fDecoder->num_animation_loops();
if (n == 0) {
return SkCodec::kRepetitionCountInfinite;
}
n--;
return n < INT_MAX ? n : INT_MAX;
}
SkCodec::IsAnimated SkWuffsCodec::onIsAnimated() {
if (fFrames.size() > 1) {
return IsAnimated::kYes;
}
return fFramesComplete ? IsAnimated::kNo : IsAnimated::kUnknown;
}
SkCodec::Result SkWuffsCodec::seekFrame(int frameIndex) {
if (fDecoderIsSuspended) {
SkCodec::Result res = this->resetDecoder();
if (res != SkCodec::kSuccess) {
return res;
}
}
uint64_t pos = 0;
if (frameIndex < 0) {
return SkCodec::kInternalError;
} else if (frameIndex == 0) {
pos = fFirstFrameIOPosition;
} else if (static_cast<size_t>(frameIndex) < fFrames.size()) {
pos = fFrames[frameIndex].ioPosition();
} else {
return SkCodec::kInternalError;
}
if (!seek_buffer(&fIOBuffer, fPrivStream.get(), pos)) {
return SkCodec::kInternalError;
}
wuffs_base__status status =
fDecoder->restart_frame(frameIndex, fIOBuffer.reader_io_position());
if (status.repr != nullptr) {
return SkCodec::kInternalError;
}
return SkCodec::kSuccess;
}
SkCodec::Result SkWuffsCodec::resetDecoder() {
if (!fPrivStream->rewind()) {
return SkCodec::kInternalError;
}
fIOBuffer.meta = wuffs_base__empty_io_buffer_meta();
SkCodec::Result result =
reset_and_decode_image_config(fDecoder.get(), nullptr, &fIOBuffer, fPrivStream.get());
if (result == SkCodec::kIncompleteInput) {
return SkCodec::kInternalError;
} else if (result != SkCodec::kSuccess) {
return result;
}
fDecoderIsSuspended = false;
return SkCodec::kSuccess;
}
const char* SkWuffsCodec::decodeFrameConfig() {
while (true) {
wuffs_base__status status =
fDecoder->decode_frame_config(&fFrameConfig, &fIOBuffer);
if ((status.repr == wuffs_base__suspension__short_read) &&
fill_buffer(&fIOBuffer, fPrivStream.get())) {
continue;
}
fDecoderIsSuspended = !status.is_complete();
this->updateNumFullyReceivedFrames();
return status.repr;
}
}
const char* SkWuffsCodec::decodeFrame() {
while (true) {
wuffs_base__status status = fDecoder->decode_frame(
&fPixelBuffer, &fIOBuffer, fIncrDecPixelBlend,
wuffs_base__make_slice_u8(fWorkbufPtr.get(), fWorkbufLen), nullptr);
if ((status.repr == wuffs_base__suspension__short_read) &&
fill_buffer(&fIOBuffer, fPrivStream.get())) {
continue;
}
fDecoderIsSuspended = !status.is_complete();
this->updateNumFullyReceivedFrames();
return status.repr;
}
}
void SkWuffsCodec::updateNumFullyReceivedFrames() {
uint64_t n = fDecoder->num_decoded_frames();
if (fNumFullyReceivedFrames < n) {
fNumFullyReceivedFrames = n;
}
}
std::unique_ptr<SkStream> SkWuffsCodec::getEncodedData() const {
SkASSERT(fPrivStream);
return fPrivStream->duplicate();
}
namespace SkGifDecoder {
bool IsGif(const void* buf, size_t bytesRead) {
constexpr const char* gif_ptr = "GIF8";
constexpr size_t gif_len = 4;
return (bytesRead >= gif_len) && (memcmp(buf, gif_ptr, gif_len) == 0);
}
std::unique_ptr<SkCodec> MakeFromStream(std::unique_ptr<SkStream> stream,
SkCodec::SelectionPolicy selectionPolicy,
SkCodec::Result* result) {
SkASSERT(result);
if (!stream) {
*result = SkCodec::kInvalidInput;
return nullptr;
}
bool canSeek = stream->hasPosition() && stream->hasLength();
if (selectionPolicy != SkCodec::SelectionPolicy::kPreferStillImage) {
if (!canSeek) {
auto data = SkStreamPriv::CopyStreamToData(stream.get());
stream = std::make_unique<SkMemoryStream>(std::move(data));
canSeek = true;
}
}
uint8_t buffer[SK_WUFFS_CODEC_BUFFER_SIZE];
wuffs_base__io_buffer iobuf =
wuffs_base__make_io_buffer(wuffs_base__make_slice_u8(buffer, SK_WUFFS_CODEC_BUFFER_SIZE),
wuffs_base__empty_io_buffer_meta());
wuffs_base__image_config imgcfg = wuffs_base__null_image_config();
void* decoder_raw = sk_malloc_canfail(sizeof__wuffs_gif__decoder());
if (!decoder_raw) {
*result = SkCodec::kInternalError;
return nullptr;
}
std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> decoder(
reinterpret_cast<wuffs_gif__decoder*>(decoder_raw), &sk_free);
SkCodec::Result reset_result =
reset_and_decode_image_config(decoder.get(), &imgcfg, &iobuf, stream.get());
if (reset_result != SkCodec::kSuccess) {
*result = reset_result;
return nullptr;
}
uint32_t width = imgcfg.pixcfg.width();
uint32_t height = imgcfg.pixcfg.height();
if ((width == 0) || (width > INT_MAX) || (height == 0) || (height > INT_MAX)) {
*result = SkCodec::kInvalidInput;
return nullptr;
}
uint64_t workbuf_len = decoder->workbuf_len().max_incl;
void* workbuf_ptr_raw = nullptr;
if (workbuf_len) {
workbuf_ptr_raw = workbuf_len <= SIZE_MAX ? sk_malloc_canfail(workbuf_len) : nullptr;
if (!workbuf_ptr_raw) {
*result = SkCodec::kInternalError;
return nullptr;
}
}
std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr(
reinterpret_cast<uint8_t*>(workbuf_ptr_raw), &sk_free);
SkEncodedInfo::Color color =
(imgcfg.pixcfg.pixel_format().repr == WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL)
? SkEncodedInfo::kBGRA_Color
: SkEncodedInfo::kRGBA_Color;
SkEncodedInfo::Alpha alpha = imgcfg.first_frame_is_opaque() ? SkEncodedInfo::kOpaque_Alpha
: SkEncodedInfo::kBinary_Alpha;
SkEncodedInfo encodedInfo = SkEncodedInfo::Make(width, height, color, alpha, 8);
*result = SkCodec::kSuccess;
return std::unique_ptr<SkCodec>(new SkWuffsCodec(std::move(encodedInfo), std::move(stream),
canSeek,
std::move(decoder), std::move(workbuf_ptr),
workbuf_len, imgcfg, iobuf));
}
std::unique_ptr<SkCodec> Decode(std::unique_ptr<SkStream> stream,
SkCodec::Result* outResult,
SkCodecs::DecodeContext ctx) {
SkCodec::Result resultStorage;
if (!outResult) {
outResult = &resultStorage;
}
auto policy = SkCodec::SelectionPolicy::kPreferStillImage;
if (ctx) {
policy = *static_cast<SkCodec::SelectionPolicy*>(ctx);
}
return MakeFromStream(std::move(stream), policy, outResult);
}
std::unique_ptr<SkCodec> Decode(sk_sp<const SkData> data,
SkCodec::Result* outResult,
SkCodecs::DecodeContext ctx) {
if (!data) {
if (outResult) {
*outResult = SkCodec::kInvalidInput;
}
return nullptr;
}
return Decode(SkMemoryStream::Make(std::move(data)), outResult, ctx);
}
}