blob: 7791076d4ce27da8b1bc85399a7d44de062fa476 [file] [log] [blame]
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001/*
2 * Copyright 2018 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
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "src/codec/SkWuffsCodec.h"
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04009
Mike Kleinc0bd9f92019-04-23 12:05:21 -050010#include "include/core/SkBitmap.h"
11#include "include/core/SkMatrix.h"
12#include "include/core/SkPaint.h"
13#include "include/private/SkMalloc.h"
14#include "src/codec/SkFrameHolder.h"
15#include "src/codec/SkSampler.h"
16#include "src/codec/SkScalingCodec.h"
17#include "src/core/SkDraw.h"
18#include "src/core/SkRasterClip.h"
19#include "src/core/SkUtils.h"
Nigel Taoa6766482019-01-07 13:41:53 +110020
Ben Wagner666a9f92019-05-02 17:45:00 -040021#include <limits.h>
22
Nigel Taoa6766482019-01-07 13:41:53 +110023// Wuffs ships as a "single file C library" or "header file library" as per
24// https://github.com/nothings/stb/blob/master/docs/stb_howto.txt
25//
26// As we have not #define'd WUFFS_IMPLEMENTATION, the #include here is
27// including a header file, even though that file name ends in ".c".
Nigel Taoe66a0b22019-03-09 15:03:14 +110028#if defined(WUFFS_IMPLEMENTATION)
29#error "SkWuffsCodec should not #define WUFFS_IMPLEMENTATION"
30#endif
Nigel Taoa6766482019-01-07 13:41:53 +110031#include "wuffs-v0.2.c"
Nigel Tao477f2212019-10-09 10:07:11 +110032#if WUFFS_VERSION_BUILD_METADATA_COMMIT_COUNT < 1942
Nigel Taoa6766482019-01-07 13:41:53 +110033#error "Wuffs version is too old. Upgrade to the latest version."
34#endif
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -040035
36#define SK_WUFFS_CODEC_BUFFER_SIZE 4096
37
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -040038static bool fill_buffer(wuffs_base__io_buffer* b, SkStream* s) {
39 b->compact();
40 size_t num_read = s->read(b->data.ptr + b->meta.wi, b->data.len - b->meta.wi);
41 b->meta.wi += num_read;
42 b->meta.closed = s->isAtEnd();
43 return num_read > 0;
44}
45
46static bool seek_buffer(wuffs_base__io_buffer* b, SkStream* s, uint64_t pos) {
47 // Try to re-position the io_buffer's meta.ri read-index first, which is
48 // cheaper than seeking in the backing SkStream.
49 if ((pos >= b->meta.pos) && (pos - b->meta.pos <= b->meta.wi)) {
50 b->meta.ri = pos - b->meta.pos;
51 return true;
52 }
53 // Seek in the backing SkStream.
54 if ((pos > SIZE_MAX) || (!s->seek(pos))) {
55 return false;
56 }
57 b->meta.wi = 0;
58 b->meta.ri = 0;
59 b->meta.pos = pos;
60 b->meta.closed = false;
61 return true;
62}
63
64static SkEncodedInfo::Alpha wuffs_blend_to_skia_alpha(wuffs_base__animation_blend w) {
65 return (w == WUFFS_BASE__ANIMATION_BLEND__OPAQUE) ? SkEncodedInfo::kOpaque_Alpha
66 : SkEncodedInfo::kUnpremul_Alpha;
67}
68
69static SkCodecAnimation::Blend wuffs_blend_to_skia_blend(wuffs_base__animation_blend w) {
70 return (w == WUFFS_BASE__ANIMATION_BLEND__SRC) ? SkCodecAnimation::Blend::kBG
71 : SkCodecAnimation::Blend::kPriorFrame;
72}
73
74static SkCodecAnimation::DisposalMethod wuffs_disposal_to_skia_disposal(
75 wuffs_base__animation_disposal w) {
76 switch (w) {
77 case WUFFS_BASE__ANIMATION_DISPOSAL__RESTORE_BACKGROUND:
78 return SkCodecAnimation::DisposalMethod::kRestoreBGColor;
79 case WUFFS_BASE__ANIMATION_DISPOSAL__RESTORE_PREVIOUS:
80 return SkCodecAnimation::DisposalMethod::kRestorePrevious;
81 default:
82 return SkCodecAnimation::DisposalMethod::kKeep;
83 }
84}
85
Nigel Tao2777cd32019-10-29 11:10:25 +110086static SkCodec::Result reset_and_decode_image_config(wuffs_gif__decoder* decoder,
87 wuffs_base__image_config* imgcfg,
88 wuffs_base__io_buffer* b,
89 SkStream* s);
90
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -040091// -------------------------------- Class definitions
92
93class SkWuffsCodec;
94
95class SkWuffsFrame final : public SkFrame {
96public:
97 SkWuffsFrame(wuffs_base__frame_config* fc);
98
99 SkCodec::FrameInfo frameInfo(bool fullyReceived) const;
100 uint64_t ioPosition() const;
101
102 // SkFrame overrides.
103 SkEncodedInfo::Alpha onReportedAlpha() const override;
104
105private:
106 uint64_t fIOPosition;
107 SkEncodedInfo::Alpha fReportedAlpha;
108
109 typedef SkFrame INHERITED;
110};
111
112// SkWuffsFrameHolder is a trivial indirector that forwards its calls onto a
113// SkWuffsCodec. It is a separate class as SkWuffsCodec would otherwise
114// inherit from both SkCodec and SkFrameHolder, and Skia style discourages
115// multiple inheritance (e.g. with its "typedef Foo INHERITED" convention).
116class SkWuffsFrameHolder final : public SkFrameHolder {
117public:
118 SkWuffsFrameHolder() : INHERITED() {}
119
120 void init(SkWuffsCodec* codec, int width, int height);
121
122 // SkFrameHolder overrides.
123 const SkFrame* onGetFrame(int i) const override;
124
125private:
126 const SkWuffsCodec* fCodec;
127
128 typedef SkFrameHolder INHERITED;
129};
130
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400131class SkWuffsCodec final : public SkScalingCodec {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400132public:
133 SkWuffsCodec(SkEncodedInfo&& encodedInfo,
134 std::unique_ptr<SkStream> stream,
135 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> dec,
136 std::unique_ptr<uint8_t, decltype(&sk_free)> pixbuf_ptr,
137 std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr,
138 size_t workbuf_len,
139 wuffs_base__image_config imgcfg,
140 wuffs_base__pixel_buffer pixbuf,
141 wuffs_base__io_buffer iobuf);
142
143 const SkWuffsFrame* frame(int i) const;
144
145private:
Nigel Tao2777cd32019-10-29 11:10:25 +1100146 // It is valid, in terms of the SkCodec API, to call SkCodec::getFrameCount
147 // while in an incremental decode (after onStartIncrementalDecode returns
148 // and before the rest of the image is decoded). Some Skia users expect
149 // getFrameCount to increase, and the SkStream to advance, when given more
150 // data.
151 //
152 // On the other hand, while in an incremental decode, the underlying Wuffs
153 // object is suspended in a coroutine. To keep its internal proof-of-safety
154 // invariants consistent, there's only two things you can safely do with a
155 // suspended Wuffs object: resume the coroutine, or reset all state (memset
156 // to zero and start again).
157 //
158 // The Wuffs API provides a limited, optional form of seeking, to the start
159 // of an animation frame's data, but does not provide arbitrary save and
160 // load of its internal state whilst in the middle of an animation frame.
161 //
162 // SkWuffsCodec therefore uses two Wuffs decoders: a primary decoder
163 // (kIncrDecode) to support startIncrementalDecode / incrementalDecode, and
164 // a secondary decoder (kFrameCount) to support getFrameCount. The two
165 // decoders' states can change independently.
166 //
167 // As of Wuffs version 0.2, both of these decoders have the same type. A
168 // future Wuffs version might let us use a different type for kFrameCount,
169 // one that is much lighter weight (in terms of memory requirements), as it
170 // doesn't have to handle decompressing pixel data.
171 enum WhichDecoder {
172 kIncrDecode,
173 kFrameCount,
174 kNumDecoders,
175 };
176
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400177 // SkCodec overrides.
178 SkEncodedImageFormat onGetEncodedFormat() const override;
179 Result onGetPixels(const SkImageInfo&, void*, size_t, const Options&, int*) override;
180 const SkFrameHolder* getFrameHolder() const override;
181 Result onStartIncrementalDecode(const SkImageInfo& dstInfo,
182 void* dst,
183 size_t rowBytes,
184 const SkCodec::Options& options) override;
185 Result onIncrementalDecode(int* rowsDecoded) override;
186 int onGetFrameCount() override;
187 bool onGetFrameInfo(int, FrameInfo*) const override;
188 int onGetRepetitionCount() override;
189
190 void readFrames();
Nigel Tao2777cd32019-10-29 11:10:25 +1100191 Result seekFrame(WhichDecoder which, int frameIndex);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400192
Nigel Tao2777cd32019-10-29 11:10:25 +1100193 void onGetFrameCountInternal();
194 Result onIncrementalDecodeInternal(int* rowsDecoded);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400195
Nigel Tao2777cd32019-10-29 11:10:25 +1100196 Result resetDecoder(WhichDecoder which);
197 const char* decodeFrameConfig(WhichDecoder which);
198 const char* decodeFrame(WhichDecoder which);
199 void updateNumFullyReceivedFrames(WhichDecoder which);
200
201 SkWuffsFrameHolder fFrameHolder;
202 std::unique_ptr<SkStream> fStream;
203 std::unique_ptr<uint8_t, decltype(&sk_free)> fPixbufPtr;
204 std::unique_ptr<uint8_t, decltype(&sk_free)> fWorkbufPtr;
205 size_t fWorkbufLen;
206
207 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> fDecoders[WhichDecoder::kNumDecoders];
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400208
209 const uint64_t fFirstFrameIOPosition;
Nigel Tao2777cd32019-10-29 11:10:25 +1100210 wuffs_base__frame_config fFrameConfigs[WhichDecoder::kNumDecoders];
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400211 wuffs_base__pixel_buffer fPixelBuffer;
212 wuffs_base__io_buffer fIOBuffer;
213
214 // Incremental decoding state.
Nigel Tao0185b952018-11-08 10:47:24 +1100215 uint8_t* fIncrDecDst;
Nigel Tao2777cd32019-10-29 11:10:25 +1100216 uint64_t fIncrDecReaderIOPosition;
Nigel Tao0185b952018-11-08 10:47:24 +1100217 size_t fIncrDecRowBytes;
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400218 bool fFirstCallToIncrementalDecode;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400219
220 uint64_t fNumFullyReceivedFrames;
221 std::vector<SkWuffsFrame> fFrames;
222 bool fFramesComplete;
223
Nigel Tao2777cd32019-10-29 11:10:25 +1100224 // If calling an fDecoders[which] method returns an incomplete status, then
225 // fDecoders[which] is suspended in a coroutine (i.e. waiting on I/O or
226 // halted on a non-recoverable error). To keep its internal proof-of-safety
227 // invariants consistent, there's only two things you can safely do with a
228 // suspended Wuffs object: resume the coroutine, or reset all state (memset
229 // to zero and start again).
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400230 //
Nigel Tao2777cd32019-10-29 11:10:25 +1100231 // If fDecoderIsSuspended[which], and we aren't sure that we're going to
232 // resume the coroutine, then we will need to call this->resetDecoder
233 // before calling other fDecoders[which] methods.
234 bool fDecoderIsSuspended[WhichDecoder::kNumDecoders];
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400235
236 uint8_t fBuffer[SK_WUFFS_CODEC_BUFFER_SIZE];
237
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400238 typedef SkScalingCodec INHERITED;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400239};
240
241// -------------------------------- SkWuffsFrame implementation
242
243SkWuffsFrame::SkWuffsFrame(wuffs_base__frame_config* fc)
244 : INHERITED(fc->index()),
245 fIOPosition(fc->io_position()),
246 fReportedAlpha(wuffs_blend_to_skia_alpha(fc->blend())) {
247 wuffs_base__rect_ie_u32 r = fc->bounds();
248 this->setXYWH(r.min_incl_x, r.min_incl_y, r.width(), r.height());
249 this->setDisposalMethod(wuffs_disposal_to_skia_disposal(fc->disposal()));
250 this->setDuration(fc->duration() / WUFFS_BASE__FLICKS_PER_MILLISECOND);
251 this->setBlend(wuffs_blend_to_skia_blend(fc->blend()));
252}
253
254SkCodec::FrameInfo SkWuffsFrame::frameInfo(bool fullyReceived) const {
Nigel Taoef40e332019-04-05 10:28:40 +1100255 SkCodec::FrameInfo ret;
256 ret.fRequiredFrame = getRequiredFrame();
257 ret.fDuration = getDuration();
258 ret.fFullyReceived = fullyReceived;
259 ret.fAlphaType = hasAlpha() ? kUnpremul_SkAlphaType : kOpaque_SkAlphaType;
260 ret.fDisposalMethod = getDisposalMethod();
261 return ret;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400262}
263
264uint64_t SkWuffsFrame::ioPosition() const {
265 return fIOPosition;
266}
267
268SkEncodedInfo::Alpha SkWuffsFrame::onReportedAlpha() const {
269 return fReportedAlpha;
270}
271
272// -------------------------------- SkWuffsFrameHolder implementation
273
274void SkWuffsFrameHolder::init(SkWuffsCodec* codec, int width, int height) {
275 fCodec = codec;
276 // Initialize SkFrameHolder's (the superclass) fields.
277 fScreenWidth = width;
278 fScreenHeight = height;
279}
280
281const SkFrame* SkWuffsFrameHolder::onGetFrame(int i) const {
282 return fCodec->frame(i);
283};
284
285// -------------------------------- SkWuffsCodec implementation
286
287SkWuffsCodec::SkWuffsCodec(SkEncodedInfo&& encodedInfo,
288 std::unique_ptr<SkStream> stream,
289 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> dec,
290 std::unique_ptr<uint8_t, decltype(&sk_free)> pixbuf_ptr,
291 std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr,
292 size_t workbuf_len,
293 wuffs_base__image_config imgcfg,
294 wuffs_base__pixel_buffer pixbuf,
295 wuffs_base__io_buffer iobuf)
296 : INHERITED(std::move(encodedInfo),
297 skcms_PixelFormat_RGBA_8888,
298 // Pass a nullptr SkStream to the SkCodec constructor. We
299 // manage the stream ourselves, as the default SkCodec behavior
300 // is too trigger-happy on rewinding the stream.
301 nullptr),
Nigel Tao0185b952018-11-08 10:47:24 +1100302 fFrameHolder(),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400303 fStream(std::move(stream)),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400304 fPixbufPtr(std::move(pixbuf_ptr)),
305 fWorkbufPtr(std::move(workbuf_ptr)),
306 fWorkbufLen(workbuf_len),
Nigel Tao2777cd32019-10-29 11:10:25 +1100307 fDecoders{
308 std::move(dec),
309 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)>(nullptr, sk_free),
310 },
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400311 fFirstFrameIOPosition(imgcfg.first_frame_io_position()),
Nigel Tao2777cd32019-10-29 11:10:25 +1100312 fFrameConfigs{
313 wuffs_base__null_frame_config(),
314 wuffs_base__null_frame_config(),
315 },
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400316 fPixelBuffer(pixbuf),
Nigel Tao96c10a02019-09-25 11:08:42 +1000317 fIOBuffer(wuffs_base__empty_io_buffer()),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400318 fIncrDecDst(nullptr),
Nigel Tao2777cd32019-10-29 11:10:25 +1100319 fIncrDecReaderIOPosition(0),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400320 fIncrDecRowBytes(0),
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400321 fFirstCallToIncrementalDecode(false),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400322 fNumFullyReceivedFrames(0),
323 fFramesComplete(false),
Nigel Tao2777cd32019-10-29 11:10:25 +1100324 fDecoderIsSuspended{
325 false,
326 false,
327 } {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400328 fFrameHolder.init(this, imgcfg.pixcfg.width(), imgcfg.pixcfg.height());
329
330 // Initialize fIOBuffer's fields, copying any outstanding data from iobuf to
331 // fIOBuffer, as iobuf's backing array may not be valid for the lifetime of
332 // this SkWuffsCodec object, but fIOBuffer's backing array (fBuffer) is.
333 SkASSERT(iobuf.data.len == SK_WUFFS_CODEC_BUFFER_SIZE);
334 memmove(fBuffer, iobuf.data.ptr, iobuf.meta.wi);
Nigel Tao48aa2212019-03-09 14:59:11 +1100335 fIOBuffer.data = wuffs_base__make_slice_u8(fBuffer, SK_WUFFS_CODEC_BUFFER_SIZE);
336 fIOBuffer.meta = iobuf.meta;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400337}
338
339const SkWuffsFrame* SkWuffsCodec::frame(int i) const {
340 if ((0 <= i) && (static_cast<size_t>(i) < fFrames.size())) {
341 return &fFrames[i];
342 }
343 return nullptr;
344}
345
346SkEncodedImageFormat SkWuffsCodec::onGetEncodedFormat() const {
347 return SkEncodedImageFormat::kGIF;
348}
349
350SkCodec::Result SkWuffsCodec::onGetPixels(const SkImageInfo& dstInfo,
351 void* dst,
352 size_t rowBytes,
353 const Options& options,
354 int* rowsDecoded) {
355 SkCodec::Result result = this->onStartIncrementalDecode(dstInfo, dst, rowBytes, options);
356 if (result != kSuccess) {
357 return result;
358 }
359 return this->onIncrementalDecode(rowsDecoded);
360}
361
362const SkFrameHolder* SkWuffsCodec::getFrameHolder() const {
363 return &fFrameHolder;
364}
365
366SkCodec::Result SkWuffsCodec::onStartIncrementalDecode(const SkImageInfo& dstInfo,
367 void* dst,
368 size_t rowBytes,
369 const SkCodec::Options& options) {
Nigel Tao1f1cd1f2019-06-22 17:35:38 +1000370 if (!dst) {
371 return SkCodec::kInvalidParameters;
372 }
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400373 if (options.fSubset) {
374 return SkCodec::kUnimplemented;
375 }
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400376 if (options.fFrameIndex > 0 && SkColorTypeIsAlwaysOpaque(dstInfo.colorType())) {
377 return SkCodec::kInvalidConversion;
378 }
Nigel Tao2777cd32019-10-29 11:10:25 +1100379 SkCodec::Result result = this->seekFrame(WhichDecoder::kIncrDecode, options.fFrameIndex);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400380 if (result != SkCodec::kSuccess) {
381 return result;
382 }
383
Nigel Tao2777cd32019-10-29 11:10:25 +1100384 const char* status = this->decodeFrameConfig(WhichDecoder::kIncrDecode);
Nigel Taob7a1b512019-02-10 12:19:50 +1100385 if (status == wuffs_base__suspension__short_read) {
Leon Scroggins IIIcb6b8842018-12-04 13:55:13 -0500386 return SkCodec::kIncompleteInput;
Nigel Taob7a1b512019-02-10 12:19:50 +1100387 } else if (status != nullptr) {
Leon Scroggins IIIcb6b8842018-12-04 13:55:13 -0500388 SkCodecPrintf("decodeFrameConfig: %s", status);
389 return SkCodec::kErrorInInput;
390 }
Nigel Taob7a1b512019-02-10 12:19:50 +1100391
Nigel Tao490e6472019-02-14 14:50:53 +1100392 uint32_t src_bits_per_pixel =
393 wuffs_base__pixel_format__bits_per_pixel(fPixelBuffer.pixcfg.pixel_format());
394 if ((src_bits_per_pixel == 0) || (src_bits_per_pixel % 8 != 0)) {
395 return SkCodec::kInternalError;
396 }
397 size_t src_bytes_per_pixel = src_bits_per_pixel / 8;
Nigel Taob7a1b512019-02-10 12:19:50 +1100398
399 // Zero-initialize Wuffs' buffer covering the frame rect.
Nigel Tao2777cd32019-10-29 11:10:25 +1100400 wuffs_base__rect_ie_u32 frame_rect = fFrameConfigs[WhichDecoder::kIncrDecode].bounds();
Nigel Taob7a1b512019-02-10 12:19:50 +1100401 wuffs_base__table_u8 pixels = fPixelBuffer.plane(0);
402 for (uint32_t y = frame_rect.min_incl_y; y < frame_rect.max_excl_y; y++) {
Nigel Tao490e6472019-02-14 14:50:53 +1100403 sk_bzero(pixels.ptr + (y * pixels.stride) + (frame_rect.min_incl_x * src_bytes_per_pixel),
404 frame_rect.width() * src_bytes_per_pixel);
Nigel Taob7a1b512019-02-10 12:19:50 +1100405 }
406
407 fIncrDecDst = static_cast<uint8_t*>(dst);
Nigel Tao2777cd32019-10-29 11:10:25 +1100408 fIncrDecReaderIOPosition = fIOBuffer.reader_io_position();
Nigel Taob7a1b512019-02-10 12:19:50 +1100409 fIncrDecRowBytes = rowBytes;
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400410 fFirstCallToIncrementalDecode = true;
Nigel Taob7a1b512019-02-10 12:19:50 +1100411 return SkCodec::kSuccess;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400412}
413
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400414static SkAlphaType to_alpha_type(bool opaque) {
415 return opaque ? kOpaque_SkAlphaType : kPremul_SkAlphaType;
Leon Scroggins III9b0ba2c2018-11-19 14:52:37 -0500416}
417
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400418SkCodec::Result SkWuffsCodec::onIncrementalDecode(int* rowsDecoded) {
419 if (!fIncrDecDst) {
420 return SkCodec::kInternalError;
421 }
422
Nigel Tao2777cd32019-10-29 11:10:25 +1100423 // If multiple SkCodec::incrementalDecode calls are made consecutively (or
424 // if SkCodec::incrementalDecode is called immediately after
425 // SkCodec::startIncrementalDecode), then this seek should be a no-op.
426 // However, it is possible to interleave SkCodec::getFrameCount calls in
427 // between SkCodec::incrementalDecode calls, and those other calls may
428 // advance the stream. This seek restores the stream to where the last
429 // SkCodec::startIncrementalDecode or SkCodec::incrementalDecode stopped.
430 if (!seek_buffer(&fIOBuffer, fStream.get(), fIncrDecReaderIOPosition)) {
431 return SkCodec::kInternalError;
432 }
433
434 SkCodec::Result result = this->onIncrementalDecodeInternal(rowsDecoded);
435 if (result == SkCodec::kSuccess) {
436 fIncrDecDst = nullptr;
437 fIncrDecReaderIOPosition = 0;
438 fIncrDecRowBytes = 0;
439 } else {
440 fIncrDecReaderIOPosition = fIOBuffer.reader_io_position();
441 }
442 return result;
443}
444
445SkCodec::Result SkWuffsCodec::onIncrementalDecodeInternal(int* rowsDecoded) {
Leon Scroggins III699d41e2019-02-07 09:25:51 -0500446 SkCodec::Result result = SkCodec::kSuccess;
Nigel Tao2777cd32019-10-29 11:10:25 +1100447 const char* status = this->decodeFrame(WhichDecoder::kIncrDecode);
448 bool independent;
449 SkAlphaType alphaType;
450 const int index = options().fFrameIndex;
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400451 if (index == 0) {
452 independent = true;
453 alphaType = to_alpha_type(getEncodedInfo().opaque());
454 } else {
455 const SkWuffsFrame* f = this->frame(index);
456 independent = f->getRequiredFrame() == SkCodec::kNoFrame;
457 alphaType = to_alpha_type(f->reportedAlpha() == SkEncodedInfo::kOpaque_Alpha);
458 }
Leon Scroggins III699d41e2019-02-07 09:25:51 -0500459 if (status != nullptr) {
460 if (status == wuffs_base__suspension__short_read) {
461 result = SkCodec::kIncompleteInput;
462 } else {
463 SkCodecPrintf("decodeFrame: %s", status);
464 result = SkCodec::kErrorInInput;
465 }
466
467 if (!independent) {
468 // For a dependent frame, we cannot blend the partial result, since
469 // that will overwrite the contribution from prior frames.
470 return result;
471 }
472 }
473
Nigel Tao490e6472019-02-14 14:50:53 +1100474 uint32_t src_bits_per_pixel =
475 wuffs_base__pixel_format__bits_per_pixel(fPixelBuffer.pixcfg.pixel_format());
476 if ((src_bits_per_pixel == 0) || (src_bits_per_pixel % 8 != 0)) {
477 return SkCodec::kInternalError;
478 }
479 size_t src_bytes_per_pixel = src_bits_per_pixel / 8;
480
Nigel Tao2777cd32019-10-29 11:10:25 +1100481 wuffs_base__rect_ie_u32 frame_rect = fFrameConfigs[WhichDecoder::kIncrDecode].bounds();
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400482 if (fFirstCallToIncrementalDecode) {
Nigel Tao490e6472019-02-14 14:50:53 +1100483 if (frame_rect.width() > (SIZE_MAX / src_bytes_per_pixel)) {
484 return SkCodec::kInternalError;
485 }
486
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400487 auto bounds = SkIRect::MakeLTRB(frame_rect.min_incl_x, frame_rect.min_incl_y,
488 frame_rect.max_excl_x, frame_rect.max_excl_y);
489
Leon Scroggins IIIcb6b8842018-12-04 13:55:13 -0500490 // If the frame rect does not fill the output, ensure that those pixels are not
Nigel Taob7a1b512019-02-10 12:19:50 +1100491 // left uninitialized.
Leon Scroggins III44076362019-02-15 13:56:44 -0500492 if (independent && (bounds != this->bounds() || result != kSuccess)) {
Nigel Tao2777cd32019-10-29 11:10:25 +1100493 SkSampler::Fill(dstInfo(), fIncrDecDst, fIncrDecRowBytes, options().fZeroInitialized);
Leon Scroggins III9b0ba2c2018-11-19 14:52:37 -0500494 }
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400495 fFirstCallToIncrementalDecode = false;
496 } else {
497 // Existing clients intend to only show frames beyond the first if they
498 // are complete (based on FrameInfo::fFullyReceived), since it might
499 // look jarring to draw a partial frame over an existing frame. If they
500 // changed their behavior and expected to continue decoding a partial
501 // frame after the first one, we'll need to update our blending code.
502 // Otherwise, if the frame were interlaced and not independent, the
503 // second pass may have an overlapping dirty_rect with the first,
504 // resulting in blending with the first pass.
505 SkASSERT(index == 0);
Nigel Tao9859ef82019-02-13 13:20:02 +1100506 }
Nigel Tao0185b952018-11-08 10:47:24 +1100507
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400508 if (rowsDecoded) {
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400509 *rowsDecoded = dstInfo().height();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400510 }
511
Leon Scroggins IIIdad4bfc2018-12-10 12:37:10 -0500512 // If the frame's dirty rect is empty, no need to swizzle.
Nigel Tao2777cd32019-10-29 11:10:25 +1100513 wuffs_base__rect_ie_u32 dirty_rect = fDecoders[WhichDecoder::kIncrDecode]->frame_dirty_rect();
Leon Scroggins IIIdad4bfc2018-12-10 12:37:10 -0500514 if (!dirty_rect.is_empty()) {
Nigel Tao490e6472019-02-14 14:50:53 +1100515 wuffs_base__table_u8 pixels = fPixelBuffer.plane(0);
Leon Scroggins III7a3805c2018-12-07 09:21:30 -0500516
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400517 // The Wuffs model is that the dst buffer is the image, not the frame.
518 // The expectation is that you allocate the buffer once, but re-use it
519 // for the N frames, regardless of each frame's top-left co-ordinate.
520 //
521 // To get from the start (in the X-direction) of the image to the start
522 // of the dirty_rect, we adjust s by (dirty_rect.min_incl_x * src_bytes_per_pixel).
Nigel Tao2777cd32019-10-29 11:10:25 +1100523 uint8_t* s = pixels.ptr + (dirty_rect.min_incl_y * pixels.stride) +
524 (dirty_rect.min_incl_x * src_bytes_per_pixel);
Leon Scroggins III7a3805c2018-12-07 09:21:30 -0500525
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400526 // Currently, this is only used for GIF, which will never have an ICC profile. When it is
527 // used for other formats that might have one, we will need to transform from profiles that
528 // do not have corresponding SkColorSpaces.
529 SkASSERT(!getEncodedInfo().profile());
530
Nigel Tao2777cd32019-10-29 11:10:25 +1100531 auto srcInfo =
532 getInfo().makeWH(dirty_rect.width(), dirty_rect.height()).makeAlphaType(alphaType);
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400533 SkBitmap src;
534 src.installPixels(srcInfo, s, pixels.stride);
535 SkPaint paint;
536 if (independent) {
537 paint.setBlendMode(SkBlendMode::kSrc);
Leon Scroggins III7a3805c2018-12-07 09:21:30 -0500538 }
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400539
540 SkDraw draw;
541 draw.fDst.reset(dstInfo(), fIncrDecDst, fIncrDecRowBytes);
542 SkMatrix matrix = SkMatrix::MakeRectToRect(SkRect::Make(this->dimensions()),
543 SkRect::Make(this->dstInfo().dimensions()),
544 SkMatrix::kFill_ScaleToFit);
545 draw.fMatrix = &matrix;
546 SkRasterClip rc(SkIRect::MakeSize(this->dstInfo().dimensions()));
547 draw.fRC = &rc;
548
549 SkMatrix translate = SkMatrix::MakeTrans(dirty_rect.min_incl_x, dirty_rect.min_incl_y);
550 draw.drawBitmap(src, translate, nullptr, paint);
Leon Scroggins III7a3805c2018-12-07 09:21:30 -0500551 }
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400552 return result;
553}
554
555int SkWuffsCodec::onGetFrameCount() {
Nigel Tao2777cd32019-10-29 11:10:25 +1100556 if (!fFramesComplete) {
557 this->onGetFrameCountInternal();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400558 }
559 return fFrames.size();
560}
561
Nigel Tao2777cd32019-10-29 11:10:25 +1100562void SkWuffsCodec::onGetFrameCountInternal() {
563 if (!seek_buffer(&fIOBuffer, fStream.get(), 0)) {
564 return;
565 }
566 if (!fDecoders[WhichDecoder::kFrameCount]) {
567 void* decoder_raw = sk_malloc_canfail(sizeof__wuffs_gif__decoder());
568 if (!decoder_raw) {
569 return;
570 }
571 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> decoder(
572 reinterpret_cast<wuffs_gif__decoder*>(decoder_raw), &sk_free);
573 fDecoders[WhichDecoder::kFrameCount] = std::move(decoder);
574 }
575 reset_and_decode_image_config(fDecoders[WhichDecoder::kFrameCount].get(), nullptr, &fIOBuffer,
576 fStream.get());
577 this->readFrames();
578}
579
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400580bool SkWuffsCodec::onGetFrameInfo(int i, SkCodec::FrameInfo* frameInfo) const {
581 const SkWuffsFrame* f = this->frame(i);
582 if (!f) {
583 return false;
584 }
585 if (frameInfo) {
586 *frameInfo = f->frameInfo(static_cast<uint64_t>(i) < this->fNumFullyReceivedFrames);
587 }
588 return true;
589}
590
591int SkWuffsCodec::onGetRepetitionCount() {
592 // Convert from Wuffs's loop count to Skia's repeat count. Wuffs' uint32_t
593 // number is how many times to play the loop. Skia's int number is how many
594 // times to play the loop *after the first play*. Wuffs and Skia use 0 and
595 // kRepetitionCountInfinite respectively to mean loop forever.
Nigel Tao2777cd32019-10-29 11:10:25 +1100596 uint32_t n = fDecoders[WhichDecoder::kIncrDecode]->num_animation_loops();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400597 if (n == 0) {
598 return SkCodec::kRepetitionCountInfinite;
599 }
600 n--;
601 return n < INT_MAX ? n : INT_MAX;
602}
603
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400604void SkWuffsCodec::readFrames() {
605 size_t n = fFrames.size();
606 int i = n ? n - 1 : 0;
Nigel Tao2777cd32019-10-29 11:10:25 +1100607 if (this->seekFrame(WhichDecoder::kFrameCount, i) != SkCodec::kSuccess) {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400608 return;
609 }
610
611 // Iterate through the frames, converting from Wuffs'
612 // wuffs_base__frame_config type to Skia's SkWuffsFrame type.
613 for (; i < INT_MAX; i++) {
Nigel Tao2777cd32019-10-29 11:10:25 +1100614 const char* status = this->decodeFrameConfig(WhichDecoder::kFrameCount);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400615 if (status == nullptr) {
616 // No-op.
617 } else if (status == wuffs_base__warning__end_of_data) {
618 break;
619 } else {
620 return;
621 }
622
623 if (static_cast<size_t>(i) < fFrames.size()) {
624 continue;
625 }
Nigel Tao2777cd32019-10-29 11:10:25 +1100626 fFrames.emplace_back(&fFrameConfigs[WhichDecoder::kFrameCount]);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400627 SkWuffsFrame* f = &fFrames[fFrames.size() - 1];
628 fFrameHolder.setAlphaAndRequiredFrame(f);
629 }
630
631 fFramesComplete = true;
632}
633
Nigel Tao2777cd32019-10-29 11:10:25 +1100634SkCodec::Result SkWuffsCodec::seekFrame(WhichDecoder which, int frameIndex) {
635 if (fDecoderIsSuspended[which]) {
636 SkCodec::Result res = this->resetDecoder(which);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400637 if (res != SkCodec::kSuccess) {
638 return res;
639 }
640 }
641
642 uint64_t pos = 0;
643 if (frameIndex < 0) {
644 return SkCodec::kInternalError;
645 } else if (frameIndex == 0) {
646 pos = fFirstFrameIOPosition;
647 } else if (static_cast<size_t>(frameIndex) < fFrames.size()) {
648 pos = fFrames[frameIndex].ioPosition();
649 } else {
650 return SkCodec::kInternalError;
651 }
652
653 if (!seek_buffer(&fIOBuffer, fStream.get(), pos)) {
654 return SkCodec::kInternalError;
655 }
Nigel Tao2777cd32019-10-29 11:10:25 +1100656 const char* status =
657 fDecoders[which]->restart_frame(frameIndex, fIOBuffer.reader_io_position());
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400658 if (status != nullptr) {
659 return SkCodec::kInternalError;
660 }
661 return SkCodec::kSuccess;
662}
663
664// An overview of the Wuffs decoding API:
665//
666// An animated image (such as GIF) has an image header and then N frames. The
667// image header gives e.g. the overall image's width and height. Each frame
668// consists of a frame header (e.g. frame rectangle bounds, display duration)
669// and a payload (the pixels).
670//
671// In Wuffs terminology, there is one image config and then N pairs of
672// (frame_config, frame). To decode everything (without knowing N in advance)
673// sequentially:
674// - call wuffs_gif__decoder::decode_image_config
675// - while (true) {
676// - call wuffs_gif__decoder::decode_frame_config
677// - if that returned wuffs_base__warning__end_of_data, break
678// - call wuffs_gif__decoder::decode_frame
679// - }
680//
681// The first argument to each decode_foo method is the destination struct to
682// store the decoded information.
683//
684// For random (instead of sequential) access to an image's frames, call
685// wuffs_gif__decoder::restart_frame to prepare to decode the i'th frame.
686// Essentially, it restores the state to be at the top of the while loop above.
687// The wuffs_base__io_buffer's reader position will also need to be set at the
688// right point in the source data stream. The position for the i'th frame is
689// calculated by the i'th decode_frame_config call. You can only call
690// restart_frame after decode_image_config is called, explicitly or implicitly
691// (see below), as decoding a single frame might require for-all-frames
692// information like the overall image dimensions and the global palette.
693//
694// All of those decode_xxx calls are optional. For example, if
695// decode_image_config is not called, then the first decode_frame_config call
696// will implicitly parse and verify the image header, before parsing the first
697// frame's header. Similarly, you can call only decode_frame N times, without
698// calling decode_image_config or decode_frame_config, if you already know
699// metadata like N and each frame's rectangle bounds by some other means (e.g.
700// this is a first party, statically known image).
701//
702// Specifically, starting with an unknown (but re-windable) GIF image, if you
703// want to just find N (i.e. count the number of frames), you can loop calling
704// only the decode_frame_config method and avoid calling the more expensive
705// decode_frame method. In terms of the underlying GIF image format, this will
706// skip over the LZW-encoded pixel data, avoiding the costly LZW decompression.
707//
708// Those decode_xxx methods are also suspendible. They will return early (with
709// a status code that is_suspendible and therefore isn't is_complete) if there
710// isn't enough source data to complete the operation: an incremental decode.
711// Calling decode_xxx again with additional source data will resume the
712// previous operation, instead of starting a new operation. Calling decode_yyy
713// whilst decode_xxx is suspended will result in an error.
714//
715// Once an error is encountered, whether from invalid source data or from a
716// programming error such as calling decode_yyy while suspended in decode_xxx,
717// all subsequent calls will be no-ops that return an error. To reset the
718// decoder into something that does productive work, memset the entire struct
719// to zero, check the Wuffs version and then, in order to be able to call
720// restart_frame, call decode_image_config. The io_buffer and its associated
721// stream will also need to be rewound.
722
723static SkCodec::Result reset_and_decode_image_config(wuffs_gif__decoder* decoder,
724 wuffs_base__image_config* imgcfg,
725 wuffs_base__io_buffer* b,
726 SkStream* s) {
Nigel Taoe39c8842019-02-27 15:57:34 +1100727 // Calling decoder->initialize will memset it to zero.
728 const char* status = decoder->initialize(sizeof__wuffs_gif__decoder(), WUFFS_VERSION, 0);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400729 if (status != nullptr) {
Nigel Taoe39c8842019-02-27 15:57:34 +1100730 SkCodecPrintf("initialize: %s", status);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400731 return SkCodec::kInternalError;
732 }
733 while (true) {
Nigel Tao6447a1a2019-09-14 12:01:00 +1000734 status = decoder->decode_image_config(imgcfg, b);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400735 if (status == nullptr) {
Nigel Tao490e6472019-02-14 14:50:53 +1100736 break;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400737 } else if (status != wuffs_base__suspension__short_read) {
738 SkCodecPrintf("decode_image_config: %s", status);
739 return SkCodec::kErrorInInput;
740 } else if (!fill_buffer(b, s)) {
741 return SkCodec::kIncompleteInput;
742 }
743 }
Nigel Tao490e6472019-02-14 14:50:53 +1100744
745 // A GIF image's natural color model is indexed color: 1 byte per pixel,
746 // indexing a 256-element palette.
747 //
748 // For Skia, we override that to decode to 4 bytes per pixel, BGRA or RGBA.
749 wuffs_base__pixel_format pixfmt = 0;
750 switch (kN32_SkColorType) {
751 case kBGRA_8888_SkColorType:
752 pixfmt = WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL;
753 break;
754 case kRGBA_8888_SkColorType:
755 pixfmt = WUFFS_BASE__PIXEL_FORMAT__RGBA_NONPREMUL;
756 break;
757 default:
758 return SkCodec::kInternalError;
759 }
Leon Scroggins III587edab2019-03-22 15:42:19 -0400760 if (imgcfg) {
761 imgcfg->pixcfg.set(pixfmt, WUFFS_BASE__PIXEL_SUBSAMPLING__NONE, imgcfg->pixcfg.width(),
762 imgcfg->pixcfg.height());
763 }
Nigel Tao490e6472019-02-14 14:50:53 +1100764
765 return SkCodec::kSuccess;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400766}
767
Nigel Tao2777cd32019-10-29 11:10:25 +1100768SkCodec::Result SkWuffsCodec::resetDecoder(WhichDecoder which) {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400769 if (!fStream->rewind()) {
770 return SkCodec::kInternalError;
771 }
Nigel Tao96c10a02019-09-25 11:08:42 +1000772 fIOBuffer.meta = wuffs_base__empty_io_buffer_meta();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400773
774 SkCodec::Result result =
Nigel Tao2777cd32019-10-29 11:10:25 +1100775 reset_and_decode_image_config(fDecoders[which].get(), nullptr, &fIOBuffer, fStream.get());
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400776 if (result == SkCodec::kIncompleteInput) {
777 return SkCodec::kInternalError;
778 } else if (result != SkCodec::kSuccess) {
779 return result;
780 }
781
Nigel Tao2777cd32019-10-29 11:10:25 +1100782 fDecoderIsSuspended[which] = false;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400783 return SkCodec::kSuccess;
784}
785
Nigel Tao2777cd32019-10-29 11:10:25 +1100786const char* SkWuffsCodec::decodeFrameConfig(WhichDecoder which) {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400787 while (true) {
Nigel Tao48aa2212019-03-09 14:59:11 +1100788 const char* status =
Nigel Tao2777cd32019-10-29 11:10:25 +1100789 fDecoders[which]->decode_frame_config(&fFrameConfigs[which], &fIOBuffer);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400790 if ((status == wuffs_base__suspension__short_read) &&
791 fill_buffer(&fIOBuffer, fStream.get())) {
792 continue;
793 }
Nigel Tao2777cd32019-10-29 11:10:25 +1100794 fDecoderIsSuspended[which] = !wuffs_base__status__is_complete(status);
795 this->updateNumFullyReceivedFrames(which);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400796 return status;
797 }
798}
799
Nigel Tao2777cd32019-10-29 11:10:25 +1100800const char* SkWuffsCodec::decodeFrame(WhichDecoder which) {
801 while (true) {
802 const char* status = fDecoders[which]->decode_frame(
803 &fPixelBuffer, &fIOBuffer, wuffs_base__make_slice_u8(fWorkbufPtr.get(), fWorkbufLen),
804 NULL);
805 if ((status == wuffs_base__suspension__short_read) &&
806 fill_buffer(&fIOBuffer, fStream.get())) {
807 continue;
808 }
809 fDecoderIsSuspended[which] = !wuffs_base__status__is_complete(status);
810 this->updateNumFullyReceivedFrames(which);
811 return status;
812 }
813}
814
815void SkWuffsCodec::updateNumFullyReceivedFrames(WhichDecoder which) {
Nigel Tao6af1edc2019-01-19 15:12:39 +1100816 // num_decoded_frames's return value, n, can change over time, both up and
817 // down, as we seek back and forth in the underlying stream.
818 // fNumFullyReceivedFrames is the highest n we've seen.
Nigel Tao2777cd32019-10-29 11:10:25 +1100819 uint64_t n = fDecoders[which]->num_decoded_frames();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400820 if (fNumFullyReceivedFrames < n) {
821 fNumFullyReceivedFrames = n;
822 }
823}
824
825// -------------------------------- SkWuffsCodec.h functions
826
827bool SkWuffsCodec_IsFormat(const void* buf, size_t bytesRead) {
828 constexpr const char* gif_ptr = "GIF8";
829 constexpr size_t gif_len = 4;
830 return (bytesRead >= gif_len) && (memcmp(buf, gif_ptr, gif_len) == 0);
831}
832
833std::unique_ptr<SkCodec> SkWuffsCodec_MakeFromStream(std::unique_ptr<SkStream> stream,
834 SkCodec::Result* result) {
Nigel Tao48aa2212019-03-09 14:59:11 +1100835 uint8_t buffer[SK_WUFFS_CODEC_BUFFER_SIZE];
836 wuffs_base__io_buffer iobuf =
837 wuffs_base__make_io_buffer(wuffs_base__make_slice_u8(buffer, SK_WUFFS_CODEC_BUFFER_SIZE),
Nigel Tao96c10a02019-09-25 11:08:42 +1000838 wuffs_base__empty_io_buffer_meta());
Nigel Tao48aa2212019-03-09 14:59:11 +1100839 wuffs_base__image_config imgcfg = wuffs_base__null_image_config();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400840
841 // Wuffs is primarily a C library, not a C++ one. Furthermore, outside of
842 // the wuffs_base__etc types, the sizeof a file format specific type like
843 // GIF's wuffs_gif__decoder can vary between Wuffs versions. If p is of
844 // type wuffs_gif__decoder*, then the supported API treats p as a pointer
845 // to an opaque type: a private implementation detail. The API is always
846 // "set_foo(p, etc)" and not "p->foo = etc".
847 //
848 // See https://en.wikipedia.org/wiki/Opaque_pointer#C
849 //
850 // Thus, we don't use C++'s new operator (which requires knowing the sizeof
851 // the struct at compile time). Instead, we use sk_malloc_canfail, with
852 // sizeof__wuffs_gif__decoder returning the appropriate value for the
853 // (statically or dynamically) linked version of the Wuffs library.
854 //
855 // As a C (not C++) library, none of the Wuffs types have constructors or
856 // destructors.
857 //
858 // In RAII style, we can still use std::unique_ptr with these pointers, but
859 // we pair the pointer with sk_free instead of C++'s delete.
860 void* decoder_raw = sk_malloc_canfail(sizeof__wuffs_gif__decoder());
861 if (!decoder_raw) {
862 *result = SkCodec::kInternalError;
863 return nullptr;
864 }
865 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> decoder(
866 reinterpret_cast<wuffs_gif__decoder*>(decoder_raw), &sk_free);
867
868 SkCodec::Result reset_result =
869 reset_and_decode_image_config(decoder.get(), &imgcfg, &iobuf, stream.get());
870 if (reset_result != SkCodec::kSuccess) {
871 *result = reset_result;
872 return nullptr;
873 }
874
875 uint32_t width = imgcfg.pixcfg.width();
876 uint32_t height = imgcfg.pixcfg.height();
877 if ((width == 0) || (width > INT_MAX) || (height == 0) || (height > INT_MAX)) {
878 *result = SkCodec::kInvalidInput;
879 return nullptr;
880 }
881
Nigel Tao6af1edc2019-01-19 15:12:39 +1100882 uint64_t workbuf_len = decoder->workbuf_len().max_incl;
Nigel Tao22e86242019-01-26 16:04:01 +1100883 void* workbuf_ptr_raw = nullptr;
884 if (workbuf_len) {
885 workbuf_ptr_raw = workbuf_len <= SIZE_MAX ? sk_malloc_canfail(workbuf_len) : nullptr;
886 if (!workbuf_ptr_raw) {
887 *result = SkCodec::kInternalError;
888 return nullptr;
889 }
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400890 }
891 std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr(
892 reinterpret_cast<uint8_t*>(workbuf_ptr_raw), &sk_free);
893
894 uint64_t pixbuf_len = imgcfg.pixcfg.pixbuf_len();
895 void* pixbuf_ptr_raw = pixbuf_len <= SIZE_MAX ? sk_malloc_canfail(pixbuf_len) : nullptr;
896 if (!pixbuf_ptr_raw) {
897 *result = SkCodec::kInternalError;
898 return nullptr;
899 }
900 std::unique_ptr<uint8_t, decltype(&sk_free)> pixbuf_ptr(
901 reinterpret_cast<uint8_t*>(pixbuf_ptr_raw), &sk_free);
Nigel Tao48aa2212019-03-09 14:59:11 +1100902 wuffs_base__pixel_buffer pixbuf = wuffs_base__null_pixel_buffer();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400903
Nigel Tao48aa2212019-03-09 14:59:11 +1100904 const char* status = pixbuf.set_from_slice(
905 &imgcfg.pixcfg, wuffs_base__make_slice_u8(pixbuf_ptr.get(), SkToSizeT(pixbuf_len)));
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400906 if (status != nullptr) {
907 SkCodecPrintf("set_from_slice: %s", status);
908 *result = SkCodec::kInternalError;
909 return nullptr;
910 }
911
Nigel Tao490e6472019-02-14 14:50:53 +1100912 SkEncodedInfo::Color color =
913 (imgcfg.pixcfg.pixel_format() == WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL)
914 ? SkEncodedInfo::kBGRA_Color
915 : SkEncodedInfo::kRGBA_Color;
916
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400917 // In Skia's API, the alpha we calculate here and return is only for the
918 // first frame.
919 SkEncodedInfo::Alpha alpha = imgcfg.first_frame_is_opaque() ? SkEncodedInfo::kOpaque_Alpha
920 : SkEncodedInfo::kBinary_Alpha;
921
Nigel Tao490e6472019-02-14 14:50:53 +1100922 SkEncodedInfo encodedInfo = SkEncodedInfo::Make(width, height, color, alpha, 8);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400923
924 *result = SkCodec::kSuccess;
925 return std::unique_ptr<SkCodec>(new SkWuffsCodec(
926 std::move(encodedInfo), std::move(stream), std::move(decoder), std::move(pixbuf_ptr),
927 std::move(workbuf_ptr), workbuf_len, imgcfg, pixbuf, iobuf));
928}