blob: fa43f79c154caf9e05be9a2b840b2621007d78e9 [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,
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400180 std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr,
181 size_t workbuf_len,
182 wuffs_base__image_config imgcfg,
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400183 wuffs_base__io_buffer iobuf);
184
185 const SkWuffsFrame* frame(int i) const;
186
187private:
Nigel Tao2777cd32019-10-29 11:10:25 +1100188 // It is valid, in terms of the SkCodec API, to call SkCodec::getFrameCount
189 // while in an incremental decode (after onStartIncrementalDecode returns
190 // and before the rest of the image is decoded). Some Skia users expect
191 // getFrameCount to increase, and the SkStream to advance, when given more
192 // data.
193 //
194 // On the other hand, while in an incremental decode, the underlying Wuffs
195 // object is suspended in a coroutine. To keep its internal proof-of-safety
196 // invariants consistent, there's only two things you can safely do with a
197 // suspended Wuffs object: resume the coroutine, or reset all state (memset
198 // to zero and start again).
199 //
200 // The Wuffs API provides a limited, optional form of seeking, to the start
201 // of an animation frame's data, but does not provide arbitrary save and
202 // load of its internal state whilst in the middle of an animation frame.
203 //
204 // SkWuffsCodec therefore uses two Wuffs decoders: a primary decoder
205 // (kIncrDecode) to support startIncrementalDecode / incrementalDecode, and
206 // a secondary decoder (kFrameCount) to support getFrameCount. The two
207 // decoders' states can change independently.
208 //
209 // As of Wuffs version 0.2, both of these decoders have the same type. A
210 // future Wuffs version might let us use a different type for kFrameCount,
211 // one that is much lighter weight (in terms of memory requirements), as it
212 // doesn't have to handle decompressing pixel data.
213 enum WhichDecoder {
214 kIncrDecode,
215 kFrameCount,
216 kNumDecoders,
217 };
218
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400219 // SkCodec overrides.
220 SkEncodedImageFormat onGetEncodedFormat() const override;
221 Result onGetPixels(const SkImageInfo&, void*, size_t, const Options&, int*) override;
222 const SkFrameHolder* getFrameHolder() const override;
223 Result onStartIncrementalDecode(const SkImageInfo& dstInfo,
224 void* dst,
225 size_t rowBytes,
226 const SkCodec::Options& options) override;
227 Result onIncrementalDecode(int* rowsDecoded) override;
228 int onGetFrameCount() override;
229 bool onGetFrameInfo(int, FrameInfo*) const override;
230 int onGetRepetitionCount() override;
231
Nigel Tao027f89b2019-12-06 10:56:24 +1100232 // Two separate implementations of onStartIncrementalDecode and
233 // onIncrementalDecode, named "one pass" and "two pass" decoding. One pass
234 // decoding writes directly from the Wuffs image decoder to the dst buffer
235 // (the dst argument to onStartIncrementalDecode). Two pass decoding first
236 // writes into an intermediate buffer, and then composites and transforms
237 // the intermediate buffer into the dst buffer.
238 //
239 // In the general case, we need the two pass decoder, because of Skia API
240 // features that Wuffs doesn't support (e.g. color correction, scaling,
241 // RGB565). But as an optimization, we use one pass decoding (it's faster
242 // and uses less memory) if applicable (see the assignment to
243 // fIncrDecOnePass that calculates when we can do so).
244 Result onStartIncrementalDecodeOnePass(const SkImageInfo& dstInfo,
245 uint8_t* dst,
246 size_t rowBytes,
247 const SkCodec::Options& options,
248 wuffs_base__pixel_format pixelFormat,
249 size_t bytesPerPixel);
250 Result onStartIncrementalDecodeTwoPass();
251 Result onIncrementalDecodeOnePass();
252 Result onIncrementalDecodeTwoPass();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400253
Nigel Tao027f89b2019-12-06 10:56:24 +1100254 void onGetFrameCountInternal();
255 Result seekFrame(WhichDecoder which, int frameIndex);
Nigel Tao2777cd32019-10-29 11:10:25 +1100256 Result resetDecoder(WhichDecoder which);
257 const char* decodeFrameConfig(WhichDecoder which);
258 const char* decodeFrame(WhichDecoder which);
259 void updateNumFullyReceivedFrames(WhichDecoder which);
260
261 SkWuffsFrameHolder fFrameHolder;
262 std::unique_ptr<SkStream> fStream;
Nigel Tao2777cd32019-10-29 11:10:25 +1100263 std::unique_ptr<uint8_t, decltype(&sk_free)> fWorkbufPtr;
264 size_t fWorkbufLen;
265
266 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> fDecoders[WhichDecoder::kNumDecoders];
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400267
268 const uint64_t fFirstFrameIOPosition;
Nigel Tao2777cd32019-10-29 11:10:25 +1100269 wuffs_base__frame_config fFrameConfigs[WhichDecoder::kNumDecoders];
Nigel Tao027f89b2019-12-06 10:56:24 +1100270 wuffs_base__pixel_config fPixelConfig;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400271 wuffs_base__pixel_buffer fPixelBuffer;
272 wuffs_base__io_buffer fIOBuffer;
273
274 // Incremental decoding state.
Nigel Tao0185b952018-11-08 10:47:24 +1100275 uint8_t* fIncrDecDst;
Nigel Tao2777cd32019-10-29 11:10:25 +1100276 uint64_t fIncrDecReaderIOPosition;
Nigel Tao0185b952018-11-08 10:47:24 +1100277 size_t fIncrDecRowBytes;
Nigel Tao027f89b2019-12-06 10:56:24 +1100278 bool fIncrDecOnePass;
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400279 bool fFirstCallToIncrementalDecode;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400280
Nigel Tao027f89b2019-12-06 10:56:24 +1100281 // Lazily allocated intermediate pixel buffer, for two pass decoding.
282 std::unique_ptr<uint8_t, decltype(&sk_free)> fTwoPassPixbufPtr;
283 size_t fTwoPassPixbufLen;
284
Nigel Tao3876a9f2019-11-14 09:04:45 +1100285 uint64_t fFrameCountReaderIOPosition;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400286 uint64_t fNumFullyReceivedFrames;
287 std::vector<SkWuffsFrame> fFrames;
288 bool fFramesComplete;
289
Nigel Tao2777cd32019-10-29 11:10:25 +1100290 // If calling an fDecoders[which] method returns an incomplete status, then
291 // fDecoders[which] is suspended in a coroutine (i.e. waiting on I/O or
292 // halted on a non-recoverable error). To keep its internal proof-of-safety
293 // invariants consistent, there's only two things you can safely do with a
294 // suspended Wuffs object: resume the coroutine, or reset all state (memset
295 // to zero and start again).
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400296 //
Nigel Tao2777cd32019-10-29 11:10:25 +1100297 // If fDecoderIsSuspended[which], and we aren't sure that we're going to
298 // resume the coroutine, then we will need to call this->resetDecoder
299 // before calling other fDecoders[which] methods.
300 bool fDecoderIsSuspended[WhichDecoder::kNumDecoders];
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400301
302 uint8_t fBuffer[SK_WUFFS_CODEC_BUFFER_SIZE];
303
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400304 typedef SkScalingCodec INHERITED;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400305};
306
307// -------------------------------- SkWuffsFrame implementation
308
309SkWuffsFrame::SkWuffsFrame(wuffs_base__frame_config* fc)
310 : INHERITED(fc->index()),
311 fIOPosition(fc->io_position()),
312 fReportedAlpha(wuffs_blend_to_skia_alpha(fc->blend())) {
313 wuffs_base__rect_ie_u32 r = fc->bounds();
314 this->setXYWH(r.min_incl_x, r.min_incl_y, r.width(), r.height());
315 this->setDisposalMethod(wuffs_disposal_to_skia_disposal(fc->disposal()));
316 this->setDuration(fc->duration() / WUFFS_BASE__FLICKS_PER_MILLISECOND);
317 this->setBlend(wuffs_blend_to_skia_blend(fc->blend()));
318}
319
320SkCodec::FrameInfo SkWuffsFrame::frameInfo(bool fullyReceived) const {
Nigel Taoef40e332019-04-05 10:28:40 +1100321 SkCodec::FrameInfo ret;
322 ret.fRequiredFrame = getRequiredFrame();
323 ret.fDuration = getDuration();
324 ret.fFullyReceived = fullyReceived;
325 ret.fAlphaType = hasAlpha() ? kUnpremul_SkAlphaType : kOpaque_SkAlphaType;
326 ret.fDisposalMethod = getDisposalMethod();
327 return ret;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400328}
329
330uint64_t SkWuffsFrame::ioPosition() const {
331 return fIOPosition;
332}
333
334SkEncodedInfo::Alpha SkWuffsFrame::onReportedAlpha() const {
335 return fReportedAlpha;
336}
337
338// -------------------------------- SkWuffsFrameHolder implementation
339
340void SkWuffsFrameHolder::init(SkWuffsCodec* codec, int width, int height) {
341 fCodec = codec;
342 // Initialize SkFrameHolder's (the superclass) fields.
343 fScreenWidth = width;
344 fScreenHeight = height;
345}
346
347const SkFrame* SkWuffsFrameHolder::onGetFrame(int i) const {
348 return fCodec->frame(i);
349};
350
351// -------------------------------- SkWuffsCodec implementation
352
353SkWuffsCodec::SkWuffsCodec(SkEncodedInfo&& encodedInfo,
354 std::unique_ptr<SkStream> stream,
355 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> dec,
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400356 std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr,
357 size_t workbuf_len,
358 wuffs_base__image_config imgcfg,
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400359 wuffs_base__io_buffer iobuf)
360 : INHERITED(std::move(encodedInfo),
361 skcms_PixelFormat_RGBA_8888,
362 // Pass a nullptr SkStream to the SkCodec constructor. We
363 // manage the stream ourselves, as the default SkCodec behavior
364 // is too trigger-happy on rewinding the stream.
365 nullptr),
Nigel Tao0185b952018-11-08 10:47:24 +1100366 fFrameHolder(),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400367 fStream(std::move(stream)),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400368 fWorkbufPtr(std::move(workbuf_ptr)),
369 fWorkbufLen(workbuf_len),
Nigel Tao2777cd32019-10-29 11:10:25 +1100370 fDecoders{
371 std::move(dec),
372 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)>(nullptr, sk_free),
373 },
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400374 fFirstFrameIOPosition(imgcfg.first_frame_io_position()),
Nigel Tao2777cd32019-10-29 11:10:25 +1100375 fFrameConfigs{
376 wuffs_base__null_frame_config(),
377 wuffs_base__null_frame_config(),
378 },
Nigel Tao027f89b2019-12-06 10:56:24 +1100379 fPixelConfig(imgcfg.pixcfg),
380 fPixelBuffer(wuffs_base__null_pixel_buffer()),
Nigel Tao96c10a02019-09-25 11:08:42 +1000381 fIOBuffer(wuffs_base__empty_io_buffer()),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400382 fIncrDecDst(nullptr),
Nigel Tao2777cd32019-10-29 11:10:25 +1100383 fIncrDecReaderIOPosition(0),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400384 fIncrDecRowBytes(0),
Nigel Tao027f89b2019-12-06 10:56:24 +1100385 fIncrDecOnePass(false),
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400386 fFirstCallToIncrementalDecode(false),
Nigel Tao027f89b2019-12-06 10:56:24 +1100387 fTwoPassPixbufPtr(nullptr, &sk_free),
388 fTwoPassPixbufLen(0),
Nigel Tao3876a9f2019-11-14 09:04:45 +1100389 fFrameCountReaderIOPosition(0),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400390 fNumFullyReceivedFrames(0),
391 fFramesComplete(false),
Nigel Tao2777cd32019-10-29 11:10:25 +1100392 fDecoderIsSuspended{
393 false,
394 false,
395 } {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400396 fFrameHolder.init(this, imgcfg.pixcfg.width(), imgcfg.pixcfg.height());
397
398 // Initialize fIOBuffer's fields, copying any outstanding data from iobuf to
399 // fIOBuffer, as iobuf's backing array may not be valid for the lifetime of
400 // this SkWuffsCodec object, but fIOBuffer's backing array (fBuffer) is.
401 SkASSERT(iobuf.data.len == SK_WUFFS_CODEC_BUFFER_SIZE);
402 memmove(fBuffer, iobuf.data.ptr, iobuf.meta.wi);
Nigel Tao48aa2212019-03-09 14:59:11 +1100403 fIOBuffer.data = wuffs_base__make_slice_u8(fBuffer, SK_WUFFS_CODEC_BUFFER_SIZE);
404 fIOBuffer.meta = iobuf.meta;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400405}
406
407const SkWuffsFrame* SkWuffsCodec::frame(int i) const {
408 if ((0 <= i) && (static_cast<size_t>(i) < fFrames.size())) {
409 return &fFrames[i];
410 }
411 return nullptr;
412}
413
414SkEncodedImageFormat SkWuffsCodec::onGetEncodedFormat() const {
415 return SkEncodedImageFormat::kGIF;
416}
417
418SkCodec::Result SkWuffsCodec::onGetPixels(const SkImageInfo& dstInfo,
419 void* dst,
420 size_t rowBytes,
421 const Options& options,
422 int* rowsDecoded) {
423 SkCodec::Result result = this->onStartIncrementalDecode(dstInfo, dst, rowBytes, options);
424 if (result != kSuccess) {
425 return result;
426 }
427 return this->onIncrementalDecode(rowsDecoded);
428}
429
430const SkFrameHolder* SkWuffsCodec::getFrameHolder() const {
431 return &fFrameHolder;
432}
433
434SkCodec::Result SkWuffsCodec::onStartIncrementalDecode(const SkImageInfo& dstInfo,
435 void* dst,
436 size_t rowBytes,
437 const SkCodec::Options& options) {
Nigel Tao1f1cd1f2019-06-22 17:35:38 +1000438 if (!dst) {
439 return SkCodec::kInvalidParameters;
440 }
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400441 if (options.fSubset) {
442 return SkCodec::kUnimplemented;
443 }
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400444 if (options.fFrameIndex > 0 && SkColorTypeIsAlwaysOpaque(dstInfo.colorType())) {
445 return SkCodec::kInvalidConversion;
446 }
Nigel Tao2777cd32019-10-29 11:10:25 +1100447 SkCodec::Result result = this->seekFrame(WhichDecoder::kIncrDecode, options.fFrameIndex);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400448 if (result != SkCodec::kSuccess) {
449 return result;
450 }
451
Nigel Tao2777cd32019-10-29 11:10:25 +1100452 const char* status = this->decodeFrameConfig(WhichDecoder::kIncrDecode);
Nigel Taob7a1b512019-02-10 12:19:50 +1100453 if (status == wuffs_base__suspension__short_read) {
Leon Scroggins IIIcb6b8842018-12-04 13:55:13 -0500454 return SkCodec::kIncompleteInput;
Nigel Taob7a1b512019-02-10 12:19:50 +1100455 } else if (status != nullptr) {
Leon Scroggins IIIcb6b8842018-12-04 13:55:13 -0500456 SkCodecPrintf("decodeFrameConfig: %s", status);
457 return SkCodec::kErrorInInput;
458 }
Nigel Taob7a1b512019-02-10 12:19:50 +1100459
Nigel Tao027f89b2019-12-06 10:56:24 +1100460 wuffs_base__pixel_format pixelFormat = WUFFS_BASE__PIXEL_FORMAT__INVALID;
461 size_t bytesPerPixel = 0;
462
463 switch (dstInfo.colorType()) {
464 case kBGRA_8888_SkColorType:
465 pixelFormat = WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL;
466 bytesPerPixel = 4;
467 break;
468 case kRGBA_8888_SkColorType:
469 pixelFormat = WUFFS_BASE__PIXEL_FORMAT__RGBA_NONPREMUL;
470 bytesPerPixel = 4;
471 break;
472 default:
473 break;
474 }
475
476 // We can use "one pass" decoding if we have a Skia pixel format that Wuffs
477 // supports...
478 fIncrDecOnePass =
479 (pixelFormat != WUFFS_BASE__PIXEL_FORMAT__INVALID) &&
480 // ...and no color profile (as Wuffs does not support them)...
481 (!getEncodedInfo().profile()) &&
482 // ...and we have an independent frame (as Wuffs does not support the
483 // equivalent of SkBlendMode::kSrcOver)...
484 ((options.fFrameIndex == 0) ||
485 (this->frame(options.fFrameIndex)->getRequiredFrame() == SkCodec::kNoFrame)) &&
486 // ...and we use the identity transform (as Wuffs does not support
487 // scaling).
488 (this->dimensions() == dstInfo.dimensions());
489
490 result = fIncrDecOnePass ? this->onStartIncrementalDecodeOnePass(
491 dstInfo, static_cast<uint8_t*>(dst), rowBytes, options,
492 pixelFormat, bytesPerPixel)
493 : this->onStartIncrementalDecodeTwoPass();
494 if (result != SkCodec::kSuccess) {
495 return result;
496 }
497
498 fIncrDecDst = static_cast<uint8_t*>(dst);
499 fIncrDecReaderIOPosition = fIOBuffer.reader_io_position();
500 fIncrDecRowBytes = rowBytes;
501 fFirstCallToIncrementalDecode = true;
502 return SkCodec::kSuccess;
503}
504
505SkCodec::Result SkWuffsCodec::onStartIncrementalDecodeOnePass(const SkImageInfo& dstInfo,
506 uint8_t* dst,
507 size_t rowBytes,
508 const SkCodec::Options& options,
509 wuffs_base__pixel_format pixelFormat,
510 size_t bytesPerPixel) {
511 wuffs_base__pixel_config pixelConfig;
512 pixelConfig.set(pixelFormat, WUFFS_BASE__PIXEL_SUBSAMPLING__NONE, dstInfo.width(),
513 dstInfo.height());
514
515 wuffs_base__table_u8 table;
516 table.ptr = dst;
517 table.width = static_cast<size_t>(dstInfo.width()) * bytesPerPixel;
518 table.height = dstInfo.height();
519 table.stride = rowBytes;
520
521 const char* status = fPixelBuffer.set_from_table(&pixelConfig, table);
522 if (status != nullptr) {
523 SkCodecPrintf("set_from_table: %s", status);
Nigel Tao490e6472019-02-14 14:50:53 +1100524 return SkCodec::kInternalError;
525 }
Nigel Taob7a1b512019-02-10 12:19:50 +1100526
Nigel Tao027f89b2019-12-06 10:56:24 +1100527 SkSampler::Fill(dstInfo, dst, rowBytes, options.fZeroInitialized);
528 return SkCodec::kSuccess;
529}
530
531SkCodec::Result SkWuffsCodec::onStartIncrementalDecodeTwoPass() {
532 // Either re-use the previously allocated "two pass" pixel buffer (and
533 // memset to zero), or allocate (and zero initialize) a new one.
534 bool already_zeroed = false;
535
536 if (!fTwoPassPixbufPtr) {
537 uint64_t pixbuf_len = fPixelConfig.pixbuf_len();
538 void* pixbuf_ptr_raw = (pixbuf_len <= SIZE_MAX)
539 ? sk_malloc_flags(pixbuf_len, SK_MALLOC_ZERO_INITIALIZE)
540 : nullptr;
541 if (!pixbuf_ptr_raw) {
542 return SkCodec::kInternalError;
543 }
544 fTwoPassPixbufPtr.reset(reinterpret_cast<uint8_t*>(pixbuf_ptr_raw));
545 fTwoPassPixbufLen = SkToSizeT(pixbuf_len);
546 already_zeroed = true;
547 }
548
549 const char* status = fPixelBuffer.set_from_slice(
550 &fPixelConfig, wuffs_base__make_slice_u8(fTwoPassPixbufPtr.get(), fTwoPassPixbufLen));
551 if (status != nullptr) {
552 SkCodecPrintf("set_from_slice: %s", status);
553 return SkCodec::kInternalError;
554 }
555
556 if (!already_zeroed) {
557 uint32_t src_bits_per_pixel =
558 wuffs_base__pixel_format__bits_per_pixel(fPixelConfig.pixel_format());
559 if ((src_bits_per_pixel == 0) || (src_bits_per_pixel % 8 != 0)) {
560 return SkCodec::kInternalError;
561 }
562 size_t src_bytes_per_pixel = src_bits_per_pixel / 8;
563
Nigel Tao39da10b2019-11-15 15:27:44 +1100564 wuffs_base__rect_ie_u32 frame_rect = fFrameConfigs[WhichDecoder::kIncrDecode].bounds();
565 wuffs_base__table_u8 pixels = fPixelBuffer.plane(0);
Nigel Tao6ec1b392019-11-20 12:28:50 +1100566
567 uint8_t* ptr = pixels.ptr + (frame_rect.min_incl_y * pixels.stride) +
568 (frame_rect.min_incl_x * src_bytes_per_pixel);
569 size_t len = frame_rect.width() * src_bytes_per_pixel;
570
571 // As an optimization, issue a single sk_bzero call, if possible.
572 // Otherwise, zero out each row separately.
573 if ((len == pixels.stride) && (frame_rect.min_incl_y < frame_rect.max_excl_y)) {
574 sk_bzero(ptr, len * (frame_rect.max_excl_y - frame_rect.min_incl_y));
575 } else {
576 for (uint32_t y = frame_rect.min_incl_y; y < frame_rect.max_excl_y; y++) {
577 sk_bzero(ptr, len);
578 ptr += pixels.stride;
579 }
Nigel Tao39da10b2019-11-15 15:27:44 +1100580 }
Nigel Taob7a1b512019-02-10 12:19:50 +1100581 }
582
Nigel Taob7a1b512019-02-10 12:19:50 +1100583 return SkCodec::kSuccess;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400584}
585
586SkCodec::Result SkWuffsCodec::onIncrementalDecode(int* rowsDecoded) {
587 if (!fIncrDecDst) {
588 return SkCodec::kInternalError;
589 }
590
Nigel Tao2777cd32019-10-29 11:10:25 +1100591 // If multiple SkCodec::incrementalDecode calls are made consecutively (or
592 // if SkCodec::incrementalDecode is called immediately after
593 // SkCodec::startIncrementalDecode), then this seek should be a no-op.
594 // However, it is possible to interleave SkCodec::getFrameCount calls in
595 // between SkCodec::incrementalDecode calls, and those other calls may
596 // advance the stream. This seek restores the stream to where the last
597 // SkCodec::startIncrementalDecode or SkCodec::incrementalDecode stopped.
598 if (!seek_buffer(&fIOBuffer, fStream.get(), fIncrDecReaderIOPosition)) {
599 return SkCodec::kInternalError;
600 }
601
Nigel Tao027f89b2019-12-06 10:56:24 +1100602 if (rowsDecoded) {
603 *rowsDecoded = dstInfo().height();
604 }
605
606 SkCodec::Result result =
607 fIncrDecOnePass ? this->onIncrementalDecodeOnePass() : this->onIncrementalDecodeTwoPass();
Nigel Tao2777cd32019-10-29 11:10:25 +1100608 if (result == SkCodec::kSuccess) {
609 fIncrDecDst = nullptr;
610 fIncrDecReaderIOPosition = 0;
611 fIncrDecRowBytes = 0;
Nigel Tao027f89b2019-12-06 10:56:24 +1100612 fIncrDecOnePass = false;
Nigel Tao2777cd32019-10-29 11:10:25 +1100613 } else {
614 fIncrDecReaderIOPosition = fIOBuffer.reader_io_position();
615 }
616 return result;
617}
618
Nigel Tao027f89b2019-12-06 10:56:24 +1100619SkCodec::Result SkWuffsCodec::onIncrementalDecodeOnePass() {
620 const char* status = this->decodeFrame(WhichDecoder::kIncrDecode);
621 if (status != nullptr) {
622 if (status == wuffs_base__suspension__short_read) {
623 return SkCodec::kIncompleteInput;
624 } else {
625 SkCodecPrintf("decodeFrame: %s", status);
626 return SkCodec::kErrorInInput;
627 }
628 }
629 return SkCodec::kSuccess;
630}
631
632SkCodec::Result SkWuffsCodec::onIncrementalDecodeTwoPass() {
Leon Scroggins III699d41e2019-02-07 09:25:51 -0500633 SkCodec::Result result = SkCodec::kSuccess;
Nigel Tao2777cd32019-10-29 11:10:25 +1100634 const char* status = this->decodeFrame(WhichDecoder::kIncrDecode);
635 bool independent;
636 SkAlphaType alphaType;
637 const int index = options().fFrameIndex;
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400638 if (index == 0) {
639 independent = true;
640 alphaType = to_alpha_type(getEncodedInfo().opaque());
641 } else {
642 const SkWuffsFrame* f = this->frame(index);
643 independent = f->getRequiredFrame() == SkCodec::kNoFrame;
644 alphaType = to_alpha_type(f->reportedAlpha() == SkEncodedInfo::kOpaque_Alpha);
645 }
Leon Scroggins III699d41e2019-02-07 09:25:51 -0500646 if (status != nullptr) {
647 if (status == wuffs_base__suspension__short_read) {
648 result = SkCodec::kIncompleteInput;
649 } else {
650 SkCodecPrintf("decodeFrame: %s", status);
651 result = SkCodec::kErrorInInput;
652 }
653
654 if (!independent) {
655 // For a dependent frame, we cannot blend the partial result, since
656 // that will overwrite the contribution from prior frames.
657 return result;
658 }
659 }
660
Nigel Tao490e6472019-02-14 14:50:53 +1100661 uint32_t src_bits_per_pixel =
662 wuffs_base__pixel_format__bits_per_pixel(fPixelBuffer.pixcfg.pixel_format());
663 if ((src_bits_per_pixel == 0) || (src_bits_per_pixel % 8 != 0)) {
664 return SkCodec::kInternalError;
665 }
666 size_t src_bytes_per_pixel = src_bits_per_pixel / 8;
667
Nigel Tao2777cd32019-10-29 11:10:25 +1100668 wuffs_base__rect_ie_u32 frame_rect = fFrameConfigs[WhichDecoder::kIncrDecode].bounds();
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400669 if (fFirstCallToIncrementalDecode) {
Nigel Tao490e6472019-02-14 14:50:53 +1100670 if (frame_rect.width() > (SIZE_MAX / src_bytes_per_pixel)) {
671 return SkCodec::kInternalError;
672 }
673
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400674 auto bounds = SkIRect::MakeLTRB(frame_rect.min_incl_x, frame_rect.min_incl_y,
675 frame_rect.max_excl_x, frame_rect.max_excl_y);
676
Leon Scroggins IIIcb6b8842018-12-04 13:55:13 -0500677 // If the frame rect does not fill the output, ensure that those pixels are not
Nigel Taob7a1b512019-02-10 12:19:50 +1100678 // left uninitialized.
Leon Scroggins III44076362019-02-15 13:56:44 -0500679 if (independent && (bounds != this->bounds() || result != kSuccess)) {
Nigel Tao2777cd32019-10-29 11:10:25 +1100680 SkSampler::Fill(dstInfo(), fIncrDecDst, fIncrDecRowBytes, options().fZeroInitialized);
Leon Scroggins III9b0ba2c2018-11-19 14:52:37 -0500681 }
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400682 fFirstCallToIncrementalDecode = false;
683 } else {
684 // Existing clients intend to only show frames beyond the first if they
685 // are complete (based on FrameInfo::fFullyReceived), since it might
686 // look jarring to draw a partial frame over an existing frame. If they
687 // changed their behavior and expected to continue decoding a partial
688 // frame after the first one, we'll need to update our blending code.
689 // Otherwise, if the frame were interlaced and not independent, the
690 // second pass may have an overlapping dirty_rect with the first,
691 // resulting in blending with the first pass.
692 SkASSERT(index == 0);
Nigel Tao9859ef82019-02-13 13:20:02 +1100693 }
Nigel Tao0185b952018-11-08 10:47:24 +1100694
Leon Scroggins IIIdad4bfc2018-12-10 12:37:10 -0500695 // If the frame's dirty rect is empty, no need to swizzle.
Nigel Tao2777cd32019-10-29 11:10:25 +1100696 wuffs_base__rect_ie_u32 dirty_rect = fDecoders[WhichDecoder::kIncrDecode]->frame_dirty_rect();
Leon Scroggins IIIdad4bfc2018-12-10 12:37:10 -0500697 if (!dirty_rect.is_empty()) {
Nigel Tao490e6472019-02-14 14:50:53 +1100698 wuffs_base__table_u8 pixels = fPixelBuffer.plane(0);
Leon Scroggins III7a3805c2018-12-07 09:21:30 -0500699
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400700 // The Wuffs model is that the dst buffer is the image, not the frame.
701 // The expectation is that you allocate the buffer once, but re-use it
702 // for the N frames, regardless of each frame's top-left co-ordinate.
703 //
704 // To get from the start (in the X-direction) of the image to the start
705 // of the dirty_rect, we adjust s by (dirty_rect.min_incl_x * src_bytes_per_pixel).
Nigel Tao2777cd32019-10-29 11:10:25 +1100706 uint8_t* s = pixels.ptr + (dirty_rect.min_incl_y * pixels.stride) +
707 (dirty_rect.min_incl_x * src_bytes_per_pixel);
Leon Scroggins III7a3805c2018-12-07 09:21:30 -0500708
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400709 // Currently, this is only used for GIF, which will never have an ICC profile. When it is
710 // used for other formats that might have one, we will need to transform from profiles that
711 // do not have corresponding SkColorSpaces.
712 SkASSERT(!getEncodedInfo().profile());
713
Nigel Tao2777cd32019-10-29 11:10:25 +1100714 auto srcInfo =
715 getInfo().makeWH(dirty_rect.width(), dirty_rect.height()).makeAlphaType(alphaType);
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400716 SkBitmap src;
717 src.installPixels(srcInfo, s, pixels.stride);
718 SkPaint paint;
719 if (independent) {
720 paint.setBlendMode(SkBlendMode::kSrc);
Leon Scroggins III7a3805c2018-12-07 09:21:30 -0500721 }
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400722
723 SkDraw draw;
724 draw.fDst.reset(dstInfo(), fIncrDecDst, fIncrDecRowBytes);
725 SkMatrix matrix = SkMatrix::MakeRectToRect(SkRect::Make(this->dimensions()),
726 SkRect::Make(this->dstInfo().dimensions()),
727 SkMatrix::kFill_ScaleToFit);
728 draw.fMatrix = &matrix;
729 SkRasterClip rc(SkIRect::MakeSize(this->dstInfo().dimensions()));
730 draw.fRC = &rc;
731
732 SkMatrix translate = SkMatrix::MakeTrans(dirty_rect.min_incl_x, dirty_rect.min_incl_y);
733 draw.drawBitmap(src, translate, nullptr, paint);
Leon Scroggins III7a3805c2018-12-07 09:21:30 -0500734 }
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400735 return result;
736}
737
738int SkWuffsCodec::onGetFrameCount() {
Nigel Tao3876a9f2019-11-14 09:04:45 +1100739 if (!fFramesComplete && seek_buffer(&fIOBuffer, fStream.get(), fFrameCountReaderIOPosition)) {
Nigel Tao2777cd32019-10-29 11:10:25 +1100740 this->onGetFrameCountInternal();
Nigel Tao3876a9f2019-11-14 09:04:45 +1100741 fFrameCountReaderIOPosition =
742 fDecoders[WhichDecoder::kFrameCount] ? fIOBuffer.reader_io_position() : 0;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400743 }
744 return fFrames.size();
745}
746
Nigel Tao2777cd32019-10-29 11:10:25 +1100747void SkWuffsCodec::onGetFrameCountInternal() {
Nigel Tao2777cd32019-10-29 11:10:25 +1100748 if (!fDecoders[WhichDecoder::kFrameCount]) {
749 void* decoder_raw = sk_malloc_canfail(sizeof__wuffs_gif__decoder());
750 if (!decoder_raw) {
751 return;
752 }
753 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> decoder(
754 reinterpret_cast<wuffs_gif__decoder*>(decoder_raw), &sk_free);
Nigel Tao3876a9f2019-11-14 09:04:45 +1100755 reset_and_decode_image_config(decoder.get(), nullptr, &fIOBuffer, fStream.get());
Nigel Tao2777cd32019-10-29 11:10:25 +1100756 fDecoders[WhichDecoder::kFrameCount] = std::move(decoder);
757 }
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400758
759 // Iterate through the frames, converting from Wuffs'
760 // wuffs_base__frame_config type to Skia's SkWuffsFrame type.
Nigel Tao3876a9f2019-11-14 09:04:45 +1100761 while (true) {
Nigel Tao2777cd32019-10-29 11:10:25 +1100762 const char* status = this->decodeFrameConfig(WhichDecoder::kFrameCount);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400763 if (status == nullptr) {
764 // No-op.
765 } else if (status == wuffs_base__warning__end_of_data) {
766 break;
767 } else {
768 return;
769 }
770
Nigel Tao3876a9f2019-11-14 09:04:45 +1100771 uint64_t i = fDecoders[WhichDecoder::kFrameCount]->num_decoded_frame_configs();
772 if (i > INT_MAX) {
773 break;
774 }
775 if ((i == 0) || (static_cast<size_t>(i - 1) != fFrames.size())) {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400776 continue;
777 }
Nigel Tao2777cd32019-10-29 11:10:25 +1100778 fFrames.emplace_back(&fFrameConfigs[WhichDecoder::kFrameCount]);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400779 SkWuffsFrame* f = &fFrames[fFrames.size() - 1];
780 fFrameHolder.setAlphaAndRequiredFrame(f);
781 }
782
783 fFramesComplete = true;
Nigel Tao5b271462019-11-12 21:02:20 +1100784
785 // We've seen the end of the animation. There'll be no more frames, so we
786 // no longer need the kFrameCount decoder. Releasing it earlier than the
787 // SkWuffsCodec destructor might help peak memory use.
788 fDecoders[WhichDecoder::kFrameCount].reset(nullptr);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400789}
790
Nigel Taocdc92382019-10-31 08:36:53 +1100791bool SkWuffsCodec::onGetFrameInfo(int i, SkCodec::FrameInfo* frameInfo) const {
792 const SkWuffsFrame* f = this->frame(i);
793 if (!f) {
794 return false;
795 }
796 if (frameInfo) {
797 *frameInfo = f->frameInfo(static_cast<uint64_t>(i) < this->fNumFullyReceivedFrames);
798 }
799 return true;
800}
801
802int SkWuffsCodec::onGetRepetitionCount() {
803 // Convert from Wuffs's loop count to Skia's repeat count. Wuffs' uint32_t
804 // number is how many times to play the loop. Skia's int number is how many
805 // times to play the loop *after the first play*. Wuffs and Skia use 0 and
806 // kRepetitionCountInfinite respectively to mean loop forever.
807 uint32_t n = fDecoders[WhichDecoder::kIncrDecode]->num_animation_loops();
808 if (n == 0) {
809 return SkCodec::kRepetitionCountInfinite;
810 }
811 n--;
812 return n < INT_MAX ? n : INT_MAX;
813}
814
Nigel Tao2777cd32019-10-29 11:10:25 +1100815SkCodec::Result SkWuffsCodec::seekFrame(WhichDecoder which, int frameIndex) {
816 if (fDecoderIsSuspended[which]) {
817 SkCodec::Result res = this->resetDecoder(which);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400818 if (res != SkCodec::kSuccess) {
819 return res;
820 }
821 }
822
823 uint64_t pos = 0;
824 if (frameIndex < 0) {
825 return SkCodec::kInternalError;
826 } else if (frameIndex == 0) {
827 pos = fFirstFrameIOPosition;
828 } else if (static_cast<size_t>(frameIndex) < fFrames.size()) {
829 pos = fFrames[frameIndex].ioPosition();
830 } else {
831 return SkCodec::kInternalError;
832 }
833
834 if (!seek_buffer(&fIOBuffer, fStream.get(), pos)) {
835 return SkCodec::kInternalError;
836 }
Nigel Tao2777cd32019-10-29 11:10:25 +1100837 const char* status =
838 fDecoders[which]->restart_frame(frameIndex, fIOBuffer.reader_io_position());
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400839 if (status != nullptr) {
840 return SkCodec::kInternalError;
841 }
842 return SkCodec::kSuccess;
843}
844
845// An overview of the Wuffs decoding API:
846//
847// An animated image (such as GIF) has an image header and then N frames. The
848// image header gives e.g. the overall image's width and height. Each frame
849// consists of a frame header (e.g. frame rectangle bounds, display duration)
850// and a payload (the pixels).
851//
852// In Wuffs terminology, there is one image config and then N pairs of
853// (frame_config, frame). To decode everything (without knowing N in advance)
854// sequentially:
855// - call wuffs_gif__decoder::decode_image_config
856// - while (true) {
857// - call wuffs_gif__decoder::decode_frame_config
858// - if that returned wuffs_base__warning__end_of_data, break
859// - call wuffs_gif__decoder::decode_frame
860// - }
861//
862// The first argument to each decode_foo method is the destination struct to
863// store the decoded information.
864//
865// For random (instead of sequential) access to an image's frames, call
866// wuffs_gif__decoder::restart_frame to prepare to decode the i'th frame.
867// Essentially, it restores the state to be at the top of the while loop above.
868// The wuffs_base__io_buffer's reader position will also need to be set at the
869// right point in the source data stream. The position for the i'th frame is
870// calculated by the i'th decode_frame_config call. You can only call
871// restart_frame after decode_image_config is called, explicitly or implicitly
872// (see below), as decoding a single frame might require for-all-frames
873// information like the overall image dimensions and the global palette.
874//
875// All of those decode_xxx calls are optional. For example, if
876// decode_image_config is not called, then the first decode_frame_config call
877// will implicitly parse and verify the image header, before parsing the first
878// frame's header. Similarly, you can call only decode_frame N times, without
879// calling decode_image_config or decode_frame_config, if you already know
880// metadata like N and each frame's rectangle bounds by some other means (e.g.
881// this is a first party, statically known image).
882//
883// Specifically, starting with an unknown (but re-windable) GIF image, if you
884// want to just find N (i.e. count the number of frames), you can loop calling
885// only the decode_frame_config method and avoid calling the more expensive
886// decode_frame method. In terms of the underlying GIF image format, this will
887// skip over the LZW-encoded pixel data, avoiding the costly LZW decompression.
888//
889// Those decode_xxx methods are also suspendible. They will return early (with
890// a status code that is_suspendible and therefore isn't is_complete) if there
891// isn't enough source data to complete the operation: an incremental decode.
892// Calling decode_xxx again with additional source data will resume the
893// previous operation, instead of starting a new operation. Calling decode_yyy
894// whilst decode_xxx is suspended will result in an error.
895//
896// Once an error is encountered, whether from invalid source data or from a
897// programming error such as calling decode_yyy while suspended in decode_xxx,
898// all subsequent calls will be no-ops that return an error. To reset the
899// decoder into something that does productive work, memset the entire struct
900// to zero, check the Wuffs version and then, in order to be able to call
901// restart_frame, call decode_image_config. The io_buffer and its associated
902// stream will also need to be rewound.
903
Nigel Tao2777cd32019-10-29 11:10:25 +1100904SkCodec::Result SkWuffsCodec::resetDecoder(WhichDecoder which) {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400905 if (!fStream->rewind()) {
906 return SkCodec::kInternalError;
907 }
Nigel Tao96c10a02019-09-25 11:08:42 +1000908 fIOBuffer.meta = wuffs_base__empty_io_buffer_meta();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400909
910 SkCodec::Result result =
Nigel Tao2777cd32019-10-29 11:10:25 +1100911 reset_and_decode_image_config(fDecoders[which].get(), nullptr, &fIOBuffer, fStream.get());
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400912 if (result == SkCodec::kIncompleteInput) {
913 return SkCodec::kInternalError;
914 } else if (result != SkCodec::kSuccess) {
915 return result;
916 }
917
Nigel Tao2777cd32019-10-29 11:10:25 +1100918 fDecoderIsSuspended[which] = false;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400919 return SkCodec::kSuccess;
920}
921
Nigel Tao2777cd32019-10-29 11:10:25 +1100922const char* SkWuffsCodec::decodeFrameConfig(WhichDecoder which) {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400923 while (true) {
Nigel Tao48aa2212019-03-09 14:59:11 +1100924 const char* status =
Nigel Tao2777cd32019-10-29 11:10:25 +1100925 fDecoders[which]->decode_frame_config(&fFrameConfigs[which], &fIOBuffer);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400926 if ((status == wuffs_base__suspension__short_read) &&
927 fill_buffer(&fIOBuffer, fStream.get())) {
928 continue;
929 }
Nigel Tao2777cd32019-10-29 11:10:25 +1100930 fDecoderIsSuspended[which] = !wuffs_base__status__is_complete(status);
931 this->updateNumFullyReceivedFrames(which);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400932 return status;
933 }
934}
935
Nigel Tao2777cd32019-10-29 11:10:25 +1100936const char* SkWuffsCodec::decodeFrame(WhichDecoder which) {
937 while (true) {
938 const char* status = fDecoders[which]->decode_frame(
939 &fPixelBuffer, &fIOBuffer, wuffs_base__make_slice_u8(fWorkbufPtr.get(), fWorkbufLen),
940 NULL);
941 if ((status == wuffs_base__suspension__short_read) &&
942 fill_buffer(&fIOBuffer, fStream.get())) {
943 continue;
944 }
945 fDecoderIsSuspended[which] = !wuffs_base__status__is_complete(status);
946 this->updateNumFullyReceivedFrames(which);
947 return status;
948 }
949}
950
951void SkWuffsCodec::updateNumFullyReceivedFrames(WhichDecoder which) {
Nigel Tao6af1edc2019-01-19 15:12:39 +1100952 // num_decoded_frames's return value, n, can change over time, both up and
953 // down, as we seek back and forth in the underlying stream.
954 // fNumFullyReceivedFrames is the highest n we've seen.
Nigel Tao2777cd32019-10-29 11:10:25 +1100955 uint64_t n = fDecoders[which]->num_decoded_frames();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400956 if (fNumFullyReceivedFrames < n) {
957 fNumFullyReceivedFrames = n;
958 }
959}
960
961// -------------------------------- SkWuffsCodec.h functions
962
963bool SkWuffsCodec_IsFormat(const void* buf, size_t bytesRead) {
964 constexpr const char* gif_ptr = "GIF8";
965 constexpr size_t gif_len = 4;
966 return (bytesRead >= gif_len) && (memcmp(buf, gif_ptr, gif_len) == 0);
967}
968
969std::unique_ptr<SkCodec> SkWuffsCodec_MakeFromStream(std::unique_ptr<SkStream> stream,
970 SkCodec::Result* result) {
Nigel Tao48aa2212019-03-09 14:59:11 +1100971 uint8_t buffer[SK_WUFFS_CODEC_BUFFER_SIZE];
972 wuffs_base__io_buffer iobuf =
973 wuffs_base__make_io_buffer(wuffs_base__make_slice_u8(buffer, SK_WUFFS_CODEC_BUFFER_SIZE),
Nigel Tao96c10a02019-09-25 11:08:42 +1000974 wuffs_base__empty_io_buffer_meta());
Nigel Tao48aa2212019-03-09 14:59:11 +1100975 wuffs_base__image_config imgcfg = wuffs_base__null_image_config();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400976
977 // Wuffs is primarily a C library, not a C++ one. Furthermore, outside of
978 // the wuffs_base__etc types, the sizeof a file format specific type like
979 // GIF's wuffs_gif__decoder can vary between Wuffs versions. If p is of
980 // type wuffs_gif__decoder*, then the supported API treats p as a pointer
981 // to an opaque type: a private implementation detail. The API is always
982 // "set_foo(p, etc)" and not "p->foo = etc".
983 //
984 // See https://en.wikipedia.org/wiki/Opaque_pointer#C
985 //
986 // Thus, we don't use C++'s new operator (which requires knowing the sizeof
987 // the struct at compile time). Instead, we use sk_malloc_canfail, with
988 // sizeof__wuffs_gif__decoder returning the appropriate value for the
989 // (statically or dynamically) linked version of the Wuffs library.
990 //
991 // As a C (not C++) library, none of the Wuffs types have constructors or
992 // destructors.
993 //
994 // In RAII style, we can still use std::unique_ptr with these pointers, but
995 // we pair the pointer with sk_free instead of C++'s delete.
996 void* decoder_raw = sk_malloc_canfail(sizeof__wuffs_gif__decoder());
997 if (!decoder_raw) {
998 *result = SkCodec::kInternalError;
999 return nullptr;
1000 }
1001 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> decoder(
1002 reinterpret_cast<wuffs_gif__decoder*>(decoder_raw), &sk_free);
1003
1004 SkCodec::Result reset_result =
1005 reset_and_decode_image_config(decoder.get(), &imgcfg, &iobuf, stream.get());
1006 if (reset_result != SkCodec::kSuccess) {
1007 *result = reset_result;
1008 return nullptr;
1009 }
1010
1011 uint32_t width = imgcfg.pixcfg.width();
1012 uint32_t height = imgcfg.pixcfg.height();
1013 if ((width == 0) || (width > INT_MAX) || (height == 0) || (height > INT_MAX)) {
1014 *result = SkCodec::kInvalidInput;
1015 return nullptr;
1016 }
1017
Nigel Tao6af1edc2019-01-19 15:12:39 +11001018 uint64_t workbuf_len = decoder->workbuf_len().max_incl;
Nigel Tao22e86242019-01-26 16:04:01 +11001019 void* workbuf_ptr_raw = nullptr;
1020 if (workbuf_len) {
1021 workbuf_ptr_raw = workbuf_len <= SIZE_MAX ? sk_malloc_canfail(workbuf_len) : nullptr;
1022 if (!workbuf_ptr_raw) {
1023 *result = SkCodec::kInternalError;
1024 return nullptr;
1025 }
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001026 }
1027 std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr(
1028 reinterpret_cast<uint8_t*>(workbuf_ptr_raw), &sk_free);
1029
Nigel Tao490e6472019-02-14 14:50:53 +11001030 SkEncodedInfo::Color color =
1031 (imgcfg.pixcfg.pixel_format() == WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL)
1032 ? SkEncodedInfo::kBGRA_Color
1033 : SkEncodedInfo::kRGBA_Color;
1034
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001035 // In Skia's API, the alpha we calculate here and return is only for the
1036 // first frame.
1037 SkEncodedInfo::Alpha alpha = imgcfg.first_frame_is_opaque() ? SkEncodedInfo::kOpaque_Alpha
1038 : SkEncodedInfo::kBinary_Alpha;
1039
Nigel Tao490e6472019-02-14 14:50:53 +11001040 SkEncodedInfo encodedInfo = SkEncodedInfo::Make(width, height, color, alpha, 8);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001041
1042 *result = SkCodec::kSuccess;
Nigel Tao027f89b2019-12-06 10:56:24 +11001043 return std::unique_ptr<SkCodec>(new SkWuffsCodec(std::move(encodedInfo), std::move(stream),
1044 std::move(decoder), std::move(workbuf_ptr),
1045 workbuf_len, imgcfg, iobuf));
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001046}