blob: b45bd47bb3410b924c0797b510b906e313dc8587 [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
159 SkCodec::FrameInfo frameInfo(bool fullyReceived) const;
160 uint64_t ioPosition() const;
161
162 // SkFrame overrides.
163 SkEncodedInfo::Alpha onReportedAlpha() const override;
164
165private:
166 uint64_t fIOPosition;
167 SkEncodedInfo::Alpha fReportedAlpha;
168
169 typedef SkFrame INHERITED;
170};
171
172// SkWuffsFrameHolder is a trivial indirector that forwards its calls onto a
173// SkWuffsCodec. It is a separate class as SkWuffsCodec would otherwise
174// inherit from both SkCodec and SkFrameHolder, and Skia style discourages
175// multiple inheritance (e.g. with its "typedef Foo INHERITED" convention).
176class SkWuffsFrameHolder final : public SkFrameHolder {
177public:
178 SkWuffsFrameHolder() : INHERITED() {}
179
180 void init(SkWuffsCodec* codec, int width, int height);
181
182 // SkFrameHolder overrides.
183 const SkFrame* onGetFrame(int i) const override;
184
185private:
186 const SkWuffsCodec* fCodec;
187
188 typedef SkFrameHolder INHERITED;
189};
190
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400191class SkWuffsCodec final : public SkScalingCodec {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400192public:
193 SkWuffsCodec(SkEncodedInfo&& encodedInfo,
194 std::unique_ptr<SkStream> stream,
195 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> dec,
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400196 std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr,
197 size_t workbuf_len,
198 wuffs_base__image_config imgcfg,
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400199 wuffs_base__io_buffer iobuf);
200
201 const SkWuffsFrame* frame(int i) const;
202
203private:
Nigel Tao2777cd32019-10-29 11:10:25 +1100204 // It is valid, in terms of the SkCodec API, to call SkCodec::getFrameCount
205 // while in an incremental decode (after onStartIncrementalDecode returns
206 // and before the rest of the image is decoded). Some Skia users expect
207 // getFrameCount to increase, and the SkStream to advance, when given more
208 // data.
209 //
210 // On the other hand, while in an incremental decode, the underlying Wuffs
211 // object is suspended in a coroutine. To keep its internal proof-of-safety
212 // invariants consistent, there's only two things you can safely do with a
213 // suspended Wuffs object: resume the coroutine, or reset all state (memset
214 // to zero and start again).
215 //
216 // The Wuffs API provides a limited, optional form of seeking, to the start
217 // of an animation frame's data, but does not provide arbitrary save and
218 // load of its internal state whilst in the middle of an animation frame.
219 //
220 // SkWuffsCodec therefore uses two Wuffs decoders: a primary decoder
221 // (kIncrDecode) to support startIncrementalDecode / incrementalDecode, and
222 // a secondary decoder (kFrameCount) to support getFrameCount. The two
223 // decoders' states can change independently.
224 //
225 // As of Wuffs version 0.2, both of these decoders have the same type. A
226 // future Wuffs version might let us use a different type for kFrameCount,
227 // one that is much lighter weight (in terms of memory requirements), as it
228 // doesn't have to handle decompressing pixel data.
229 enum WhichDecoder {
230 kIncrDecode,
231 kFrameCount,
232 kNumDecoders,
233 };
234
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400235 // SkCodec overrides.
236 SkEncodedImageFormat onGetEncodedFormat() const override;
237 Result onGetPixels(const SkImageInfo&, void*, size_t, const Options&, int*) override;
238 const SkFrameHolder* getFrameHolder() const override;
239 Result onStartIncrementalDecode(const SkImageInfo& dstInfo,
240 void* dst,
241 size_t rowBytes,
242 const SkCodec::Options& options) override;
243 Result onIncrementalDecode(int* rowsDecoded) override;
244 int onGetFrameCount() override;
245 bool onGetFrameInfo(int, FrameInfo*) const override;
246 int onGetRepetitionCount() override;
247
Nigel Tao027f89b2019-12-06 10:56:24 +1100248 // Two separate implementations of onStartIncrementalDecode and
249 // onIncrementalDecode, named "one pass" and "two pass" decoding. One pass
250 // decoding writes directly from the Wuffs image decoder to the dst buffer
251 // (the dst argument to onStartIncrementalDecode). Two pass decoding first
252 // writes into an intermediate buffer, and then composites and transforms
253 // the intermediate buffer into the dst buffer.
254 //
255 // In the general case, we need the two pass decoder, because of Skia API
256 // features that Wuffs doesn't support (e.g. color correction, scaling,
257 // RGB565). But as an optimization, we use one pass decoding (it's faster
258 // and uses less memory) if applicable (see the assignment to
259 // fIncrDecOnePass that calculates when we can do so).
Nigel Taob54946b2020-06-18 23:36:27 +1000260 Result onStartIncrementalDecodeOnePass(const SkImageInfo& dstInfo,
261 uint8_t* dst,
262 size_t rowBytes,
263 const SkCodec::Options& options,
264 uint32_t pixelFormat,
265 size_t bytesPerPixel);
Nigel Tao027f89b2019-12-06 10:56:24 +1100266 Result onStartIncrementalDecodeTwoPass();
267 Result onIncrementalDecodeOnePass();
268 Result onIncrementalDecodeTwoPass();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400269
Nigel Tao027f89b2019-12-06 10:56:24 +1100270 void onGetFrameCountInternal();
271 Result seekFrame(WhichDecoder which, int frameIndex);
Nigel Tao2777cd32019-10-29 11:10:25 +1100272 Result resetDecoder(WhichDecoder which);
273 const char* decodeFrameConfig(WhichDecoder which);
274 const char* decodeFrame(WhichDecoder which);
275 void updateNumFullyReceivedFrames(WhichDecoder which);
276
277 SkWuffsFrameHolder fFrameHolder;
278 std::unique_ptr<SkStream> fStream;
Nigel Tao2777cd32019-10-29 11:10:25 +1100279 std::unique_ptr<uint8_t, decltype(&sk_free)> fWorkbufPtr;
280 size_t fWorkbufLen;
281
282 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> fDecoders[WhichDecoder::kNumDecoders];
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400283
284 const uint64_t fFirstFrameIOPosition;
Nigel Tao2777cd32019-10-29 11:10:25 +1100285 wuffs_base__frame_config fFrameConfigs[WhichDecoder::kNumDecoders];
Nigel Tao027f89b2019-12-06 10:56:24 +1100286 wuffs_base__pixel_config fPixelConfig;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400287 wuffs_base__pixel_buffer fPixelBuffer;
288 wuffs_base__io_buffer fIOBuffer;
289
290 // Incremental decoding state.
Nigel Tao0185b952018-11-08 10:47:24 +1100291 uint8_t* fIncrDecDst;
Nigel Tao2777cd32019-10-29 11:10:25 +1100292 uint64_t fIncrDecReaderIOPosition;
Nigel Tao0185b952018-11-08 10:47:24 +1100293 size_t fIncrDecRowBytes;
Nigel Tao027f89b2019-12-06 10:56:24 +1100294 bool fIncrDecOnePass;
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400295 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
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400320 typedef SkScalingCodec INHERITED;
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);
Nigel Taob54946b2020-06-18 23:36:27 +1000334 this->setBlend(fc->overwrite_instead_of_blend() ? SkCodecAnimation::Blend::kBG
335 : SkCodecAnimation::Blend::kPriorFrame);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400336}
337
338SkCodec::FrameInfo SkWuffsFrame::frameInfo(bool fullyReceived) const {
Nigel Taoef40e332019-04-05 10:28:40 +1100339 SkCodec::FrameInfo ret;
340 ret.fRequiredFrame = getRequiredFrame();
341 ret.fDuration = getDuration();
342 ret.fFullyReceived = fullyReceived;
343 ret.fAlphaType = hasAlpha() ? kUnpremul_SkAlphaType : kOpaque_SkAlphaType;
344 ret.fDisposalMethod = getDisposalMethod();
345 return ret;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400346}
347
348uint64_t SkWuffsFrame::ioPosition() const {
349 return fIOPosition;
350}
351
352SkEncodedInfo::Alpha SkWuffsFrame::onReportedAlpha() const {
353 return fReportedAlpha;
354}
355
356// -------------------------------- SkWuffsFrameHolder implementation
357
358void SkWuffsFrameHolder::init(SkWuffsCodec* codec, int width, int height) {
359 fCodec = codec;
360 // Initialize SkFrameHolder's (the superclass) fields.
361 fScreenWidth = width;
362 fScreenHeight = height;
363}
364
365const SkFrame* SkWuffsFrameHolder::onGetFrame(int i) const {
366 return fCodec->frame(i);
367};
368
369// -------------------------------- SkWuffsCodec implementation
370
371SkWuffsCodec::SkWuffsCodec(SkEncodedInfo&& encodedInfo,
372 std::unique_ptr<SkStream> stream,
373 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> dec,
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400374 std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr,
375 size_t workbuf_len,
376 wuffs_base__image_config imgcfg,
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400377 wuffs_base__io_buffer iobuf)
378 : INHERITED(std::move(encodedInfo),
379 skcms_PixelFormat_RGBA_8888,
380 // Pass a nullptr SkStream to the SkCodec constructor. We
381 // manage the stream ourselves, as the default SkCodec behavior
382 // is too trigger-happy on rewinding the stream.
383 nullptr),
Nigel Tao0185b952018-11-08 10:47:24 +1100384 fFrameHolder(),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400385 fStream(std::move(stream)),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400386 fWorkbufPtr(std::move(workbuf_ptr)),
387 fWorkbufLen(workbuf_len),
Nigel Tao2777cd32019-10-29 11:10:25 +1100388 fDecoders{
389 std::move(dec),
390 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)>(nullptr, sk_free),
391 },
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400392 fFirstFrameIOPosition(imgcfg.first_frame_io_position()),
Nigel Tao2777cd32019-10-29 11:10:25 +1100393 fFrameConfigs{
394 wuffs_base__null_frame_config(),
395 wuffs_base__null_frame_config(),
396 },
Nigel Tao027f89b2019-12-06 10:56:24 +1100397 fPixelConfig(imgcfg.pixcfg),
398 fPixelBuffer(wuffs_base__null_pixel_buffer()),
Nigel Tao96c10a02019-09-25 11:08:42 +1000399 fIOBuffer(wuffs_base__empty_io_buffer()),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400400 fIncrDecDst(nullptr),
Nigel Tao2777cd32019-10-29 11:10:25 +1100401 fIncrDecReaderIOPosition(0),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400402 fIncrDecRowBytes(0),
Nigel Tao027f89b2019-12-06 10:56:24 +1100403 fIncrDecOnePass(false),
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400404 fFirstCallToIncrementalDecode(false),
Nigel Tao027f89b2019-12-06 10:56:24 +1100405 fTwoPassPixbufPtr(nullptr, &sk_free),
406 fTwoPassPixbufLen(0),
Nigel Tao3876a9f2019-11-14 09:04:45 +1100407 fFrameCountReaderIOPosition(0),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400408 fNumFullyReceivedFrames(0),
409 fFramesComplete(false),
Nigel Tao2777cd32019-10-29 11:10:25 +1100410 fDecoderIsSuspended{
411 false,
412 false,
413 } {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400414 fFrameHolder.init(this, imgcfg.pixcfg.width(), imgcfg.pixcfg.height());
415
416 // Initialize fIOBuffer's fields, copying any outstanding data from iobuf to
417 // fIOBuffer, as iobuf's backing array may not be valid for the lifetime of
418 // this SkWuffsCodec object, but fIOBuffer's backing array (fBuffer) is.
419 SkASSERT(iobuf.data.len == SK_WUFFS_CODEC_BUFFER_SIZE);
420 memmove(fBuffer, iobuf.data.ptr, iobuf.meta.wi);
Nigel Tao48aa2212019-03-09 14:59:11 +1100421 fIOBuffer.data = wuffs_base__make_slice_u8(fBuffer, SK_WUFFS_CODEC_BUFFER_SIZE);
422 fIOBuffer.meta = iobuf.meta;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400423}
424
425const SkWuffsFrame* SkWuffsCodec::frame(int i) const {
426 if ((0 <= i) && (static_cast<size_t>(i) < fFrames.size())) {
427 return &fFrames[i];
428 }
429 return nullptr;
430}
431
432SkEncodedImageFormat SkWuffsCodec::onGetEncodedFormat() const {
433 return SkEncodedImageFormat::kGIF;
434}
435
436SkCodec::Result SkWuffsCodec::onGetPixels(const SkImageInfo& dstInfo,
437 void* dst,
438 size_t rowBytes,
439 const Options& options,
440 int* rowsDecoded) {
441 SkCodec::Result result = this->onStartIncrementalDecode(dstInfo, dst, rowBytes, options);
442 if (result != kSuccess) {
443 return result;
444 }
445 return this->onIncrementalDecode(rowsDecoded);
446}
447
448const SkFrameHolder* SkWuffsCodec::getFrameHolder() const {
449 return &fFrameHolder;
450}
451
452SkCodec::Result SkWuffsCodec::onStartIncrementalDecode(const SkImageInfo& dstInfo,
453 void* dst,
454 size_t rowBytes,
455 const SkCodec::Options& options) {
Nigel Tao1f1cd1f2019-06-22 17:35:38 +1000456 if (!dst) {
457 return SkCodec::kInvalidParameters;
458 }
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400459 if (options.fSubset) {
460 return SkCodec::kUnimplemented;
461 }
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400462 if (options.fFrameIndex > 0 && SkColorTypeIsAlwaysOpaque(dstInfo.colorType())) {
463 return SkCodec::kInvalidConversion;
464 }
Nigel Tao2777cd32019-10-29 11:10:25 +1100465 SkCodec::Result result = this->seekFrame(WhichDecoder::kIncrDecode, options.fFrameIndex);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400466 if (result != SkCodec::kSuccess) {
467 return result;
468 }
469
Nigel Tao2777cd32019-10-29 11:10:25 +1100470 const char* status = this->decodeFrameConfig(WhichDecoder::kIncrDecode);
Nigel Taob7a1b512019-02-10 12:19:50 +1100471 if (status == wuffs_base__suspension__short_read) {
Leon Scroggins IIIcb6b8842018-12-04 13:55:13 -0500472 return SkCodec::kIncompleteInput;
Nigel Taob7a1b512019-02-10 12:19:50 +1100473 } else if (status != nullptr) {
Leon Scroggins IIIcb6b8842018-12-04 13:55:13 -0500474 SkCodecPrintf("decodeFrameConfig: %s", status);
475 return SkCodec::kErrorInInput;
476 }
Nigel Taob7a1b512019-02-10 12:19:50 +1100477
Nigel Taob54946b2020-06-18 23:36:27 +1000478 uint32_t pixelFormat = WUFFS_BASE__PIXEL_FORMAT__INVALID;
Nigel Tao5cfa7192020-08-17 21:14:13 +1000479 size_t bytesPerPixel = 0;
Nigel Tao027f89b2019-12-06 10:56:24 +1100480
481 switch (dstInfo.colorType()) {
482 case kBGRA_8888_SkColorType:
483 pixelFormat = WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL;
484 bytesPerPixel = 4;
485 break;
486 case kRGBA_8888_SkColorType:
487 pixelFormat = WUFFS_BASE__PIXEL_FORMAT__RGBA_NONPREMUL;
488 bytesPerPixel = 4;
489 break;
490 default:
491 break;
492 }
493
494 // We can use "one pass" decoding if we have a Skia pixel format that Wuffs
495 // supports...
496 fIncrDecOnePass =
497 (pixelFormat != WUFFS_BASE__PIXEL_FORMAT__INVALID) &&
498 // ...and no color profile (as Wuffs does not support them)...
499 (!getEncodedInfo().profile()) &&
500 // ...and we have an independent frame (as Wuffs does not support the
501 // equivalent of SkBlendMode::kSrcOver)...
502 ((options.fFrameIndex == 0) ||
503 (this->frame(options.fFrameIndex)->getRequiredFrame() == SkCodec::kNoFrame)) &&
504 // ...and we use the identity transform (as Wuffs does not support
505 // scaling).
506 (this->dimensions() == dstInfo.dimensions());
507
508 result = fIncrDecOnePass ? this->onStartIncrementalDecodeOnePass(
509 dstInfo, static_cast<uint8_t*>(dst), rowBytes, options,
510 pixelFormat, bytesPerPixel)
511 : this->onStartIncrementalDecodeTwoPass();
512 if (result != SkCodec::kSuccess) {
513 return result;
514 }
515
516 fIncrDecDst = static_cast<uint8_t*>(dst);
517 fIncrDecReaderIOPosition = fIOBuffer.reader_io_position();
518 fIncrDecRowBytes = rowBytes;
519 fFirstCallToIncrementalDecode = true;
520 return SkCodec::kSuccess;
521}
522
Nigel Taob54946b2020-06-18 23:36:27 +1000523SkCodec::Result SkWuffsCodec::onStartIncrementalDecodeOnePass(const SkImageInfo& dstInfo,
524 uint8_t* dst,
525 size_t rowBytes,
526 const SkCodec::Options& options,
527 uint32_t pixelFormat,
Nigel Tao027f89b2019-12-06 10:56:24 +1100528 size_t bytesPerPixel) {
529 wuffs_base__pixel_config pixelConfig;
530 pixelConfig.set(pixelFormat, WUFFS_BASE__PIXEL_SUBSAMPLING__NONE, dstInfo.width(),
531 dstInfo.height());
532
533 wuffs_base__table_u8 table;
534 table.ptr = dst;
535 table.width = static_cast<size_t>(dstInfo.width()) * bytesPerPixel;
536 table.height = dstInfo.height();
537 table.stride = rowBytes;
538
Nigel Taob54946b2020-06-18 23:36:27 +1000539 wuffs_base__status status = fPixelBuffer.set_from_table(&pixelConfig, table);
Nigel Taob54946b2020-06-18 23:36:27 +1000540 if (status.repr != nullptr) {
541 SkCodecPrintf("set_from_table: %s", status.message());
542 return SkCodec::kInternalError;
543 }
Nigel Taob7a1b512019-02-10 12:19:50 +1100544
Nigel Tao027f89b2019-12-06 10:56:24 +1100545 SkSampler::Fill(dstInfo, dst, rowBytes, options.fZeroInitialized);
546 return SkCodec::kSuccess;
547}
548
549SkCodec::Result SkWuffsCodec::onStartIncrementalDecodeTwoPass() {
550 // Either re-use the previously allocated "two pass" pixel buffer (and
551 // memset to zero), or allocate (and zero initialize) a new one.
552 bool already_zeroed = false;
553
554 if (!fTwoPassPixbufPtr) {
555 uint64_t pixbuf_len = fPixelConfig.pixbuf_len();
556 void* pixbuf_ptr_raw = (pixbuf_len <= SIZE_MAX)
Nigel Tao5cfa7192020-08-17 21:14:13 +1000557 ? sk_malloc_flags(pixbuf_len, SK_MALLOC_ZERO_INITIALIZE)
558 : nullptr;
Nigel Tao027f89b2019-12-06 10:56:24 +1100559 if (!pixbuf_ptr_raw) {
560 return SkCodec::kInternalError;
561 }
562 fTwoPassPixbufPtr.reset(reinterpret_cast<uint8_t*>(pixbuf_ptr_raw));
563 fTwoPassPixbufLen = SkToSizeT(pixbuf_len);
564 already_zeroed = true;
565 }
566
Nigel Taob54946b2020-06-18 23:36:27 +1000567 wuffs_base__status status = fPixelBuffer.set_from_slice(
Nigel Tao027f89b2019-12-06 10:56:24 +1100568 &fPixelConfig, wuffs_base__make_slice_u8(fTwoPassPixbufPtr.get(), fTwoPassPixbufLen));
Nigel Taob54946b2020-06-18 23:36:27 +1000569 if (status.repr != nullptr) {
570 SkCodecPrintf("set_from_slice: %s", status.message());
571 return SkCodec::kInternalError;
572 }
Nigel Tao027f89b2019-12-06 10:56:24 +1100573
574 if (!already_zeroed) {
Nigel Taob54946b2020-06-18 23:36:27 +1000575 uint32_t src_bits_per_pixel = fPixelConfig.pixel_format().bits_per_pixel();
Nigel Tao027f89b2019-12-06 10:56:24 +1100576 if ((src_bits_per_pixel == 0) || (src_bits_per_pixel % 8 != 0)) {
577 return SkCodec::kInternalError;
578 }
579 size_t src_bytes_per_pixel = src_bits_per_pixel / 8;
580
Nigel Tao39da10b2019-11-15 15:27:44 +1100581 wuffs_base__rect_ie_u32 frame_rect = fFrameConfigs[WhichDecoder::kIncrDecode].bounds();
582 wuffs_base__table_u8 pixels = fPixelBuffer.plane(0);
Nigel Tao6ec1b392019-11-20 12:28:50 +1100583
584 uint8_t* ptr = pixels.ptr + (frame_rect.min_incl_y * pixels.stride) +
585 (frame_rect.min_incl_x * src_bytes_per_pixel);
586 size_t len = frame_rect.width() * src_bytes_per_pixel;
587
588 // As an optimization, issue a single sk_bzero call, if possible.
589 // Otherwise, zero out each row separately.
590 if ((len == pixels.stride) && (frame_rect.min_incl_y < frame_rect.max_excl_y)) {
591 sk_bzero(ptr, len * (frame_rect.max_excl_y - frame_rect.min_incl_y));
592 } else {
593 for (uint32_t y = frame_rect.min_incl_y; y < frame_rect.max_excl_y; y++) {
594 sk_bzero(ptr, len);
595 ptr += pixels.stride;
596 }
Nigel Tao39da10b2019-11-15 15:27:44 +1100597 }
Nigel Taob7a1b512019-02-10 12:19:50 +1100598 }
599
Nigel Taob7a1b512019-02-10 12:19:50 +1100600 return SkCodec::kSuccess;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400601}
602
603SkCodec::Result SkWuffsCodec::onIncrementalDecode(int* rowsDecoded) {
604 if (!fIncrDecDst) {
605 return SkCodec::kInternalError;
606 }
607
Nigel Tao2777cd32019-10-29 11:10:25 +1100608 // If multiple SkCodec::incrementalDecode calls are made consecutively (or
609 // if SkCodec::incrementalDecode is called immediately after
610 // SkCodec::startIncrementalDecode), then this seek should be a no-op.
611 // However, it is possible to interleave SkCodec::getFrameCount calls in
612 // between SkCodec::incrementalDecode calls, and those other calls may
613 // advance the stream. This seek restores the stream to where the last
614 // SkCodec::startIncrementalDecode or SkCodec::incrementalDecode stopped.
615 if (!seek_buffer(&fIOBuffer, fStream.get(), fIncrDecReaderIOPosition)) {
616 return SkCodec::kInternalError;
617 }
618
Nigel Tao027f89b2019-12-06 10:56:24 +1100619 if (rowsDecoded) {
620 *rowsDecoded = dstInfo().height();
621 }
622
623 SkCodec::Result result =
624 fIncrDecOnePass ? this->onIncrementalDecodeOnePass() : this->onIncrementalDecodeTwoPass();
Nigel Tao2777cd32019-10-29 11:10:25 +1100625 if (result == SkCodec::kSuccess) {
626 fIncrDecDst = nullptr;
627 fIncrDecReaderIOPosition = 0;
628 fIncrDecRowBytes = 0;
Nigel Tao027f89b2019-12-06 10:56:24 +1100629 fIncrDecOnePass = false;
Nigel Tao2777cd32019-10-29 11:10:25 +1100630 } else {
631 fIncrDecReaderIOPosition = fIOBuffer.reader_io_position();
632 }
633 return result;
634}
635
Nigel Tao027f89b2019-12-06 10:56:24 +1100636SkCodec::Result SkWuffsCodec::onIncrementalDecodeOnePass() {
637 const char* status = this->decodeFrame(WhichDecoder::kIncrDecode);
638 if (status != nullptr) {
639 if (status == wuffs_base__suspension__short_read) {
640 return SkCodec::kIncompleteInput;
641 } else {
642 SkCodecPrintf("decodeFrame: %s", status);
643 return SkCodec::kErrorInInput;
644 }
645 }
646 return SkCodec::kSuccess;
647}
648
649SkCodec::Result SkWuffsCodec::onIncrementalDecodeTwoPass() {
Leon Scroggins III699d41e2019-02-07 09:25:51 -0500650 SkCodec::Result result = SkCodec::kSuccess;
Nigel Tao2777cd32019-10-29 11:10:25 +1100651 const char* status = this->decodeFrame(WhichDecoder::kIncrDecode);
652 bool independent;
653 SkAlphaType alphaType;
654 const int index = options().fFrameIndex;
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400655 if (index == 0) {
656 independent = true;
657 alphaType = to_alpha_type(getEncodedInfo().opaque());
658 } else {
659 const SkWuffsFrame* f = this->frame(index);
660 independent = f->getRequiredFrame() == SkCodec::kNoFrame;
661 alphaType = to_alpha_type(f->reportedAlpha() == SkEncodedInfo::kOpaque_Alpha);
662 }
Leon Scroggins III699d41e2019-02-07 09:25:51 -0500663 if (status != nullptr) {
664 if (status == wuffs_base__suspension__short_read) {
665 result = SkCodec::kIncompleteInput;
666 } else {
667 SkCodecPrintf("decodeFrame: %s", status);
668 result = SkCodec::kErrorInInput;
669 }
670
671 if (!independent) {
672 // For a dependent frame, we cannot blend the partial result, since
673 // that will overwrite the contribution from prior frames.
674 return result;
675 }
676 }
677
Nigel Taob54946b2020-06-18 23:36:27 +1000678 uint32_t src_bits_per_pixel = fPixelBuffer.pixcfg.pixel_format().bits_per_pixel();
Nigel Tao490e6472019-02-14 14:50:53 +1100679 if ((src_bits_per_pixel == 0) || (src_bits_per_pixel % 8 != 0)) {
680 return SkCodec::kInternalError;
681 }
682 size_t src_bytes_per_pixel = src_bits_per_pixel / 8;
683
Nigel Tao2777cd32019-10-29 11:10:25 +1100684 wuffs_base__rect_ie_u32 frame_rect = fFrameConfigs[WhichDecoder::kIncrDecode].bounds();
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400685 if (fFirstCallToIncrementalDecode) {
Nigel Tao490e6472019-02-14 14:50:53 +1100686 if (frame_rect.width() > (SIZE_MAX / src_bytes_per_pixel)) {
687 return SkCodec::kInternalError;
688 }
689
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400690 auto bounds = SkIRect::MakeLTRB(frame_rect.min_incl_x, frame_rect.min_incl_y,
691 frame_rect.max_excl_x, frame_rect.max_excl_y);
692
Leon Scroggins IIIcb6b8842018-12-04 13:55:13 -0500693 // If the frame rect does not fill the output, ensure that those pixels are not
Nigel Taob7a1b512019-02-10 12:19:50 +1100694 // left uninitialized.
Leon Scroggins III44076362019-02-15 13:56:44 -0500695 if (independent && (bounds != this->bounds() || result != kSuccess)) {
Nigel Tao2777cd32019-10-29 11:10:25 +1100696 SkSampler::Fill(dstInfo(), fIncrDecDst, fIncrDecRowBytes, options().fZeroInitialized);
Leon Scroggins III9b0ba2c2018-11-19 14:52:37 -0500697 }
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400698 fFirstCallToIncrementalDecode = false;
699 } else {
700 // Existing clients intend to only show frames beyond the first if they
701 // are complete (based on FrameInfo::fFullyReceived), since it might
702 // look jarring to draw a partial frame over an existing frame. If they
703 // changed their behavior and expected to continue decoding a partial
704 // frame after the first one, we'll need to update our blending code.
705 // Otherwise, if the frame were interlaced and not independent, the
706 // second pass may have an overlapping dirty_rect with the first,
707 // resulting in blending with the first pass.
708 SkASSERT(index == 0);
Nigel Tao9859ef82019-02-13 13:20:02 +1100709 }
Nigel Tao0185b952018-11-08 10:47:24 +1100710
Leon Scroggins IIIdad4bfc2018-12-10 12:37:10 -0500711 // If the frame's dirty rect is empty, no need to swizzle.
Nigel Tao2777cd32019-10-29 11:10:25 +1100712 wuffs_base__rect_ie_u32 dirty_rect = fDecoders[WhichDecoder::kIncrDecode]->frame_dirty_rect();
Leon Scroggins IIIdad4bfc2018-12-10 12:37:10 -0500713 if (!dirty_rect.is_empty()) {
Nigel Tao490e6472019-02-14 14:50:53 +1100714 wuffs_base__table_u8 pixels = fPixelBuffer.plane(0);
Leon Scroggins III7a3805c2018-12-07 09:21:30 -0500715
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400716 // The Wuffs model is that the dst buffer is the image, not the frame.
717 // The expectation is that you allocate the buffer once, but re-use it
718 // for the N frames, regardless of each frame's top-left co-ordinate.
719 //
720 // To get from the start (in the X-direction) of the image to the start
721 // of the dirty_rect, we adjust s by (dirty_rect.min_incl_x * src_bytes_per_pixel).
Nigel Tao2777cd32019-10-29 11:10:25 +1100722 uint8_t* s = pixels.ptr + (dirty_rect.min_incl_y * pixels.stride) +
723 (dirty_rect.min_incl_x * src_bytes_per_pixel);
Leon Scroggins III7a3805c2018-12-07 09:21:30 -0500724
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400725 // Currently, this is only used for GIF, which will never have an ICC profile. When it is
726 // used for other formats that might have one, we will need to transform from profiles that
727 // do not have corresponding SkColorSpaces.
728 SkASSERT(!getEncodedInfo().profile());
729
Nigel Tao2777cd32019-10-29 11:10:25 +1100730 auto srcInfo =
731 getInfo().makeWH(dirty_rect.width(), dirty_rect.height()).makeAlphaType(alphaType);
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400732 SkBitmap src;
733 src.installPixels(srcInfo, s, pixels.stride);
734 SkPaint paint;
735 if (independent) {
736 paint.setBlendMode(SkBlendMode::kSrc);
Leon Scroggins III7a3805c2018-12-07 09:21:30 -0500737 }
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400738
739 SkDraw draw;
740 draw.fDst.reset(dstInfo(), fIncrDecDst, fIncrDecRowBytes);
Nigel Tao5cfa7192020-08-17 21:14:13 +1000741 SkMatrix matrix = SkMatrix::MakeRectToRect(SkRect::Make(this->dimensions()),
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400742 SkRect::Make(this->dstInfo().dimensions()),
743 SkMatrix::kFill_ScaleToFit);
Brian Osman9aaec362020-05-08 14:54:37 -0400744 SkSimpleMatrixProvider matrixProvider(matrix);
745 draw.fMatrixProvider = &matrixProvider;
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400746 SkRasterClip rc(SkIRect::MakeSize(this->dstInfo().dimensions()));
747 draw.fRC = &rc;
748
Mike Reed1f607332020-05-21 12:11:27 -0400749 SkMatrix translate = SkMatrix::Translate(dirty_rect.min_incl_x, dirty_rect.min_incl_y);
Leon Scroggins III70d8f4f2019-04-01 12:57:46 -0400750 draw.drawBitmap(src, translate, nullptr, paint);
Leon Scroggins III7a3805c2018-12-07 09:21:30 -0500751 }
Nigel Taof0148c42019-12-08 19:12:13 +1100752
753 if (result == SkCodec::kSuccess) {
754 // On success, we are done using the "two pass" pixel buffer for this
755 // frame. We have the option of releasing its memory, but there is a
756 // trade-off. If decoding a subsequent frame will also need "two pass"
757 // decoding, it would have to re-allocate the buffer instead of just
758 // re-using it. On the other hand, if there is no subsequent frame, and
759 // the SkWuffsCodec object isn't deleted soon, then we are holding
760 // megabytes of memory longer than we need to.
761 //
762 // For example, when the Chromium web browser decodes the <img> tags in
763 // a HTML page, the SkCodec object can live until navigating away from
764 // the page, which can be much longer than when the pixels are fully
765 // decoded, especially for a still (non-animated) image. Even for
766 // looping animations, caching the decoded frames (at the higher HTML
767 // renderer layer) may mean that each frame is only decoded once (at
768 // the lower SkCodec layer), in sequence.
769 //
770 // The heuristic we use here is to free the memory if we have decoded
771 // the last frame of the animation (or, for still images, the only
772 // frame). The output of the next decode request (if any) should be the
773 // same either way, but the steady state memory use should hopefully be
774 // lower than always keeping the fTwoPassPixbufPtr buffer up until the
775 // SkWuffsCodec destructor runs.
776 //
777 // This only applies to "two pass" decoding. "One pass" decoding does
778 // not allocate, free or otherwise use fTwoPassPixbufPtr.
779 if (fFramesComplete && (static_cast<size_t>(options().fFrameIndex) == fFrames.size() - 1)) {
780 fTwoPassPixbufPtr.reset(nullptr);
781 fTwoPassPixbufLen = 0;
782 }
783 }
784
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400785 return result;
786}
787
788int SkWuffsCodec::onGetFrameCount() {
Nigel Tao3876a9f2019-11-14 09:04:45 +1100789 if (!fFramesComplete && seek_buffer(&fIOBuffer, fStream.get(), fFrameCountReaderIOPosition)) {
Nigel Tao2777cd32019-10-29 11:10:25 +1100790 this->onGetFrameCountInternal();
Nigel Tao3876a9f2019-11-14 09:04:45 +1100791 fFrameCountReaderIOPosition =
792 fDecoders[WhichDecoder::kFrameCount] ? fIOBuffer.reader_io_position() : 0;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400793 }
794 return fFrames.size();
795}
796
Nigel Tao2777cd32019-10-29 11:10:25 +1100797void SkWuffsCodec::onGetFrameCountInternal() {
Nigel Tao2777cd32019-10-29 11:10:25 +1100798 if (!fDecoders[WhichDecoder::kFrameCount]) {
799 void* decoder_raw = sk_malloc_canfail(sizeof__wuffs_gif__decoder());
800 if (!decoder_raw) {
801 return;
802 }
803 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> decoder(
804 reinterpret_cast<wuffs_gif__decoder*>(decoder_raw), &sk_free);
Nigel Tao3876a9f2019-11-14 09:04:45 +1100805 reset_and_decode_image_config(decoder.get(), nullptr, &fIOBuffer, fStream.get());
Nigel Tao2777cd32019-10-29 11:10:25 +1100806 fDecoders[WhichDecoder::kFrameCount] = std::move(decoder);
807 }
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400808
809 // Iterate through the frames, converting from Wuffs'
810 // wuffs_base__frame_config type to Skia's SkWuffsFrame type.
Nigel Tao3876a9f2019-11-14 09:04:45 +1100811 while (true) {
Nigel Tao2777cd32019-10-29 11:10:25 +1100812 const char* status = this->decodeFrameConfig(WhichDecoder::kFrameCount);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400813 if (status == nullptr) {
814 // No-op.
Nigel Taob54946b2020-06-18 23:36:27 +1000815 } else if (status == wuffs_base__note__end_of_data) {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400816 break;
817 } else {
818 return;
819 }
820
Nigel Tao3876a9f2019-11-14 09:04:45 +1100821 uint64_t i = fDecoders[WhichDecoder::kFrameCount]->num_decoded_frame_configs();
822 if (i > INT_MAX) {
823 break;
824 }
825 if ((i == 0) || (static_cast<size_t>(i - 1) != fFrames.size())) {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400826 continue;
827 }
Nigel Tao2777cd32019-10-29 11:10:25 +1100828 fFrames.emplace_back(&fFrameConfigs[WhichDecoder::kFrameCount]);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400829 SkWuffsFrame* f = &fFrames[fFrames.size() - 1];
830 fFrameHolder.setAlphaAndRequiredFrame(f);
831 }
832
833 fFramesComplete = true;
Nigel Tao5b271462019-11-12 21:02:20 +1100834
835 // We've seen the end of the animation. There'll be no more frames, so we
836 // no longer need the kFrameCount decoder. Releasing it earlier than the
837 // SkWuffsCodec destructor might help peak memory use.
838 fDecoders[WhichDecoder::kFrameCount].reset(nullptr);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400839}
840
Nigel Taocdc92382019-10-31 08:36:53 +1100841bool SkWuffsCodec::onGetFrameInfo(int i, SkCodec::FrameInfo* frameInfo) const {
842 const SkWuffsFrame* f = this->frame(i);
843 if (!f) {
844 return false;
845 }
846 if (frameInfo) {
847 *frameInfo = f->frameInfo(static_cast<uint64_t>(i) < this->fNumFullyReceivedFrames);
848 }
849 return true;
850}
851
852int SkWuffsCodec::onGetRepetitionCount() {
853 // Convert from Wuffs's loop count to Skia's repeat count. Wuffs' uint32_t
854 // number is how many times to play the loop. Skia's int number is how many
855 // times to play the loop *after the first play*. Wuffs and Skia use 0 and
856 // kRepetitionCountInfinite respectively to mean loop forever.
857 uint32_t n = fDecoders[WhichDecoder::kIncrDecode]->num_animation_loops();
858 if (n == 0) {
859 return SkCodec::kRepetitionCountInfinite;
860 }
861 n--;
862 return n < INT_MAX ? n : INT_MAX;
863}
864
Nigel Tao2777cd32019-10-29 11:10:25 +1100865SkCodec::Result SkWuffsCodec::seekFrame(WhichDecoder which, int frameIndex) {
866 if (fDecoderIsSuspended[which]) {
867 SkCodec::Result res = this->resetDecoder(which);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400868 if (res != SkCodec::kSuccess) {
869 return res;
870 }
871 }
872
873 uint64_t pos = 0;
874 if (frameIndex < 0) {
875 return SkCodec::kInternalError;
876 } else if (frameIndex == 0) {
877 pos = fFirstFrameIOPosition;
878 } else if (static_cast<size_t>(frameIndex) < fFrames.size()) {
879 pos = fFrames[frameIndex].ioPosition();
880 } else {
881 return SkCodec::kInternalError;
882 }
883
884 if (!seek_buffer(&fIOBuffer, fStream.get(), pos)) {
885 return SkCodec::kInternalError;
886 }
Nigel Taob54946b2020-06-18 23:36:27 +1000887 wuffs_base__status status =
Nigel Tao2777cd32019-10-29 11:10:25 +1100888 fDecoders[which]->restart_frame(frameIndex, fIOBuffer.reader_io_position());
Nigel Taob54946b2020-06-18 23:36:27 +1000889 if (status.repr != nullptr) {
890 return SkCodec::kInternalError;
891 }
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400892 return SkCodec::kSuccess;
893}
894
Nigel Tao2777cd32019-10-29 11:10:25 +1100895SkCodec::Result SkWuffsCodec::resetDecoder(WhichDecoder which) {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400896 if (!fStream->rewind()) {
897 return SkCodec::kInternalError;
898 }
Nigel Tao96c10a02019-09-25 11:08:42 +1000899 fIOBuffer.meta = wuffs_base__empty_io_buffer_meta();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400900
901 SkCodec::Result result =
Nigel Tao2777cd32019-10-29 11:10:25 +1100902 reset_and_decode_image_config(fDecoders[which].get(), nullptr, &fIOBuffer, fStream.get());
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400903 if (result == SkCodec::kIncompleteInput) {
904 return SkCodec::kInternalError;
905 } else if (result != SkCodec::kSuccess) {
906 return result;
907 }
908
Nigel Tao2777cd32019-10-29 11:10:25 +1100909 fDecoderIsSuspended[which] = false;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400910 return SkCodec::kSuccess;
911}
912
Nigel Tao2777cd32019-10-29 11:10:25 +1100913const char* SkWuffsCodec::decodeFrameConfig(WhichDecoder which) {
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400914 while (true) {
Nigel Taob54946b2020-06-18 23:36:27 +1000915 wuffs_base__status status =
Nigel Tao2777cd32019-10-29 11:10:25 +1100916 fDecoders[which]->decode_frame_config(&fFrameConfigs[which], &fIOBuffer);
Nigel Taob54946b2020-06-18 23:36:27 +1000917 if ((status.repr == wuffs_base__suspension__short_read) &&
918 fill_buffer(&fIOBuffer, fStream.get())) {
919 continue;
920 }
921 fDecoderIsSuspended[which] = !status.is_complete();
922 this->updateNumFullyReceivedFrames(which);
923 return status.repr;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400924 }
925}
926
Nigel Tao2777cd32019-10-29 11:10:25 +1100927const char* SkWuffsCodec::decodeFrame(WhichDecoder which) {
928 while (true) {
Nigel Taob54946b2020-06-18 23:36:27 +1000929 wuffs_base__status status = fDecoders[which]->decode_frame(
930 &fPixelBuffer, &fIOBuffer, WUFFS_BASE__PIXEL_BLEND__SRC,
931 wuffs_base__make_slice_u8(fWorkbufPtr.get(), fWorkbufLen), NULL);
932 if ((status.repr == wuffs_base__suspension__short_read) &&
933 fill_buffer(&fIOBuffer, fStream.get())) {
934 continue;
935 }
936 fDecoderIsSuspended[which] = !status.is_complete();
937 this->updateNumFullyReceivedFrames(which);
938 return status.repr;
Nigel Tao2777cd32019-10-29 11:10:25 +1100939 }
940}
941
942void SkWuffsCodec::updateNumFullyReceivedFrames(WhichDecoder which) {
Nigel Tao6af1edc2019-01-19 15:12:39 +1100943 // num_decoded_frames's return value, n, can change over time, both up and
944 // down, as we seek back and forth in the underlying stream.
945 // fNumFullyReceivedFrames is the highest n we've seen.
Nigel Tao2777cd32019-10-29 11:10:25 +1100946 uint64_t n = fDecoders[which]->num_decoded_frames();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400947 if (fNumFullyReceivedFrames < n) {
948 fNumFullyReceivedFrames = n;
949 }
950}
951
952// -------------------------------- SkWuffsCodec.h functions
953
954bool SkWuffsCodec_IsFormat(const void* buf, size_t bytesRead) {
955 constexpr const char* gif_ptr = "GIF8";
956 constexpr size_t gif_len = 4;
957 return (bytesRead >= gif_len) && (memcmp(buf, gif_ptr, gif_len) == 0);
958}
959
960std::unique_ptr<SkCodec> SkWuffsCodec_MakeFromStream(std::unique_ptr<SkStream> stream,
961 SkCodec::Result* result) {
Nigel Tao48aa2212019-03-09 14:59:11 +1100962 uint8_t buffer[SK_WUFFS_CODEC_BUFFER_SIZE];
963 wuffs_base__io_buffer iobuf =
964 wuffs_base__make_io_buffer(wuffs_base__make_slice_u8(buffer, SK_WUFFS_CODEC_BUFFER_SIZE),
Nigel Tao96c10a02019-09-25 11:08:42 +1000965 wuffs_base__empty_io_buffer_meta());
Nigel Tao48aa2212019-03-09 14:59:11 +1100966 wuffs_base__image_config imgcfg = wuffs_base__null_image_config();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400967
968 // Wuffs is primarily a C library, not a C++ one. Furthermore, outside of
969 // the wuffs_base__etc types, the sizeof a file format specific type like
970 // GIF's wuffs_gif__decoder can vary between Wuffs versions. If p is of
971 // type wuffs_gif__decoder*, then the supported API treats p as a pointer
972 // to an opaque type: a private implementation detail. The API is always
973 // "set_foo(p, etc)" and not "p->foo = etc".
974 //
975 // See https://en.wikipedia.org/wiki/Opaque_pointer#C
976 //
977 // Thus, we don't use C++'s new operator (which requires knowing the sizeof
978 // the struct at compile time). Instead, we use sk_malloc_canfail, with
979 // sizeof__wuffs_gif__decoder returning the appropriate value for the
980 // (statically or dynamically) linked version of the Wuffs library.
981 //
982 // As a C (not C++) library, none of the Wuffs types have constructors or
983 // destructors.
984 //
985 // In RAII style, we can still use std::unique_ptr with these pointers, but
986 // we pair the pointer with sk_free instead of C++'s delete.
987 void* decoder_raw = sk_malloc_canfail(sizeof__wuffs_gif__decoder());
988 if (!decoder_raw) {
989 *result = SkCodec::kInternalError;
990 return nullptr;
991 }
992 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> decoder(
993 reinterpret_cast<wuffs_gif__decoder*>(decoder_raw), &sk_free);
994
995 SkCodec::Result reset_result =
996 reset_and_decode_image_config(decoder.get(), &imgcfg, &iobuf, stream.get());
997 if (reset_result != SkCodec::kSuccess) {
998 *result = reset_result;
999 return nullptr;
1000 }
1001
1002 uint32_t width = imgcfg.pixcfg.width();
1003 uint32_t height = imgcfg.pixcfg.height();
1004 if ((width == 0) || (width > INT_MAX) || (height == 0) || (height > INT_MAX)) {
1005 *result = SkCodec::kInvalidInput;
1006 return nullptr;
1007 }
1008
Nigel Tao6af1edc2019-01-19 15:12:39 +11001009 uint64_t workbuf_len = decoder->workbuf_len().max_incl;
Nigel Tao22e86242019-01-26 16:04:01 +11001010 void* workbuf_ptr_raw = nullptr;
1011 if (workbuf_len) {
1012 workbuf_ptr_raw = workbuf_len <= SIZE_MAX ? sk_malloc_canfail(workbuf_len) : nullptr;
1013 if (!workbuf_ptr_raw) {
1014 *result = SkCodec::kInternalError;
1015 return nullptr;
1016 }
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001017 }
1018 std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr(
1019 reinterpret_cast<uint8_t*>(workbuf_ptr_raw), &sk_free);
1020
Nigel Tao490e6472019-02-14 14:50:53 +11001021 SkEncodedInfo::Color color =
Nigel Taob54946b2020-06-18 23:36:27 +10001022 (imgcfg.pixcfg.pixel_format().repr == WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL)
Nigel Tao490e6472019-02-14 14:50:53 +11001023 ? SkEncodedInfo::kBGRA_Color
1024 : SkEncodedInfo::kRGBA_Color;
1025
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001026 // In Skia's API, the alpha we calculate here and return is only for the
1027 // first frame.
1028 SkEncodedInfo::Alpha alpha = imgcfg.first_frame_is_opaque() ? SkEncodedInfo::kOpaque_Alpha
1029 : SkEncodedInfo::kBinary_Alpha;
1030
Nigel Tao490e6472019-02-14 14:50:53 +11001031 SkEncodedInfo encodedInfo = SkEncodedInfo::Make(width, height, color, alpha, 8);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001032
1033 *result = SkCodec::kSuccess;
Nigel Tao027f89b2019-12-06 10:56:24 +11001034 return std::unique_ptr<SkCodec>(new SkWuffsCodec(std::move(encodedInfo), std::move(stream),
1035 std::move(decoder), std::move(workbuf_ptr),
1036 workbuf_len, imgcfg, iobuf));
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001037}