blob: 8b828b26a8f84d7f84e132828b1826db95f953c2 [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 Taob54946b2020-06-18 23:36:27 +100038#include "wuffs-v0.3.c"
Nigel Tao5cfa7192020-08-17 21:14:13 +100039// Commit count 2514 is Wuffs 0.3.0-alpha.4.
40#if WUFFS_VERSION_BUILD_METADATA_COMMIT_COUNT < 2514
Nigel Taoa6766482019-01-07 13:41:53 +110041#error "Wuffs version is too old. Upgrade to the latest version."
42#endif
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -040043
44#define SK_WUFFS_CODEC_BUFFER_SIZE 4096
45
Nigel Tao3dc31212019-12-07 11:46:16 +110046// Configuring a Skia build with
47// SK_WUFFS_FAVORS_PERFORMANCE_OVER_ADDITIONAL_MEMORY_SAFETY can improve decode
48// performance by some fixed amount (independent of the image size), which can
49// be a noticeable proportional improvement if the input is relatively small.
50//
51// The Wuffs library is still memory-safe either way, in that there are no
52// out-of-bounds reads or writes, and the library endeavours not to read
53// uninitialized memory. There are just fewer compiler-enforced guarantees
54// against reading uninitialized memory. For more detail, see
55// https://github.com/google/wuffs/blob/master/doc/note/initialization.md#partial-zero-initialization
56#if defined(SK_WUFFS_FAVORS_PERFORMANCE_OVER_ADDITIONAL_MEMORY_SAFETY)
57#define SK_WUFFS_INITIALIZE_FLAGS WUFFS_INITIALIZE__LEAVE_INTERNAL_BUFFERS_UNINITIALIZED
58#else
59#define SK_WUFFS_INITIALIZE_FLAGS WUFFS_INITIALIZE__DEFAULT_OPTIONS
60#endif
61
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -040062static bool fill_buffer(wuffs_base__io_buffer* b, SkStream* s) {
63 b->compact();
64 size_t num_read = s->read(b->data.ptr + b->meta.wi, b->data.len - b->meta.wi);
65 b->meta.wi += num_read;
66 b->meta.closed = s->isAtEnd();
67 return num_read > 0;
68}
69
70static bool seek_buffer(wuffs_base__io_buffer* b, SkStream* s, uint64_t pos) {
71 // Try to re-position the io_buffer's meta.ri read-index first, which is
72 // cheaper than seeking in the backing SkStream.
73 if ((pos >= b->meta.pos) && (pos - b->meta.pos <= b->meta.wi)) {
74 b->meta.ri = pos - b->meta.pos;
75 return true;
76 }
77 // Seek in the backing SkStream.
78 if ((pos > SIZE_MAX) || (!s->seek(pos))) {
79 return false;
80 }
81 b->meta.wi = 0;
82 b->meta.ri = 0;
83 b->meta.pos = pos;
84 b->meta.closed = false;
85 return true;
86}
87
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -040088static SkCodecAnimation::DisposalMethod wuffs_disposal_to_skia_disposal(
89 wuffs_base__animation_disposal w) {
90 switch (w) {
91 case WUFFS_BASE__ANIMATION_DISPOSAL__RESTORE_BACKGROUND:
92 return SkCodecAnimation::DisposalMethod::kRestoreBGColor;
93 case WUFFS_BASE__ANIMATION_DISPOSAL__RESTORE_PREVIOUS:
94 return SkCodecAnimation::DisposalMethod::kRestorePrevious;
95 default:
96 return SkCodecAnimation::DisposalMethod::kKeep;
97 }
98}
99
Nigel Tao4f32a292019-11-13 15:41:55 +1100100static SkAlphaType to_alpha_type(bool opaque) {
101 return opaque ? kOpaque_SkAlphaType : kPremul_SkAlphaType;
102}
103
Nigel Tao2777cd32019-10-29 11:10:25 +1100104static SkCodec::Result reset_and_decode_image_config(wuffs_gif__decoder* decoder,
105 wuffs_base__image_config* imgcfg,
106 wuffs_base__io_buffer* b,
Nigel Tao4f32a292019-11-13 15:41:55 +1100107 SkStream* s) {
Nigel Tao3dc31212019-12-07 11:46:16 +1100108 // Calling decoder->initialize will memset most or all of it to zero,
109 // depending on SK_WUFFS_INITIALIZE_FLAGS.
Nigel Taob54946b2020-06-18 23:36:27 +1000110 wuffs_base__status status =
Nigel Tao3dc31212019-12-07 11:46:16 +1100111 decoder->initialize(sizeof__wuffs_gif__decoder(), WUFFS_VERSION, SK_WUFFS_INITIALIZE_FLAGS);
Nigel Taob54946b2020-06-18 23:36:27 +1000112 if (status.repr != nullptr) {
113 SkCodecPrintf("initialize: %s", status.message());
114 return SkCodec::kInternalError;
115 }
116 while (true) {
117 status = decoder->decode_image_config(imgcfg, b);
118 if (status.repr == nullptr) {
119 break;
120 } else if (status.repr != wuffs_base__suspension__short_read) {
121 SkCodecPrintf("decode_image_config: %s", status.message());
122 return SkCodec::kErrorInInput;
123 } else if (!fill_buffer(b, s)) {
124 return SkCodec::kIncompleteInput;
125 }
126 }
Nigel Tao4f32a292019-11-13 15:41:55 +1100127
128 // A GIF image's natural color model is indexed color: 1 byte per pixel,
129 // indexing a 256-element palette.
130 //
131 // For Skia, we override that to decode to 4 bytes per pixel, BGRA or RGBA.
Nigel Taob54946b2020-06-18 23:36:27 +1000132 uint32_t pixfmt = WUFFS_BASE__PIXEL_FORMAT__INVALID;
Nigel Tao4f32a292019-11-13 15:41:55 +1100133 switch (kN32_SkColorType) {
134 case kBGRA_8888_SkColorType:
135 pixfmt = WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL;
136 break;
137 case kRGBA_8888_SkColorType:
138 pixfmt = WUFFS_BASE__PIXEL_FORMAT__RGBA_NONPREMUL;
139 break;
140 default:
141 return SkCodec::kInternalError;
142 }
143 if (imgcfg) {
144 imgcfg->pixcfg.set(pixfmt, WUFFS_BASE__PIXEL_SUBSAMPLING__NONE, imgcfg->pixcfg.width(),
145 imgcfg->pixcfg.height());
146 }
147
148 return SkCodec::kSuccess;
149}
150
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400151// -------------------------------- Class definitions
152
153class SkWuffsCodec;
154
155class SkWuffsFrame final : public SkFrame {
156public:
157 SkWuffsFrame(wuffs_base__frame_config* fc);
158
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400159 uint64_t ioPosition() const;
160
161 // SkFrame overrides.
162 SkEncodedInfo::Alpha onReportedAlpha() const override;
163
164private:
165 uint64_t fIOPosition;
166 SkEncodedInfo::Alpha fReportedAlpha;
167
John Stiles7571f9e2020-09-02 22:42:33 -0400168 using INHERITED = SkFrame;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400169};
170
171// SkWuffsFrameHolder is a trivial indirector that forwards its calls onto a
172// SkWuffsCodec. It is a separate class as SkWuffsCodec would otherwise
173// inherit from both SkCodec and SkFrameHolder, and Skia style discourages
174// multiple inheritance (e.g. with its "typedef Foo INHERITED" convention).
175class SkWuffsFrameHolder final : public SkFrameHolder {
176public:
177 SkWuffsFrameHolder() : INHERITED() {}
178
179 void init(SkWuffsCodec* codec, int width, int height);
180
181 // SkFrameHolder overrides.
182 const SkFrame* onGetFrame(int i) const override;
183
184private:
185 const SkWuffsCodec* fCodec;
186
John Stiles7571f9e2020-09-02 22:42:33 -0400187 using INHERITED = SkFrameHolder;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400188};
189
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400190class SkWuffsCodec final : public SkScalingCodec {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400191public:
192 SkWuffsCodec(SkEncodedInfo&& encodedInfo,
193 std::unique_ptr<SkStream> stream,
194 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> dec,
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400195 std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr,
196 size_t workbuf_len,
197 wuffs_base__image_config imgcfg,
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400198 wuffs_base__io_buffer iobuf);
199
200 const SkWuffsFrame* frame(int i) const;
201
202private:
Nigel Tao2777cd32019-10-29 11:10:25 +1100203 // It is valid, in terms of the SkCodec API, to call SkCodec::getFrameCount
204 // while in an incremental decode (after onStartIncrementalDecode returns
205 // and before the rest of the image is decoded). Some Skia users expect
206 // getFrameCount to increase, and the SkStream to advance, when given more
207 // data.
208 //
209 // On the other hand, while in an incremental decode, the underlying Wuffs
210 // object is suspended in a coroutine. To keep its internal proof-of-safety
211 // invariants consistent, there's only two things you can safely do with a
212 // suspended Wuffs object: resume the coroutine, or reset all state (memset
213 // to zero and start again).
214 //
215 // The Wuffs API provides a limited, optional form of seeking, to the start
216 // of an animation frame's data, but does not provide arbitrary save and
217 // load of its internal state whilst in the middle of an animation frame.
218 //
219 // SkWuffsCodec therefore uses two Wuffs decoders: a primary decoder
220 // (kIncrDecode) to support startIncrementalDecode / incrementalDecode, and
221 // a secondary decoder (kFrameCount) to support getFrameCount. The two
222 // decoders' states can change independently.
223 //
224 // As of Wuffs version 0.2, both of these decoders have the same type. A
225 // future Wuffs version might let us use a different type for kFrameCount,
226 // one that is much lighter weight (in terms of memory requirements), as it
227 // doesn't have to handle decompressing pixel data.
228 enum WhichDecoder {
229 kIncrDecode,
230 kFrameCount,
231 kNumDecoders,
232 };
233
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400234 // SkCodec overrides.
235 SkEncodedImageFormat onGetEncodedFormat() const override;
236 Result onGetPixels(const SkImageInfo&, void*, size_t, const Options&, int*) override;
237 const SkFrameHolder* getFrameHolder() const override;
238 Result onStartIncrementalDecode(const SkImageInfo& dstInfo,
239 void* dst,
240 size_t rowBytes,
241 const SkCodec::Options& options) override;
242 Result onIncrementalDecode(int* rowsDecoded) override;
243 int onGetFrameCount() override;
244 bool onGetFrameInfo(int, FrameInfo*) const override;
245 int onGetRepetitionCount() override;
246
Nigel Tao027f89b2019-12-06 10:56:24 +1100247 // Two separate implementations of onStartIncrementalDecode and
248 // onIncrementalDecode, named "one pass" and "two pass" decoding. One pass
249 // decoding writes directly from the Wuffs image decoder to the dst buffer
250 // (the dst argument to onStartIncrementalDecode). Two pass decoding first
251 // writes into an intermediate buffer, and then composites and transforms
252 // the intermediate buffer into the dst buffer.
253 //
254 // In the general case, we need the two pass decoder, because of Skia API
255 // features that Wuffs doesn't support (e.g. color correction, scaling,
256 // RGB565). But as an optimization, we use one pass decoding (it's faster
257 // and uses less memory) if applicable (see the assignment to
258 // fIncrDecOnePass that calculates when we can do so).
Nigel Taob54946b2020-06-18 23:36:27 +1000259 Result onStartIncrementalDecodeOnePass(const SkImageInfo& dstInfo,
260 uint8_t* dst,
261 size_t rowBytes,
262 const SkCodec::Options& options,
263 uint32_t pixelFormat,
264 size_t bytesPerPixel);
Nigel Tao027f89b2019-12-06 10:56:24 +1100265 Result onStartIncrementalDecodeTwoPass();
266 Result onIncrementalDecodeOnePass();
267 Result onIncrementalDecodeTwoPass();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400268
Nigel Tao027f89b2019-12-06 10:56:24 +1100269 void onGetFrameCountInternal();
270 Result seekFrame(WhichDecoder which, int frameIndex);
Nigel Tao2777cd32019-10-29 11:10:25 +1100271 Result resetDecoder(WhichDecoder which);
272 const char* decodeFrameConfig(WhichDecoder which);
273 const char* decodeFrame(WhichDecoder which);
274 void updateNumFullyReceivedFrames(WhichDecoder which);
275
276 SkWuffsFrameHolder fFrameHolder;
277 std::unique_ptr<SkStream> fStream;
Nigel Tao2777cd32019-10-29 11:10:25 +1100278 std::unique_ptr<uint8_t, decltype(&sk_free)> fWorkbufPtr;
279 size_t fWorkbufLen;
280
281 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> fDecoders[WhichDecoder::kNumDecoders];
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400282
283 const uint64_t fFirstFrameIOPosition;
Nigel Tao2777cd32019-10-29 11:10:25 +1100284 wuffs_base__frame_config fFrameConfigs[WhichDecoder::kNumDecoders];
Nigel Tao027f89b2019-12-06 10:56:24 +1100285 wuffs_base__pixel_config fPixelConfig;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400286 wuffs_base__pixel_buffer fPixelBuffer;
287 wuffs_base__io_buffer fIOBuffer;
288
289 // Incremental decoding state.
Nigel Taobf4605f2020-09-28 21:53:07 +1000290 uint8_t* fIncrDecDst;
291 uint64_t fIncrDecReaderIOPosition;
292 size_t fIncrDecRowBytes;
293 wuffs_base__pixel_blend fIncrDecPixelBlend;
294 bool fIncrDecOnePass;
295 bool fFirstCallToIncrementalDecode;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400296
Nigel Tao027f89b2019-12-06 10:56:24 +1100297 // Lazily allocated intermediate pixel buffer, for two pass decoding.
298 std::unique_ptr<uint8_t, decltype(&sk_free)> fTwoPassPixbufPtr;
299 size_t fTwoPassPixbufLen;
300
Nigel Tao3876a9f2019-11-14 09:04:45 +1100301 uint64_t fFrameCountReaderIOPosition;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400302 uint64_t fNumFullyReceivedFrames;
303 std::vector<SkWuffsFrame> fFrames;
304 bool fFramesComplete;
305
Nigel Tao2777cd32019-10-29 11:10:25 +1100306 // If calling an fDecoders[which] method returns an incomplete status, then
307 // fDecoders[which] is suspended in a coroutine (i.e. waiting on I/O or
308 // halted on a non-recoverable error). To keep its internal proof-of-safety
309 // invariants consistent, there's only two things you can safely do with a
310 // suspended Wuffs object: resume the coroutine, or reset all state (memset
311 // to zero and start again).
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400312 //
Nigel Tao2777cd32019-10-29 11:10:25 +1100313 // If fDecoderIsSuspended[which], and we aren't sure that we're going to
314 // resume the coroutine, then we will need to call this->resetDecoder
315 // before calling other fDecoders[which] methods.
316 bool fDecoderIsSuspended[WhichDecoder::kNumDecoders];
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400317
318 uint8_t fBuffer[SK_WUFFS_CODEC_BUFFER_SIZE];
319
John Stiles7571f9e2020-09-02 22:42:33 -0400320 using INHERITED = SkScalingCodec;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400321};
322
323// -------------------------------- SkWuffsFrame implementation
324
325SkWuffsFrame::SkWuffsFrame(wuffs_base__frame_config* fc)
326 : INHERITED(fc->index()),
327 fIOPosition(fc->io_position()),
Nigel Taob54946b2020-06-18 23:36:27 +1000328 fReportedAlpha(fc->opaque_within_bounds() ? SkEncodedInfo::kOpaque_Alpha
Nigel Tao5cfa7192020-08-17 21:14:13 +1000329 : SkEncodedInfo::kUnpremul_Alpha) {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400330 wuffs_base__rect_ie_u32 r = fc->bounds();
331 this->setXYWH(r.min_incl_x, r.min_incl_y, r.width(), r.height());
332 this->setDisposalMethod(wuffs_disposal_to_skia_disposal(fc->disposal()));
333 this->setDuration(fc->duration() / WUFFS_BASE__FLICKS_PER_MILLISECOND);
Leon Scroggins III469d67e2020-11-11 12:45:40 -0500334 this->setBlend(fc->overwrite_instead_of_blend() ? SkCodecAnimation::Blend::kSrc
335 : SkCodecAnimation::Blend::kSrcOver);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400336}
337
338uint64_t SkWuffsFrame::ioPosition() const {
339 return fIOPosition;
340}
341
342SkEncodedInfo::Alpha SkWuffsFrame::onReportedAlpha() const {
343 return fReportedAlpha;
344}
345
346// -------------------------------- SkWuffsFrameHolder implementation
347
348void SkWuffsFrameHolder::init(SkWuffsCodec* codec, int width, int height) {
349 fCodec = codec;
350 // Initialize SkFrameHolder's (the superclass) fields.
351 fScreenWidth = width;
352 fScreenHeight = height;
353}
354
355const SkFrame* SkWuffsFrameHolder::onGetFrame(int i) const {
356 return fCodec->frame(i);
357};
358
359// -------------------------------- SkWuffsCodec implementation
360
361SkWuffsCodec::SkWuffsCodec(SkEncodedInfo&& encodedInfo,
362 std::unique_ptr<SkStream> stream,
363 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> dec,
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400364 std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr,
365 size_t workbuf_len,
366 wuffs_base__image_config imgcfg,
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400367 wuffs_base__io_buffer iobuf)
368 : INHERITED(std::move(encodedInfo),
369 skcms_PixelFormat_RGBA_8888,
370 // Pass a nullptr SkStream to the SkCodec constructor. We
371 // manage the stream ourselves, as the default SkCodec behavior
372 // is too trigger-happy on rewinding the stream.
373 nullptr),
Nigel Tao0185b952018-11-08 10:47:24 +1100374 fFrameHolder(),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400375 fStream(std::move(stream)),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400376 fWorkbufPtr(std::move(workbuf_ptr)),
377 fWorkbufLen(workbuf_len),
Nigel Tao2777cd32019-10-29 11:10:25 +1100378 fDecoders{
379 std::move(dec),
380 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)>(nullptr, sk_free),
381 },
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400382 fFirstFrameIOPosition(imgcfg.first_frame_io_position()),
Nigel Tao2777cd32019-10-29 11:10:25 +1100383 fFrameConfigs{
384 wuffs_base__null_frame_config(),
385 wuffs_base__null_frame_config(),
386 },
Nigel Tao027f89b2019-12-06 10:56:24 +1100387 fPixelConfig(imgcfg.pixcfg),
388 fPixelBuffer(wuffs_base__null_pixel_buffer()),
Nigel Tao96c10a02019-09-25 11:08:42 +1000389 fIOBuffer(wuffs_base__empty_io_buffer()),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400390 fIncrDecDst(nullptr),
Nigel Tao2777cd32019-10-29 11:10:25 +1100391 fIncrDecReaderIOPosition(0),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400392 fIncrDecRowBytes(0),
Nigel Taobf4605f2020-09-28 21:53:07 +1000393 fIncrDecPixelBlend(WUFFS_BASE__PIXEL_BLEND__SRC),
Nigel Tao027f89b2019-12-06 10:56:24 +1100394 fIncrDecOnePass(false),
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400395 fFirstCallToIncrementalDecode(false),
Nigel Tao027f89b2019-12-06 10:56:24 +1100396 fTwoPassPixbufPtr(nullptr, &sk_free),
397 fTwoPassPixbufLen(0),
Nigel Tao3876a9f2019-11-14 09:04:45 +1100398 fFrameCountReaderIOPosition(0),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400399 fNumFullyReceivedFrames(0),
400 fFramesComplete(false),
Nigel Tao2777cd32019-10-29 11:10:25 +1100401 fDecoderIsSuspended{
402 false,
403 false,
404 } {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400405 fFrameHolder.init(this, imgcfg.pixcfg.width(), imgcfg.pixcfg.height());
406
407 // Initialize fIOBuffer's fields, copying any outstanding data from iobuf to
408 // fIOBuffer, as iobuf's backing array may not be valid for the lifetime of
409 // this SkWuffsCodec object, but fIOBuffer's backing array (fBuffer) is.
410 SkASSERT(iobuf.data.len == SK_WUFFS_CODEC_BUFFER_SIZE);
411 memmove(fBuffer, iobuf.data.ptr, iobuf.meta.wi);
Nigel Tao48aa2212019-03-09 14:59:11 +1100412 fIOBuffer.data = wuffs_base__make_slice_u8(fBuffer, SK_WUFFS_CODEC_BUFFER_SIZE);
413 fIOBuffer.meta = iobuf.meta;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400414}
415
416const SkWuffsFrame* SkWuffsCodec::frame(int i) const {
417 if ((0 <= i) && (static_cast<size_t>(i) < fFrames.size())) {
418 return &fFrames[i];
419 }
420 return nullptr;
421}
422
423SkEncodedImageFormat SkWuffsCodec::onGetEncodedFormat() const {
424 return SkEncodedImageFormat::kGIF;
425}
426
427SkCodec::Result SkWuffsCodec::onGetPixels(const SkImageInfo& dstInfo,
428 void* dst,
429 size_t rowBytes,
430 const Options& options,
431 int* rowsDecoded) {
432 SkCodec::Result result = this->onStartIncrementalDecode(dstInfo, dst, rowBytes, options);
433 if (result != kSuccess) {
434 return result;
435 }
436 return this->onIncrementalDecode(rowsDecoded);
437}
438
439const SkFrameHolder* SkWuffsCodec::getFrameHolder() const {
440 return &fFrameHolder;
441}
442
443SkCodec::Result SkWuffsCodec::onStartIncrementalDecode(const SkImageInfo& dstInfo,
444 void* dst,
445 size_t rowBytes,
446 const SkCodec::Options& options) {
Nigel Tao1f1cd1f2019-06-22 17:35:38 +1000447 if (!dst) {
448 return SkCodec::kInvalidParameters;
449 }
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400450 if (options.fSubset) {
451 return SkCodec::kUnimplemented;
452 }
Nigel Tao2777cd32019-10-29 11:10:25 +1100453 SkCodec::Result result = this->seekFrame(WhichDecoder::kIncrDecode, options.fFrameIndex);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400454 if (result != SkCodec::kSuccess) {
455 return result;
456 }
457
Nigel Tao2777cd32019-10-29 11:10:25 +1100458 const char* status = this->decodeFrameConfig(WhichDecoder::kIncrDecode);
Nigel Taob7a1b512019-02-10 12:19:50 +1100459 if (status == wuffs_base__suspension__short_read) {
Leon Scroggins IIIcb6b8842018-12-04 13:55:13 -0500460 return SkCodec::kIncompleteInput;
Nigel Taob7a1b512019-02-10 12:19:50 +1100461 } else if (status != nullptr) {
Leon Scroggins IIIcb6b8842018-12-04 13:55:13 -0500462 SkCodecPrintf("decodeFrameConfig: %s", status);
463 return SkCodec::kErrorInInput;
464 }
Nigel Taob7a1b512019-02-10 12:19:50 +1100465
Nigel Taob54946b2020-06-18 23:36:27 +1000466 uint32_t pixelFormat = WUFFS_BASE__PIXEL_FORMAT__INVALID;
Nigel Tao5cfa7192020-08-17 21:14:13 +1000467 size_t bytesPerPixel = 0;
Nigel Tao027f89b2019-12-06 10:56:24 +1100468
469 switch (dstInfo.colorType()) {
Nigel Taof933e4f2020-10-29 09:42:11 +1100470 case kRGB_565_SkColorType:
471 pixelFormat = WUFFS_BASE__PIXEL_FORMAT__BGR_565;
472 bytesPerPixel = 2;
473 break;
Nigel Tao027f89b2019-12-06 10:56:24 +1100474 case kBGRA_8888_SkColorType:
475 pixelFormat = WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL;
476 bytesPerPixel = 4;
477 break;
478 case kRGBA_8888_SkColorType:
479 pixelFormat = WUFFS_BASE__PIXEL_FORMAT__RGBA_NONPREMUL;
480 bytesPerPixel = 4;
481 break;
482 default:
483 break;
484 }
485
486 // We can use "one pass" decoding if we have a Skia pixel format that Wuffs
487 // supports...
Nigel Taobf4605f2020-09-28 21:53:07 +1000488 fIncrDecOnePass = (pixelFormat != WUFFS_BASE__PIXEL_FORMAT__INVALID) &&
489 // ...and no color profile (as Wuffs does not support them)...
490 (!getEncodedInfo().profile()) &&
491 // ...and we use the identity transform (as Wuffs does
492 // not support scaling).
493 (this->dimensions() == dstInfo.dimensions());
Nigel Tao027f89b2019-12-06 10:56:24 +1100494
495 result = fIncrDecOnePass ? this->onStartIncrementalDecodeOnePass(
496 dstInfo, static_cast<uint8_t*>(dst), rowBytes, options,
497 pixelFormat, bytesPerPixel)
498 : this->onStartIncrementalDecodeTwoPass();
499 if (result != SkCodec::kSuccess) {
500 return result;
501 }
502
503 fIncrDecDst = static_cast<uint8_t*>(dst);
504 fIncrDecReaderIOPosition = fIOBuffer.reader_io_position();
505 fIncrDecRowBytes = rowBytes;
506 fFirstCallToIncrementalDecode = true;
507 return SkCodec::kSuccess;
508}
509
Nigel Taob54946b2020-06-18 23:36:27 +1000510SkCodec::Result SkWuffsCodec::onStartIncrementalDecodeOnePass(const SkImageInfo& dstInfo,
511 uint8_t* dst,
512 size_t rowBytes,
513 const SkCodec::Options& options,
514 uint32_t pixelFormat,
Nigel Tao027f89b2019-12-06 10:56:24 +1100515 size_t bytesPerPixel) {
516 wuffs_base__pixel_config pixelConfig;
517 pixelConfig.set(pixelFormat, WUFFS_BASE__PIXEL_SUBSAMPLING__NONE, dstInfo.width(),
518 dstInfo.height());
519
520 wuffs_base__table_u8 table;
521 table.ptr = dst;
522 table.width = static_cast<size_t>(dstInfo.width()) * bytesPerPixel;
523 table.height = dstInfo.height();
524 table.stride = rowBytes;
525
Nigel Taob54946b2020-06-18 23:36:27 +1000526 wuffs_base__status status = fPixelBuffer.set_from_table(&pixelConfig, table);
Nigel Taob54946b2020-06-18 23:36:27 +1000527 if (status.repr != nullptr) {
528 SkCodecPrintf("set_from_table: %s", status.message());
529 return SkCodec::kInternalError;
530 }
Nigel Taob7a1b512019-02-10 12:19:50 +1100531
Nigel Taobf4605f2020-09-28 21:53:07 +1000532 // SRC is usually faster than SRC_OVER, but for a dependent frame, dst is
533 // assumed to hold the previous frame's pixels (after processing the
534 // DisposalMethod). For one-pass decoding, we therefore use SRC_OVER.
535 if ((options.fFrameIndex != 0) &&
536 (this->frame(options.fFrameIndex)->getRequiredFrame() != SkCodec::kNoFrame)) {
537 fIncrDecPixelBlend = WUFFS_BASE__PIXEL_BLEND__SRC_OVER;
538 } else {
539 SkSampler::Fill(dstInfo, dst, rowBytes, options.fZeroInitialized);
540 fIncrDecPixelBlend = WUFFS_BASE__PIXEL_BLEND__SRC;
541 }
542
Nigel Tao027f89b2019-12-06 10:56:24 +1100543 return SkCodec::kSuccess;
544}
545
546SkCodec::Result SkWuffsCodec::onStartIncrementalDecodeTwoPass() {
547 // Either re-use the previously allocated "two pass" pixel buffer (and
548 // memset to zero), or allocate (and zero initialize) a new one.
549 bool already_zeroed = false;
550
551 if (!fTwoPassPixbufPtr) {
552 uint64_t pixbuf_len = fPixelConfig.pixbuf_len();
553 void* pixbuf_ptr_raw = (pixbuf_len <= SIZE_MAX)
Nigel Tao5cfa7192020-08-17 21:14:13 +1000554 ? sk_malloc_flags(pixbuf_len, SK_MALLOC_ZERO_INITIALIZE)
555 : nullptr;
Nigel Tao027f89b2019-12-06 10:56:24 +1100556 if (!pixbuf_ptr_raw) {
557 return SkCodec::kInternalError;
558 }
559 fTwoPassPixbufPtr.reset(reinterpret_cast<uint8_t*>(pixbuf_ptr_raw));
560 fTwoPassPixbufLen = SkToSizeT(pixbuf_len);
561 already_zeroed = true;
562 }
563
Nigel Taob54946b2020-06-18 23:36:27 +1000564 wuffs_base__status status = fPixelBuffer.set_from_slice(
Nigel Tao027f89b2019-12-06 10:56:24 +1100565 &fPixelConfig, wuffs_base__make_slice_u8(fTwoPassPixbufPtr.get(), fTwoPassPixbufLen));
Nigel Taob54946b2020-06-18 23:36:27 +1000566 if (status.repr != nullptr) {
567 SkCodecPrintf("set_from_slice: %s", status.message());
568 return SkCodec::kInternalError;
569 }
Nigel Tao027f89b2019-12-06 10:56:24 +1100570
571 if (!already_zeroed) {
Nigel Taob54946b2020-06-18 23:36:27 +1000572 uint32_t src_bits_per_pixel = fPixelConfig.pixel_format().bits_per_pixel();
Nigel Tao027f89b2019-12-06 10:56:24 +1100573 if ((src_bits_per_pixel == 0) || (src_bits_per_pixel % 8 != 0)) {
574 return SkCodec::kInternalError;
575 }
576 size_t src_bytes_per_pixel = src_bits_per_pixel / 8;
577
Nigel Tao39da10b2019-11-15 15:27:44 +1100578 wuffs_base__rect_ie_u32 frame_rect = fFrameConfigs[WhichDecoder::kIncrDecode].bounds();
579 wuffs_base__table_u8 pixels = fPixelBuffer.plane(0);
Nigel Tao6ec1b392019-11-20 12:28:50 +1100580
581 uint8_t* ptr = pixels.ptr + (frame_rect.min_incl_y * pixels.stride) +
582 (frame_rect.min_incl_x * src_bytes_per_pixel);
583 size_t len = frame_rect.width() * src_bytes_per_pixel;
584
585 // As an optimization, issue a single sk_bzero call, if possible.
586 // Otherwise, zero out each row separately.
587 if ((len == pixels.stride) && (frame_rect.min_incl_y < frame_rect.max_excl_y)) {
588 sk_bzero(ptr, len * (frame_rect.max_excl_y - frame_rect.min_incl_y));
589 } else {
590 for (uint32_t y = frame_rect.min_incl_y; y < frame_rect.max_excl_y; y++) {
591 sk_bzero(ptr, len);
592 ptr += pixels.stride;
593 }
Nigel Tao39da10b2019-11-15 15:27:44 +1100594 }
Nigel Taob7a1b512019-02-10 12:19:50 +1100595 }
596
Nigel Taobf4605f2020-09-28 21:53:07 +1000597 fIncrDecPixelBlend = WUFFS_BASE__PIXEL_BLEND__SRC;
Nigel Taob7a1b512019-02-10 12:19:50 +1100598 return SkCodec::kSuccess;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400599}
600
601SkCodec::Result SkWuffsCodec::onIncrementalDecode(int* rowsDecoded) {
602 if (!fIncrDecDst) {
603 return SkCodec::kInternalError;
604 }
605
Nigel Tao2777cd32019-10-29 11:10:25 +1100606 // If multiple SkCodec::incrementalDecode calls are made consecutively (or
607 // if SkCodec::incrementalDecode is called immediately after
608 // SkCodec::startIncrementalDecode), then this seek should be a no-op.
609 // However, it is possible to interleave SkCodec::getFrameCount calls in
610 // between SkCodec::incrementalDecode calls, and those other calls may
611 // advance the stream. This seek restores the stream to where the last
612 // SkCodec::startIncrementalDecode or SkCodec::incrementalDecode stopped.
613 if (!seek_buffer(&fIOBuffer, fStream.get(), fIncrDecReaderIOPosition)) {
614 return SkCodec::kInternalError;
615 }
616
Nigel Tao027f89b2019-12-06 10:56:24 +1100617 if (rowsDecoded) {
618 *rowsDecoded = dstInfo().height();
619 }
620
621 SkCodec::Result result =
622 fIncrDecOnePass ? this->onIncrementalDecodeOnePass() : this->onIncrementalDecodeTwoPass();
Nigel Tao2777cd32019-10-29 11:10:25 +1100623 if (result == SkCodec::kSuccess) {
624 fIncrDecDst = nullptr;
625 fIncrDecReaderIOPosition = 0;
626 fIncrDecRowBytes = 0;
Nigel Taobf4605f2020-09-28 21:53:07 +1000627 fIncrDecPixelBlend = WUFFS_BASE__PIXEL_BLEND__SRC;
Nigel Tao027f89b2019-12-06 10:56:24 +1100628 fIncrDecOnePass = false;
Nigel Tao2777cd32019-10-29 11:10:25 +1100629 } else {
630 fIncrDecReaderIOPosition = fIOBuffer.reader_io_position();
631 }
632 return result;
633}
634
Nigel Tao027f89b2019-12-06 10:56:24 +1100635SkCodec::Result SkWuffsCodec::onIncrementalDecodeOnePass() {
636 const char* status = this->decodeFrame(WhichDecoder::kIncrDecode);
637 if (status != nullptr) {
638 if (status == wuffs_base__suspension__short_read) {
639 return SkCodec::kIncompleteInput;
640 } else {
641 SkCodecPrintf("decodeFrame: %s", status);
642 return SkCodec::kErrorInInput;
643 }
644 }
645 return SkCodec::kSuccess;
646}
647
648SkCodec::Result SkWuffsCodec::onIncrementalDecodeTwoPass() {
Leon Scroggins III699d41e2019-02-07 09:25:51 -0500649 SkCodec::Result result = SkCodec::kSuccess;
Nigel Tao2777cd32019-10-29 11:10:25 +1100650 const char* status = this->decodeFrame(WhichDecoder::kIncrDecode);
651 bool independent;
652 SkAlphaType alphaType;
653 const int index = options().fFrameIndex;
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400654 if (index == 0) {
655 independent = true;
656 alphaType = to_alpha_type(getEncodedInfo().opaque());
657 } else {
658 const SkWuffsFrame* f = this->frame(index);
659 independent = f->getRequiredFrame() == SkCodec::kNoFrame;
660 alphaType = to_alpha_type(f->reportedAlpha() == SkEncodedInfo::kOpaque_Alpha);
661 }
Leon Scroggins III699d41e2019-02-07 09:25:51 -0500662 if (status != nullptr) {
663 if (status == wuffs_base__suspension__short_read) {
664 result = SkCodec::kIncompleteInput;
665 } else {
666 SkCodecPrintf("decodeFrame: %s", status);
667 result = SkCodec::kErrorInInput;
668 }
669
670 if (!independent) {
671 // For a dependent frame, we cannot blend the partial result, since
672 // that will overwrite the contribution from prior frames.
673 return result;
674 }
675 }
676
Nigel Taob54946b2020-06-18 23:36:27 +1000677 uint32_t src_bits_per_pixel = fPixelBuffer.pixcfg.pixel_format().bits_per_pixel();
Nigel Tao490e6472019-02-14 14:50:53 +1100678 if ((src_bits_per_pixel == 0) || (src_bits_per_pixel % 8 != 0)) {
679 return SkCodec::kInternalError;
680 }
681 size_t src_bytes_per_pixel = src_bits_per_pixel / 8;
682
Nigel Tao2777cd32019-10-29 11:10:25 +1100683 wuffs_base__rect_ie_u32 frame_rect = fFrameConfigs[WhichDecoder::kIncrDecode].bounds();
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400684 if (fFirstCallToIncrementalDecode) {
Nigel Tao490e6472019-02-14 14:50:53 +1100685 if (frame_rect.width() > (SIZE_MAX / src_bytes_per_pixel)) {
686 return SkCodec::kInternalError;
687 }
688
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400689 auto bounds = SkIRect::MakeLTRB(frame_rect.min_incl_x, frame_rect.min_incl_y,
690 frame_rect.max_excl_x, frame_rect.max_excl_y);
691
Leon Scroggins IIIcb6b8842018-12-04 13:55:13 -0500692 // If the frame rect does not fill the output, ensure that those pixels are not
Nigel Taob7a1b512019-02-10 12:19:50 +1100693 // left uninitialized.
Leon Scroggins III44076362019-02-15 13:56:44 -0500694 if (independent && (bounds != this->bounds() || result != kSuccess)) {
Nigel Tao2777cd32019-10-29 11:10:25 +1100695 SkSampler::Fill(dstInfo(), fIncrDecDst, fIncrDecRowBytes, options().fZeroInitialized);
Leon Scroggins III9b0ba2c2018-11-19 14:52:37 -0500696 }
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400697 fFirstCallToIncrementalDecode = false;
698 } else {
699 // Existing clients intend to only show frames beyond the first if they
700 // are complete (based on FrameInfo::fFullyReceived), since it might
701 // look jarring to draw a partial frame over an existing frame. If they
702 // changed their behavior and expected to continue decoding a partial
703 // frame after the first one, we'll need to update our blending code.
704 // Otherwise, if the frame were interlaced and not independent, the
705 // second pass may have an overlapping dirty_rect with the first,
706 // resulting in blending with the first pass.
707 SkASSERT(index == 0);
Nigel Tao9859ef82019-02-13 13:20:02 +1100708 }
Nigel Tao0185b952018-11-08 10:47:24 +1100709
Leon Scroggins IIIdad4bfc2018-12-10 12:37:10 -0500710 // If the frame's dirty rect is empty, no need to swizzle.
Nigel Tao2777cd32019-10-29 11:10:25 +1100711 wuffs_base__rect_ie_u32 dirty_rect = fDecoders[WhichDecoder::kIncrDecode]->frame_dirty_rect();
Leon Scroggins IIIdad4bfc2018-12-10 12:37:10 -0500712 if (!dirty_rect.is_empty()) {
Nigel Tao490e6472019-02-14 14:50:53 +1100713 wuffs_base__table_u8 pixels = fPixelBuffer.plane(0);
Leon Scroggins III7a3805c2018-12-07 09:21:30 -0500714
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400715 // The Wuffs model is that the dst buffer is the image, not the frame.
716 // The expectation is that you allocate the buffer once, but re-use it
717 // for the N frames, regardless of each frame's top-left co-ordinate.
718 //
719 // To get from the start (in the X-direction) of the image to the start
720 // of the dirty_rect, we adjust s by (dirty_rect.min_incl_x * src_bytes_per_pixel).
Nigel Tao2777cd32019-10-29 11:10:25 +1100721 uint8_t* s = pixels.ptr + (dirty_rect.min_incl_y * pixels.stride) +
722 (dirty_rect.min_incl_x * src_bytes_per_pixel);
Leon Scroggins III7a3805c2018-12-07 09:21:30 -0500723
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400724 // Currently, this is only used for GIF, which will never have an ICC profile. When it is
725 // used for other formats that might have one, we will need to transform from profiles that
726 // do not have corresponding SkColorSpaces.
727 SkASSERT(!getEncodedInfo().profile());
728
Nigel Tao2777cd32019-10-29 11:10:25 +1100729 auto srcInfo =
730 getInfo().makeWH(dirty_rect.width(), dirty_rect.height()).makeAlphaType(alphaType);
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400731 SkBitmap src;
732 src.installPixels(srcInfo, s, pixels.stride);
733 SkPaint paint;
734 if (independent) {
735 paint.setBlendMode(SkBlendMode::kSrc);
Leon Scroggins III7a3805c2018-12-07 09:21:30 -0500736 }
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400737
738 SkDraw draw;
739 draw.fDst.reset(dstInfo(), fIncrDecDst, fIncrDecRowBytes);
Nigel Tao5cfa7192020-08-17 21:14:13 +1000740 SkMatrix matrix = SkMatrix::MakeRectToRect(SkRect::Make(this->dimensions()),
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400741 SkRect::Make(this->dstInfo().dimensions()),
742 SkMatrix::kFill_ScaleToFit);
Brian Osman9aaec362020-05-08 14:54:37 -0400743 SkSimpleMatrixProvider matrixProvider(matrix);
744 draw.fMatrixProvider = &matrixProvider;
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400745 SkRasterClip rc(SkIRect::MakeSize(this->dstInfo().dimensions()));
746 draw.fRC = &rc;
747
Mike Reed1f607332020-05-21 12:11:27 -0400748 SkMatrix translate = SkMatrix::Translate(dirty_rect.min_incl_x, dirty_rect.min_incl_y);
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400749 draw.drawBitmap(src, translate, nullptr, paint);
Leon Scroggins III7a3805c2018-12-07 09:21:30 -0500750 }
Nigel Taof0148c42019-12-08 19:12:13 +1100751
752 if (result == SkCodec::kSuccess) {
753 // On success, we are done using the "two pass" pixel buffer for this
754 // frame. We have the option of releasing its memory, but there is a
755 // trade-off. If decoding a subsequent frame will also need "two pass"
756 // decoding, it would have to re-allocate the buffer instead of just
757 // re-using it. On the other hand, if there is no subsequent frame, and
758 // the SkWuffsCodec object isn't deleted soon, then we are holding
759 // megabytes of memory longer than we need to.
760 //
761 // For example, when the Chromium web browser decodes the <img> tags in
762 // a HTML page, the SkCodec object can live until navigating away from
763 // the page, which can be much longer than when the pixels are fully
764 // decoded, especially for a still (non-animated) image. Even for
765 // looping animations, caching the decoded frames (at the higher HTML
766 // renderer layer) may mean that each frame is only decoded once (at
767 // the lower SkCodec layer), in sequence.
768 //
769 // The heuristic we use here is to free the memory if we have decoded
770 // the last frame of the animation (or, for still images, the only
771 // frame). The output of the next decode request (if any) should be the
772 // same either way, but the steady state memory use should hopefully be
773 // lower than always keeping the fTwoPassPixbufPtr buffer up until the
774 // SkWuffsCodec destructor runs.
775 //
776 // This only applies to "two pass" decoding. "One pass" decoding does
777 // not allocate, free or otherwise use fTwoPassPixbufPtr.
778 if (fFramesComplete && (static_cast<size_t>(options().fFrameIndex) == fFrames.size() - 1)) {
779 fTwoPassPixbufPtr.reset(nullptr);
780 fTwoPassPixbufLen = 0;
781 }
782 }
783
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400784 return result;
785}
786
787int SkWuffsCodec::onGetFrameCount() {
Nigel Tao3876a9f2019-11-14 09:04:45 +1100788 if (!fFramesComplete && seek_buffer(&fIOBuffer, fStream.get(), fFrameCountReaderIOPosition)) {
Nigel Tao2777cd32019-10-29 11:10:25 +1100789 this->onGetFrameCountInternal();
Nigel Tao3876a9f2019-11-14 09:04:45 +1100790 fFrameCountReaderIOPosition =
791 fDecoders[WhichDecoder::kFrameCount] ? fIOBuffer.reader_io_position() : 0;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400792 }
793 return fFrames.size();
794}
795
Nigel Tao2777cd32019-10-29 11:10:25 +1100796void SkWuffsCodec::onGetFrameCountInternal() {
Nigel Tao2777cd32019-10-29 11:10:25 +1100797 if (!fDecoders[WhichDecoder::kFrameCount]) {
798 void* decoder_raw = sk_malloc_canfail(sizeof__wuffs_gif__decoder());
799 if (!decoder_raw) {
800 return;
801 }
802 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> decoder(
803 reinterpret_cast<wuffs_gif__decoder*>(decoder_raw), &sk_free);
Nigel Tao3876a9f2019-11-14 09:04:45 +1100804 reset_and_decode_image_config(decoder.get(), nullptr, &fIOBuffer, fStream.get());
Nigel Tao2777cd32019-10-29 11:10:25 +1100805 fDecoders[WhichDecoder::kFrameCount] = std::move(decoder);
806 }
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400807
808 // Iterate through the frames, converting from Wuffs'
809 // wuffs_base__frame_config type to Skia's SkWuffsFrame type.
Nigel Tao3876a9f2019-11-14 09:04:45 +1100810 while (true) {
Nigel Tao2777cd32019-10-29 11:10:25 +1100811 const char* status = this->decodeFrameConfig(WhichDecoder::kFrameCount);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400812 if (status == nullptr) {
813 // No-op.
Nigel Taob54946b2020-06-18 23:36:27 +1000814 } else if (status == wuffs_base__note__end_of_data) {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400815 break;
816 } else {
817 return;
818 }
819
Nigel Tao3876a9f2019-11-14 09:04:45 +1100820 uint64_t i = fDecoders[WhichDecoder::kFrameCount]->num_decoded_frame_configs();
821 if (i > INT_MAX) {
822 break;
823 }
824 if ((i == 0) || (static_cast<size_t>(i - 1) != fFrames.size())) {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400825 continue;
826 }
Nigel Tao2777cd32019-10-29 11:10:25 +1100827 fFrames.emplace_back(&fFrameConfigs[WhichDecoder::kFrameCount]);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400828 SkWuffsFrame* f = &fFrames[fFrames.size() - 1];
829 fFrameHolder.setAlphaAndRequiredFrame(f);
830 }
831
832 fFramesComplete = true;
Nigel Tao5b271462019-11-12 21:02:20 +1100833
834 // We've seen the end of the animation. There'll be no more frames, so we
835 // no longer need the kFrameCount decoder. Releasing it earlier than the
836 // SkWuffsCodec destructor might help peak memory use.
837 fDecoders[WhichDecoder::kFrameCount].reset(nullptr);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400838}
839
Nigel Taocdc92382019-10-31 08:36:53 +1100840bool SkWuffsCodec::onGetFrameInfo(int i, SkCodec::FrameInfo* frameInfo) const {
841 const SkWuffsFrame* f = this->frame(i);
842 if (!f) {
843 return false;
844 }
845 if (frameInfo) {
Leon Scroggins III469d67e2020-11-11 12:45:40 -0500846 f->fillIn(frameInfo, static_cast<uint64_t>(i) < this->fNumFullyReceivedFrames);
Nigel Taocdc92382019-10-31 08:36:53 +1100847 }
848 return true;
849}
850
851int SkWuffsCodec::onGetRepetitionCount() {
852 // Convert from Wuffs's loop count to Skia's repeat count. Wuffs' uint32_t
853 // number is how many times to play the loop. Skia's int number is how many
854 // times to play the loop *after the first play*. Wuffs and Skia use 0 and
855 // kRepetitionCountInfinite respectively to mean loop forever.
856 uint32_t n = fDecoders[WhichDecoder::kIncrDecode]->num_animation_loops();
857 if (n == 0) {
858 return SkCodec::kRepetitionCountInfinite;
859 }
860 n--;
861 return n < INT_MAX ? n : INT_MAX;
862}
863
Nigel Tao2777cd32019-10-29 11:10:25 +1100864SkCodec::Result SkWuffsCodec::seekFrame(WhichDecoder which, int frameIndex) {
865 if (fDecoderIsSuspended[which]) {
866 SkCodec::Result res = this->resetDecoder(which);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400867 if (res != SkCodec::kSuccess) {
868 return res;
869 }
870 }
871
872 uint64_t pos = 0;
873 if (frameIndex < 0) {
874 return SkCodec::kInternalError;
875 } else if (frameIndex == 0) {
876 pos = fFirstFrameIOPosition;
877 } else if (static_cast<size_t>(frameIndex) < fFrames.size()) {
878 pos = fFrames[frameIndex].ioPosition();
879 } else {
880 return SkCodec::kInternalError;
881 }
882
883 if (!seek_buffer(&fIOBuffer, fStream.get(), pos)) {
884 return SkCodec::kInternalError;
885 }
Nigel Taob54946b2020-06-18 23:36:27 +1000886 wuffs_base__status status =
Nigel Tao2777cd32019-10-29 11:10:25 +1100887 fDecoders[which]->restart_frame(frameIndex, fIOBuffer.reader_io_position());
Nigel Taob54946b2020-06-18 23:36:27 +1000888 if (status.repr != nullptr) {
889 return SkCodec::kInternalError;
890 }
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400891 return SkCodec::kSuccess;
892}
893
Nigel Tao2777cd32019-10-29 11:10:25 +1100894SkCodec::Result SkWuffsCodec::resetDecoder(WhichDecoder which) {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400895 if (!fStream->rewind()) {
896 return SkCodec::kInternalError;
897 }
Nigel Tao96c10a02019-09-25 11:08:42 +1000898 fIOBuffer.meta = wuffs_base__empty_io_buffer_meta();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400899
900 SkCodec::Result result =
Nigel Tao2777cd32019-10-29 11:10:25 +1100901 reset_and_decode_image_config(fDecoders[which].get(), nullptr, &fIOBuffer, fStream.get());
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400902 if (result == SkCodec::kIncompleteInput) {
903 return SkCodec::kInternalError;
904 } else if (result != SkCodec::kSuccess) {
905 return result;
906 }
907
Nigel Tao2777cd32019-10-29 11:10:25 +1100908 fDecoderIsSuspended[which] = false;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400909 return SkCodec::kSuccess;
910}
911
Nigel Tao2777cd32019-10-29 11:10:25 +1100912const char* SkWuffsCodec::decodeFrameConfig(WhichDecoder which) {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400913 while (true) {
Nigel Taob54946b2020-06-18 23:36:27 +1000914 wuffs_base__status status =
Nigel Tao2777cd32019-10-29 11:10:25 +1100915 fDecoders[which]->decode_frame_config(&fFrameConfigs[which], &fIOBuffer);
Nigel Taob54946b2020-06-18 23:36:27 +1000916 if ((status.repr == wuffs_base__suspension__short_read) &&
917 fill_buffer(&fIOBuffer, fStream.get())) {
918 continue;
919 }
920 fDecoderIsSuspended[which] = !status.is_complete();
921 this->updateNumFullyReceivedFrames(which);
922 return status.repr;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400923 }
924}
925
Nigel Tao2777cd32019-10-29 11:10:25 +1100926const char* SkWuffsCodec::decodeFrame(WhichDecoder which) {
927 while (true) {
Nigel Taob54946b2020-06-18 23:36:27 +1000928 wuffs_base__status status = fDecoders[which]->decode_frame(
Nigel Taobf4605f2020-09-28 21:53:07 +1000929 &fPixelBuffer, &fIOBuffer, fIncrDecPixelBlend,
Nigel Tao09e541c2020-10-29 16:18:36 +1100930 wuffs_base__make_slice_u8(fWorkbufPtr.get(), fWorkbufLen), nullptr);
Nigel Taob54946b2020-06-18 23:36:27 +1000931 if ((status.repr == wuffs_base__suspension__short_read) &&
932 fill_buffer(&fIOBuffer, fStream.get())) {
933 continue;
934 }
935 fDecoderIsSuspended[which] = !status.is_complete();
936 this->updateNumFullyReceivedFrames(which);
937 return status.repr;
Nigel Tao2777cd32019-10-29 11:10:25 +1100938 }
939}
940
941void SkWuffsCodec::updateNumFullyReceivedFrames(WhichDecoder which) {
Nigel Tao6af1edc2019-01-19 15:12:39 +1100942 // num_decoded_frames's return value, n, can change over time, both up and
943 // down, as we seek back and forth in the underlying stream.
944 // fNumFullyReceivedFrames is the highest n we've seen.
Nigel Tao2777cd32019-10-29 11:10:25 +1100945 uint64_t n = fDecoders[which]->num_decoded_frames();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400946 if (fNumFullyReceivedFrames < n) {
947 fNumFullyReceivedFrames = n;
948 }
949}
950
951// -------------------------------- SkWuffsCodec.h functions
952
953bool SkWuffsCodec_IsFormat(const void* buf, size_t bytesRead) {
954 constexpr const char* gif_ptr = "GIF8";
955 constexpr size_t gif_len = 4;
956 return (bytesRead >= gif_len) && (memcmp(buf, gif_ptr, gif_len) == 0);
957}
958
959std::unique_ptr<SkCodec> SkWuffsCodec_MakeFromStream(std::unique_ptr<SkStream> stream,
960 SkCodec::Result* result) {
Nigel Tao48aa2212019-03-09 14:59:11 +1100961 uint8_t buffer[SK_WUFFS_CODEC_BUFFER_SIZE];
962 wuffs_base__io_buffer iobuf =
963 wuffs_base__make_io_buffer(wuffs_base__make_slice_u8(buffer, SK_WUFFS_CODEC_BUFFER_SIZE),
Nigel Tao96c10a02019-09-25 11:08:42 +1000964 wuffs_base__empty_io_buffer_meta());
Nigel Tao48aa2212019-03-09 14:59:11 +1100965 wuffs_base__image_config imgcfg = wuffs_base__null_image_config();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400966
967 // Wuffs is primarily a C library, not a C++ one. Furthermore, outside of
968 // the wuffs_base__etc types, the sizeof a file format specific type like
969 // GIF's wuffs_gif__decoder can vary between Wuffs versions. If p is of
970 // type wuffs_gif__decoder*, then the supported API treats p as a pointer
971 // to an opaque type: a private implementation detail. The API is always
972 // "set_foo(p, etc)" and not "p->foo = etc".
973 //
974 // See https://en.wikipedia.org/wiki/Opaque_pointer#C
975 //
976 // Thus, we don't use C++'s new operator (which requires knowing the sizeof
977 // the struct at compile time). Instead, we use sk_malloc_canfail, with
978 // sizeof__wuffs_gif__decoder returning the appropriate value for the
979 // (statically or dynamically) linked version of the Wuffs library.
980 //
981 // As a C (not C++) library, none of the Wuffs types have constructors or
982 // destructors.
983 //
984 // In RAII style, we can still use std::unique_ptr with these pointers, but
985 // we pair the pointer with sk_free instead of C++'s delete.
986 void* decoder_raw = sk_malloc_canfail(sizeof__wuffs_gif__decoder());
987 if (!decoder_raw) {
988 *result = SkCodec::kInternalError;
989 return nullptr;
990 }
991 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> decoder(
992 reinterpret_cast<wuffs_gif__decoder*>(decoder_raw), &sk_free);
993
994 SkCodec::Result reset_result =
995 reset_and_decode_image_config(decoder.get(), &imgcfg, &iobuf, stream.get());
996 if (reset_result != SkCodec::kSuccess) {
997 *result = reset_result;
998 return nullptr;
999 }
1000
1001 uint32_t width = imgcfg.pixcfg.width();
1002 uint32_t height = imgcfg.pixcfg.height();
1003 if ((width == 0) || (width > INT_MAX) || (height == 0) || (height > INT_MAX)) {
1004 *result = SkCodec::kInvalidInput;
1005 return nullptr;
1006 }
1007
Nigel Tao6af1edc2019-01-19 15:12:39 +11001008 uint64_t workbuf_len = decoder->workbuf_len().max_incl;
Nigel Tao22e86242019-01-26 16:04:01 +11001009 void* workbuf_ptr_raw = nullptr;
1010 if (workbuf_len) {
1011 workbuf_ptr_raw = workbuf_len <= SIZE_MAX ? sk_malloc_canfail(workbuf_len) : nullptr;
1012 if (!workbuf_ptr_raw) {
1013 *result = SkCodec::kInternalError;
1014 return nullptr;
1015 }
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001016 }
1017 std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr(
1018 reinterpret_cast<uint8_t*>(workbuf_ptr_raw), &sk_free);
1019
Nigel Tao490e6472019-02-14 14:50:53 +11001020 SkEncodedInfo::Color color =
Nigel Taob54946b2020-06-18 23:36:27 +10001021 (imgcfg.pixcfg.pixel_format().repr == WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL)
Nigel Tao490e6472019-02-14 14:50:53 +11001022 ? SkEncodedInfo::kBGRA_Color
1023 : SkEncodedInfo::kRGBA_Color;
1024
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001025 // In Skia's API, the alpha we calculate here and return is only for the
1026 // first frame.
1027 SkEncodedInfo::Alpha alpha = imgcfg.first_frame_is_opaque() ? SkEncodedInfo::kOpaque_Alpha
1028 : SkEncodedInfo::kBinary_Alpha;
1029
Nigel Tao490e6472019-02-14 14:50:53 +11001030 SkEncodedInfo encodedInfo = SkEncodedInfo::Make(width, height, color, alpha, 8);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001031
1032 *result = SkCodec::kSuccess;
Nigel Tao027f89b2019-12-06 10:56:24 +11001033 return std::unique_ptr<SkCodec>(new SkWuffsCodec(std::move(encodedInfo), std::move(stream),
1034 std::move(decoder), std::move(workbuf_ptr),
1035 workbuf_len, imgcfg, iobuf));
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001036}