blob: ac62b20efd77da2f8bacd9203de33898ccbbe356 [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 Tao4f32a292019-11-13 15:41:55 +110086static SkAlphaType to_alpha_type(bool opaque) {
87 return opaque ? kOpaque_SkAlphaType : kPremul_SkAlphaType;
88}
89
Nigel Tao2777cd32019-10-29 11:10:25 +110090static SkCodec::Result reset_and_decode_image_config(wuffs_gif__decoder* decoder,
91 wuffs_base__image_config* imgcfg,
92 wuffs_base__io_buffer* b,
Nigel Tao4f32a292019-11-13 15:41:55 +110093 SkStream* s) {
94 // Calling decoder->initialize will memset it to zero.
95 const char* status = decoder->initialize(sizeof__wuffs_gif__decoder(), WUFFS_VERSION, 0);
96 if (status != nullptr) {
97 SkCodecPrintf("initialize: %s", status);
98 return SkCodec::kInternalError;
99 }
100 while (true) {
101 status = decoder->decode_image_config(imgcfg, b);
102 if (status == nullptr) {
103 break;
104 } else if (status != wuffs_base__suspension__short_read) {
105 SkCodecPrintf("decode_image_config: %s", status);
106 return SkCodec::kErrorInInput;
107 } else if (!fill_buffer(b, s)) {
108 return SkCodec::kIncompleteInput;
109 }
110 }
111
112 // A GIF image's natural color model is indexed color: 1 byte per pixel,
113 // indexing a 256-element palette.
114 //
115 // For Skia, we override that to decode to 4 bytes per pixel, BGRA or RGBA.
116 wuffs_base__pixel_format pixfmt = 0;
117 switch (kN32_SkColorType) {
118 case kBGRA_8888_SkColorType:
119 pixfmt = WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL;
120 break;
121 case kRGBA_8888_SkColorType:
122 pixfmt = WUFFS_BASE__PIXEL_FORMAT__RGBA_NONPREMUL;
123 break;
124 default:
125 return SkCodec::kInternalError;
126 }
127 if (imgcfg) {
128 imgcfg->pixcfg.set(pixfmt, WUFFS_BASE__PIXEL_SUBSAMPLING__NONE, imgcfg->pixcfg.width(),
129 imgcfg->pixcfg.height());
130 }
131
132 return SkCodec::kSuccess;
133}
134
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400135// -------------------------------- Class definitions
136
137class SkWuffsCodec;
138
139class SkWuffsFrame final : public SkFrame {
140public:
141 SkWuffsFrame(wuffs_base__frame_config* fc);
142
143 SkCodec::FrameInfo frameInfo(bool fullyReceived) const;
144 uint64_t ioPosition() const;
145
146 // SkFrame overrides.
147 SkEncodedInfo::Alpha onReportedAlpha() const override;
148
149private:
150 uint64_t fIOPosition;
151 SkEncodedInfo::Alpha fReportedAlpha;
152
153 typedef SkFrame INHERITED;
154};
155
156// SkWuffsFrameHolder is a trivial indirector that forwards its calls onto a
157// SkWuffsCodec. It is a separate class as SkWuffsCodec would otherwise
158// inherit from both SkCodec and SkFrameHolder, and Skia style discourages
159// multiple inheritance (e.g. with its "typedef Foo INHERITED" convention).
160class SkWuffsFrameHolder final : public SkFrameHolder {
161public:
162 SkWuffsFrameHolder() : INHERITED() {}
163
164 void init(SkWuffsCodec* codec, int width, int height);
165
166 // SkFrameHolder overrides.
167 const SkFrame* onGetFrame(int i) const override;
168
169private:
170 const SkWuffsCodec* fCodec;
171
172 typedef SkFrameHolder INHERITED;
173};
174
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400175class SkWuffsCodec final : public SkScalingCodec {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400176public:
177 SkWuffsCodec(SkEncodedInfo&& encodedInfo,
178 std::unique_ptr<SkStream> stream,
179 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> dec,
180 std::unique_ptr<uint8_t, decltype(&sk_free)> pixbuf_ptr,
Nigel Tao39da10b2019-11-15 15:27:44 +1100181 bool pixbuf_zeroed,
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400182 std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr,
183 size_t workbuf_len,
184 wuffs_base__image_config imgcfg,
185 wuffs_base__pixel_buffer pixbuf,
186 wuffs_base__io_buffer iobuf);
187
188 const SkWuffsFrame* frame(int i) const;
189
190private:
Nigel Tao2777cd32019-10-29 11:10:25 +1100191 // It is valid, in terms of the SkCodec API, to call SkCodec::getFrameCount
192 // while in an incremental decode (after onStartIncrementalDecode returns
193 // and before the rest of the image is decoded). Some Skia users expect
194 // getFrameCount to increase, and the SkStream to advance, when given more
195 // data.
196 //
197 // On the other hand, while in an incremental decode, the underlying Wuffs
198 // object is suspended in a coroutine. To keep its internal proof-of-safety
199 // invariants consistent, there's only two things you can safely do with a
200 // suspended Wuffs object: resume the coroutine, or reset all state (memset
201 // to zero and start again).
202 //
203 // The Wuffs API provides a limited, optional form of seeking, to the start
204 // of an animation frame's data, but does not provide arbitrary save and
205 // load of its internal state whilst in the middle of an animation frame.
206 //
207 // SkWuffsCodec therefore uses two Wuffs decoders: a primary decoder
208 // (kIncrDecode) to support startIncrementalDecode / incrementalDecode, and
209 // a secondary decoder (kFrameCount) to support getFrameCount. The two
210 // decoders' states can change independently.
211 //
212 // As of Wuffs version 0.2, both of these decoders have the same type. A
213 // future Wuffs version might let us use a different type for kFrameCount,
214 // one that is much lighter weight (in terms of memory requirements), as it
215 // doesn't have to handle decompressing pixel data.
216 enum WhichDecoder {
217 kIncrDecode,
218 kFrameCount,
219 kNumDecoders,
220 };
221
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400222 // SkCodec overrides.
223 SkEncodedImageFormat onGetEncodedFormat() const override;
224 Result onGetPixels(const SkImageInfo&, void*, size_t, const Options&, int*) override;
225 const SkFrameHolder* getFrameHolder() const override;
226 Result onStartIncrementalDecode(const SkImageInfo& dstInfo,
227 void* dst,
228 size_t rowBytes,
229 const SkCodec::Options& options) override;
230 Result onIncrementalDecode(int* rowsDecoded) override;
231 int onGetFrameCount() override;
232 bool onGetFrameInfo(int, FrameInfo*) const override;
233 int onGetRepetitionCount() override;
234
Nigel Tao2777cd32019-10-29 11:10:25 +1100235 Result seekFrame(WhichDecoder which, int frameIndex);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400236
Nigel Tao2777cd32019-10-29 11:10:25 +1100237 void onGetFrameCountInternal();
238 Result onIncrementalDecodeInternal(int* rowsDecoded);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400239
Nigel Tao2777cd32019-10-29 11:10:25 +1100240 Result resetDecoder(WhichDecoder which);
241 const char* decodeFrameConfig(WhichDecoder which);
242 const char* decodeFrame(WhichDecoder which);
243 void updateNumFullyReceivedFrames(WhichDecoder which);
244
245 SkWuffsFrameHolder fFrameHolder;
246 std::unique_ptr<SkStream> fStream;
247 std::unique_ptr<uint8_t, decltype(&sk_free)> fPixbufPtr;
248 std::unique_ptr<uint8_t, decltype(&sk_free)> fWorkbufPtr;
249 size_t fWorkbufLen;
250
251 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> fDecoders[WhichDecoder::kNumDecoders];
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400252
253 const uint64_t fFirstFrameIOPosition;
Nigel Tao2777cd32019-10-29 11:10:25 +1100254 wuffs_base__frame_config fFrameConfigs[WhichDecoder::kNumDecoders];
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400255 wuffs_base__pixel_buffer fPixelBuffer;
256 wuffs_base__io_buffer fIOBuffer;
257
258 // Incremental decoding state.
Nigel Tao0185b952018-11-08 10:47:24 +1100259 uint8_t* fIncrDecDst;
Nigel Tao2777cd32019-10-29 11:10:25 +1100260 uint64_t fIncrDecReaderIOPosition;
Nigel Tao0185b952018-11-08 10:47:24 +1100261 size_t fIncrDecRowBytes;
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400262 bool fFirstCallToIncrementalDecode;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400263
Nigel Tao3876a9f2019-11-14 09:04:45 +1100264 uint64_t fFrameCountReaderIOPosition;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400265 uint64_t fNumFullyReceivedFrames;
266 std::vector<SkWuffsFrame> fFrames;
267 bool fFramesComplete;
268
Nigel Tao39da10b2019-11-15 15:27:44 +1100269 // True if fPixelBuffer's contents are known to be already zeroed. This is
270 // conservative, and may be false even if the buffer is zeroed.
271 bool fPixbufZeroed;
272
Nigel Tao2777cd32019-10-29 11:10:25 +1100273 // If calling an fDecoders[which] method returns an incomplete status, then
274 // fDecoders[which] is suspended in a coroutine (i.e. waiting on I/O or
275 // halted on a non-recoverable error). To keep its internal proof-of-safety
276 // invariants consistent, there's only two things you can safely do with a
277 // suspended Wuffs object: resume the coroutine, or reset all state (memset
278 // to zero and start again).
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400279 //
Nigel Tao2777cd32019-10-29 11:10:25 +1100280 // If fDecoderIsSuspended[which], and we aren't sure that we're going to
281 // resume the coroutine, then we will need to call this->resetDecoder
282 // before calling other fDecoders[which] methods.
283 bool fDecoderIsSuspended[WhichDecoder::kNumDecoders];
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400284
285 uint8_t fBuffer[SK_WUFFS_CODEC_BUFFER_SIZE];
286
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400287 typedef SkScalingCodec INHERITED;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400288};
289
290// -------------------------------- SkWuffsFrame implementation
291
292SkWuffsFrame::SkWuffsFrame(wuffs_base__frame_config* fc)
293 : INHERITED(fc->index()),
294 fIOPosition(fc->io_position()),
295 fReportedAlpha(wuffs_blend_to_skia_alpha(fc->blend())) {
296 wuffs_base__rect_ie_u32 r = fc->bounds();
297 this->setXYWH(r.min_incl_x, r.min_incl_y, r.width(), r.height());
298 this->setDisposalMethod(wuffs_disposal_to_skia_disposal(fc->disposal()));
299 this->setDuration(fc->duration() / WUFFS_BASE__FLICKS_PER_MILLISECOND);
300 this->setBlend(wuffs_blend_to_skia_blend(fc->blend()));
301}
302
303SkCodec::FrameInfo SkWuffsFrame::frameInfo(bool fullyReceived) const {
Nigel Taoef40e332019-04-05 10:28:40 +1100304 SkCodec::FrameInfo ret;
305 ret.fRequiredFrame = getRequiredFrame();
306 ret.fDuration = getDuration();
307 ret.fFullyReceived = fullyReceived;
308 ret.fAlphaType = hasAlpha() ? kUnpremul_SkAlphaType : kOpaque_SkAlphaType;
309 ret.fDisposalMethod = getDisposalMethod();
310 return ret;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400311}
312
313uint64_t SkWuffsFrame::ioPosition() const {
314 return fIOPosition;
315}
316
317SkEncodedInfo::Alpha SkWuffsFrame::onReportedAlpha() const {
318 return fReportedAlpha;
319}
320
321// -------------------------------- SkWuffsFrameHolder implementation
322
323void SkWuffsFrameHolder::init(SkWuffsCodec* codec, int width, int height) {
324 fCodec = codec;
325 // Initialize SkFrameHolder's (the superclass) fields.
326 fScreenWidth = width;
327 fScreenHeight = height;
328}
329
330const SkFrame* SkWuffsFrameHolder::onGetFrame(int i) const {
331 return fCodec->frame(i);
332};
333
334// -------------------------------- SkWuffsCodec implementation
335
336SkWuffsCodec::SkWuffsCodec(SkEncodedInfo&& encodedInfo,
337 std::unique_ptr<SkStream> stream,
338 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> dec,
339 std::unique_ptr<uint8_t, decltype(&sk_free)> pixbuf_ptr,
Nigel Tao39da10b2019-11-15 15:27:44 +1100340 bool pixbuf_zeroed,
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400341 std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr,
342 size_t workbuf_len,
343 wuffs_base__image_config imgcfg,
344 wuffs_base__pixel_buffer pixbuf,
345 wuffs_base__io_buffer iobuf)
346 : INHERITED(std::move(encodedInfo),
347 skcms_PixelFormat_RGBA_8888,
348 // Pass a nullptr SkStream to the SkCodec constructor. We
349 // manage the stream ourselves, as the default SkCodec behavior
350 // is too trigger-happy on rewinding the stream.
351 nullptr),
Nigel Tao0185b952018-11-08 10:47:24 +1100352 fFrameHolder(),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400353 fStream(std::move(stream)),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400354 fPixbufPtr(std::move(pixbuf_ptr)),
355 fWorkbufPtr(std::move(workbuf_ptr)),
356 fWorkbufLen(workbuf_len),
Nigel Tao2777cd32019-10-29 11:10:25 +1100357 fDecoders{
358 std::move(dec),
359 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)>(nullptr, sk_free),
360 },
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400361 fFirstFrameIOPosition(imgcfg.first_frame_io_position()),
Nigel Tao2777cd32019-10-29 11:10:25 +1100362 fFrameConfigs{
363 wuffs_base__null_frame_config(),
364 wuffs_base__null_frame_config(),
365 },
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400366 fPixelBuffer(pixbuf),
Nigel Tao96c10a02019-09-25 11:08:42 +1000367 fIOBuffer(wuffs_base__empty_io_buffer()),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400368 fIncrDecDst(nullptr),
Nigel Tao2777cd32019-10-29 11:10:25 +1100369 fIncrDecReaderIOPosition(0),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400370 fIncrDecRowBytes(0),
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400371 fFirstCallToIncrementalDecode(false),
Nigel Tao3876a9f2019-11-14 09:04:45 +1100372 fFrameCountReaderIOPosition(0),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400373 fNumFullyReceivedFrames(0),
374 fFramesComplete(false),
Nigel Tao39da10b2019-11-15 15:27:44 +1100375 fPixbufZeroed(pixbuf_zeroed),
Nigel Tao2777cd32019-10-29 11:10:25 +1100376 fDecoderIsSuspended{
377 false,
378 false,
379 } {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400380 fFrameHolder.init(this, imgcfg.pixcfg.width(), imgcfg.pixcfg.height());
381
382 // Initialize fIOBuffer's fields, copying any outstanding data from iobuf to
383 // fIOBuffer, as iobuf's backing array may not be valid for the lifetime of
384 // this SkWuffsCodec object, but fIOBuffer's backing array (fBuffer) is.
385 SkASSERT(iobuf.data.len == SK_WUFFS_CODEC_BUFFER_SIZE);
386 memmove(fBuffer, iobuf.data.ptr, iobuf.meta.wi);
Nigel Tao48aa2212019-03-09 14:59:11 +1100387 fIOBuffer.data = wuffs_base__make_slice_u8(fBuffer, SK_WUFFS_CODEC_BUFFER_SIZE);
388 fIOBuffer.meta = iobuf.meta;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400389}
390
391const SkWuffsFrame* SkWuffsCodec::frame(int i) const {
392 if ((0 <= i) && (static_cast<size_t>(i) < fFrames.size())) {
393 return &fFrames[i];
394 }
395 return nullptr;
396}
397
398SkEncodedImageFormat SkWuffsCodec::onGetEncodedFormat() const {
399 return SkEncodedImageFormat::kGIF;
400}
401
402SkCodec::Result SkWuffsCodec::onGetPixels(const SkImageInfo& dstInfo,
403 void* dst,
404 size_t rowBytes,
405 const Options& options,
406 int* rowsDecoded) {
407 SkCodec::Result result = this->onStartIncrementalDecode(dstInfo, dst, rowBytes, options);
408 if (result != kSuccess) {
409 return result;
410 }
411 return this->onIncrementalDecode(rowsDecoded);
412}
413
414const SkFrameHolder* SkWuffsCodec::getFrameHolder() const {
415 return &fFrameHolder;
416}
417
418SkCodec::Result SkWuffsCodec::onStartIncrementalDecode(const SkImageInfo& dstInfo,
419 void* dst,
420 size_t rowBytes,
421 const SkCodec::Options& options) {
Nigel Tao1f1cd1f2019-06-22 17:35:38 +1000422 if (!dst) {
423 return SkCodec::kInvalidParameters;
424 }
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400425 if (options.fSubset) {
426 return SkCodec::kUnimplemented;
427 }
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400428 if (options.fFrameIndex > 0 && SkColorTypeIsAlwaysOpaque(dstInfo.colorType())) {
429 return SkCodec::kInvalidConversion;
430 }
Nigel Tao2777cd32019-10-29 11:10:25 +1100431 SkCodec::Result result = this->seekFrame(WhichDecoder::kIncrDecode, options.fFrameIndex);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400432 if (result != SkCodec::kSuccess) {
433 return result;
434 }
435
Nigel Tao2777cd32019-10-29 11:10:25 +1100436 const char* status = this->decodeFrameConfig(WhichDecoder::kIncrDecode);
Nigel Taob7a1b512019-02-10 12:19:50 +1100437 if (status == wuffs_base__suspension__short_read) {
Leon Scroggins IIIcb6b8842018-12-04 13:55:13 -0500438 return SkCodec::kIncompleteInput;
Nigel Taob7a1b512019-02-10 12:19:50 +1100439 } else if (status != nullptr) {
Leon Scroggins IIIcb6b8842018-12-04 13:55:13 -0500440 SkCodecPrintf("decodeFrameConfig: %s", status);
441 return SkCodec::kErrorInInput;
442 }
Nigel Taob7a1b512019-02-10 12:19:50 +1100443
Nigel Tao490e6472019-02-14 14:50:53 +1100444 uint32_t src_bits_per_pixel =
445 wuffs_base__pixel_format__bits_per_pixel(fPixelBuffer.pixcfg.pixel_format());
446 if ((src_bits_per_pixel == 0) || (src_bits_per_pixel % 8 != 0)) {
447 return SkCodec::kInternalError;
448 }
449 size_t src_bytes_per_pixel = src_bits_per_pixel / 8;
Nigel Taob7a1b512019-02-10 12:19:50 +1100450
451 // Zero-initialize Wuffs' buffer covering the frame rect.
Nigel Tao39da10b2019-11-15 15:27:44 +1100452 if (!fPixbufZeroed) {
453 wuffs_base__rect_ie_u32 frame_rect = fFrameConfigs[WhichDecoder::kIncrDecode].bounds();
454 wuffs_base__table_u8 pixels = fPixelBuffer.plane(0);
Nigel Tao6ec1b392019-11-20 12:28:50 +1100455
456 uint8_t* ptr = pixels.ptr + (frame_rect.min_incl_y * pixels.stride) +
457 (frame_rect.min_incl_x * src_bytes_per_pixel);
458 size_t len = frame_rect.width() * src_bytes_per_pixel;
459
460 // As an optimization, issue a single sk_bzero call, if possible.
461 // Otherwise, zero out each row separately.
462 if ((len == pixels.stride) && (frame_rect.min_incl_y < frame_rect.max_excl_y)) {
463 sk_bzero(ptr, len * (frame_rect.max_excl_y - frame_rect.min_incl_y));
464 } else {
465 for (uint32_t y = frame_rect.min_incl_y; y < frame_rect.max_excl_y; y++) {
466 sk_bzero(ptr, len);
467 ptr += pixels.stride;
468 }
Nigel Tao39da10b2019-11-15 15:27:44 +1100469 }
Nigel Taob7a1b512019-02-10 12:19:50 +1100470 }
Nigel Tao39da10b2019-11-15 15:27:44 +1100471 // The buffer is zeroed now, but this onStartIncrementalDecode call will
472 // almost certainly be followed by some onIncrementalDecode calls that can
473 // modify fPixelBuffer's contents. We set fPixbufZeroed to false so that
474 // the next onStartIncrementalDecode call will zero-initialize the buffer.
475 fPixbufZeroed = false;
Nigel Taob7a1b512019-02-10 12:19:50 +1100476
477 fIncrDecDst = static_cast<uint8_t*>(dst);
Nigel Tao2777cd32019-10-29 11:10:25 +1100478 fIncrDecReaderIOPosition = fIOBuffer.reader_io_position();
Nigel Taob7a1b512019-02-10 12:19:50 +1100479 fIncrDecRowBytes = rowBytes;
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400480 fFirstCallToIncrementalDecode = true;
Nigel Taob7a1b512019-02-10 12:19:50 +1100481 return SkCodec::kSuccess;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400482}
483
484SkCodec::Result SkWuffsCodec::onIncrementalDecode(int* rowsDecoded) {
485 if (!fIncrDecDst) {
486 return SkCodec::kInternalError;
487 }
488
Nigel Tao2777cd32019-10-29 11:10:25 +1100489 // If multiple SkCodec::incrementalDecode calls are made consecutively (or
490 // if SkCodec::incrementalDecode is called immediately after
491 // SkCodec::startIncrementalDecode), then this seek should be a no-op.
492 // However, it is possible to interleave SkCodec::getFrameCount calls in
493 // between SkCodec::incrementalDecode calls, and those other calls may
494 // advance the stream. This seek restores the stream to where the last
495 // SkCodec::startIncrementalDecode or SkCodec::incrementalDecode stopped.
496 if (!seek_buffer(&fIOBuffer, fStream.get(), fIncrDecReaderIOPosition)) {
497 return SkCodec::kInternalError;
498 }
499
500 SkCodec::Result result = this->onIncrementalDecodeInternal(rowsDecoded);
501 if (result == SkCodec::kSuccess) {
502 fIncrDecDst = nullptr;
503 fIncrDecReaderIOPosition = 0;
504 fIncrDecRowBytes = 0;
505 } else {
506 fIncrDecReaderIOPosition = fIOBuffer.reader_io_position();
507 }
508 return result;
509}
510
511SkCodec::Result SkWuffsCodec::onIncrementalDecodeInternal(int* rowsDecoded) {
Leon Scroggins III699d41e2019-02-07 09:25:51 -0500512 SkCodec::Result result = SkCodec::kSuccess;
Nigel Tao2777cd32019-10-29 11:10:25 +1100513 const char* status = this->decodeFrame(WhichDecoder::kIncrDecode);
514 bool independent;
515 SkAlphaType alphaType;
516 const int index = options().fFrameIndex;
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400517 if (index == 0) {
518 independent = true;
519 alphaType = to_alpha_type(getEncodedInfo().opaque());
520 } else {
521 const SkWuffsFrame* f = this->frame(index);
522 independent = f->getRequiredFrame() == SkCodec::kNoFrame;
523 alphaType = to_alpha_type(f->reportedAlpha() == SkEncodedInfo::kOpaque_Alpha);
524 }
Leon Scroggins III699d41e2019-02-07 09:25:51 -0500525 if (status != nullptr) {
526 if (status == wuffs_base__suspension__short_read) {
527 result = SkCodec::kIncompleteInput;
528 } else {
529 SkCodecPrintf("decodeFrame: %s", status);
530 result = SkCodec::kErrorInInput;
531 }
532
533 if (!independent) {
534 // For a dependent frame, we cannot blend the partial result, since
535 // that will overwrite the contribution from prior frames.
536 return result;
537 }
538 }
539
Nigel Tao490e6472019-02-14 14:50:53 +1100540 uint32_t src_bits_per_pixel =
541 wuffs_base__pixel_format__bits_per_pixel(fPixelBuffer.pixcfg.pixel_format());
542 if ((src_bits_per_pixel == 0) || (src_bits_per_pixel % 8 != 0)) {
543 return SkCodec::kInternalError;
544 }
545 size_t src_bytes_per_pixel = src_bits_per_pixel / 8;
546
Nigel Tao2777cd32019-10-29 11:10:25 +1100547 wuffs_base__rect_ie_u32 frame_rect = fFrameConfigs[WhichDecoder::kIncrDecode].bounds();
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400548 if (fFirstCallToIncrementalDecode) {
Nigel Tao490e6472019-02-14 14:50:53 +1100549 if (frame_rect.width() > (SIZE_MAX / src_bytes_per_pixel)) {
550 return SkCodec::kInternalError;
551 }
552
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400553 auto bounds = SkIRect::MakeLTRB(frame_rect.min_incl_x, frame_rect.min_incl_y,
554 frame_rect.max_excl_x, frame_rect.max_excl_y);
555
Leon Scroggins IIIcb6b8842018-12-04 13:55:13 -0500556 // If the frame rect does not fill the output, ensure that those pixels are not
Nigel Taob7a1b512019-02-10 12:19:50 +1100557 // left uninitialized.
Leon Scroggins III44076362019-02-15 13:56:44 -0500558 if (independent && (bounds != this->bounds() || result != kSuccess)) {
Nigel Tao2777cd32019-10-29 11:10:25 +1100559 SkSampler::Fill(dstInfo(), fIncrDecDst, fIncrDecRowBytes, options().fZeroInitialized);
Leon Scroggins III9b0ba2c2018-11-19 14:52:37 -0500560 }
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400561 fFirstCallToIncrementalDecode = false;
562 } else {
563 // Existing clients intend to only show frames beyond the first if they
564 // are complete (based on FrameInfo::fFullyReceived), since it might
565 // look jarring to draw a partial frame over an existing frame. If they
566 // changed their behavior and expected to continue decoding a partial
567 // frame after the first one, we'll need to update our blending code.
568 // Otherwise, if the frame were interlaced and not independent, the
569 // second pass may have an overlapping dirty_rect with the first,
570 // resulting in blending with the first pass.
571 SkASSERT(index == 0);
Nigel Tao9859ef82019-02-13 13:20:02 +1100572 }
Nigel Tao0185b952018-11-08 10:47:24 +1100573
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400574 if (rowsDecoded) {
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400575 *rowsDecoded = dstInfo().height();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400576 }
577
Leon Scroggins IIIdad4bfc2018-12-10 12:37:10 -0500578 // If the frame's dirty rect is empty, no need to swizzle.
Nigel Tao2777cd32019-10-29 11:10:25 +1100579 wuffs_base__rect_ie_u32 dirty_rect = fDecoders[WhichDecoder::kIncrDecode]->frame_dirty_rect();
Leon Scroggins IIIdad4bfc2018-12-10 12:37:10 -0500580 if (!dirty_rect.is_empty()) {
Nigel Tao490e6472019-02-14 14:50:53 +1100581 wuffs_base__table_u8 pixels = fPixelBuffer.plane(0);
Leon Scroggins III7a3805c2018-12-07 09:21:30 -0500582
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400583 // The Wuffs model is that the dst buffer is the image, not the frame.
584 // The expectation is that you allocate the buffer once, but re-use it
585 // for the N frames, regardless of each frame's top-left co-ordinate.
586 //
587 // To get from the start (in the X-direction) of the image to the start
588 // of the dirty_rect, we adjust s by (dirty_rect.min_incl_x * src_bytes_per_pixel).
Nigel Tao2777cd32019-10-29 11:10:25 +1100589 uint8_t* s = pixels.ptr + (dirty_rect.min_incl_y * pixels.stride) +
590 (dirty_rect.min_incl_x * src_bytes_per_pixel);
Leon Scroggins III7a3805c2018-12-07 09:21:30 -0500591
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400592 // Currently, this is only used for GIF, which will never have an ICC profile. When it is
593 // used for other formats that might have one, we will need to transform from profiles that
594 // do not have corresponding SkColorSpaces.
595 SkASSERT(!getEncodedInfo().profile());
596
Nigel Tao2777cd32019-10-29 11:10:25 +1100597 auto srcInfo =
598 getInfo().makeWH(dirty_rect.width(), dirty_rect.height()).makeAlphaType(alphaType);
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400599 SkBitmap src;
600 src.installPixels(srcInfo, s, pixels.stride);
601 SkPaint paint;
602 if (independent) {
603 paint.setBlendMode(SkBlendMode::kSrc);
Leon Scroggins III7a3805c2018-12-07 09:21:30 -0500604 }
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400605
606 SkDraw draw;
607 draw.fDst.reset(dstInfo(), fIncrDecDst, fIncrDecRowBytes);
608 SkMatrix matrix = SkMatrix::MakeRectToRect(SkRect::Make(this->dimensions()),
609 SkRect::Make(this->dstInfo().dimensions()),
610 SkMatrix::kFill_ScaleToFit);
611 draw.fMatrix = &matrix;
612 SkRasterClip rc(SkIRect::MakeSize(this->dstInfo().dimensions()));
613 draw.fRC = &rc;
614
615 SkMatrix translate = SkMatrix::MakeTrans(dirty_rect.min_incl_x, dirty_rect.min_incl_y);
616 draw.drawBitmap(src, translate, nullptr, paint);
Leon Scroggins III7a3805c2018-12-07 09:21:30 -0500617 }
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400618 return result;
619}
620
621int SkWuffsCodec::onGetFrameCount() {
Nigel Tao3876a9f2019-11-14 09:04:45 +1100622 if (!fFramesComplete && seek_buffer(&fIOBuffer, fStream.get(), fFrameCountReaderIOPosition)) {
Nigel Tao2777cd32019-10-29 11:10:25 +1100623 this->onGetFrameCountInternal();
Nigel Tao3876a9f2019-11-14 09:04:45 +1100624 fFrameCountReaderIOPosition =
625 fDecoders[WhichDecoder::kFrameCount] ? fIOBuffer.reader_io_position() : 0;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400626 }
627 return fFrames.size();
628}
629
Nigel Tao2777cd32019-10-29 11:10:25 +1100630void SkWuffsCodec::onGetFrameCountInternal() {
Nigel Tao2777cd32019-10-29 11:10:25 +1100631 if (!fDecoders[WhichDecoder::kFrameCount]) {
632 void* decoder_raw = sk_malloc_canfail(sizeof__wuffs_gif__decoder());
633 if (!decoder_raw) {
634 return;
635 }
636 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> decoder(
637 reinterpret_cast<wuffs_gif__decoder*>(decoder_raw), &sk_free);
Nigel Tao3876a9f2019-11-14 09:04:45 +1100638 reset_and_decode_image_config(decoder.get(), nullptr, &fIOBuffer, fStream.get());
Nigel Tao2777cd32019-10-29 11:10:25 +1100639 fDecoders[WhichDecoder::kFrameCount] = std::move(decoder);
640 }
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400641
642 // Iterate through the frames, converting from Wuffs'
643 // wuffs_base__frame_config type to Skia's SkWuffsFrame type.
Nigel Tao3876a9f2019-11-14 09:04:45 +1100644 while (true) {
Nigel Tao2777cd32019-10-29 11:10:25 +1100645 const char* status = this->decodeFrameConfig(WhichDecoder::kFrameCount);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400646 if (status == nullptr) {
647 // No-op.
648 } else if (status == wuffs_base__warning__end_of_data) {
649 break;
650 } else {
651 return;
652 }
653
Nigel Tao3876a9f2019-11-14 09:04:45 +1100654 uint64_t i = fDecoders[WhichDecoder::kFrameCount]->num_decoded_frame_configs();
655 if (i > INT_MAX) {
656 break;
657 }
658 if ((i == 0) || (static_cast<size_t>(i - 1) != fFrames.size())) {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400659 continue;
660 }
Nigel Tao2777cd32019-10-29 11:10:25 +1100661 fFrames.emplace_back(&fFrameConfigs[WhichDecoder::kFrameCount]);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400662 SkWuffsFrame* f = &fFrames[fFrames.size() - 1];
663 fFrameHolder.setAlphaAndRequiredFrame(f);
664 }
665
666 fFramesComplete = true;
Nigel Tao5b271462019-11-12 21:02:20 +1100667
668 // We've seen the end of the animation. There'll be no more frames, so we
669 // no longer need the kFrameCount decoder. Releasing it earlier than the
670 // SkWuffsCodec destructor might help peak memory use.
671 fDecoders[WhichDecoder::kFrameCount].reset(nullptr);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400672}
673
Nigel Taocdc92382019-10-31 08:36:53 +1100674bool SkWuffsCodec::onGetFrameInfo(int i, SkCodec::FrameInfo* frameInfo) const {
675 const SkWuffsFrame* f = this->frame(i);
676 if (!f) {
677 return false;
678 }
679 if (frameInfo) {
680 *frameInfo = f->frameInfo(static_cast<uint64_t>(i) < this->fNumFullyReceivedFrames);
681 }
682 return true;
683}
684
685int SkWuffsCodec::onGetRepetitionCount() {
686 // Convert from Wuffs's loop count to Skia's repeat count. Wuffs' uint32_t
687 // number is how many times to play the loop. Skia's int number is how many
688 // times to play the loop *after the first play*. Wuffs and Skia use 0 and
689 // kRepetitionCountInfinite respectively to mean loop forever.
690 uint32_t n = fDecoders[WhichDecoder::kIncrDecode]->num_animation_loops();
691 if (n == 0) {
692 return SkCodec::kRepetitionCountInfinite;
693 }
694 n--;
695 return n < INT_MAX ? n : INT_MAX;
696}
697
Nigel Tao2777cd32019-10-29 11:10:25 +1100698SkCodec::Result SkWuffsCodec::seekFrame(WhichDecoder which, int frameIndex) {
699 if (fDecoderIsSuspended[which]) {
700 SkCodec::Result res = this->resetDecoder(which);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400701 if (res != SkCodec::kSuccess) {
702 return res;
703 }
704 }
705
706 uint64_t pos = 0;
707 if (frameIndex < 0) {
708 return SkCodec::kInternalError;
709 } else if (frameIndex == 0) {
710 pos = fFirstFrameIOPosition;
711 } else if (static_cast<size_t>(frameIndex) < fFrames.size()) {
712 pos = fFrames[frameIndex].ioPosition();
713 } else {
714 return SkCodec::kInternalError;
715 }
716
717 if (!seek_buffer(&fIOBuffer, fStream.get(), pos)) {
718 return SkCodec::kInternalError;
719 }
Nigel Tao2777cd32019-10-29 11:10:25 +1100720 const char* status =
721 fDecoders[which]->restart_frame(frameIndex, fIOBuffer.reader_io_position());
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400722 if (status != nullptr) {
723 return SkCodec::kInternalError;
724 }
725 return SkCodec::kSuccess;
726}
727
728// An overview of the Wuffs decoding API:
729//
730// An animated image (such as GIF) has an image header and then N frames. The
731// image header gives e.g. the overall image's width and height. Each frame
732// consists of a frame header (e.g. frame rectangle bounds, display duration)
733// and a payload (the pixels).
734//
735// In Wuffs terminology, there is one image config and then N pairs of
736// (frame_config, frame). To decode everything (without knowing N in advance)
737// sequentially:
738// - call wuffs_gif__decoder::decode_image_config
739// - while (true) {
740// - call wuffs_gif__decoder::decode_frame_config
741// - if that returned wuffs_base__warning__end_of_data, break
742// - call wuffs_gif__decoder::decode_frame
743// - }
744//
745// The first argument to each decode_foo method is the destination struct to
746// store the decoded information.
747//
748// For random (instead of sequential) access to an image's frames, call
749// wuffs_gif__decoder::restart_frame to prepare to decode the i'th frame.
750// Essentially, it restores the state to be at the top of the while loop above.
751// The wuffs_base__io_buffer's reader position will also need to be set at the
752// right point in the source data stream. The position for the i'th frame is
753// calculated by the i'th decode_frame_config call. You can only call
754// restart_frame after decode_image_config is called, explicitly or implicitly
755// (see below), as decoding a single frame might require for-all-frames
756// information like the overall image dimensions and the global palette.
757//
758// All of those decode_xxx calls are optional. For example, if
759// decode_image_config is not called, then the first decode_frame_config call
760// will implicitly parse and verify the image header, before parsing the first
761// frame's header. Similarly, you can call only decode_frame N times, without
762// calling decode_image_config or decode_frame_config, if you already know
763// metadata like N and each frame's rectangle bounds by some other means (e.g.
764// this is a first party, statically known image).
765//
766// Specifically, starting with an unknown (but re-windable) GIF image, if you
767// want to just find N (i.e. count the number of frames), you can loop calling
768// only the decode_frame_config method and avoid calling the more expensive
769// decode_frame method. In terms of the underlying GIF image format, this will
770// skip over the LZW-encoded pixel data, avoiding the costly LZW decompression.
771//
772// Those decode_xxx methods are also suspendible. They will return early (with
773// a status code that is_suspendible and therefore isn't is_complete) if there
774// isn't enough source data to complete the operation: an incremental decode.
775// Calling decode_xxx again with additional source data will resume the
776// previous operation, instead of starting a new operation. Calling decode_yyy
777// whilst decode_xxx is suspended will result in an error.
778//
779// Once an error is encountered, whether from invalid source data or from a
780// programming error such as calling decode_yyy while suspended in decode_xxx,
781// all subsequent calls will be no-ops that return an error. To reset the
782// decoder into something that does productive work, memset the entire struct
783// to zero, check the Wuffs version and then, in order to be able to call
784// restart_frame, call decode_image_config. The io_buffer and its associated
785// stream will also need to be rewound.
786
Nigel Tao2777cd32019-10-29 11:10:25 +1100787SkCodec::Result SkWuffsCodec::resetDecoder(WhichDecoder which) {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400788 if (!fStream->rewind()) {
789 return SkCodec::kInternalError;
790 }
Nigel Tao96c10a02019-09-25 11:08:42 +1000791 fIOBuffer.meta = wuffs_base__empty_io_buffer_meta();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400792
793 SkCodec::Result result =
Nigel Tao2777cd32019-10-29 11:10:25 +1100794 reset_and_decode_image_config(fDecoders[which].get(), nullptr, &fIOBuffer, fStream.get());
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400795 if (result == SkCodec::kIncompleteInput) {
796 return SkCodec::kInternalError;
797 } else if (result != SkCodec::kSuccess) {
798 return result;
799 }
800
Nigel Tao2777cd32019-10-29 11:10:25 +1100801 fDecoderIsSuspended[which] = false;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400802 return SkCodec::kSuccess;
803}
804
Nigel Tao2777cd32019-10-29 11:10:25 +1100805const char* SkWuffsCodec::decodeFrameConfig(WhichDecoder which) {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400806 while (true) {
Nigel Tao48aa2212019-03-09 14:59:11 +1100807 const char* status =
Nigel Tao2777cd32019-10-29 11:10:25 +1100808 fDecoders[which]->decode_frame_config(&fFrameConfigs[which], &fIOBuffer);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400809 if ((status == wuffs_base__suspension__short_read) &&
810 fill_buffer(&fIOBuffer, fStream.get())) {
811 continue;
812 }
Nigel Tao2777cd32019-10-29 11:10:25 +1100813 fDecoderIsSuspended[which] = !wuffs_base__status__is_complete(status);
814 this->updateNumFullyReceivedFrames(which);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400815 return status;
816 }
817}
818
Nigel Tao2777cd32019-10-29 11:10:25 +1100819const char* SkWuffsCodec::decodeFrame(WhichDecoder which) {
820 while (true) {
821 const char* status = fDecoders[which]->decode_frame(
822 &fPixelBuffer, &fIOBuffer, wuffs_base__make_slice_u8(fWorkbufPtr.get(), fWorkbufLen),
823 NULL);
824 if ((status == wuffs_base__suspension__short_read) &&
825 fill_buffer(&fIOBuffer, fStream.get())) {
826 continue;
827 }
828 fDecoderIsSuspended[which] = !wuffs_base__status__is_complete(status);
829 this->updateNumFullyReceivedFrames(which);
830 return status;
831 }
832}
833
834void SkWuffsCodec::updateNumFullyReceivedFrames(WhichDecoder which) {
Nigel Tao6af1edc2019-01-19 15:12:39 +1100835 // num_decoded_frames's return value, n, can change over time, both up and
836 // down, as we seek back and forth in the underlying stream.
837 // fNumFullyReceivedFrames is the highest n we've seen.
Nigel Tao2777cd32019-10-29 11:10:25 +1100838 uint64_t n = fDecoders[which]->num_decoded_frames();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400839 if (fNumFullyReceivedFrames < n) {
840 fNumFullyReceivedFrames = n;
841 }
842}
843
844// -------------------------------- SkWuffsCodec.h functions
845
846bool SkWuffsCodec_IsFormat(const void* buf, size_t bytesRead) {
847 constexpr const char* gif_ptr = "GIF8";
848 constexpr size_t gif_len = 4;
849 return (bytesRead >= gif_len) && (memcmp(buf, gif_ptr, gif_len) == 0);
850}
851
852std::unique_ptr<SkCodec> SkWuffsCodec_MakeFromStream(std::unique_ptr<SkStream> stream,
853 SkCodec::Result* result) {
Nigel Tao48aa2212019-03-09 14:59:11 +1100854 uint8_t buffer[SK_WUFFS_CODEC_BUFFER_SIZE];
855 wuffs_base__io_buffer iobuf =
856 wuffs_base__make_io_buffer(wuffs_base__make_slice_u8(buffer, SK_WUFFS_CODEC_BUFFER_SIZE),
Nigel Tao96c10a02019-09-25 11:08:42 +1000857 wuffs_base__empty_io_buffer_meta());
Nigel Tao48aa2212019-03-09 14:59:11 +1100858 wuffs_base__image_config imgcfg = wuffs_base__null_image_config();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400859
860 // Wuffs is primarily a C library, not a C++ one. Furthermore, outside of
861 // the wuffs_base__etc types, the sizeof a file format specific type like
862 // GIF's wuffs_gif__decoder can vary between Wuffs versions. If p is of
863 // type wuffs_gif__decoder*, then the supported API treats p as a pointer
864 // to an opaque type: a private implementation detail. The API is always
865 // "set_foo(p, etc)" and not "p->foo = etc".
866 //
867 // See https://en.wikipedia.org/wiki/Opaque_pointer#C
868 //
869 // Thus, we don't use C++'s new operator (which requires knowing the sizeof
870 // the struct at compile time). Instead, we use sk_malloc_canfail, with
871 // sizeof__wuffs_gif__decoder returning the appropriate value for the
872 // (statically or dynamically) linked version of the Wuffs library.
873 //
874 // As a C (not C++) library, none of the Wuffs types have constructors or
875 // destructors.
876 //
877 // In RAII style, we can still use std::unique_ptr with these pointers, but
878 // we pair the pointer with sk_free instead of C++'s delete.
879 void* decoder_raw = sk_malloc_canfail(sizeof__wuffs_gif__decoder());
880 if (!decoder_raw) {
881 *result = SkCodec::kInternalError;
882 return nullptr;
883 }
884 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> decoder(
885 reinterpret_cast<wuffs_gif__decoder*>(decoder_raw), &sk_free);
886
887 SkCodec::Result reset_result =
888 reset_and_decode_image_config(decoder.get(), &imgcfg, &iobuf, stream.get());
889 if (reset_result != SkCodec::kSuccess) {
890 *result = reset_result;
891 return nullptr;
892 }
893
894 uint32_t width = imgcfg.pixcfg.width();
895 uint32_t height = imgcfg.pixcfg.height();
896 if ((width == 0) || (width > INT_MAX) || (height == 0) || (height > INT_MAX)) {
897 *result = SkCodec::kInvalidInput;
898 return nullptr;
899 }
900
Nigel Tao6af1edc2019-01-19 15:12:39 +1100901 uint64_t workbuf_len = decoder->workbuf_len().max_incl;
Nigel Tao22e86242019-01-26 16:04:01 +1100902 void* workbuf_ptr_raw = nullptr;
903 if (workbuf_len) {
904 workbuf_ptr_raw = workbuf_len <= SIZE_MAX ? sk_malloc_canfail(workbuf_len) : nullptr;
905 if (!workbuf_ptr_raw) {
906 *result = SkCodec::kInternalError;
907 return nullptr;
908 }
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400909 }
910 std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr(
911 reinterpret_cast<uint8_t*>(workbuf_ptr_raw), &sk_free);
912
Nigel Tao39da10b2019-11-15 15:27:44 +1100913 constexpr int pixbuf_sk_malloc_flags = SK_MALLOC_ZERO_INITIALIZE;
914 uint64_t pixbuf_len = imgcfg.pixcfg.pixbuf_len();
915 void* pixbuf_ptr_raw =
916 pixbuf_len <= SIZE_MAX ? sk_malloc_flags(pixbuf_len, pixbuf_sk_malloc_flags) : nullptr;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400917 if (!pixbuf_ptr_raw) {
918 *result = SkCodec::kInternalError;
919 return nullptr;
920 }
921 std::unique_ptr<uint8_t, decltype(&sk_free)> pixbuf_ptr(
922 reinterpret_cast<uint8_t*>(pixbuf_ptr_raw), &sk_free);
Nigel Tao48aa2212019-03-09 14:59:11 +1100923 wuffs_base__pixel_buffer pixbuf = wuffs_base__null_pixel_buffer();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400924
Nigel Tao48aa2212019-03-09 14:59:11 +1100925 const char* status = pixbuf.set_from_slice(
926 &imgcfg.pixcfg, wuffs_base__make_slice_u8(pixbuf_ptr.get(), SkToSizeT(pixbuf_len)));
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400927 if (status != nullptr) {
928 SkCodecPrintf("set_from_slice: %s", status);
929 *result = SkCodec::kInternalError;
930 return nullptr;
931 }
932
Nigel Tao490e6472019-02-14 14:50:53 +1100933 SkEncodedInfo::Color color =
934 (imgcfg.pixcfg.pixel_format() == WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL)
935 ? SkEncodedInfo::kBGRA_Color
936 : SkEncodedInfo::kRGBA_Color;
937
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400938 // In Skia's API, the alpha we calculate here and return is only for the
939 // first frame.
940 SkEncodedInfo::Alpha alpha = imgcfg.first_frame_is_opaque() ? SkEncodedInfo::kOpaque_Alpha
941 : SkEncodedInfo::kBinary_Alpha;
942
Nigel Tao490e6472019-02-14 14:50:53 +1100943 SkEncodedInfo encodedInfo = SkEncodedInfo::Make(width, height, color, alpha, 8);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400944
945 *result = SkCodec::kSuccess;
946 return std::unique_ptr<SkCodec>(new SkWuffsCodec(
947 std::move(encodedInfo), std::move(stream), std::move(decoder), std::move(pixbuf_ptr),
Nigel Tao39da10b2019-11-15 15:27:44 +1100948 (pixbuf_sk_malloc_flags & SK_MALLOC_ZERO_INITIALIZE) != 0, std::move(workbuf_ptr),
949 workbuf_len, imgcfg, pixbuf, iobuf));
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400950}