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