Debian Codegraph @

src/codec/SkWuffsCodec.cpp

raw
1 /*
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
8 #include "include/codec/SkCodec.h"
9 #include "include/codec/SkCodecAnimation.h"
10 #include "include/codec/SkEncodedImageFormat.h"
11 #include "include/codec/SkGifDecoder.h"
12 #include "include/core/SkAlphaType.h"
13 #include "include/core/SkBitmap.h"
14 #include "include/core/SkBlendMode.h"
15 #include "include/core/SkColorType.h"
16 #include "include/core/SkData.h"
17 #include "include/core/SkImageInfo.h"
18 #include "include/core/SkMatrix.h"
19 #include "include/core/SkPaint.h"
20 #include "include/core/SkPixmap.h"
21 #include "include/core/SkRect.h"
22 #include "include/core/SkRefCnt.h"
23 #include "include/core/SkSamplingOptions.h"
24 #include "include/core/SkSize.h"
25 #include "include/core/SkStream.h"
26 #include "include/core/SkTypes.h"
27 #include "include/private/SkEncodedInfo.h"
28 #include "include/private/base/SkMalloc.h"
29 #include "include/private/base/SkTo.h"
30 #include "modules/skcms/skcms.h"
31 #include "src/codec/SkCodecPriv.h"
32 #include "src/codec/SkFrameHolder.h"
33 #include "src/codec/SkSampler.h"
34 #include "src/codec/SkScalingCodec.h"
35 #include "src/core/SkDraw.h"
36 #include "src/core/SkMipmap.h"
37 #include "src/core/SkRasterClip.h"
38 #include "src/core/SkStreamPriv.h"
39
40 #include <climits>
41 #include <cstdint>
42 #include <cstring>
43 #include <memory>
44 #include <utility>
45 #include <vector>
46
47 // Documentation on the Wuffs language and standard library (in general) and
48 // its image decoding API (in particular) is at:
49 //
50 // - https://github.com/google/wuffs/tree/master/doc
51 // - https://github.com/google/wuffs/blob/master/doc/std/image-decoders.md
52
53 // Wuffs ships as a "single file C library" or "header file library" as per
54 // https://github.com/nothings/stb/blob/master/docs/stb_howto.txt
55 //
56 // As we have not #define'd WUFFS_IMPLEMENTATION, the #include here is
57 // including a header file, even though that file name ends in ".c".
58 #if defined(WUFFS_IMPLEMENTATION)
59 #error "SkWuffsCodec should not #define WUFFS_IMPLEMENTATION"
60 #endif
61 #include "wuffs-v0.3.c" // NO_G3_REWRITE
62 // Commit count 2514 is Wuffs 0.3.0-alpha.4.
63 #if WUFFS_VERSION_BUILD_METADATA_COMMIT_COUNT < 2514
64 #error "Wuffs version is too old. Upgrade to the latest version."
65 #endif
66
67 #define SK_WUFFS_CODEC_BUFFER_SIZE 4096
68
69 // Configuring a Skia build with
70 // SK_WUFFS_FAVORS_PERFORMANCE_OVER_ADDITIONAL_MEMORY_SAFETY can improve decode
71 // performance by some fixed amount (independent of the image size), which can
72 // be a noticeable proportional improvement if the input is relatively small.
73 //
74 // The Wuffs library is still memory-safe either way, in that there are no
75 // out-of-bounds reads or writes, and the library endeavours not to read
76 // uninitialized memory. There are just fewer compiler-enforced guarantees
77 // against reading uninitialized memory. For more detail, see
78 // https://github.com/google/wuffs/blob/master/doc/note/initialization.md#partial-zero-initialization
79 #if defined(SK_WUFFS_FAVORS_PERFORMANCE_OVER_ADDITIONAL_MEMORY_SAFETY)
80 #define SK_WUFFS_INITIALIZE_FLAGS WUFFS_INITIALIZE__LEAVE_INTERNAL_BUFFERS_UNINITIALIZED
81 #else
82 #define SK_WUFFS_INITIALIZE_FLAGS WUFFS_INITIALIZE__DEFAULT_OPTIONS
83 #endif
84
85 static bool fill_buffer(wuffs_base__io_buffer* b, SkStream* s) {
86 b->compact();
87 size_t num_read = s->read(b->data.ptr + b->meta.wi, b->data.len - b->meta.wi);
88 b->meta.wi += num_read;
89 // We hard-code false instead of s->isAtEnd(). In theory, Skia's
90 // SkStream::isAtEnd() method has the same semantics as Wuffs'
91 // wuffs_base__io_buffer_meta::closed field. Specifically, both are false
92 // when reading from a network socket when all bytes *available right now*
93 // have been read but there might be more later.
94 //
95 // However, SkStream is designed around synchronous I/O. The SkStream::read
96 // method does not take a callback and, per its documentation comments, a
97 // read request for N bytes should block until a full N bytes are
98 // available. In practice, Blink's SkStream subclass builds on top of async
99 // I/O and cannot afford to block. While it satisfies "the letter of the
100 // law", in terms of what the C++ compiler needs, it does not satisfy "the
101 // spirit of the law". Its read() can return short without blocking and its
102 // isAtEnd() can return false positives.
103 //
104 // When closed is true, Wuffs treats incomplete input as a fatal error
105 // instead of a recoverable "short read" suspension. We therefore hard-code
106 // false and return kIncompleteInput (instead of kErrorInInput) up the call
107 // stack even if the SkStream isAtEnd. The caller usually has more context
108 // (more than what's in the SkStream) to differentiate the two, like this:
109 // https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/platform/image-decoders/gif/gif_image_decoder.cc;l=115;drc=277dcc4d810ae4c0286d8af96d270ed9b686c5ff
110 b->meta.closed = false;
111 return num_read > 0;
112 }
113
114 static bool seek_buffer(wuffs_base__io_buffer* b, SkStream* s, uint64_t pos) {
115 // Try to re-position the io_buffer's meta.ri read-index first, which is
116 // cheaper than seeking in the backing SkStream.
117 if ((pos >= b->meta.pos) && (pos - b->meta.pos <= b->meta.wi)) {
118 b->meta.ri = pos - b->meta.pos;
119 return true;
120 }
121 // Seek in the backing SkStream.
122 if ((pos > SIZE_MAX) || (!s->seek(pos))) {
123 return false;
124 }
125 b->meta.wi = 0;
126 b->meta.ri = 0;
127 b->meta.pos = pos;
128 b->meta.closed = false;
129 return true;
130 }
131
132 static SkCodecAnimation::DisposalMethod wuffs_disposal_to_skia_disposal(
133 wuffs_base__animation_disposal w) {
134 switch (w) {
135 case WUFFS_BASE__ANIMATION_DISPOSAL__RESTORE_BACKGROUND:
136 return SkCodecAnimation::DisposalMethod::kRestoreBGColor;
137 case WUFFS_BASE__ANIMATION_DISPOSAL__RESTORE_PREVIOUS:
138 return SkCodecAnimation::DisposalMethod::kRestorePrevious;
139 default:
140 return SkCodecAnimation::DisposalMethod::kKeep;
141 }
142 }
143
144 static SkAlphaType to_alpha_type(bool opaque) {
145 return opaque ? kOpaque_SkAlphaType : kPremul_SkAlphaType;
146 }
147
148 static SkCodec::Result reset_and_decode_image_config(wuffs_gif__decoder* decoder,
149 wuffs_base__image_config* imgcfg,
150 wuffs_base__io_buffer* b,
151 SkStream* s) {
152 // Calling decoder->initialize will memset most or all of it to zero,
153 // depending on SK_WUFFS_INITIALIZE_FLAGS.
154 wuffs_base__status status =
155 decoder->initialize(sizeof__wuffs_gif__decoder(), WUFFS_VERSION, SK_WUFFS_INITIALIZE_FLAGS);
156 if (status.repr != nullptr) {
157 SkCodecPrintf("initialize: %s", status.message());
158 return SkCodec::kInternalError;
159 }
160
161 // See https://bugs.chromium.org/p/skia/issues/detail?id=12055
162 decoder->set_quirk_enabled(WUFFS_GIF__QUIRK_IGNORE_TOO_MUCH_PIXEL_DATA, true);
163
164 while (true) {
165 status = decoder->decode_image_config(imgcfg, b);
166 if (status.repr == nullptr) {
167 break;
168 } else if (status.repr != wuffs_base__suspension__short_read) {
169 SkCodecPrintf("decode_image_config: %s", status.message());
170 return SkCodec::kErrorInInput;
171 } else if (!fill_buffer(b, s)) {
172 return SkCodec::kIncompleteInput;
173 }
174 }
175
176 // A GIF image's natural color model is indexed color: 1 byte per pixel,
177 // indexing a 256-element palette.
178 //
179 // For Skia, we override that to decode to 4 bytes per pixel, BGRA or RGBA.
180 uint32_t pixfmt = WUFFS_BASE__PIXEL_FORMAT__INVALID;
181 switch (kN32_SkColorType) {
182 case kBGRA_8888_SkColorType:
183 pixfmt = WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL;
184 break;
185 case kRGBA_8888_SkColorType:
186 pixfmt = WUFFS_BASE__PIXEL_FORMAT__RGBA_NONPREMUL;
187 break;
188 default:
189 return SkCodec::kInternalError;
190 }
191 if (imgcfg) {
192 imgcfg->pixcfg.set(pixfmt, WUFFS_BASE__PIXEL_SUBSAMPLING__NONE, imgcfg->pixcfg.width(),
193 imgcfg->pixcfg.height());
194 }
195
196 return SkCodec::kSuccess;
197 }
198
199 // -------------------------------- Class definitions
200
201 class SkWuffsCodec;
202
203 class SkWuffsFrame final : public SkFrame {
204 public:
205 SkWuffsFrame(wuffs_base__frame_config* fc);
206
207 uint64_t ioPosition() const;
208
209 // SkFrame overrides.
210 SkEncodedInfo::Alpha onReportedAlpha() const override;
211
212 private:
213 uint64_t fIOPosition;
214 SkEncodedInfo::Alpha fReportedAlpha;
215
216 using INHERITED = SkFrame;
217 };
218
219 // SkWuffsFrameHolder is a trivial indirector that forwards its calls onto a
220 // SkWuffsCodec. It is a separate class as SkWuffsCodec would otherwise
221 // inherit from both SkCodec and SkFrameHolder, and Skia style discourages
222 // multiple inheritance (e.g. with its "typedef Foo INHERITED" convention).
223 class SkWuffsFrameHolder final : public SkFrameHolder {
224 public:
225 SkWuffsFrameHolder() : INHERITED() {}
226
227 void init(SkWuffsCodec* codec, int width, int height);
228
229 // SkFrameHolder overrides.
230 const SkFrame* onGetFrame(int i) const override;
231
232 private:
233 const SkWuffsCodec* fCodec;
234
235 using INHERITED = SkFrameHolder;
236 };
237
238 class SkWuffsCodec final : public SkScalingCodec {
239 public:
240 SkWuffsCodec(SkEncodedInfo&& encodedInfo,
241 std::unique_ptr<SkStream> stream,
242 bool canSeek,
243 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> dec,
244 std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr,
245 size_t workbuf_len,
246 wuffs_base__image_config imgcfg,
247 wuffs_base__io_buffer iobuf);
248
249 const SkWuffsFrame* frame(int i) const;
250
251 std::unique_ptr<SkStream> getEncodedData() const override;
252
253 private:
254 // SkCodec overrides.
255 SkEncodedImageFormat onGetEncodedFormat() const override;
256 Result onGetPixels(const SkImageInfo&, void*, size_t, const Options&, int*) override;
257 const SkFrameHolder* getFrameHolder() const override;
258 bool onSupportsIncrementalDecode(const SkImageInfo&) override { return true; }
259 Result onStartIncrementalDecode(const SkImageInfo& dstInfo,
260 void* dst,
261 size_t rowBytes,
262 const SkCodec::Options& options) override;
263 Result onIncrementalDecode(int* rowsDecoded) override;
264 int onGetFrameCount() override;
265 bool onGetFrameInfo(int, FrameInfo*) const override;
266 int onGetRepetitionCount() override;
267 IsAnimated onIsAnimated() override;
268
269 // Two separate implementations of onStartIncrementalDecode and
270 // onIncrementalDecode, named "one pass" and "two pass" decoding. One pass
271 // decoding writes directly from the Wuffs image decoder to the dst buffer
272 // (the dst argument to onStartIncrementalDecode). Two pass decoding first
273 // writes into an intermediate buffer, and then composites and transforms
274 // the intermediate buffer into the dst buffer.
275 //
276 // In the general case, we need the two pass decoder, because of Skia API
277 // features that Wuffs doesn't support (e.g. color correction, scaling,
278 // RGB565). But as an optimization, we use one pass decoding (it's faster
279 // and uses less memory) if applicable (see the assignment to
280 // fIncrDecOnePass that calculates when we can do so).
281 Result onStartIncrementalDecodeOnePass(const SkImageInfo& dstInfo,
282 uint8_t* dst,
283 size_t rowBytes,
284 const SkCodec::Options& options,
285 uint32_t pixelFormat,
286 size_t bytesPerPixel);
287 Result onStartIncrementalDecodeTwoPass();
288 Result onIncrementalDecodeOnePass();
289 Result onIncrementalDecodeTwoPass();
290
291 void onGetFrameCountInternal();
292 Result seekFrame(int frameIndex);
293 Result resetDecoder();
294 const char* decodeFrameConfig();
295 const char* decodeFrame();
296 void updateNumFullyReceivedFrames();
297
298 SkWuffsFrameHolder fFrameHolder;
299 std::unique_ptr<SkStream> fPrivStream;
300 std::unique_ptr<uint8_t, decltype(&sk_free)> fWorkbufPtr;
301 size_t fWorkbufLen;
302
303 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> fDecoder;
304
305 const uint64_t fFirstFrameIOPosition;
306 wuffs_base__frame_config fFrameConfig;
307 wuffs_base__pixel_config fPixelConfig;
308 wuffs_base__pixel_buffer fPixelBuffer;
309 wuffs_base__io_buffer fIOBuffer;
310
311 // Incremental decoding state.
312 uint8_t* fIncrDecDst;
313 size_t fIncrDecRowBytes;
314 wuffs_base__pixel_blend fIncrDecPixelBlend;
315 bool fIncrDecOnePass;
316 bool fFirstCallToIncrementalDecode;
317
318 // Lazily allocated intermediate pixel buffer, for two pass decoding.
319 std::unique_ptr<uint8_t, decltype(&sk_free)> fTwoPassPixbufPtr;
320 size_t fTwoPassPixbufLen;
321
322 uint64_t fNumFullyReceivedFrames;
323 std::vector<SkWuffsFrame> fFrames;
324 bool fFramesComplete;
325
326 // If calling an fDecoder method returns an incomplete status, then
327 // fDecoder is suspended in a coroutine (i.e. waiting on I/O or halted on a
328 // non-recoverable error). To keep its internal proof-of-safety invariants
329 // consistent, there's only two things you can safely do with a suspended
330 // Wuffs object: resume the coroutine, or reset all state (memset to zero
331 // and start again).
332 //
333 // If fDecoderIsSuspended, and we aren't sure that we're going to resume
334 // the coroutine, then we will need to call this->resetDecoder before
335 // calling other fDecoder methods.
336 bool fDecoderIsSuspended;
337
338 uint8_t fBuffer[SK_WUFFS_CODEC_BUFFER_SIZE];
339
340 const bool fCanSeek;
341
342 using INHERITED = SkScalingCodec;
343 };
344
345 // -------------------------------- SkWuffsFrame implementation
346
347 SkWuffsFrame::SkWuffsFrame(wuffs_base__frame_config* fc)
348 : INHERITED(fc->index()),
349 fIOPosition(fc->io_position()),
350 fReportedAlpha(fc->opaque_within_bounds() ? SkEncodedInfo::kOpaque_Alpha
351 : SkEncodedInfo::kUnpremul_Alpha) {
352 wuffs_base__rect_ie_u32 r = fc->bounds();
353 this->setXYWH(r.min_incl_x, r.min_incl_y, r.width(), r.height());
354 this->setDisposalMethod(wuffs_disposal_to_skia_disposal(fc->disposal()));
355 this->setDuration(fc->duration() / WUFFS_BASE__FLICKS_PER_MILLISECOND);
356 this->setBlend(fc->overwrite_instead_of_blend() ? SkCodecAnimation::Blend::kSrc
357 : SkCodecAnimation::Blend::kSrcOver);
358 }
359
360 uint64_t SkWuffsFrame::ioPosition() const {
361 return fIOPosition;
362 }
363
364 SkEncodedInfo::Alpha SkWuffsFrame::onReportedAlpha() const {
365 return fReportedAlpha;
366 }
367
368 // -------------------------------- SkWuffsFrameHolder implementation
369
370 void SkWuffsFrameHolder::init(SkWuffsCodec* codec, int width, int height) {
371 fCodec = codec;
372 // Initialize SkFrameHolder's (the superclass) fields.
373 fScreenWidth = width;
374 fScreenHeight = height;
375 }
376
377 const SkFrame* SkWuffsFrameHolder::onGetFrame(int i) const {
378 return fCodec->frame(i);
379 }
380
381 // -------------------------------- SkWuffsCodec implementation
382
383 SkWuffsCodec::SkWuffsCodec(SkEncodedInfo&& encodedInfo,
384 std::unique_ptr<SkStream> stream,
385 bool canSeek,
386 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> dec,
387 std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr,
388 size_t workbuf_len,
389 wuffs_base__image_config imgcfg,
390 wuffs_base__io_buffer iobuf)
391 : INHERITED(std::move(encodedInfo),
392 skcms_PixelFormat_RGBA_8888,
393 // Pass a nullptr SkStream to the SkCodec constructor. We
394 // manage the stream ourselves, as the default SkCodec behavior
395 // is too trigger-happy on rewinding the stream.
396 //
397 // TODO(https://crbug.com/370522089): See if `SkCodec` can be
398 // tweaked to avoid the need to hide the stream from it.
399 nullptr)
400 , fFrameHolder()
401 , fPrivStream(std::move(stream))
402 , fWorkbufPtr(std::move(workbuf_ptr))
403 , fWorkbufLen(workbuf_len)
404 , fDecoder(std::move(dec))
405 , fFirstFrameIOPosition(imgcfg.first_frame_io_position())
406 , fFrameConfig(wuffs_base__null_frame_config())
407 , fPixelConfig(imgcfg.pixcfg)
408 , fPixelBuffer(wuffs_base__null_pixel_buffer())
409 , fIOBuffer(wuffs_base__empty_io_buffer())
410 , fIncrDecDst(nullptr)
411 , fIncrDecRowBytes(0)
412 , fIncrDecPixelBlend(WUFFS_BASE__PIXEL_BLEND__SRC)
413 , fIncrDecOnePass(false)
414 , fFirstCallToIncrementalDecode(false)
415 , fTwoPassPixbufPtr(nullptr, &sk_free)
416 , fTwoPassPixbufLen(0)
417 , fNumFullyReceivedFrames(0)
418 , fFramesComplete(false)
419 , fDecoderIsSuspended(false)
420 , fCanSeek(canSeek) {
421 fFrameHolder.init(this, imgcfg.pixcfg.width(), imgcfg.pixcfg.height());
422
423 // Initialize fIOBuffer's fields, copying any outstanding data from iobuf to
424 // fIOBuffer, as iobuf's backing array may not be valid for the lifetime of
425 // this SkWuffsCodec object, but fIOBuffer's backing array (fBuffer) is.
426 SkASSERT(iobuf.data.len == SK_WUFFS_CODEC_BUFFER_SIZE);
427 memmove(fBuffer, iobuf.data.ptr, iobuf.meta.wi);
428 fIOBuffer.data = wuffs_base__make_slice_u8(fBuffer, SK_WUFFS_CODEC_BUFFER_SIZE);
429 fIOBuffer.meta = iobuf.meta;
430 }
431
432 const SkWuffsFrame* SkWuffsCodec::frame(int i) const {
433 if ((0 <= i) && (static_cast<size_t>(i) < fFrames.size())) {
434 return &fFrames[i];
435 }
436 return nullptr;
437 }
438
439 SkEncodedImageFormat SkWuffsCodec::onGetEncodedFormat() const {
440 return SkEncodedImageFormat::kGIF;
441 }
442
443 SkCodec::Result SkWuffsCodec::onGetPixels(const SkImageInfo& dstInfo,
444 void* dst,
445 size_t rowBytes,
446 const Options& options,
447 int* rowsDecoded) {
448 SkCodec::Result result = this->onStartIncrementalDecode(dstInfo, dst, rowBytes, options);
449 if (result != kSuccess) {
450 return result;
451 }
452 return this->onIncrementalDecode(rowsDecoded);
453 }
454
455 const SkFrameHolder* SkWuffsCodec::getFrameHolder() const {
456 return &fFrameHolder;
457 }
458
459 SkCodec::Result SkWuffsCodec::onStartIncrementalDecode(const SkImageInfo& dstInfo,
460 void* dst,
461 size_t rowBytes,
462 const SkCodec::Options& options) {
463 if (!dst) {
464 return SkCodec::kInvalidParameters;
465 }
466 if (options.fSubset) {
467 return SkCodec::kUnimplemented;
468 }
469 SkCodec::Result result = this->seekFrame(options.fFrameIndex);
470 if (result != SkCodec::kSuccess) {
471 return result;
472 }
473
474 const char* status = this->decodeFrameConfig();
475 if (status == wuffs_base__suspension__short_read) {
476 return SkCodec::kIncompleteInput;
477 } else if (status != nullptr) {
478 SkCodecPrintf("decodeFrameConfig: %s", status);
479 return SkCodec::kErrorInInput;
480 }
481
482 uint32_t pixelFormat = WUFFS_BASE__PIXEL_FORMAT__INVALID;
483 size_t bytesPerPixel = 0;
484
485 switch (dstInfo.colorType()) {
486 case kRGB_565_SkColorType:
487 pixelFormat = WUFFS_BASE__PIXEL_FORMAT__BGR_565;
488 bytesPerPixel = 2;
489 break;
490 case kBGRA_8888_SkColorType:
491 pixelFormat = WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL;
492 bytesPerPixel = 4;
493 break;
494 case kRGBA_8888_SkColorType:
495 pixelFormat = WUFFS_BASE__PIXEL_FORMAT__RGBA_NONPREMUL;
496 bytesPerPixel = 4;
497 break;
498 default:
499 break;
500 }
501
502 // We can use "one pass" decoding if we have a Skia pixel format that Wuffs
503 // supports...
504 fIncrDecOnePass = (pixelFormat != WUFFS_BASE__PIXEL_FORMAT__INVALID) &&
505 // ...and no color profile (as Wuffs does not support them)...
506 (!getEncodedInfo().colorProfile()) &&
507 // ...and we use the identity transform (as Wuffs does
508 // not support scaling).
509 (this->dimensions() == dstInfo.dimensions());
510
511 result = fIncrDecOnePass ? this->onStartIncrementalDecodeOnePass(
512 dstInfo, static_cast<uint8_t*>(dst), rowBytes, options,
513 pixelFormat, bytesPerPixel)
514 : this->onStartIncrementalDecodeTwoPass();
515 if (result != SkCodec::kSuccess) {
516 return result;
517 }
518
519 fIncrDecDst = static_cast<uint8_t*>(dst);
520 fIncrDecRowBytes = rowBytes;
521 fFirstCallToIncrementalDecode = true;
522 return SkCodec::kSuccess;
523 }
524
525 SkCodec::Result SkWuffsCodec::onStartIncrementalDecodeOnePass(const SkImageInfo& dstInfo,
526 uint8_t* dst,
527 size_t rowBytes,
528 const SkCodec::Options& options,
529 uint32_t pixelFormat,
530 size_t bytesPerPixel) {
531 wuffs_base__pixel_config pixelConfig;
532 pixelConfig.set(pixelFormat, WUFFS_BASE__PIXEL_SUBSAMPLING__NONE, dstInfo.width(),
533 dstInfo.height());
534
535 wuffs_base__table_u8 table;
536 table.ptr = dst;
537 table.width = static_cast<size_t>(dstInfo.width()) * bytesPerPixel;
538 table.height = dstInfo.height();
539 table.stride = rowBytes;
540
541 wuffs_base__status status = fPixelBuffer.set_from_table(&pixelConfig, table);
542 if (status.repr != nullptr) {
543 SkCodecPrintf("set_from_table: %s", status.message());
544 return SkCodec::kInternalError;
545 }
546
547 // SRC is usually faster than SRC_OVER, but for a dependent frame, dst is
548 // assumed to hold the previous frame's pixels (after processing the
549 // DisposalMethod). For one-pass decoding, we therefore use SRC_OVER.
550 if ((options.fFrameIndex != 0) &&
551 (this->frame(options.fFrameIndex)->getRequiredFrame() != SkCodec::kNoFrame)) {
552 fIncrDecPixelBlend = WUFFS_BASE__PIXEL_BLEND__SRC_OVER;
553 } else {
554 SkSampler::Fill(dstInfo, dst, rowBytes, options.fZeroInitialized);
555 fIncrDecPixelBlend = WUFFS_BASE__PIXEL_BLEND__SRC;
556 }
557
558 return SkCodec::kSuccess;
559 }
560
561 SkCodec::Result SkWuffsCodec::onStartIncrementalDecodeTwoPass() {
562 // Either re-use the previously allocated "two pass" pixel buffer (and
563 // memset to zero), or allocate (and zero initialize) a new one.
564 bool already_zeroed = false;
565
566 if (!fTwoPassPixbufPtr) {
567 uint64_t pixbuf_len = fPixelConfig.pixbuf_len();
568 void* pixbuf_ptr_raw = (pixbuf_len <= SIZE_MAX)
569 ? sk_malloc_flags(pixbuf_len, SK_MALLOC_ZERO_INITIALIZE)
570 : nullptr;
571 if (!pixbuf_ptr_raw) {
572 return SkCodec::kInternalError;
573 }
574 fTwoPassPixbufPtr.reset(reinterpret_cast<uint8_t*>(pixbuf_ptr_raw));
575 fTwoPassPixbufLen = SkToSizeT(pixbuf_len);
576 already_zeroed = true;
577 }
578
579 wuffs_base__status status = fPixelBuffer.set_from_slice(
580 &fPixelConfig, wuffs_base__make_slice_u8(fTwoPassPixbufPtr.get(), fTwoPassPixbufLen));
581 if (status.repr != nullptr) {
582 SkCodecPrintf("set_from_slice: %s", status.message());
583 return SkCodec::kInternalError;
584 }
585
586 if (!already_zeroed) {
587 uint32_t src_bits_per_pixel = fPixelConfig.pixel_format().bits_per_pixel();
588 if ((src_bits_per_pixel == 0) || (src_bits_per_pixel % 8 != 0)) {
589 return SkCodec::kInternalError;
590 }
591 size_t src_bytes_per_pixel = src_bits_per_pixel / 8;
592
593 wuffs_base__rect_ie_u32 frame_rect = fFrameConfig.bounds();
594 wuffs_base__table_u8 pixels = fPixelBuffer.plane(0);
595
596 uint8_t* ptr = pixels.ptr + (frame_rect.min_incl_y * pixels.stride) +
597 (frame_rect.min_incl_x * src_bytes_per_pixel);
598 size_t len = frame_rect.width() * src_bytes_per_pixel;
599
600 // As an optimization, issue a single sk_bzero call, if possible.
601 // Otherwise, zero out each row separately.
602 if ((len == pixels.stride) && (frame_rect.min_incl_y < frame_rect.max_excl_y)) {
603 sk_bzero(ptr, len * (frame_rect.max_excl_y - frame_rect.min_incl_y));
604 } else {
605 for (uint32_t y = frame_rect.min_incl_y; y < frame_rect.max_excl_y; y++) {
606 sk_bzero(ptr, len);
607 ptr += pixels.stride;
608 }
609 }
610 }
611
612 fIncrDecPixelBlend = WUFFS_BASE__PIXEL_BLEND__SRC;
613 return SkCodec::kSuccess;
614 }
615
616 SkCodec::Result SkWuffsCodec::onIncrementalDecode(int* rowsDecoded) {
617 if (!fIncrDecDst) {
618 return SkCodec::kInternalError;
619 }
620
621 if (rowsDecoded) {
622 *rowsDecoded = dstInfo().height();
623 }
624
625 SkCodec::Result result =
626 fIncrDecOnePass ? this->onIncrementalDecodeOnePass() : this->onIncrementalDecodeTwoPass();
627 if (result == SkCodec::kSuccess) {
628 fIncrDecDst = nullptr;
629 fIncrDecRowBytes = 0;
630 fIncrDecPixelBlend = WUFFS_BASE__PIXEL_BLEND__SRC;
631 fIncrDecOnePass = false;
632 }
633 return result;
634 }
635
636 SkCodec::Result SkWuffsCodec::onIncrementalDecodeOnePass() {
637 const char* status = this->decodeFrame();
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
649 SkCodec::Result SkWuffsCodec::onIncrementalDecodeTwoPass() {
650 SkCodec::Result result = SkCodec::kSuccess;
651 const char* status = this->decodeFrame();
652 bool independent;
653 SkAlphaType alphaType;
654 const int index = options().fFrameIndex;
655 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 }
663 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
678 uint32_t src_bits_per_pixel = fPixelBuffer.pixcfg.pixel_format().bits_per_pixel();
679 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
684 wuffs_base__rect_ie_u32 frame_rect = fFrameConfig.bounds();
685 if (fFirstCallToIncrementalDecode) {
686 if (frame_rect.width() > (SIZE_MAX / src_bytes_per_pixel)) {
687 return SkCodec::kInternalError;
688 }
689
690 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
693 // If the frame rect does not fill the output, ensure that those pixels are not
694 // left uninitialized.
695 if (independent && (bounds != this->bounds() || result != kSuccess)) {
696 SkSampler::Fill(dstInfo(), fIncrDecDst, fIncrDecRowBytes, options().fZeroInitialized);
697 }
698 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);
709 }
710
711 // If the frame's dirty rect is empty, no need to swizzle.
712 wuffs_base__rect_ie_u32 dirty_rect = fDecoder->frame_dirty_rect();
713 if (!dirty_rect.is_empty()) {
714 wuffs_base__table_u8 pixels = fPixelBuffer.plane(0);
715
716 // 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).
722 uint8_t* s = pixels.ptr + (dirty_rect.min_incl_y * pixels.stride) +
723 (dirty_rect.min_incl_x * src_bytes_per_pixel);
724
725 // 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().colorProfile());
729
730 auto srcInfo =
731 getInfo().makeWH(dirty_rect.width(), dirty_rect.height()).makeAlphaType(alphaType);
732 SkBitmap src;
733 src.installPixels(srcInfo, s, pixels.stride);
734 SkPaint paint;
735 if (independent) {
736 paint.setBlendMode(SkBlendMode::kSrc);
737 }
738
739 skcpu::Draw draw;
740 draw.fDst.reset(dstInfo(), fIncrDecDst, fIncrDecRowBytes);
741 SkMatrix matrix = SkMatrix::RectToRectOrIdentity(SkRect::Make(this->dimensions()),
742 SkRect::Make(this->dstInfo().dimensions()));
743 draw.fCTM = &matrix;
744 SkRasterClip rc(SkIRect::MakeSize(this->dstInfo().dimensions()));
745 draw.fRC = &rc;
746
747 SkMatrix translate = SkMatrix::Translate(dirty_rect.min_incl_x, dirty_rect.min_incl_y);
748 draw.drawBitmap(src, translate, nullptr, SkSamplingOptions(), paint, nullptr);
749 }
750
751 if (result == SkCodec::kSuccess) {
752 // On success, we are done using the "two pass" pixel buffer for this
753 // frame. We have the option of releasing its memory, but there is a
754 // trade-off. If decoding a subsequent frame will also need "two pass"
755 // decoding, it would have to re-allocate the buffer instead of just
756 // re-using it. On the other hand, if there is no subsequent frame, and
757 // the SkWuffsCodec object isn't deleted soon, then we are holding
758 // megabytes of memory longer than we need to.
759 //
760 // For example, when the Chromium web browser decodes the <img> tags in
761 // a HTML page, the SkCodec object can live until navigating away from
762 // the page, which can be much longer than when the pixels are fully
763 // decoded, especially for a still (non-animated) image. Even for
764 // looping animations, caching the decoded frames (at the higher HTML
765 // renderer layer) may mean that each frame is only decoded once (at
766 // the lower SkCodec layer), in sequence.
767 //
768 // The heuristic we use here is to free the memory if we have decoded
769 // the last frame of the animation (or, for still images, the only
770 // frame). The output of the next decode request (if any) should be the
771 // same either way, but the steady state memory use should hopefully be
772 // lower than always keeping the fTwoPassPixbufPtr buffer up until the
773 // SkWuffsCodec destructor runs.
774 //
775 // This only applies to "two pass" decoding. "One pass" decoding does
776 // not allocate, free or otherwise use fTwoPassPixbufPtr.
777 if (fFramesComplete && (static_cast<size_t>(options().fFrameIndex) == fFrames.size() - 1)) {
778 fTwoPassPixbufPtr.reset(nullptr);
779 fTwoPassPixbufLen = 0;
780 }
781 }
782
783 return result;
784 }
785
786 int SkWuffsCodec::onGetFrameCount() {
787 if (!fCanSeek) {
788 return 1;
789 }
790
791 // It is valid, in terms of the SkCodec API, to call SkCodec::getFrameCount
792 // while in an incremental decode (after onStartIncrementalDecode returns
793 // and before onIncrementalDecode returns kSuccess).
794 //
795 // We should not advance the SkWuffsCodec' stream while doing so, even
796 // though other SkCodec implementations can return increasing values from
797 // onGetFrameCount when given more data. If we tried to do so, the
798 // subsequent resume of the incremental decode would continue reading from
799 // a different position in the I/O stream, leading to an incorrect error.
800 //
801 // Other SkCodec implementations can move the stream forward during
802 // onGetFrameCount because they assume that the stream is rewindable /
803 // seekable. For example, an alternative GIF implementation may choose to
804 // store, for each frame walked past when merely counting the number of
805 // frames, the I/O position of each of the frame's GIF data blocks. (A GIF
806 // frame's compressed data can have multiple data blocks, each at most 255
807 // bytes in length). Obviously, this can require O(numberOfFrames) extra
808 // memory to store these I/O positions. The constant factor is small, but
809 // it's still O(N), not O(1).
810 //
811 // Wuffs and SkWuffsCodec try to minimize relying on the rewindable /
812 // seekable assumption. By design, Wuffs per se aims for O(1) memory use
813 // (after any pixel buffers are allocated) instead of O(N), and its I/O
814 // type, wuffs_base__io_buffer, is not necessarily rewindable or seekable.
815 //
816 // The Wuffs API provides a limited, optional form of seeking, to the start
817 // of an animation frame's data, but does not provide arbitrary save and
818 // load of its internal state whilst in the middle of an animation frame.
819 bool incrementalDecodeIsInProgress = fIncrDecDst != nullptr;
820
821 if (!fFramesComplete && !incrementalDecodeIsInProgress) {
822 this->onGetFrameCountInternal();
823 this->updateNumFullyReceivedFrames();
824 }
825 return fFrames.size();
826 }
827
828 void SkWuffsCodec::onGetFrameCountInternal() {
829 size_t n = fFrames.size();
830 int i = n ? n - 1 : 0;
831 if (this->seekFrame(i) != SkCodec::kSuccess) {
832 return;
833 }
834
835 // Iterate through the frames, converting from Wuffs'
836 // wuffs_base__frame_config type to Skia's SkWuffsFrame type.
837 for (; i < INT_MAX; i++) {
838 const char* status = this->decodeFrameConfig();
839 if (status == nullptr) {
840 // No-op.
841 } else if (status == wuffs_base__note__end_of_data) {
842 break;
843 } else {
844 return;
845 }
846
847 if (static_cast<size_t>(i) < fFrames.size()) {
848 continue;
849 }
850 fFrames.emplace_back(&fFrameConfig);
851 SkWuffsFrame* f = &fFrames[fFrames.size() - 1];
852 fFrameHolder.setAlphaAndRequiredFrame(f);
853 }
854
855 fFramesComplete = true;
856 }
857
858 bool SkWuffsCodec::onGetFrameInfo(int i, SkCodec::FrameInfo* frameInfo) const {
859 if (!fCanSeek) {
860 // We haven't read forward in the stream, so this info isn't available.
861 return false;
862 }
863
864 const SkWuffsFrame* f = this->frame(i);
865 if (!f) {
866 return false;
867 }
868 if (frameInfo) {
869 f->fillIn(frameInfo, static_cast<uint64_t>(i) < this->fNumFullyReceivedFrames);
870 }
871 return true;
872 }
873
874 int SkWuffsCodec::onGetRepetitionCount() {
875 // Convert from Wuffs's loop count to Skia's repeat count. Wuffs' uint32_t
876 // number is how many times to play the loop. Skia's int number is how many
877 // times to play the loop *after the first play*. Wuffs and Skia use 0 and
878 // kRepetitionCountInfinite respectively to mean loop forever.
879 uint32_t n = fDecoder->num_animation_loops();
880 if (n == 0) {
881 return SkCodec::kRepetitionCountInfinite;
882 }
883 n--;
884 return n < INT_MAX ? n : INT_MAX;
885 }
886
887 SkCodec::IsAnimated SkWuffsCodec::onIsAnimated() {
888 if (fFrames.size() > 1) {
889 return IsAnimated::kYes;
890 }
891
892 // If we only have encounted a single image frame so far, then we have an
893 // ambiguous situation - maybe more frames will come, but maybe not.
894 return fFramesComplete ? IsAnimated::kNo : IsAnimated::kUnknown;
895 }
896
897 SkCodec::Result SkWuffsCodec::seekFrame(int frameIndex) {
898 if (fDecoderIsSuspended) {
899 SkCodec::Result res = this->resetDecoder();
900 if (res != SkCodec::kSuccess) {
901 return res;
902 }
903 }
904
905 uint64_t pos = 0;
906 if (frameIndex < 0) {
907 return SkCodec::kInternalError;
908 } else if (frameIndex == 0) {
909 pos = fFirstFrameIOPosition;
910 } else if (static_cast<size_t>(frameIndex) < fFrames.size()) {
911 pos = fFrames[frameIndex].ioPosition();
912 } else {
913 return SkCodec::kInternalError;
914 }
915
916 if (!seek_buffer(&fIOBuffer, fPrivStream.get(), pos)) {
917 return SkCodec::kInternalError;
918 }
919 wuffs_base__status status =
920 fDecoder->restart_frame(frameIndex, fIOBuffer.reader_io_position());
921 if (status.repr != nullptr) {
922 return SkCodec::kInternalError;
923 }
924 return SkCodec::kSuccess;
925 }
926
927 SkCodec::Result SkWuffsCodec::resetDecoder() {
928 if (!fPrivStream->rewind()) {
929 return SkCodec::kInternalError;
930 }
931 fIOBuffer.meta = wuffs_base__empty_io_buffer_meta();
932
933 SkCodec::Result result =
934 reset_and_decode_image_config(fDecoder.get(), nullptr, &fIOBuffer, fPrivStream.get());
935 if (result == SkCodec::kIncompleteInput) {
936 return SkCodec::kInternalError;
937 } else if (result != SkCodec::kSuccess) {
938 return result;
939 }
940
941 fDecoderIsSuspended = false;
942 return SkCodec::kSuccess;
943 }
944
945 const char* SkWuffsCodec::decodeFrameConfig() {
946 while (true) {
947 wuffs_base__status status =
948 fDecoder->decode_frame_config(&fFrameConfig, &fIOBuffer);
949 if ((status.repr == wuffs_base__suspension__short_read) &&
950 fill_buffer(&fIOBuffer, fPrivStream.get())) {
951 continue;
952 }
953 fDecoderIsSuspended = !status.is_complete();
954 this->updateNumFullyReceivedFrames();
955 return status.repr;
956 }
957 }
958
959 const char* SkWuffsCodec::decodeFrame() {
960 while (true) {
961 wuffs_base__status status = fDecoder->decode_frame(
962 &fPixelBuffer, &fIOBuffer, fIncrDecPixelBlend,
963 wuffs_base__make_slice_u8(fWorkbufPtr.get(), fWorkbufLen), nullptr);
964 if ((status.repr == wuffs_base__suspension__short_read) &&
965 fill_buffer(&fIOBuffer, fPrivStream.get())) {
966 continue;
967 }
968 fDecoderIsSuspended = !status.is_complete();
969 this->updateNumFullyReceivedFrames();
970 return status.repr;
971 }
972 }
973
974 void SkWuffsCodec::updateNumFullyReceivedFrames() {
975 // num_decoded_frames's return value, n, can change over time, both up and
976 // down, as we seek back and forth in the underlying stream.
977 // fNumFullyReceivedFrames is the highest n we've seen.
978 uint64_t n = fDecoder->num_decoded_frames();
979 if (fNumFullyReceivedFrames < n) {
980 fNumFullyReceivedFrames = n;
981 }
982 }
983
984 // We cannot use the SkCodec implementation since we pass nullptr to the superclass out of
985 // an abundance of caution w/r to rewinding the stream.
986 //
987 // TODO(https://crbug.com/370522089): See if `SkCodec` can be tweaked to avoid
988 // the need to hide the stream from it.
989 std::unique_ptr<SkStream> SkWuffsCodec::getEncodedData() const {
990 SkASSERT(fPrivStream);
991 return fPrivStream->duplicate();
992 }
993
994 namespace SkGifDecoder {
995
996 bool IsGif(const void* buf, size_t bytesRead) {
997 constexpr const char* gif_ptr = "GIF8";
998 constexpr size_t gif_len = 4;
999 return (bytesRead >= gif_len) && (memcmp(buf, gif_ptr, gif_len) == 0);
1000 }
1001
1002 std::unique_ptr<SkCodec> MakeFromStream(std::unique_ptr<SkStream> stream,
1003 SkCodec::SelectionPolicy selectionPolicy,
1004 SkCodec::Result* result) {
1005 SkASSERT(result);
1006 if (!stream) {
1007 *result = SkCodec::kInvalidInput;
1008 return nullptr;
1009 }
1010
1011 bool canSeek = stream->hasPosition() && stream->hasLength();
1012
1013 if (selectionPolicy != SkCodec::SelectionPolicy::kPreferStillImage) {
1014 // Some clients (e.g. Android) need to be able to seek the stream, but may
1015 // not provide a seekable stream. Copy the stream to one that can seek.
1016 if (!canSeek) {
1017 auto data = SkStreamPriv::CopyStreamToData(stream.get());
1018 stream = std::make_unique<SkMemoryStream>(std::move(data));
1019 canSeek = true;
1020 }
1021 }
1022
1023 uint8_t buffer[SK_WUFFS_CODEC_BUFFER_SIZE];
1024 wuffs_base__io_buffer iobuf =
1025 wuffs_base__make_io_buffer(wuffs_base__make_slice_u8(buffer, SK_WUFFS_CODEC_BUFFER_SIZE),
1026 wuffs_base__empty_io_buffer_meta());
1027 wuffs_base__image_config imgcfg = wuffs_base__null_image_config();
1028
1029 // Wuffs is primarily a C library, not a C++ one. Furthermore, outside of
1030 // the wuffs_base__etc types, the sizeof a file format specific type like
1031 // GIF's wuffs_gif__decoder can vary between Wuffs versions. If p is of
1032 // type wuffs_gif__decoder*, then the supported API treats p as a pointer
1033 // to an opaque type: a private implementation detail. The API is always
1034 // "set_foo(p, etc)" and not "p->foo = etc".
1035 //
1036 // See https://en.wikipedia.org/wiki/Opaque_pointer#C
1037 //
1038 // Thus, we don't use C++'s new operator (which requires knowing the sizeof
1039 // the struct at compile time). Instead, we use sk_malloc_canfail, with
1040 // sizeof__wuffs_gif__decoder returning the appropriate value for the
1041 // (statically or dynamically) linked version of the Wuffs library.
1042 //
1043 // As a C (not C++) library, none of the Wuffs types have constructors or
1044 // destructors.
1045 //
1046 // In RAII style, we can still use std::unique_ptr with these pointers, but
1047 // we pair the pointer with sk_free instead of C++'s delete.
1048 void* decoder_raw = sk_malloc_canfail(sizeof__wuffs_gif__decoder());
1049 if (!decoder_raw) {
1050 *result = SkCodec::kInternalError;
1051 return nullptr;
1052 }
1053 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> decoder(
1054 reinterpret_cast<wuffs_gif__decoder*>(decoder_raw), &sk_free);
1055
1056 SkCodec::Result reset_result =
1057 reset_and_decode_image_config(decoder.get(), &imgcfg, &iobuf, stream.get());
1058 if (reset_result != SkCodec::kSuccess) {
1059 *result = reset_result;
1060 return nullptr;
1061 }
1062
1063 uint32_t width = imgcfg.pixcfg.width();
1064 uint32_t height = imgcfg.pixcfg.height();
1065 if ((width == 0) || (width > INT_MAX) || (height == 0) || (height > INT_MAX)) {
1066 *result = SkCodec::kInvalidInput;
1067 return nullptr;
1068 }
1069
1070 uint64_t workbuf_len = decoder->workbuf_len().max_incl;
1071 void* workbuf_ptr_raw = nullptr;
1072 if (workbuf_len) {
1073 workbuf_ptr_raw = workbuf_len <= SIZE_MAX ? sk_malloc_canfail(workbuf_len) : nullptr;
1074 if (!workbuf_ptr_raw) {
1075 *result = SkCodec::kInternalError;
1076 return nullptr;
1077 }
1078 }
1079 std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr(
1080 reinterpret_cast<uint8_t*>(workbuf_ptr_raw), &sk_free);
1081
1082 SkEncodedInfo::Color color =
1083 (imgcfg.pixcfg.pixel_format().repr == WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL)
1084 ? SkEncodedInfo::kBGRA_Color
1085 : SkEncodedInfo::kRGBA_Color;
1086
1087 // In Skia's API, the alpha we calculate here and return is only for the
1088 // first frame.
1089 SkEncodedInfo::Alpha alpha = imgcfg.first_frame_is_opaque() ? SkEncodedInfo::kOpaque_Alpha
1090 : SkEncodedInfo::kBinary_Alpha;
1091
1092 SkEncodedInfo encodedInfo = SkEncodedInfo::Make(width, height, color, alpha, 8);
1093
1094 *result = SkCodec::kSuccess;
1095 return std::unique_ptr<SkCodec>(new SkWuffsCodec(std::move(encodedInfo), std::move(stream),
1096 canSeek,
1097 std::move(decoder), std::move(workbuf_ptr),
1098 workbuf_len, imgcfg, iobuf));
1099 }
1100
1101 std::unique_ptr<SkCodec> Decode(std::unique_ptr<SkStream> stream,
1102 SkCodec::Result* outResult,
1103 SkCodecs::DecodeContext ctx) {
1104 SkCodec::Result resultStorage;
1105 if (!outResult) {
1106 outResult = &resultStorage;
1107 }
1108 auto policy = SkCodec::SelectionPolicy::kPreferStillImage;
1109 if (ctx) {
1110 policy = *static_cast<SkCodec::SelectionPolicy*>(ctx);
1111 }
1112 return MakeFromStream(std::move(stream), policy, outResult);
1113 }
1114
1115 std::unique_ptr<SkCodec> Decode(sk_sp<const SkData> data,
1116 SkCodec::Result* outResult,
1117 SkCodecs::DecodeContext ctx) {
1118 if (!data) {
1119 if (outResult) {
1120 *outResult = SkCodec::kInvalidInput;
1121 }
1122 return nullptr;
1123 }
1124 return Decode(SkMemoryStream::Make(std::move(data)), outResult, ctx);
1125 }
1126 } // namespace SkGifDecoder
1127