blob: 88394b3c80b1567141728825ded946d836d6bc75 [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"
Brian Osman9aaec362020-05-08 14:54:37 -040018#include "src/core/SkMatrixProvider.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050019#include "src/core/SkRasterClip.h"
20#include "src/core/SkUtils.h"
Nigel Taoa6766482019-01-07 13:41:53 +110021
Ben Wagner666a9f92019-05-02 17:45:00 -040022#include <limits.h>
23
Nigel Tao7b8b0ec2019-12-16 17:41:25 +110024// Documentation on the Wuffs language and standard library (in general) and
25// its image decoding API (in particular) is at:
26//
27// - https://github.com/google/wuffs/tree/master/doc
28// - https://github.com/google/wuffs/blob/master/doc/std/image-decoders.md
29
Nigel Taoa6766482019-01-07 13:41:53 +110030// Wuffs ships as a "single file C library" or "header file library" as per
31// https://github.com/nothings/stb/blob/master/docs/stb_howto.txt
32//
33// As we have not #define'd WUFFS_IMPLEMENTATION, the #include here is
34// including a header file, even though that file name ends in ".c".
Nigel Taoe66a0b22019-03-09 15:03:14 +110035#if defined(WUFFS_IMPLEMENTATION)
36#error "SkWuffsCodec should not #define WUFFS_IMPLEMENTATION"
37#endif
Nigel Taoa6766482019-01-07 13:41:53 +110038#include "wuffs-v0.2.c"
Nigel Tao477f2212019-10-09 10:07:11 +110039#if WUFFS_VERSION_BUILD_METADATA_COMMIT_COUNT < 1942
Nigel Taoa6766482019-01-07 13:41:53 +110040#error "Wuffs version is too old. Upgrade to the latest version."
41#endif
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -040042
43#define SK_WUFFS_CODEC_BUFFER_SIZE 4096
44
Nigel Tao3dc31212019-12-07 11:46:16 +110045// Configuring a Skia build with
46// SK_WUFFS_FAVORS_PERFORMANCE_OVER_ADDITIONAL_MEMORY_SAFETY can improve decode
47// performance by some fixed amount (independent of the image size), which can
48// be a noticeable proportional improvement if the input is relatively small.
49//
50// The Wuffs library is still memory-safe either way, in that there are no
51// out-of-bounds reads or writes, and the library endeavours not to read
52// uninitialized memory. There are just fewer compiler-enforced guarantees
53// against reading uninitialized memory. For more detail, see
54// https://github.com/google/wuffs/blob/master/doc/note/initialization.md#partial-zero-initialization
55#if defined(SK_WUFFS_FAVORS_PERFORMANCE_OVER_ADDITIONAL_MEMORY_SAFETY)
56#define SK_WUFFS_INITIALIZE_FLAGS WUFFS_INITIALIZE__LEAVE_INTERNAL_BUFFERS_UNINITIALIZED
57#else
58#define SK_WUFFS_INITIALIZE_FLAGS WUFFS_INITIALIZE__DEFAULT_OPTIONS
59#endif
60
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -040061static bool fill_buffer(wuffs_base__io_buffer* b, SkStream* s) {
62 b->compact();
63 size_t num_read = s->read(b->data.ptr + b->meta.wi, b->data.len - b->meta.wi);
64 b->meta.wi += num_read;
65 b->meta.closed = s->isAtEnd();
66 return num_read > 0;
67}
68
69static bool seek_buffer(wuffs_base__io_buffer* b, SkStream* s, uint64_t pos) {
70 // Try to re-position the io_buffer's meta.ri read-index first, which is
71 // cheaper than seeking in the backing SkStream.
72 if ((pos >= b->meta.pos) && (pos - b->meta.pos <= b->meta.wi)) {
73 b->meta.ri = pos - b->meta.pos;
74 return true;
75 }
76 // Seek in the backing SkStream.
77 if ((pos > SIZE_MAX) || (!s->seek(pos))) {
78 return false;
79 }
80 b->meta.wi = 0;
81 b->meta.ri = 0;
82 b->meta.pos = pos;
83 b->meta.closed = false;
84 return true;
85}
86
87static SkEncodedInfo::Alpha wuffs_blend_to_skia_alpha(wuffs_base__animation_blend w) {
88 return (w == WUFFS_BASE__ANIMATION_BLEND__OPAQUE) ? SkEncodedInfo::kOpaque_Alpha
89 : SkEncodedInfo::kUnpremul_Alpha;
90}
91
92static SkCodecAnimation::Blend wuffs_blend_to_skia_blend(wuffs_base__animation_blend w) {
93 return (w == WUFFS_BASE__ANIMATION_BLEND__SRC) ? SkCodecAnimation::Blend::kBG
94 : SkCodecAnimation::Blend::kPriorFrame;
95}
96
97static SkCodecAnimation::DisposalMethod wuffs_disposal_to_skia_disposal(
98 wuffs_base__animation_disposal w) {
99 switch (w) {
100 case WUFFS_BASE__ANIMATION_DISPOSAL__RESTORE_BACKGROUND:
101 return SkCodecAnimation::DisposalMethod::kRestoreBGColor;
102 case WUFFS_BASE__ANIMATION_DISPOSAL__RESTORE_PREVIOUS:
103 return SkCodecAnimation::DisposalMethod::kRestorePrevious;
104 default:
105 return SkCodecAnimation::DisposalMethod::kKeep;
106 }
107}
108
Nigel Tao4f32a292019-11-13 15:41:55 +1100109static SkAlphaType to_alpha_type(bool opaque) {
110 return opaque ? kOpaque_SkAlphaType : kPremul_SkAlphaType;
111}
112
Nigel Tao2777cd32019-10-29 11:10:25 +1100113static SkCodec::Result reset_and_decode_image_config(wuffs_gif__decoder* decoder,
114 wuffs_base__image_config* imgcfg,
115 wuffs_base__io_buffer* b,
Nigel Tao4f32a292019-11-13 15:41:55 +1100116 SkStream* s) {
Nigel Tao3dc31212019-12-07 11:46:16 +1100117 // Calling decoder->initialize will memset most or all of it to zero,
118 // depending on SK_WUFFS_INITIALIZE_FLAGS.
119 const char* status =
120 decoder->initialize(sizeof__wuffs_gif__decoder(), WUFFS_VERSION, SK_WUFFS_INITIALIZE_FLAGS);
Nigel Tao4f32a292019-11-13 15:41:55 +1100121 if (status != nullptr) {
122 SkCodecPrintf("initialize: %s", status);
123 return SkCodec::kInternalError;
124 }
125 while (true) {
126 status = decoder->decode_image_config(imgcfg, b);
127 if (status == nullptr) {
128 break;
129 } else if (status != wuffs_base__suspension__short_read) {
130 SkCodecPrintf("decode_image_config: %s", status);
131 return SkCodec::kErrorInInput;
132 } else if (!fill_buffer(b, s)) {
133 return SkCodec::kIncompleteInput;
134 }
135 }
136
137 // A GIF image's natural color model is indexed color: 1 byte per pixel,
138 // indexing a 256-element palette.
139 //
140 // For Skia, we override that to decode to 4 bytes per pixel, BGRA or RGBA.
141 wuffs_base__pixel_format pixfmt = 0;
142 switch (kN32_SkColorType) {
143 case kBGRA_8888_SkColorType:
144 pixfmt = WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL;
145 break;
146 case kRGBA_8888_SkColorType:
147 pixfmt = WUFFS_BASE__PIXEL_FORMAT__RGBA_NONPREMUL;
148 break;
149 default:
150 return SkCodec::kInternalError;
151 }
152 if (imgcfg) {
153 imgcfg->pixcfg.set(pixfmt, WUFFS_BASE__PIXEL_SUBSAMPLING__NONE, imgcfg->pixcfg.width(),
154 imgcfg->pixcfg.height());
155 }
156
157 return SkCodec::kSuccess;
158}
159
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400160// -------------------------------- Class definitions
161
162class SkWuffsCodec;
163
164class SkWuffsFrame final : public SkFrame {
165public:
166 SkWuffsFrame(wuffs_base__frame_config* fc);
167
168 SkCodec::FrameInfo frameInfo(bool fullyReceived) const;
169 uint64_t ioPosition() const;
170
171 // SkFrame overrides.
172 SkEncodedInfo::Alpha onReportedAlpha() const override;
173
174private:
175 uint64_t fIOPosition;
176 SkEncodedInfo::Alpha fReportedAlpha;
177
178 typedef SkFrame INHERITED;
179};
180
181// SkWuffsFrameHolder is a trivial indirector that forwards its calls onto a
182// SkWuffsCodec. It is a separate class as SkWuffsCodec would otherwise
183// inherit from both SkCodec and SkFrameHolder, and Skia style discourages
184// multiple inheritance (e.g. with its "typedef Foo INHERITED" convention).
185class SkWuffsFrameHolder final : public SkFrameHolder {
186public:
187 SkWuffsFrameHolder() : INHERITED() {}
188
189 void init(SkWuffsCodec* codec, int width, int height);
190
191 // SkFrameHolder overrides.
192 const SkFrame* onGetFrame(int i) const override;
193
194private:
195 const SkWuffsCodec* fCodec;
196
197 typedef SkFrameHolder INHERITED;
198};
199
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400200class SkWuffsCodec final : public SkScalingCodec {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400201public:
202 SkWuffsCodec(SkEncodedInfo&& encodedInfo,
203 std::unique_ptr<SkStream> stream,
204 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> dec,
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400205 std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr,
206 size_t workbuf_len,
207 wuffs_base__image_config imgcfg,
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400208 wuffs_base__io_buffer iobuf);
209
210 const SkWuffsFrame* frame(int i) const;
211
212private:
Nigel Tao2777cd32019-10-29 11:10:25 +1100213 // It is valid, in terms of the SkCodec API, to call SkCodec::getFrameCount
214 // while in an incremental decode (after onStartIncrementalDecode returns
215 // and before the rest of the image is decoded). Some Skia users expect
216 // getFrameCount to increase, and the SkStream to advance, when given more
217 // data.
218 //
219 // On the other hand, while in an incremental decode, the underlying Wuffs
220 // object is suspended in a coroutine. To keep its internal proof-of-safety
221 // invariants consistent, there's only two things you can safely do with a
222 // suspended Wuffs object: resume the coroutine, or reset all state (memset
223 // to zero and start again).
224 //
225 // The Wuffs API provides a limited, optional form of seeking, to the start
226 // of an animation frame's data, but does not provide arbitrary save and
227 // load of its internal state whilst in the middle of an animation frame.
228 //
229 // SkWuffsCodec therefore uses two Wuffs decoders: a primary decoder
230 // (kIncrDecode) to support startIncrementalDecode / incrementalDecode, and
231 // a secondary decoder (kFrameCount) to support getFrameCount. The two
232 // decoders' states can change independently.
233 //
234 // As of Wuffs version 0.2, both of these decoders have the same type. A
235 // future Wuffs version might let us use a different type for kFrameCount,
236 // one that is much lighter weight (in terms of memory requirements), as it
237 // doesn't have to handle decompressing pixel data.
238 enum WhichDecoder {
239 kIncrDecode,
240 kFrameCount,
241 kNumDecoders,
242 };
243
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400244 // SkCodec overrides.
245 SkEncodedImageFormat onGetEncodedFormat() const override;
246 Result onGetPixels(const SkImageInfo&, void*, size_t, const Options&, int*) override;
247 const SkFrameHolder* getFrameHolder() const override;
248 Result onStartIncrementalDecode(const SkImageInfo& dstInfo,
249 void* dst,
250 size_t rowBytes,
251 const SkCodec::Options& options) override;
252 Result onIncrementalDecode(int* rowsDecoded) override;
253 int onGetFrameCount() override;
254 bool onGetFrameInfo(int, FrameInfo*) const override;
255 int onGetRepetitionCount() override;
256
Nigel Tao027f89b2019-12-06 10:56:24 +1100257 // Two separate implementations of onStartIncrementalDecode and
258 // onIncrementalDecode, named "one pass" and "two pass" decoding. One pass
259 // decoding writes directly from the Wuffs image decoder to the dst buffer
260 // (the dst argument to onStartIncrementalDecode). Two pass decoding first
261 // writes into an intermediate buffer, and then composites and transforms
262 // the intermediate buffer into the dst buffer.
263 //
264 // In the general case, we need the two pass decoder, because of Skia API
265 // features that Wuffs doesn't support (e.g. color correction, scaling,
266 // RGB565). But as an optimization, we use one pass decoding (it's faster
267 // and uses less memory) if applicable (see the assignment to
268 // fIncrDecOnePass that calculates when we can do so).
269 Result onStartIncrementalDecodeOnePass(const SkImageInfo& dstInfo,
270 uint8_t* dst,
271 size_t rowBytes,
272 const SkCodec::Options& options,
273 wuffs_base__pixel_format pixelFormat,
274 size_t bytesPerPixel);
275 Result onStartIncrementalDecodeTwoPass();
276 Result onIncrementalDecodeOnePass();
277 Result onIncrementalDecodeTwoPass();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400278
Nigel Tao027f89b2019-12-06 10:56:24 +1100279 void onGetFrameCountInternal();
280 Result seekFrame(WhichDecoder which, int frameIndex);
Nigel Tao2777cd32019-10-29 11:10:25 +1100281 Result resetDecoder(WhichDecoder which);
282 const char* decodeFrameConfig(WhichDecoder which);
283 const char* decodeFrame(WhichDecoder which);
284 void updateNumFullyReceivedFrames(WhichDecoder which);
285
286 SkWuffsFrameHolder fFrameHolder;
287 std::unique_ptr<SkStream> fStream;
Nigel Tao2777cd32019-10-29 11:10:25 +1100288 std::unique_ptr<uint8_t, decltype(&sk_free)> fWorkbufPtr;
289 size_t fWorkbufLen;
290
291 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> fDecoders[WhichDecoder::kNumDecoders];
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400292
293 const uint64_t fFirstFrameIOPosition;
Nigel Tao2777cd32019-10-29 11:10:25 +1100294 wuffs_base__frame_config fFrameConfigs[WhichDecoder::kNumDecoders];
Nigel Tao027f89b2019-12-06 10:56:24 +1100295 wuffs_base__pixel_config fPixelConfig;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400296 wuffs_base__pixel_buffer fPixelBuffer;
297 wuffs_base__io_buffer fIOBuffer;
298
299 // Incremental decoding state.
Nigel Tao0185b952018-11-08 10:47:24 +1100300 uint8_t* fIncrDecDst;
Nigel Tao2777cd32019-10-29 11:10:25 +1100301 uint64_t fIncrDecReaderIOPosition;
Nigel Tao0185b952018-11-08 10:47:24 +1100302 size_t fIncrDecRowBytes;
Nigel Tao027f89b2019-12-06 10:56:24 +1100303 bool fIncrDecOnePass;
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400304 bool fFirstCallToIncrementalDecode;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400305
Nigel Tao027f89b2019-12-06 10:56:24 +1100306 // Lazily allocated intermediate pixel buffer, for two pass decoding.
307 std::unique_ptr<uint8_t, decltype(&sk_free)> fTwoPassPixbufPtr;
308 size_t fTwoPassPixbufLen;
309
Nigel Tao3876a9f2019-11-14 09:04:45 +1100310 uint64_t fFrameCountReaderIOPosition;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400311 uint64_t fNumFullyReceivedFrames;
312 std::vector<SkWuffsFrame> fFrames;
313 bool fFramesComplete;
314
Nigel Tao2777cd32019-10-29 11:10:25 +1100315 // If calling an fDecoders[which] method returns an incomplete status, then
316 // fDecoders[which] is suspended in a coroutine (i.e. waiting on I/O or
317 // halted on a non-recoverable error). To keep its internal proof-of-safety
318 // invariants consistent, there's only two things you can safely do with a
319 // suspended Wuffs object: resume the coroutine, or reset all state (memset
320 // to zero and start again).
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400321 //
Nigel Tao2777cd32019-10-29 11:10:25 +1100322 // If fDecoderIsSuspended[which], and we aren't sure that we're going to
323 // resume the coroutine, then we will need to call this->resetDecoder
324 // before calling other fDecoders[which] methods.
325 bool fDecoderIsSuspended[WhichDecoder::kNumDecoders];
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400326
327 uint8_t fBuffer[SK_WUFFS_CODEC_BUFFER_SIZE];
328
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400329 typedef SkScalingCodec INHERITED;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400330};
331
332// -------------------------------- SkWuffsFrame implementation
333
334SkWuffsFrame::SkWuffsFrame(wuffs_base__frame_config* fc)
335 : INHERITED(fc->index()),
336 fIOPosition(fc->io_position()),
337 fReportedAlpha(wuffs_blend_to_skia_alpha(fc->blend())) {
338 wuffs_base__rect_ie_u32 r = fc->bounds();
339 this->setXYWH(r.min_incl_x, r.min_incl_y, r.width(), r.height());
340 this->setDisposalMethod(wuffs_disposal_to_skia_disposal(fc->disposal()));
341 this->setDuration(fc->duration() / WUFFS_BASE__FLICKS_PER_MILLISECOND);
342 this->setBlend(wuffs_blend_to_skia_blend(fc->blend()));
343}
344
345SkCodec::FrameInfo SkWuffsFrame::frameInfo(bool fullyReceived) const {
Nigel Taoef40e332019-04-05 10:28:40 +1100346 SkCodec::FrameInfo ret;
347 ret.fRequiredFrame = getRequiredFrame();
348 ret.fDuration = getDuration();
349 ret.fFullyReceived = fullyReceived;
350 ret.fAlphaType = hasAlpha() ? kUnpremul_SkAlphaType : kOpaque_SkAlphaType;
351 ret.fDisposalMethod = getDisposalMethod();
352 return ret;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400353}
354
355uint64_t SkWuffsFrame::ioPosition() const {
356 return fIOPosition;
357}
358
359SkEncodedInfo::Alpha SkWuffsFrame::onReportedAlpha() const {
360 return fReportedAlpha;
361}
362
363// -------------------------------- SkWuffsFrameHolder implementation
364
365void SkWuffsFrameHolder::init(SkWuffsCodec* codec, int width, int height) {
366 fCodec = codec;
367 // Initialize SkFrameHolder's (the superclass) fields.
368 fScreenWidth = width;
369 fScreenHeight = height;
370}
371
372const SkFrame* SkWuffsFrameHolder::onGetFrame(int i) const {
373 return fCodec->frame(i);
374};
375
376// -------------------------------- SkWuffsCodec implementation
377
378SkWuffsCodec::SkWuffsCodec(SkEncodedInfo&& encodedInfo,
379 std::unique_ptr<SkStream> stream,
380 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> dec,
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400381 std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr,
382 size_t workbuf_len,
383 wuffs_base__image_config imgcfg,
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400384 wuffs_base__io_buffer iobuf)
385 : INHERITED(std::move(encodedInfo),
386 skcms_PixelFormat_RGBA_8888,
387 // Pass a nullptr SkStream to the SkCodec constructor. We
388 // manage the stream ourselves, as the default SkCodec behavior
389 // is too trigger-happy on rewinding the stream.
390 nullptr),
Nigel Tao0185b952018-11-08 10:47:24 +1100391 fFrameHolder(),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400392 fStream(std::move(stream)),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400393 fWorkbufPtr(std::move(workbuf_ptr)),
394 fWorkbufLen(workbuf_len),
Nigel Tao2777cd32019-10-29 11:10:25 +1100395 fDecoders{
396 std::move(dec),
397 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)>(nullptr, sk_free),
398 },
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400399 fFirstFrameIOPosition(imgcfg.first_frame_io_position()),
Nigel Tao2777cd32019-10-29 11:10:25 +1100400 fFrameConfigs{
401 wuffs_base__null_frame_config(),
402 wuffs_base__null_frame_config(),
403 },
Nigel Tao027f89b2019-12-06 10:56:24 +1100404 fPixelConfig(imgcfg.pixcfg),
405 fPixelBuffer(wuffs_base__null_pixel_buffer()),
Nigel Tao96c10a02019-09-25 11:08:42 +1000406 fIOBuffer(wuffs_base__empty_io_buffer()),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400407 fIncrDecDst(nullptr),
Nigel Tao2777cd32019-10-29 11:10:25 +1100408 fIncrDecReaderIOPosition(0),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400409 fIncrDecRowBytes(0),
Nigel Tao027f89b2019-12-06 10:56:24 +1100410 fIncrDecOnePass(false),
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400411 fFirstCallToIncrementalDecode(false),
Nigel Tao027f89b2019-12-06 10:56:24 +1100412 fTwoPassPixbufPtr(nullptr, &sk_free),
413 fTwoPassPixbufLen(0),
Nigel Tao3876a9f2019-11-14 09:04:45 +1100414 fFrameCountReaderIOPosition(0),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400415 fNumFullyReceivedFrames(0),
416 fFramesComplete(false),
Nigel Tao2777cd32019-10-29 11:10:25 +1100417 fDecoderIsSuspended{
418 false,
419 false,
420 } {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400421 fFrameHolder.init(this, imgcfg.pixcfg.width(), imgcfg.pixcfg.height());
422
423 // Initialize fIOBuffer's fields, copying any outstanding data from iobuf to
424 // fIOBuffer, as iobuf's backing array may not be valid for the lifetime of
425 // this SkWuffsCodec object, but fIOBuffer's backing array (fBuffer) is.
426 SkASSERT(iobuf.data.len == SK_WUFFS_CODEC_BUFFER_SIZE);
427 memmove(fBuffer, iobuf.data.ptr, iobuf.meta.wi);
Nigel Tao48aa2212019-03-09 14:59:11 +1100428 fIOBuffer.data = wuffs_base__make_slice_u8(fBuffer, SK_WUFFS_CODEC_BUFFER_SIZE);
429 fIOBuffer.meta = iobuf.meta;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400430}
431
432const SkWuffsFrame* SkWuffsCodec::frame(int i) const {
433 if ((0 <= i) && (static_cast<size_t>(i) < fFrames.size())) {
434 return &fFrames[i];
435 }
436 return nullptr;
437}
438
439SkEncodedImageFormat SkWuffsCodec::onGetEncodedFormat() const {
440 return SkEncodedImageFormat::kGIF;
441}
442
443SkCodec::Result SkWuffsCodec::onGetPixels(const SkImageInfo& dstInfo,
444 void* dst,
445 size_t rowBytes,
446 const Options& options,
447 int* rowsDecoded) {
448 SkCodec::Result result = this->onStartIncrementalDecode(dstInfo, dst, rowBytes, options);
449 if (result != kSuccess) {
450 return result;
451 }
452 return this->onIncrementalDecode(rowsDecoded);
453}
454
455const SkFrameHolder* SkWuffsCodec::getFrameHolder() const {
456 return &fFrameHolder;
457}
458
459SkCodec::Result SkWuffsCodec::onStartIncrementalDecode(const SkImageInfo& dstInfo,
460 void* dst,
461 size_t rowBytes,
462 const SkCodec::Options& options) {
Nigel Tao1f1cd1f2019-06-22 17:35:38 +1000463 if (!dst) {
464 return SkCodec::kInvalidParameters;
465 }
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400466 if (options.fSubset) {
467 return SkCodec::kUnimplemented;
468 }
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400469 if (options.fFrameIndex > 0 && SkColorTypeIsAlwaysOpaque(dstInfo.colorType())) {
470 return SkCodec::kInvalidConversion;
471 }
Nigel Tao2777cd32019-10-29 11:10:25 +1100472 SkCodec::Result result = this->seekFrame(WhichDecoder::kIncrDecode, options.fFrameIndex);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400473 if (result != SkCodec::kSuccess) {
474 return result;
475 }
476
Nigel Tao2777cd32019-10-29 11:10:25 +1100477 const char* status = this->decodeFrameConfig(WhichDecoder::kIncrDecode);
Nigel Taob7a1b512019-02-10 12:19:50 +1100478 if (status == wuffs_base__suspension__short_read) {
Leon Scroggins IIIcb6b8842018-12-04 13:55:13 -0500479 return SkCodec::kIncompleteInput;
Nigel Taob7a1b512019-02-10 12:19:50 +1100480 } else if (status != nullptr) {
Leon Scroggins IIIcb6b8842018-12-04 13:55:13 -0500481 SkCodecPrintf("decodeFrameConfig: %s", status);
482 return SkCodec::kErrorInInput;
483 }
Nigel Taob7a1b512019-02-10 12:19:50 +1100484
Nigel Tao027f89b2019-12-06 10:56:24 +1100485 wuffs_base__pixel_format pixelFormat = WUFFS_BASE__PIXEL_FORMAT__INVALID;
486 size_t bytesPerPixel = 0;
487
488 switch (dstInfo.colorType()) {
489 case kBGRA_8888_SkColorType:
490 pixelFormat = WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL;
491 bytesPerPixel = 4;
492 break;
493 case kRGBA_8888_SkColorType:
494 pixelFormat = WUFFS_BASE__PIXEL_FORMAT__RGBA_NONPREMUL;
495 bytesPerPixel = 4;
496 break;
497 default:
498 break;
499 }
500
501 // We can use "one pass" decoding if we have a Skia pixel format that Wuffs
502 // supports...
503 fIncrDecOnePass =
504 (pixelFormat != WUFFS_BASE__PIXEL_FORMAT__INVALID) &&
505 // ...and no color profile (as Wuffs does not support them)...
506 (!getEncodedInfo().profile()) &&
507 // ...and we have an independent frame (as Wuffs does not support the
508 // equivalent of SkBlendMode::kSrcOver)...
509 ((options.fFrameIndex == 0) ||
510 (this->frame(options.fFrameIndex)->getRequiredFrame() == SkCodec::kNoFrame)) &&
511 // ...and we use the identity transform (as Wuffs does not support
512 // scaling).
513 (this->dimensions() == dstInfo.dimensions());
514
515 result = fIncrDecOnePass ? this->onStartIncrementalDecodeOnePass(
516 dstInfo, static_cast<uint8_t*>(dst), rowBytes, options,
517 pixelFormat, bytesPerPixel)
518 : this->onStartIncrementalDecodeTwoPass();
519 if (result != SkCodec::kSuccess) {
520 return result;
521 }
522
523 fIncrDecDst = static_cast<uint8_t*>(dst);
524 fIncrDecReaderIOPosition = fIOBuffer.reader_io_position();
525 fIncrDecRowBytes = rowBytes;
526 fFirstCallToIncrementalDecode = true;
527 return SkCodec::kSuccess;
528}
529
530SkCodec::Result SkWuffsCodec::onStartIncrementalDecodeOnePass(const SkImageInfo& dstInfo,
531 uint8_t* dst,
532 size_t rowBytes,
533 const SkCodec::Options& options,
534 wuffs_base__pixel_format pixelFormat,
535 size_t bytesPerPixel) {
536 wuffs_base__pixel_config pixelConfig;
537 pixelConfig.set(pixelFormat, WUFFS_BASE__PIXEL_SUBSAMPLING__NONE, dstInfo.width(),
538 dstInfo.height());
539
540 wuffs_base__table_u8 table;
541 table.ptr = dst;
542 table.width = static_cast<size_t>(dstInfo.width()) * bytesPerPixel;
543 table.height = dstInfo.height();
544 table.stride = rowBytes;
545
546 const char* status = fPixelBuffer.set_from_table(&pixelConfig, table);
547 if (status != nullptr) {
548 SkCodecPrintf("set_from_table: %s", status);
Nigel Tao490e6472019-02-14 14:50:53 +1100549 return SkCodec::kInternalError;
550 }
Nigel Taob7a1b512019-02-10 12:19:50 +1100551
Nigel Tao027f89b2019-12-06 10:56:24 +1100552 SkSampler::Fill(dstInfo, dst, rowBytes, options.fZeroInitialized);
553 return SkCodec::kSuccess;
554}
555
556SkCodec::Result SkWuffsCodec::onStartIncrementalDecodeTwoPass() {
557 // Either re-use the previously allocated "two pass" pixel buffer (and
558 // memset to zero), or allocate (and zero initialize) a new one.
559 bool already_zeroed = false;
560
561 if (!fTwoPassPixbufPtr) {
562 uint64_t pixbuf_len = fPixelConfig.pixbuf_len();
563 void* pixbuf_ptr_raw = (pixbuf_len <= SIZE_MAX)
564 ? sk_malloc_flags(pixbuf_len, SK_MALLOC_ZERO_INITIALIZE)
565 : nullptr;
566 if (!pixbuf_ptr_raw) {
567 return SkCodec::kInternalError;
568 }
569 fTwoPassPixbufPtr.reset(reinterpret_cast<uint8_t*>(pixbuf_ptr_raw));
570 fTwoPassPixbufLen = SkToSizeT(pixbuf_len);
571 already_zeroed = true;
572 }
573
574 const char* status = fPixelBuffer.set_from_slice(
575 &fPixelConfig, wuffs_base__make_slice_u8(fTwoPassPixbufPtr.get(), fTwoPassPixbufLen));
576 if (status != nullptr) {
577 SkCodecPrintf("set_from_slice: %s", status);
578 return SkCodec::kInternalError;
579 }
580
581 if (!already_zeroed) {
582 uint32_t src_bits_per_pixel =
583 wuffs_base__pixel_format__bits_per_pixel(fPixelConfig.pixel_format());
584 if ((src_bits_per_pixel == 0) || (src_bits_per_pixel % 8 != 0)) {
585 return SkCodec::kInternalError;
586 }
587 size_t src_bytes_per_pixel = src_bits_per_pixel / 8;
588
Nigel Tao39da10b2019-11-15 15:27:44 +1100589 wuffs_base__rect_ie_u32 frame_rect = fFrameConfigs[WhichDecoder::kIncrDecode].bounds();
590 wuffs_base__table_u8 pixels = fPixelBuffer.plane(0);
Nigel Tao6ec1b392019-11-20 12:28:50 +1100591
592 uint8_t* ptr = pixels.ptr + (frame_rect.min_incl_y * pixels.stride) +
593 (frame_rect.min_incl_x * src_bytes_per_pixel);
594 size_t len = frame_rect.width() * src_bytes_per_pixel;
595
596 // As an optimization, issue a single sk_bzero call, if possible.
597 // Otherwise, zero out each row separately.
598 if ((len == pixels.stride) && (frame_rect.min_incl_y < frame_rect.max_excl_y)) {
599 sk_bzero(ptr, len * (frame_rect.max_excl_y - frame_rect.min_incl_y));
600 } else {
601 for (uint32_t y = frame_rect.min_incl_y; y < frame_rect.max_excl_y; y++) {
602 sk_bzero(ptr, len);
603 ptr += pixels.stride;
604 }
Nigel Tao39da10b2019-11-15 15:27:44 +1100605 }
Nigel Taob7a1b512019-02-10 12:19:50 +1100606 }
607
Nigel Taob7a1b512019-02-10 12:19:50 +1100608 return SkCodec::kSuccess;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400609}
610
611SkCodec::Result SkWuffsCodec::onIncrementalDecode(int* rowsDecoded) {
612 if (!fIncrDecDst) {
613 return SkCodec::kInternalError;
614 }
615
Nigel Tao2777cd32019-10-29 11:10:25 +1100616 // If multiple SkCodec::incrementalDecode calls are made consecutively (or
617 // if SkCodec::incrementalDecode is called immediately after
618 // SkCodec::startIncrementalDecode), then this seek should be a no-op.
619 // However, it is possible to interleave SkCodec::getFrameCount calls in
620 // between SkCodec::incrementalDecode calls, and those other calls may
621 // advance the stream. This seek restores the stream to where the last
622 // SkCodec::startIncrementalDecode or SkCodec::incrementalDecode stopped.
623 if (!seek_buffer(&fIOBuffer, fStream.get(), fIncrDecReaderIOPosition)) {
624 return SkCodec::kInternalError;
625 }
626
Nigel Tao027f89b2019-12-06 10:56:24 +1100627 if (rowsDecoded) {
628 *rowsDecoded = dstInfo().height();
629 }
630
631 SkCodec::Result result =
632 fIncrDecOnePass ? this->onIncrementalDecodeOnePass() : this->onIncrementalDecodeTwoPass();
Nigel Tao2777cd32019-10-29 11:10:25 +1100633 if (result == SkCodec::kSuccess) {
634 fIncrDecDst = nullptr;
635 fIncrDecReaderIOPosition = 0;
636 fIncrDecRowBytes = 0;
Nigel Tao027f89b2019-12-06 10:56:24 +1100637 fIncrDecOnePass = false;
Nigel Tao2777cd32019-10-29 11:10:25 +1100638 } else {
639 fIncrDecReaderIOPosition = fIOBuffer.reader_io_position();
640 }
641 return result;
642}
643
Nigel Tao027f89b2019-12-06 10:56:24 +1100644SkCodec::Result SkWuffsCodec::onIncrementalDecodeOnePass() {
645 const char* status = this->decodeFrame(WhichDecoder::kIncrDecode);
646 if (status != nullptr) {
647 if (status == wuffs_base__suspension__short_read) {
648 return SkCodec::kIncompleteInput;
649 } else {
650 SkCodecPrintf("decodeFrame: %s", status);
651 return SkCodec::kErrorInInput;
652 }
653 }
654 return SkCodec::kSuccess;
655}
656
657SkCodec::Result SkWuffsCodec::onIncrementalDecodeTwoPass() {
Leon Scroggins III699d41e2019-02-07 09:25:51 -0500658 SkCodec::Result result = SkCodec::kSuccess;
Nigel Tao2777cd32019-10-29 11:10:25 +1100659 const char* status = this->decodeFrame(WhichDecoder::kIncrDecode);
660 bool independent;
661 SkAlphaType alphaType;
662 const int index = options().fFrameIndex;
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400663 if (index == 0) {
664 independent = true;
665 alphaType = to_alpha_type(getEncodedInfo().opaque());
666 } else {
667 const SkWuffsFrame* f = this->frame(index);
668 independent = f->getRequiredFrame() == SkCodec::kNoFrame;
669 alphaType = to_alpha_type(f->reportedAlpha() == SkEncodedInfo::kOpaque_Alpha);
670 }
Leon Scroggins III699d41e2019-02-07 09:25:51 -0500671 if (status != nullptr) {
672 if (status == wuffs_base__suspension__short_read) {
673 result = SkCodec::kIncompleteInput;
674 } else {
675 SkCodecPrintf("decodeFrame: %s", status);
676 result = SkCodec::kErrorInInput;
677 }
678
679 if (!independent) {
680 // For a dependent frame, we cannot blend the partial result, since
681 // that will overwrite the contribution from prior frames.
682 return result;
683 }
684 }
685
Nigel Tao490e6472019-02-14 14:50:53 +1100686 uint32_t src_bits_per_pixel =
687 wuffs_base__pixel_format__bits_per_pixel(fPixelBuffer.pixcfg.pixel_format());
688 if ((src_bits_per_pixel == 0) || (src_bits_per_pixel % 8 != 0)) {
689 return SkCodec::kInternalError;
690 }
691 size_t src_bytes_per_pixel = src_bits_per_pixel / 8;
692
Nigel Tao2777cd32019-10-29 11:10:25 +1100693 wuffs_base__rect_ie_u32 frame_rect = fFrameConfigs[WhichDecoder::kIncrDecode].bounds();
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400694 if (fFirstCallToIncrementalDecode) {
Nigel Tao490e6472019-02-14 14:50:53 +1100695 if (frame_rect.width() > (SIZE_MAX / src_bytes_per_pixel)) {
696 return SkCodec::kInternalError;
697 }
698
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400699 auto bounds = SkIRect::MakeLTRB(frame_rect.min_incl_x, frame_rect.min_incl_y,
700 frame_rect.max_excl_x, frame_rect.max_excl_y);
701
Leon Scroggins IIIcb6b8842018-12-04 13:55:13 -0500702 // If the frame rect does not fill the output, ensure that those pixels are not
Nigel Taob7a1b512019-02-10 12:19:50 +1100703 // left uninitialized.
Leon Scroggins III44076362019-02-15 13:56:44 -0500704 if (independent && (bounds != this->bounds() || result != kSuccess)) {
Nigel Tao2777cd32019-10-29 11:10:25 +1100705 SkSampler::Fill(dstInfo(), fIncrDecDst, fIncrDecRowBytes, options().fZeroInitialized);
Leon Scroggins III9b0ba2c2018-11-19 14:52:37 -0500706 }
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400707 fFirstCallToIncrementalDecode = false;
708 } else {
709 // Existing clients intend to only show frames beyond the first if they
710 // are complete (based on FrameInfo::fFullyReceived), since it might
711 // look jarring to draw a partial frame over an existing frame. If they
712 // changed their behavior and expected to continue decoding a partial
713 // frame after the first one, we'll need to update our blending code.
714 // Otherwise, if the frame were interlaced and not independent, the
715 // second pass may have an overlapping dirty_rect with the first,
716 // resulting in blending with the first pass.
717 SkASSERT(index == 0);
Nigel Tao9859ef82019-02-13 13:20:02 +1100718 }
Nigel Tao0185b952018-11-08 10:47:24 +1100719
Leon Scroggins IIIdad4bfc2018-12-10 12:37:10 -0500720 // If the frame's dirty rect is empty, no need to swizzle.
Nigel Tao2777cd32019-10-29 11:10:25 +1100721 wuffs_base__rect_ie_u32 dirty_rect = fDecoders[WhichDecoder::kIncrDecode]->frame_dirty_rect();
Leon Scroggins IIIdad4bfc2018-12-10 12:37:10 -0500722 if (!dirty_rect.is_empty()) {
Nigel Tao490e6472019-02-14 14:50:53 +1100723 wuffs_base__table_u8 pixels = fPixelBuffer.plane(0);
Leon Scroggins III7a3805c2018-12-07 09:21:30 -0500724
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400725 // The Wuffs model is that the dst buffer is the image, not the frame.
726 // The expectation is that you allocate the buffer once, but re-use it
727 // for the N frames, regardless of each frame's top-left co-ordinate.
728 //
729 // To get from the start (in the X-direction) of the image to the start
730 // of the dirty_rect, we adjust s by (dirty_rect.min_incl_x * src_bytes_per_pixel).
Nigel Tao2777cd32019-10-29 11:10:25 +1100731 uint8_t* s = pixels.ptr + (dirty_rect.min_incl_y * pixels.stride) +
732 (dirty_rect.min_incl_x * src_bytes_per_pixel);
Leon Scroggins III7a3805c2018-12-07 09:21:30 -0500733
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400734 // Currently, this is only used for GIF, which will never have an ICC profile. When it is
735 // used for other formats that might have one, we will need to transform from profiles that
736 // do not have corresponding SkColorSpaces.
737 SkASSERT(!getEncodedInfo().profile());
738
Nigel Tao2777cd32019-10-29 11:10:25 +1100739 auto srcInfo =
740 getInfo().makeWH(dirty_rect.width(), dirty_rect.height()).makeAlphaType(alphaType);
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400741 SkBitmap src;
742 src.installPixels(srcInfo, s, pixels.stride);
743 SkPaint paint;
744 if (independent) {
745 paint.setBlendMode(SkBlendMode::kSrc);
Leon Scroggins III7a3805c2018-12-07 09:21:30 -0500746 }
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400747
748 SkDraw draw;
749 draw.fDst.reset(dstInfo(), fIncrDecDst, fIncrDecRowBytes);
750 SkMatrix matrix = SkMatrix::MakeRectToRect(SkRect::Make(this->dimensions()),
751 SkRect::Make(this->dstInfo().dimensions()),
752 SkMatrix::kFill_ScaleToFit);
Brian Osman9aaec362020-05-08 14:54:37 -0400753 SkSimpleMatrixProvider matrixProvider(matrix);
754 draw.fMatrixProvider = &matrixProvider;
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400755 SkRasterClip rc(SkIRect::MakeSize(this->dstInfo().dimensions()));
756 draw.fRC = &rc;
757
Mike Reedc80ee452020-05-21 16:05:02 +0000758 SkMatrix translate = SkMatrix::MakeTrans(dirty_rect.min_incl_x, dirty_rect.min_incl_y);
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400759 draw.drawBitmap(src, translate, nullptr, paint);
Leon Scroggins III7a3805c2018-12-07 09:21:30 -0500760 }
Nigel Taof0148c42019-12-08 19:12:13 +1100761
762 if (result == SkCodec::kSuccess) {
763 // On success, we are done using the "two pass" pixel buffer for this
764 // frame. We have the option of releasing its memory, but there is a
765 // trade-off. If decoding a subsequent frame will also need "two pass"
766 // decoding, it would have to re-allocate the buffer instead of just
767 // re-using it. On the other hand, if there is no subsequent frame, and
768 // the SkWuffsCodec object isn't deleted soon, then we are holding
769 // megabytes of memory longer than we need to.
770 //
771 // For example, when the Chromium web browser decodes the <img> tags in
772 // a HTML page, the SkCodec object can live until navigating away from
773 // the page, which can be much longer than when the pixels are fully
774 // decoded, especially for a still (non-animated) image. Even for
775 // looping animations, caching the decoded frames (at the higher HTML
776 // renderer layer) may mean that each frame is only decoded once (at
777 // the lower SkCodec layer), in sequence.
778 //
779 // The heuristic we use here is to free the memory if we have decoded
780 // the last frame of the animation (or, for still images, the only
781 // frame). The output of the next decode request (if any) should be the
782 // same either way, but the steady state memory use should hopefully be
783 // lower than always keeping the fTwoPassPixbufPtr buffer up until the
784 // SkWuffsCodec destructor runs.
785 //
786 // This only applies to "two pass" decoding. "One pass" decoding does
787 // not allocate, free or otherwise use fTwoPassPixbufPtr.
788 if (fFramesComplete && (static_cast<size_t>(options().fFrameIndex) == fFrames.size() - 1)) {
789 fTwoPassPixbufPtr.reset(nullptr);
790 fTwoPassPixbufLen = 0;
791 }
792 }
793
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400794 return result;
795}
796
797int SkWuffsCodec::onGetFrameCount() {
Nigel Tao3876a9f2019-11-14 09:04:45 +1100798 if (!fFramesComplete && seek_buffer(&fIOBuffer, fStream.get(), fFrameCountReaderIOPosition)) {
Nigel Tao2777cd32019-10-29 11:10:25 +1100799 this->onGetFrameCountInternal();
Nigel Tao3876a9f2019-11-14 09:04:45 +1100800 fFrameCountReaderIOPosition =
801 fDecoders[WhichDecoder::kFrameCount] ? fIOBuffer.reader_io_position() : 0;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400802 }
803 return fFrames.size();
804}
805
Nigel Tao2777cd32019-10-29 11:10:25 +1100806void SkWuffsCodec::onGetFrameCountInternal() {
Nigel Tao2777cd32019-10-29 11:10:25 +1100807 if (!fDecoders[WhichDecoder::kFrameCount]) {
808 void* decoder_raw = sk_malloc_canfail(sizeof__wuffs_gif__decoder());
809 if (!decoder_raw) {
810 return;
811 }
812 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> decoder(
813 reinterpret_cast<wuffs_gif__decoder*>(decoder_raw), &sk_free);
Nigel Tao3876a9f2019-11-14 09:04:45 +1100814 reset_and_decode_image_config(decoder.get(), nullptr, &fIOBuffer, fStream.get());
Nigel Tao2777cd32019-10-29 11:10:25 +1100815 fDecoders[WhichDecoder::kFrameCount] = std::move(decoder);
816 }
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400817
818 // Iterate through the frames, converting from Wuffs'
819 // wuffs_base__frame_config type to Skia's SkWuffsFrame type.
Nigel Tao3876a9f2019-11-14 09:04:45 +1100820 while (true) {
Nigel Tao2777cd32019-10-29 11:10:25 +1100821 const char* status = this->decodeFrameConfig(WhichDecoder::kFrameCount);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400822 if (status == nullptr) {
823 // No-op.
824 } else if (status == wuffs_base__warning__end_of_data) {
825 break;
826 } else {
827 return;
828 }
829
Nigel Tao3876a9f2019-11-14 09:04:45 +1100830 uint64_t i = fDecoders[WhichDecoder::kFrameCount]->num_decoded_frame_configs();
831 if (i > INT_MAX) {
832 break;
833 }
834 if ((i == 0) || (static_cast<size_t>(i - 1) != fFrames.size())) {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400835 continue;
836 }
Nigel Tao2777cd32019-10-29 11:10:25 +1100837 fFrames.emplace_back(&fFrameConfigs[WhichDecoder::kFrameCount]);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400838 SkWuffsFrame* f = &fFrames[fFrames.size() - 1];
839 fFrameHolder.setAlphaAndRequiredFrame(f);
840 }
841
842 fFramesComplete = true;
Nigel Tao5b271462019-11-12 21:02:20 +1100843
844 // We've seen the end of the animation. There'll be no more frames, so we
845 // no longer need the kFrameCount decoder. Releasing it earlier than the
846 // SkWuffsCodec destructor might help peak memory use.
847 fDecoders[WhichDecoder::kFrameCount].reset(nullptr);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400848}
849
Nigel Taocdc92382019-10-31 08:36:53 +1100850bool SkWuffsCodec::onGetFrameInfo(int i, SkCodec::FrameInfo* frameInfo) const {
851 const SkWuffsFrame* f = this->frame(i);
852 if (!f) {
853 return false;
854 }
855 if (frameInfo) {
856 *frameInfo = f->frameInfo(static_cast<uint64_t>(i) < this->fNumFullyReceivedFrames);
857 }
858 return true;
859}
860
861int SkWuffsCodec::onGetRepetitionCount() {
862 // Convert from Wuffs's loop count to Skia's repeat count. Wuffs' uint32_t
863 // number is how many times to play the loop. Skia's int number is how many
864 // times to play the loop *after the first play*. Wuffs and Skia use 0 and
865 // kRepetitionCountInfinite respectively to mean loop forever.
866 uint32_t n = fDecoders[WhichDecoder::kIncrDecode]->num_animation_loops();
867 if (n == 0) {
868 return SkCodec::kRepetitionCountInfinite;
869 }
870 n--;
871 return n < INT_MAX ? n : INT_MAX;
872}
873
Nigel Tao2777cd32019-10-29 11:10:25 +1100874SkCodec::Result SkWuffsCodec::seekFrame(WhichDecoder which, int frameIndex) {
875 if (fDecoderIsSuspended[which]) {
876 SkCodec::Result res = this->resetDecoder(which);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400877 if (res != SkCodec::kSuccess) {
878 return res;
879 }
880 }
881
882 uint64_t pos = 0;
883 if (frameIndex < 0) {
884 return SkCodec::kInternalError;
885 } else if (frameIndex == 0) {
886 pos = fFirstFrameIOPosition;
887 } else if (static_cast<size_t>(frameIndex) < fFrames.size()) {
888 pos = fFrames[frameIndex].ioPosition();
889 } else {
890 return SkCodec::kInternalError;
891 }
892
893 if (!seek_buffer(&fIOBuffer, fStream.get(), pos)) {
894 return SkCodec::kInternalError;
895 }
Nigel Tao2777cd32019-10-29 11:10:25 +1100896 const char* status =
897 fDecoders[which]->restart_frame(frameIndex, fIOBuffer.reader_io_position());
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400898 if (status != nullptr) {
899 return SkCodec::kInternalError;
900 }
901 return SkCodec::kSuccess;
902}
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}