blob: 1f0a3a1a80eb6cdce12e18f286356b90015201fd [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
Nigel Tao97771572020-12-15 20:28:32 +1100159 uint64_t ioPosition() const;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400160
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 Tao97771572020-12-15 20:28:32 +1100203 // TODO: delete this enum and all of the "which" function arguments. The
204 // "array of 1 Foo" typed fields can also simplify to "Foo".
Nigel Tao2777cd32019-10-29 11:10:25 +1100205 enum WhichDecoder {
206 kIncrDecode,
Nigel Tao2777cd32019-10-29 11:10:25 +1100207 kNumDecoders,
208 };
209
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400210 // SkCodec overrides.
211 SkEncodedImageFormat onGetEncodedFormat() const override;
212 Result onGetPixels(const SkImageInfo&, void*, size_t, const Options&, int*) override;
213 const SkFrameHolder* getFrameHolder() const override;
214 Result onStartIncrementalDecode(const SkImageInfo& dstInfo,
215 void* dst,
216 size_t rowBytes,
217 const SkCodec::Options& options) override;
218 Result onIncrementalDecode(int* rowsDecoded) override;
219 int onGetFrameCount() override;
220 bool onGetFrameInfo(int, FrameInfo*) const override;
221 int onGetRepetitionCount() override;
222
Nigel Tao027f89b2019-12-06 10:56:24 +1100223 // Two separate implementations of onStartIncrementalDecode and
224 // onIncrementalDecode, named "one pass" and "two pass" decoding. One pass
225 // decoding writes directly from the Wuffs image decoder to the dst buffer
226 // (the dst argument to onStartIncrementalDecode). Two pass decoding first
227 // writes into an intermediate buffer, and then composites and transforms
228 // the intermediate buffer into the dst buffer.
229 //
230 // In the general case, we need the two pass decoder, because of Skia API
231 // features that Wuffs doesn't support (e.g. color correction, scaling,
232 // RGB565). But as an optimization, we use one pass decoding (it's faster
233 // and uses less memory) if applicable (see the assignment to
234 // fIncrDecOnePass that calculates when we can do so).
Nigel Taob54946b2020-06-18 23:36:27 +1000235 Result onStartIncrementalDecodeOnePass(const SkImageInfo& dstInfo,
236 uint8_t* dst,
237 size_t rowBytes,
238 const SkCodec::Options& options,
239 uint32_t pixelFormat,
240 size_t bytesPerPixel);
Nigel Tao027f89b2019-12-06 10:56:24 +1100241 Result onStartIncrementalDecodeTwoPass();
242 Result onIncrementalDecodeOnePass();
243 Result onIncrementalDecodeTwoPass();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400244
Nigel Tao027f89b2019-12-06 10:56:24 +1100245 void onGetFrameCountInternal();
246 Result seekFrame(WhichDecoder which, int frameIndex);
Nigel Tao2777cd32019-10-29 11:10:25 +1100247 Result resetDecoder(WhichDecoder which);
248 const char* decodeFrameConfig(WhichDecoder which);
249 const char* decodeFrame(WhichDecoder which);
250 void updateNumFullyReceivedFrames(WhichDecoder which);
251
252 SkWuffsFrameHolder fFrameHolder;
253 std::unique_ptr<SkStream> fStream;
Nigel Tao2777cd32019-10-29 11:10:25 +1100254 std::unique_ptr<uint8_t, decltype(&sk_free)> fWorkbufPtr;
255 size_t fWorkbufLen;
256
257 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> fDecoders[WhichDecoder::kNumDecoders];
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400258
259 const uint64_t fFirstFrameIOPosition;
Nigel Tao2777cd32019-10-29 11:10:25 +1100260 wuffs_base__frame_config fFrameConfigs[WhichDecoder::kNumDecoders];
Nigel Tao027f89b2019-12-06 10:56:24 +1100261 wuffs_base__pixel_config fPixelConfig;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400262 wuffs_base__pixel_buffer fPixelBuffer;
263 wuffs_base__io_buffer fIOBuffer;
264
265 // Incremental decoding state.
Nigel Taobf4605f2020-09-28 21:53:07 +1000266 uint8_t* fIncrDecDst;
Nigel Taobf4605f2020-09-28 21:53:07 +1000267 size_t fIncrDecRowBytes;
268 wuffs_base__pixel_blend fIncrDecPixelBlend;
269 bool fIncrDecOnePass;
270 bool fFirstCallToIncrementalDecode;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400271
Nigel Tao027f89b2019-12-06 10:56:24 +1100272 // Lazily allocated intermediate pixel buffer, for two pass decoding.
273 std::unique_ptr<uint8_t, decltype(&sk_free)> fTwoPassPixbufPtr;
274 size_t fTwoPassPixbufLen;
275
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400276 uint64_t fNumFullyReceivedFrames;
277 std::vector<SkWuffsFrame> fFrames;
278 bool fFramesComplete;
279
Nigel Tao2777cd32019-10-29 11:10:25 +1100280 // If calling an fDecoders[which] method returns an incomplete status, then
281 // fDecoders[which] is suspended in a coroutine (i.e. waiting on I/O or
282 // halted on a non-recoverable error). To keep its internal proof-of-safety
283 // invariants consistent, there's only two things you can safely do with a
284 // suspended Wuffs object: resume the coroutine, or reset all state (memset
285 // to zero and start again).
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400286 //
Nigel Tao2777cd32019-10-29 11:10:25 +1100287 // If fDecoderIsSuspended[which], and we aren't sure that we're going to
288 // resume the coroutine, then we will need to call this->resetDecoder
289 // before calling other fDecoders[which] methods.
290 bool fDecoderIsSuspended[WhichDecoder::kNumDecoders];
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400291
292 uint8_t fBuffer[SK_WUFFS_CODEC_BUFFER_SIZE];
293
John Stiles7571f9e2020-09-02 22:42:33 -0400294 using INHERITED = SkScalingCodec;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400295};
296
297// -------------------------------- SkWuffsFrame implementation
298
299SkWuffsFrame::SkWuffsFrame(wuffs_base__frame_config* fc)
300 : INHERITED(fc->index()),
301 fIOPosition(fc->io_position()),
Nigel Taob54946b2020-06-18 23:36:27 +1000302 fReportedAlpha(fc->opaque_within_bounds() ? SkEncodedInfo::kOpaque_Alpha
Nigel Tao5cfa7192020-08-17 21:14:13 +1000303 : SkEncodedInfo::kUnpremul_Alpha) {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400304 wuffs_base__rect_ie_u32 r = fc->bounds();
305 this->setXYWH(r.min_incl_x, r.min_incl_y, r.width(), r.height());
306 this->setDisposalMethod(wuffs_disposal_to_skia_disposal(fc->disposal()));
307 this->setDuration(fc->duration() / WUFFS_BASE__FLICKS_PER_MILLISECOND);
Leon Scroggins III469d67e2020-11-11 12:45:40 -0500308 this->setBlend(fc->overwrite_instead_of_blend() ? SkCodecAnimation::Blend::kSrc
309 : SkCodecAnimation::Blend::kSrcOver);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400310}
311
312uint64_t SkWuffsFrame::ioPosition() const {
313 return fIOPosition;
314}
315
316SkEncodedInfo::Alpha SkWuffsFrame::onReportedAlpha() const {
317 return fReportedAlpha;
318}
319
320// -------------------------------- SkWuffsFrameHolder implementation
321
322void SkWuffsFrameHolder::init(SkWuffsCodec* codec, int width, int height) {
323 fCodec = codec;
324 // Initialize SkFrameHolder's (the superclass) fields.
325 fScreenWidth = width;
326 fScreenHeight = height;
327}
328
329const SkFrame* SkWuffsFrameHolder::onGetFrame(int i) const {
330 return fCodec->frame(i);
331};
332
333// -------------------------------- SkWuffsCodec implementation
334
335SkWuffsCodec::SkWuffsCodec(SkEncodedInfo&& encodedInfo,
336 std::unique_ptr<SkStream> stream,
337 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> dec,
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400338 std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr,
339 size_t workbuf_len,
340 wuffs_base__image_config imgcfg,
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400341 wuffs_base__io_buffer iobuf)
342 : INHERITED(std::move(encodedInfo),
343 skcms_PixelFormat_RGBA_8888,
344 // Pass a nullptr SkStream to the SkCodec constructor. We
345 // manage the stream ourselves, as the default SkCodec behavior
346 // is too trigger-happy on rewinding the stream.
347 nullptr),
Nigel Tao0185b952018-11-08 10:47:24 +1100348 fFrameHolder(),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400349 fStream(std::move(stream)),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400350 fWorkbufPtr(std::move(workbuf_ptr)),
351 fWorkbufLen(workbuf_len),
Nigel Tao2777cd32019-10-29 11:10:25 +1100352 fDecoders{
353 std::move(dec),
Nigel Tao2777cd32019-10-29 11:10:25 +1100354 },
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400355 fFirstFrameIOPosition(imgcfg.first_frame_io_position()),
Nigel Tao2777cd32019-10-29 11:10:25 +1100356 fFrameConfigs{
357 wuffs_base__null_frame_config(),
Nigel Tao2777cd32019-10-29 11:10:25 +1100358 },
Nigel Tao027f89b2019-12-06 10:56:24 +1100359 fPixelConfig(imgcfg.pixcfg),
360 fPixelBuffer(wuffs_base__null_pixel_buffer()),
Nigel Tao96c10a02019-09-25 11:08:42 +1000361 fIOBuffer(wuffs_base__empty_io_buffer()),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400362 fIncrDecDst(nullptr),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400363 fIncrDecRowBytes(0),
Nigel Taobf4605f2020-09-28 21:53:07 +1000364 fIncrDecPixelBlend(WUFFS_BASE__PIXEL_BLEND__SRC),
Nigel Tao027f89b2019-12-06 10:56:24 +1100365 fIncrDecOnePass(false),
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400366 fFirstCallToIncrementalDecode(false),
Nigel Tao027f89b2019-12-06 10:56:24 +1100367 fTwoPassPixbufPtr(nullptr, &sk_free),
368 fTwoPassPixbufLen(0),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400369 fNumFullyReceivedFrames(0),
370 fFramesComplete(false),
Nigel Tao2777cd32019-10-29 11:10:25 +1100371 fDecoderIsSuspended{
372 false,
Nigel Tao2777cd32019-10-29 11:10:25 +1100373 } {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400374 fFrameHolder.init(this, imgcfg.pixcfg.width(), imgcfg.pixcfg.height());
375
376 // Initialize fIOBuffer's fields, copying any outstanding data from iobuf to
377 // fIOBuffer, as iobuf's backing array may not be valid for the lifetime of
378 // this SkWuffsCodec object, but fIOBuffer's backing array (fBuffer) is.
379 SkASSERT(iobuf.data.len == SK_WUFFS_CODEC_BUFFER_SIZE);
380 memmove(fBuffer, iobuf.data.ptr, iobuf.meta.wi);
Nigel Tao48aa2212019-03-09 14:59:11 +1100381 fIOBuffer.data = wuffs_base__make_slice_u8(fBuffer, SK_WUFFS_CODEC_BUFFER_SIZE);
382 fIOBuffer.meta = iobuf.meta;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400383}
384
385const SkWuffsFrame* SkWuffsCodec::frame(int i) const {
386 if ((0 <= i) && (static_cast<size_t>(i) < fFrames.size())) {
387 return &fFrames[i];
388 }
389 return nullptr;
390}
391
392SkEncodedImageFormat SkWuffsCodec::onGetEncodedFormat() const {
393 return SkEncodedImageFormat::kGIF;
394}
395
396SkCodec::Result SkWuffsCodec::onGetPixels(const SkImageInfo& dstInfo,
397 void* dst,
398 size_t rowBytes,
399 const Options& options,
400 int* rowsDecoded) {
401 SkCodec::Result result = this->onStartIncrementalDecode(dstInfo, dst, rowBytes, options);
402 if (result != kSuccess) {
403 return result;
404 }
405 return this->onIncrementalDecode(rowsDecoded);
406}
407
408const SkFrameHolder* SkWuffsCodec::getFrameHolder() const {
409 return &fFrameHolder;
410}
411
412SkCodec::Result SkWuffsCodec::onStartIncrementalDecode(const SkImageInfo& dstInfo,
413 void* dst,
414 size_t rowBytes,
415 const SkCodec::Options& options) {
Nigel Tao1f1cd1f2019-06-22 17:35:38 +1000416 if (!dst) {
417 return SkCodec::kInvalidParameters;
418 }
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400419 if (options.fSubset) {
420 return SkCodec::kUnimplemented;
421 }
Nigel Tao2777cd32019-10-29 11:10:25 +1100422 SkCodec::Result result = this->seekFrame(WhichDecoder::kIncrDecode, options.fFrameIndex);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400423 if (result != SkCodec::kSuccess) {
424 return result;
425 }
426
Nigel Tao2777cd32019-10-29 11:10:25 +1100427 const char* status = this->decodeFrameConfig(WhichDecoder::kIncrDecode);
Nigel Taob7a1b512019-02-10 12:19:50 +1100428 if (status == wuffs_base__suspension__short_read) {
Leon Scroggins IIIcb6b8842018-12-04 13:55:13 -0500429 return SkCodec::kIncompleteInput;
Nigel Taob7a1b512019-02-10 12:19:50 +1100430 } else if (status != nullptr) {
Leon Scroggins IIIcb6b8842018-12-04 13:55:13 -0500431 SkCodecPrintf("decodeFrameConfig: %s", status);
432 return SkCodec::kErrorInInput;
433 }
Nigel Taob7a1b512019-02-10 12:19:50 +1100434
Nigel Taob54946b2020-06-18 23:36:27 +1000435 uint32_t pixelFormat = WUFFS_BASE__PIXEL_FORMAT__INVALID;
Nigel Tao5cfa7192020-08-17 21:14:13 +1000436 size_t bytesPerPixel = 0;
Nigel Tao027f89b2019-12-06 10:56:24 +1100437
438 switch (dstInfo.colorType()) {
Nigel Taof933e4f2020-10-29 09:42:11 +1100439 case kRGB_565_SkColorType:
440 pixelFormat = WUFFS_BASE__PIXEL_FORMAT__BGR_565;
441 bytesPerPixel = 2;
442 break;
Nigel Tao027f89b2019-12-06 10:56:24 +1100443 case kBGRA_8888_SkColorType:
444 pixelFormat = WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL;
445 bytesPerPixel = 4;
446 break;
447 case kRGBA_8888_SkColorType:
448 pixelFormat = WUFFS_BASE__PIXEL_FORMAT__RGBA_NONPREMUL;
449 bytesPerPixel = 4;
450 break;
451 default:
452 break;
453 }
454
455 // We can use "one pass" decoding if we have a Skia pixel format that Wuffs
456 // supports...
Nigel Taobf4605f2020-09-28 21:53:07 +1000457 fIncrDecOnePass = (pixelFormat != WUFFS_BASE__PIXEL_FORMAT__INVALID) &&
458 // ...and no color profile (as Wuffs does not support them)...
459 (!getEncodedInfo().profile()) &&
460 // ...and we use the identity transform (as Wuffs does
461 // not support scaling).
462 (this->dimensions() == dstInfo.dimensions());
Nigel Tao027f89b2019-12-06 10:56:24 +1100463
464 result = fIncrDecOnePass ? this->onStartIncrementalDecodeOnePass(
465 dstInfo, static_cast<uint8_t*>(dst), rowBytes, options,
466 pixelFormat, bytesPerPixel)
467 : this->onStartIncrementalDecodeTwoPass();
468 if (result != SkCodec::kSuccess) {
469 return result;
470 }
471
472 fIncrDecDst = static_cast<uint8_t*>(dst);
Nigel Tao027f89b2019-12-06 10:56:24 +1100473 fIncrDecRowBytes = rowBytes;
474 fFirstCallToIncrementalDecode = true;
475 return SkCodec::kSuccess;
476}
477
Nigel Taob54946b2020-06-18 23:36:27 +1000478SkCodec::Result SkWuffsCodec::onStartIncrementalDecodeOnePass(const SkImageInfo& dstInfo,
479 uint8_t* dst,
480 size_t rowBytes,
481 const SkCodec::Options& options,
482 uint32_t pixelFormat,
Nigel Tao027f89b2019-12-06 10:56:24 +1100483 size_t bytesPerPixel) {
484 wuffs_base__pixel_config pixelConfig;
485 pixelConfig.set(pixelFormat, WUFFS_BASE__PIXEL_SUBSAMPLING__NONE, dstInfo.width(),
486 dstInfo.height());
487
488 wuffs_base__table_u8 table;
489 table.ptr = dst;
490 table.width = static_cast<size_t>(dstInfo.width()) * bytesPerPixel;
491 table.height = dstInfo.height();
492 table.stride = rowBytes;
493
Nigel Taob54946b2020-06-18 23:36:27 +1000494 wuffs_base__status status = fPixelBuffer.set_from_table(&pixelConfig, table);
Nigel Taob54946b2020-06-18 23:36:27 +1000495 if (status.repr != nullptr) {
496 SkCodecPrintf("set_from_table: %s", status.message());
497 return SkCodec::kInternalError;
498 }
Nigel Taob7a1b512019-02-10 12:19:50 +1100499
Nigel Taobf4605f2020-09-28 21:53:07 +1000500 // SRC is usually faster than SRC_OVER, but for a dependent frame, dst is
501 // assumed to hold the previous frame's pixels (after processing the
502 // DisposalMethod). For one-pass decoding, we therefore use SRC_OVER.
503 if ((options.fFrameIndex != 0) &&
504 (this->frame(options.fFrameIndex)->getRequiredFrame() != SkCodec::kNoFrame)) {
505 fIncrDecPixelBlend = WUFFS_BASE__PIXEL_BLEND__SRC_OVER;
506 } else {
507 SkSampler::Fill(dstInfo, dst, rowBytes, options.fZeroInitialized);
508 fIncrDecPixelBlend = WUFFS_BASE__PIXEL_BLEND__SRC;
509 }
510
Nigel Tao027f89b2019-12-06 10:56:24 +1100511 return SkCodec::kSuccess;
512}
513
514SkCodec::Result SkWuffsCodec::onStartIncrementalDecodeTwoPass() {
515 // Either re-use the previously allocated "two pass" pixel buffer (and
516 // memset to zero), or allocate (and zero initialize) a new one.
517 bool already_zeroed = false;
518
519 if (!fTwoPassPixbufPtr) {
520 uint64_t pixbuf_len = fPixelConfig.pixbuf_len();
521 void* pixbuf_ptr_raw = (pixbuf_len <= SIZE_MAX)
Nigel Tao5cfa7192020-08-17 21:14:13 +1000522 ? sk_malloc_flags(pixbuf_len, SK_MALLOC_ZERO_INITIALIZE)
523 : nullptr;
Nigel Tao027f89b2019-12-06 10:56:24 +1100524 if (!pixbuf_ptr_raw) {
525 return SkCodec::kInternalError;
526 }
527 fTwoPassPixbufPtr.reset(reinterpret_cast<uint8_t*>(pixbuf_ptr_raw));
528 fTwoPassPixbufLen = SkToSizeT(pixbuf_len);
529 already_zeroed = true;
530 }
531
Nigel Taob54946b2020-06-18 23:36:27 +1000532 wuffs_base__status status = fPixelBuffer.set_from_slice(
Nigel Tao027f89b2019-12-06 10:56:24 +1100533 &fPixelConfig, wuffs_base__make_slice_u8(fTwoPassPixbufPtr.get(), fTwoPassPixbufLen));
Nigel Taob54946b2020-06-18 23:36:27 +1000534 if (status.repr != nullptr) {
535 SkCodecPrintf("set_from_slice: %s", status.message());
536 return SkCodec::kInternalError;
537 }
Nigel Tao027f89b2019-12-06 10:56:24 +1100538
539 if (!already_zeroed) {
Nigel Taob54946b2020-06-18 23:36:27 +1000540 uint32_t src_bits_per_pixel = fPixelConfig.pixel_format().bits_per_pixel();
Nigel Tao027f89b2019-12-06 10:56:24 +1100541 if ((src_bits_per_pixel == 0) || (src_bits_per_pixel % 8 != 0)) {
542 return SkCodec::kInternalError;
543 }
544 size_t src_bytes_per_pixel = src_bits_per_pixel / 8;
545
Nigel Tao39da10b2019-11-15 15:27:44 +1100546 wuffs_base__rect_ie_u32 frame_rect = fFrameConfigs[WhichDecoder::kIncrDecode].bounds();
547 wuffs_base__table_u8 pixels = fPixelBuffer.plane(0);
Nigel Tao6ec1b392019-11-20 12:28:50 +1100548
549 uint8_t* ptr = pixels.ptr + (frame_rect.min_incl_y * pixels.stride) +
550 (frame_rect.min_incl_x * src_bytes_per_pixel);
551 size_t len = frame_rect.width() * src_bytes_per_pixel;
552
553 // As an optimization, issue a single sk_bzero call, if possible.
554 // Otherwise, zero out each row separately.
555 if ((len == pixels.stride) && (frame_rect.min_incl_y < frame_rect.max_excl_y)) {
556 sk_bzero(ptr, len * (frame_rect.max_excl_y - frame_rect.min_incl_y));
557 } else {
558 for (uint32_t y = frame_rect.min_incl_y; y < frame_rect.max_excl_y; y++) {
559 sk_bzero(ptr, len);
560 ptr += pixels.stride;
561 }
Nigel Tao39da10b2019-11-15 15:27:44 +1100562 }
Nigel Taob7a1b512019-02-10 12:19:50 +1100563 }
564
Nigel Taobf4605f2020-09-28 21:53:07 +1000565 fIncrDecPixelBlend = WUFFS_BASE__PIXEL_BLEND__SRC;
Nigel Taob7a1b512019-02-10 12:19:50 +1100566 return SkCodec::kSuccess;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400567}
568
569SkCodec::Result SkWuffsCodec::onIncrementalDecode(int* rowsDecoded) {
570 if (!fIncrDecDst) {
571 return SkCodec::kInternalError;
572 }
573
Nigel Tao027f89b2019-12-06 10:56:24 +1100574 if (rowsDecoded) {
575 *rowsDecoded = dstInfo().height();
576 }
577
578 SkCodec::Result result =
579 fIncrDecOnePass ? this->onIncrementalDecodeOnePass() : this->onIncrementalDecodeTwoPass();
Nigel Tao2777cd32019-10-29 11:10:25 +1100580 if (result == SkCodec::kSuccess) {
581 fIncrDecDst = nullptr;
Nigel Tao2777cd32019-10-29 11:10:25 +1100582 fIncrDecRowBytes = 0;
Nigel Taobf4605f2020-09-28 21:53:07 +1000583 fIncrDecPixelBlend = WUFFS_BASE__PIXEL_BLEND__SRC;
Nigel Tao027f89b2019-12-06 10:56:24 +1100584 fIncrDecOnePass = false;
Nigel Tao2777cd32019-10-29 11:10:25 +1100585 }
586 return result;
587}
588
Nigel Tao027f89b2019-12-06 10:56:24 +1100589SkCodec::Result SkWuffsCodec::onIncrementalDecodeOnePass() {
590 const char* status = this->decodeFrame(WhichDecoder::kIncrDecode);
591 if (status != nullptr) {
592 if (status == wuffs_base__suspension__short_read) {
593 return SkCodec::kIncompleteInput;
594 } else {
595 SkCodecPrintf("decodeFrame: %s", status);
596 return SkCodec::kErrorInInput;
597 }
598 }
599 return SkCodec::kSuccess;
600}
601
602SkCodec::Result SkWuffsCodec::onIncrementalDecodeTwoPass() {
Leon Scroggins III699d41e2019-02-07 09:25:51 -0500603 SkCodec::Result result = SkCodec::kSuccess;
Nigel Tao2777cd32019-10-29 11:10:25 +1100604 const char* status = this->decodeFrame(WhichDecoder::kIncrDecode);
605 bool independent;
606 SkAlphaType alphaType;
607 const int index = options().fFrameIndex;
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400608 if (index == 0) {
609 independent = true;
610 alphaType = to_alpha_type(getEncodedInfo().opaque());
611 } else {
612 const SkWuffsFrame* f = this->frame(index);
613 independent = f->getRequiredFrame() == SkCodec::kNoFrame;
614 alphaType = to_alpha_type(f->reportedAlpha() == SkEncodedInfo::kOpaque_Alpha);
615 }
Leon Scroggins III699d41e2019-02-07 09:25:51 -0500616 if (status != nullptr) {
617 if (status == wuffs_base__suspension__short_read) {
618 result = SkCodec::kIncompleteInput;
619 } else {
620 SkCodecPrintf("decodeFrame: %s", status);
621 result = SkCodec::kErrorInInput;
622 }
623
624 if (!independent) {
625 // For a dependent frame, we cannot blend the partial result, since
626 // that will overwrite the contribution from prior frames.
627 return result;
628 }
629 }
630
Nigel Taob54946b2020-06-18 23:36:27 +1000631 uint32_t src_bits_per_pixel = fPixelBuffer.pixcfg.pixel_format().bits_per_pixel();
Nigel Tao490e6472019-02-14 14:50:53 +1100632 if ((src_bits_per_pixel == 0) || (src_bits_per_pixel % 8 != 0)) {
633 return SkCodec::kInternalError;
634 }
635 size_t src_bytes_per_pixel = src_bits_per_pixel / 8;
636
Nigel Tao2777cd32019-10-29 11:10:25 +1100637 wuffs_base__rect_ie_u32 frame_rect = fFrameConfigs[WhichDecoder::kIncrDecode].bounds();
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400638 if (fFirstCallToIncrementalDecode) {
Nigel Tao490e6472019-02-14 14:50:53 +1100639 if (frame_rect.width() > (SIZE_MAX / src_bytes_per_pixel)) {
640 return SkCodec::kInternalError;
641 }
642
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400643 auto bounds = SkIRect::MakeLTRB(frame_rect.min_incl_x, frame_rect.min_incl_y,
644 frame_rect.max_excl_x, frame_rect.max_excl_y);
645
Leon Scroggins IIIcb6b8842018-12-04 13:55:13 -0500646 // If the frame rect does not fill the output, ensure that those pixels are not
Nigel Taob7a1b512019-02-10 12:19:50 +1100647 // left uninitialized.
Leon Scroggins III44076362019-02-15 13:56:44 -0500648 if (independent && (bounds != this->bounds() || result != kSuccess)) {
Nigel Tao2777cd32019-10-29 11:10:25 +1100649 SkSampler::Fill(dstInfo(), fIncrDecDst, fIncrDecRowBytes, options().fZeroInitialized);
Leon Scroggins III9b0ba2c2018-11-19 14:52:37 -0500650 }
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400651 fFirstCallToIncrementalDecode = false;
652 } else {
653 // Existing clients intend to only show frames beyond the first if they
654 // are complete (based on FrameInfo::fFullyReceived), since it might
655 // look jarring to draw a partial frame over an existing frame. If they
656 // changed their behavior and expected to continue decoding a partial
657 // frame after the first one, we'll need to update our blending code.
658 // Otherwise, if the frame were interlaced and not independent, the
659 // second pass may have an overlapping dirty_rect with the first,
660 // resulting in blending with the first pass.
661 SkASSERT(index == 0);
Nigel Tao9859ef82019-02-13 13:20:02 +1100662 }
Nigel Tao0185b952018-11-08 10:47:24 +1100663
Leon Scroggins IIIdad4bfc2018-12-10 12:37:10 -0500664 // If the frame's dirty rect is empty, no need to swizzle.
Nigel Tao2777cd32019-10-29 11:10:25 +1100665 wuffs_base__rect_ie_u32 dirty_rect = fDecoders[WhichDecoder::kIncrDecode]->frame_dirty_rect();
Leon Scroggins IIIdad4bfc2018-12-10 12:37:10 -0500666 if (!dirty_rect.is_empty()) {
Nigel Tao490e6472019-02-14 14:50:53 +1100667 wuffs_base__table_u8 pixels = fPixelBuffer.plane(0);
Leon Scroggins III7a3805c2018-12-07 09:21:30 -0500668
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400669 // The Wuffs model is that the dst buffer is the image, not the frame.
670 // The expectation is that you allocate the buffer once, but re-use it
671 // for the N frames, regardless of each frame's top-left co-ordinate.
672 //
673 // To get from the start (in the X-direction) of the image to the start
674 // of the dirty_rect, we adjust s by (dirty_rect.min_incl_x * src_bytes_per_pixel).
Nigel Tao2777cd32019-10-29 11:10:25 +1100675 uint8_t* s = pixels.ptr + (dirty_rect.min_incl_y * pixels.stride) +
676 (dirty_rect.min_incl_x * src_bytes_per_pixel);
Leon Scroggins III7a3805c2018-12-07 09:21:30 -0500677
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400678 // Currently, this is only used for GIF, which will never have an ICC profile. When it is
679 // used for other formats that might have one, we will need to transform from profiles that
680 // do not have corresponding SkColorSpaces.
681 SkASSERT(!getEncodedInfo().profile());
682
Nigel Tao2777cd32019-10-29 11:10:25 +1100683 auto srcInfo =
684 getInfo().makeWH(dirty_rect.width(), dirty_rect.height()).makeAlphaType(alphaType);
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400685 SkBitmap src;
686 src.installPixels(srcInfo, s, pixels.stride);
687 SkPaint paint;
688 if (independent) {
689 paint.setBlendMode(SkBlendMode::kSrc);
Leon Scroggins III7a3805c2018-12-07 09:21:30 -0500690 }
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400691
692 SkDraw draw;
693 draw.fDst.reset(dstInfo(), fIncrDecDst, fIncrDecRowBytes);
Nigel Tao5cfa7192020-08-17 21:14:13 +1000694 SkMatrix matrix = SkMatrix::MakeRectToRect(SkRect::Make(this->dimensions()),
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400695 SkRect::Make(this->dstInfo().dimensions()),
696 SkMatrix::kFill_ScaleToFit);
Brian Osman9aaec362020-05-08 14:54:37 -0400697 SkSimpleMatrixProvider matrixProvider(matrix);
698 draw.fMatrixProvider = &matrixProvider;
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400699 SkRasterClip rc(SkIRect::MakeSize(this->dstInfo().dimensions()));
700 draw.fRC = &rc;
701
Mike Reed1f607332020-05-21 12:11:27 -0400702 SkMatrix translate = SkMatrix::Translate(dirty_rect.min_incl_x, dirty_rect.min_incl_y);
Mike Reed172ba9e2020-12-17 15:57:55 -0500703 draw.drawBitmap(src, translate, nullptr, SkSamplingOptions(), paint);
Leon Scroggins III7a3805c2018-12-07 09:21:30 -0500704 }
Nigel Taof0148c42019-12-08 19:12:13 +1100705
706 if (result == SkCodec::kSuccess) {
707 // On success, we are done using the "two pass" pixel buffer for this
708 // frame. We have the option of releasing its memory, but there is a
709 // trade-off. If decoding a subsequent frame will also need "two pass"
710 // decoding, it would have to re-allocate the buffer instead of just
711 // re-using it. On the other hand, if there is no subsequent frame, and
712 // the SkWuffsCodec object isn't deleted soon, then we are holding
713 // megabytes of memory longer than we need to.
714 //
715 // For example, when the Chromium web browser decodes the <img> tags in
716 // a HTML page, the SkCodec object can live until navigating away from
717 // the page, which can be much longer than when the pixels are fully
718 // decoded, especially for a still (non-animated) image. Even for
719 // looping animations, caching the decoded frames (at the higher HTML
720 // renderer layer) may mean that each frame is only decoded once (at
721 // the lower SkCodec layer), in sequence.
722 //
723 // The heuristic we use here is to free the memory if we have decoded
724 // the last frame of the animation (or, for still images, the only
725 // frame). The output of the next decode request (if any) should be the
726 // same either way, but the steady state memory use should hopefully be
727 // lower than always keeping the fTwoPassPixbufPtr buffer up until the
728 // SkWuffsCodec destructor runs.
729 //
730 // This only applies to "two pass" decoding. "One pass" decoding does
731 // not allocate, free or otherwise use fTwoPassPixbufPtr.
732 if (fFramesComplete && (static_cast<size_t>(options().fFrameIndex) == fFrames.size() - 1)) {
733 fTwoPassPixbufPtr.reset(nullptr);
734 fTwoPassPixbufLen = 0;
735 }
736 }
737
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400738 return result;
739}
740
741int SkWuffsCodec::onGetFrameCount() {
Nigel Tao97771572020-12-15 20:28:32 +1100742 // It is valid, in terms of the SkCodec API, to call SkCodec::getFrameCount
743 // while in an incremental decode (after onStartIncrementalDecode returns
744 // and before onIncrementalDecode returns kSuccess).
745 //
746 // We should not advance the SkWuffsCodec' stream while doing so, even
747 // though other SkCodec implementations can return increasing values from
748 // onGetFrameCount when given more data. If we tried to do so, the
749 // subsequent resume of the incremental decode would continue reading from
750 // a different position in the I/O stream, leading to an incorrect error.
751 //
752 // Other SkCodec implementations can move the stream forward during
753 // onGetFrameCount because they assume that the stream is rewindable /
754 // seekable. For example, an alternative GIF implementation may choose to
755 // store, for each frame walked past when merely counting the number of
756 // frames, the I/O position of each of the frame's GIF data blocks. (A GIF
757 // frame's compressed data can have multiple data blocks, each at most 255
758 // bytes in length). Obviously, this can require O(numberOfFrames) extra
759 // memory to store these I/O positions. The constant factor is small, but
760 // it's still O(N), not O(1).
761 //
762 // Wuffs and SkWuffsCodec try to minimize relying on the rewindable /
763 // seekable assumption. By design, Wuffs per se aims for O(1) memory use
764 // (after any pixel buffers are allocated) instead of O(N), and its I/O
765 // type, wuffs_base__io_buffer, is not necessarily rewindable or seekable.
766 //
767 // The Wuffs API provides a limited, optional form of seeking, to the start
768 // of an animation frame's data, but does not provide arbitrary save and
769 // load of its internal state whilst in the middle of an animation frame.
770 bool incrementalDecodeIsInProgress = fIncrDecDst != nullptr;
771
772 if (!fFramesComplete && !incrementalDecodeIsInProgress) {
Nigel Tao2777cd32019-10-29 11:10:25 +1100773 this->onGetFrameCountInternal();
Nigel Tao97771572020-12-15 20:28:32 +1100774 this->updateNumFullyReceivedFrames(WhichDecoder::kIncrDecode);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400775 }
776 return fFrames.size();
777}
778
Nigel Tao2777cd32019-10-29 11:10:25 +1100779void SkWuffsCodec::onGetFrameCountInternal() {
Nigel Tao97771572020-12-15 20:28:32 +1100780 size_t n = fFrames.size();
781 int i = n ? n - 1 : 0;
782 if (this->seekFrame(WhichDecoder::kIncrDecode, i) != SkCodec::kSuccess) {
783 return;
Nigel Tao2777cd32019-10-29 11:10:25 +1100784 }
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400785
786 // Iterate through the frames, converting from Wuffs'
787 // wuffs_base__frame_config type to Skia's SkWuffsFrame type.
Nigel Tao97771572020-12-15 20:28:32 +1100788 for (; i < INT_MAX; i++) {
789 const char* status = this->decodeFrameConfig(WhichDecoder::kIncrDecode);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400790 if (status == nullptr) {
791 // No-op.
Nigel Taob54946b2020-06-18 23:36:27 +1000792 } else if (status == wuffs_base__note__end_of_data) {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400793 break;
794 } else {
795 return;
796 }
797
Nigel Tao97771572020-12-15 20:28:32 +1100798 if (static_cast<size_t>(i) < fFrames.size()) {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400799 continue;
800 }
Nigel Tao97771572020-12-15 20:28:32 +1100801 fFrames.emplace_back(&fFrameConfigs[WhichDecoder::kIncrDecode]);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400802 SkWuffsFrame* f = &fFrames[fFrames.size() - 1];
803 fFrameHolder.setAlphaAndRequiredFrame(f);
804 }
805
806 fFramesComplete = true;
807}
808
Nigel Taocdc92382019-10-31 08:36:53 +1100809bool SkWuffsCodec::onGetFrameInfo(int i, SkCodec::FrameInfo* frameInfo) const {
810 const SkWuffsFrame* f = this->frame(i);
811 if (!f) {
812 return false;
813 }
814 if (frameInfo) {
Leon Scroggins III469d67e2020-11-11 12:45:40 -0500815 f->fillIn(frameInfo, static_cast<uint64_t>(i) < this->fNumFullyReceivedFrames);
Nigel Taocdc92382019-10-31 08:36:53 +1100816 }
817 return true;
818}
819
820int SkWuffsCodec::onGetRepetitionCount() {
821 // Convert from Wuffs's loop count to Skia's repeat count. Wuffs' uint32_t
822 // number is how many times to play the loop. Skia's int number is how many
823 // times to play the loop *after the first play*. Wuffs and Skia use 0 and
824 // kRepetitionCountInfinite respectively to mean loop forever.
825 uint32_t n = fDecoders[WhichDecoder::kIncrDecode]->num_animation_loops();
826 if (n == 0) {
827 return SkCodec::kRepetitionCountInfinite;
828 }
829 n--;
830 return n < INT_MAX ? n : INT_MAX;
831}
832
Nigel Tao2777cd32019-10-29 11:10:25 +1100833SkCodec::Result SkWuffsCodec::seekFrame(WhichDecoder which, int frameIndex) {
834 if (fDecoderIsSuspended[which]) {
835 SkCodec::Result res = this->resetDecoder(which);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400836 if (res != SkCodec::kSuccess) {
837 return res;
838 }
839 }
840
841 uint64_t pos = 0;
842 if (frameIndex < 0) {
843 return SkCodec::kInternalError;
844 } else if (frameIndex == 0) {
845 pos = fFirstFrameIOPosition;
846 } else if (static_cast<size_t>(frameIndex) < fFrames.size()) {
847 pos = fFrames[frameIndex].ioPosition();
848 } else {
849 return SkCodec::kInternalError;
850 }
851
852 if (!seek_buffer(&fIOBuffer, fStream.get(), pos)) {
853 return SkCodec::kInternalError;
854 }
Nigel Taob54946b2020-06-18 23:36:27 +1000855 wuffs_base__status status =
Nigel Tao2777cd32019-10-29 11:10:25 +1100856 fDecoders[which]->restart_frame(frameIndex, fIOBuffer.reader_io_position());
Nigel Taob54946b2020-06-18 23:36:27 +1000857 if (status.repr != nullptr) {
858 return SkCodec::kInternalError;
859 }
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400860 return SkCodec::kSuccess;
861}
862
Nigel Tao2777cd32019-10-29 11:10:25 +1100863SkCodec::Result SkWuffsCodec::resetDecoder(WhichDecoder which) {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400864 if (!fStream->rewind()) {
865 return SkCodec::kInternalError;
866 }
Nigel Tao96c10a02019-09-25 11:08:42 +1000867 fIOBuffer.meta = wuffs_base__empty_io_buffer_meta();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400868
869 SkCodec::Result result =
Nigel Tao2777cd32019-10-29 11:10:25 +1100870 reset_and_decode_image_config(fDecoders[which].get(), nullptr, &fIOBuffer, fStream.get());
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400871 if (result == SkCodec::kIncompleteInput) {
872 return SkCodec::kInternalError;
873 } else if (result != SkCodec::kSuccess) {
874 return result;
875 }
876
Nigel Tao2777cd32019-10-29 11:10:25 +1100877 fDecoderIsSuspended[which] = false;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400878 return SkCodec::kSuccess;
879}
880
Nigel Tao2777cd32019-10-29 11:10:25 +1100881const char* SkWuffsCodec::decodeFrameConfig(WhichDecoder which) {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400882 while (true) {
Nigel Taob54946b2020-06-18 23:36:27 +1000883 wuffs_base__status status =
Nigel Tao2777cd32019-10-29 11:10:25 +1100884 fDecoders[which]->decode_frame_config(&fFrameConfigs[which], &fIOBuffer);
Nigel Taob54946b2020-06-18 23:36:27 +1000885 if ((status.repr == wuffs_base__suspension__short_read) &&
886 fill_buffer(&fIOBuffer, fStream.get())) {
887 continue;
888 }
889 fDecoderIsSuspended[which] = !status.is_complete();
890 this->updateNumFullyReceivedFrames(which);
891 return status.repr;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400892 }
893}
894
Nigel Tao2777cd32019-10-29 11:10:25 +1100895const char* SkWuffsCodec::decodeFrame(WhichDecoder which) {
896 while (true) {
Nigel Taob54946b2020-06-18 23:36:27 +1000897 wuffs_base__status status = fDecoders[which]->decode_frame(
Nigel Taobf4605f2020-09-28 21:53:07 +1000898 &fPixelBuffer, &fIOBuffer, fIncrDecPixelBlend,
Nigel Tao09e541c2020-10-29 16:18:36 +1100899 wuffs_base__make_slice_u8(fWorkbufPtr.get(), fWorkbufLen), nullptr);
Nigel Taob54946b2020-06-18 23:36:27 +1000900 if ((status.repr == wuffs_base__suspension__short_read) &&
901 fill_buffer(&fIOBuffer, fStream.get())) {
902 continue;
903 }
904 fDecoderIsSuspended[which] = !status.is_complete();
905 this->updateNumFullyReceivedFrames(which);
906 return status.repr;
Nigel Tao2777cd32019-10-29 11:10:25 +1100907 }
908}
909
910void SkWuffsCodec::updateNumFullyReceivedFrames(WhichDecoder which) {
Nigel Tao6af1edc2019-01-19 15:12:39 +1100911 // num_decoded_frames's return value, n, can change over time, both up and
912 // down, as we seek back and forth in the underlying stream.
913 // fNumFullyReceivedFrames is the highest n we've seen.
Nigel Tao2777cd32019-10-29 11:10:25 +1100914 uint64_t n = fDecoders[which]->num_decoded_frames();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400915 if (fNumFullyReceivedFrames < n) {
916 fNumFullyReceivedFrames = n;
917 }
918}
919
920// -------------------------------- SkWuffsCodec.h functions
921
922bool SkWuffsCodec_IsFormat(const void* buf, size_t bytesRead) {
923 constexpr const char* gif_ptr = "GIF8";
924 constexpr size_t gif_len = 4;
925 return (bytesRead >= gif_len) && (memcmp(buf, gif_ptr, gif_len) == 0);
926}
927
928std::unique_ptr<SkCodec> SkWuffsCodec_MakeFromStream(std::unique_ptr<SkStream> stream,
929 SkCodec::Result* result) {
Nigel Tao48aa2212019-03-09 14:59:11 +1100930 uint8_t buffer[SK_WUFFS_CODEC_BUFFER_SIZE];
931 wuffs_base__io_buffer iobuf =
932 wuffs_base__make_io_buffer(wuffs_base__make_slice_u8(buffer, SK_WUFFS_CODEC_BUFFER_SIZE),
Nigel Tao96c10a02019-09-25 11:08:42 +1000933 wuffs_base__empty_io_buffer_meta());
Nigel Tao48aa2212019-03-09 14:59:11 +1100934 wuffs_base__image_config imgcfg = wuffs_base__null_image_config();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400935
936 // Wuffs is primarily a C library, not a C++ one. Furthermore, outside of
937 // the wuffs_base__etc types, the sizeof a file format specific type like
938 // GIF's wuffs_gif__decoder can vary between Wuffs versions. If p is of
939 // type wuffs_gif__decoder*, then the supported API treats p as a pointer
940 // to an opaque type: a private implementation detail. The API is always
941 // "set_foo(p, etc)" and not "p->foo = etc".
942 //
943 // See https://en.wikipedia.org/wiki/Opaque_pointer#C
944 //
945 // Thus, we don't use C++'s new operator (which requires knowing the sizeof
946 // the struct at compile time). Instead, we use sk_malloc_canfail, with
947 // sizeof__wuffs_gif__decoder returning the appropriate value for the
948 // (statically or dynamically) linked version of the Wuffs library.
949 //
950 // As a C (not C++) library, none of the Wuffs types have constructors or
951 // destructors.
952 //
953 // In RAII style, we can still use std::unique_ptr with these pointers, but
954 // we pair the pointer with sk_free instead of C++'s delete.
955 void* decoder_raw = sk_malloc_canfail(sizeof__wuffs_gif__decoder());
956 if (!decoder_raw) {
957 *result = SkCodec::kInternalError;
958 return nullptr;
959 }
960 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> decoder(
961 reinterpret_cast<wuffs_gif__decoder*>(decoder_raw), &sk_free);
962
963 SkCodec::Result reset_result =
964 reset_and_decode_image_config(decoder.get(), &imgcfg, &iobuf, stream.get());
965 if (reset_result != SkCodec::kSuccess) {
966 *result = reset_result;
967 return nullptr;
968 }
969
970 uint32_t width = imgcfg.pixcfg.width();
971 uint32_t height = imgcfg.pixcfg.height();
972 if ((width == 0) || (width > INT_MAX) || (height == 0) || (height > INT_MAX)) {
973 *result = SkCodec::kInvalidInput;
974 return nullptr;
975 }
976
Nigel Tao6af1edc2019-01-19 15:12:39 +1100977 uint64_t workbuf_len = decoder->workbuf_len().max_incl;
Nigel Tao22e86242019-01-26 16:04:01 +1100978 void* workbuf_ptr_raw = nullptr;
979 if (workbuf_len) {
980 workbuf_ptr_raw = workbuf_len <= SIZE_MAX ? sk_malloc_canfail(workbuf_len) : nullptr;
981 if (!workbuf_ptr_raw) {
982 *result = SkCodec::kInternalError;
983 return nullptr;
984 }
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400985 }
986 std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr(
987 reinterpret_cast<uint8_t*>(workbuf_ptr_raw), &sk_free);
988
Nigel Tao490e6472019-02-14 14:50:53 +1100989 SkEncodedInfo::Color color =
Nigel Taob54946b2020-06-18 23:36:27 +1000990 (imgcfg.pixcfg.pixel_format().repr == WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL)
Nigel Tao490e6472019-02-14 14:50:53 +1100991 ? SkEncodedInfo::kBGRA_Color
992 : SkEncodedInfo::kRGBA_Color;
993
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400994 // In Skia's API, the alpha we calculate here and return is only for the
995 // first frame.
996 SkEncodedInfo::Alpha alpha = imgcfg.first_frame_is_opaque() ? SkEncodedInfo::kOpaque_Alpha
997 : SkEncodedInfo::kBinary_Alpha;
998
Nigel Tao490e6472019-02-14 14:50:53 +1100999 SkEncodedInfo encodedInfo = SkEncodedInfo::Make(width, height, color, alpha, 8);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001000
1001 *result = SkCodec::kSuccess;
Nigel Tao027f89b2019-12-06 10:56:24 +11001002 return std::unique_ptr<SkCodec>(new SkWuffsCodec(std::move(encodedInfo), std::move(stream),
1003 std::move(decoder), std::move(workbuf_ptr),
1004 workbuf_len, imgcfg, iobuf));
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001005}