xref: /aosp_15_r20/external/skia/src/codec/SkWuffsCodec.cpp (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
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 
266     // Two separate implementations of onStartIncrementalDecode and
267     // onIncrementalDecode, named "one pass" and "two pass" decoding. One pass
268     // decoding writes directly from the Wuffs image decoder to the dst buffer
269     // (the dst argument to onStartIncrementalDecode). Two pass decoding first
270     // writes into an intermediate buffer, and then composites and transforms
271     // the intermediate buffer into the dst buffer.
272     //
273     // In the general case, we need the two pass decoder, because of Skia API
274     // features that Wuffs doesn't support (e.g. color correction, scaling,
275     // RGB565). But as an optimization, we use one pass decoding (it's faster
276     // and uses less memory) if applicable (see the assignment to
277     // fIncrDecOnePass that calculates when we can do so).
278     Result onStartIncrementalDecodeOnePass(const SkImageInfo&      dstInfo,
279                                            uint8_t*                dst,
280                                            size_t                  rowBytes,
281                                            const SkCodec::Options& options,
282                                            uint32_t                pixelFormat,
283                                            size_t                  bytesPerPixel);
284     Result onStartIncrementalDecodeTwoPass();
285     Result onIncrementalDecodeOnePass();
286     Result onIncrementalDecodeTwoPass();
287 
288     void        onGetFrameCountInternal();
289     Result      seekFrame(int frameIndex);
290     Result      resetDecoder();
291     const char* decodeFrameConfig();
292     const char* decodeFrame();
293     void        updateNumFullyReceivedFrames();
294 
295     SkWuffsFrameHolder                           fFrameHolder;
296     std::unique_ptr<SkStream>                    fPrivStream;
297     std::unique_ptr<uint8_t, decltype(&sk_free)> fWorkbufPtr;
298     size_t                                       fWorkbufLen;
299 
300     std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> fDecoder;
301 
302     const uint64_t           fFirstFrameIOPosition;
303     wuffs_base__frame_config fFrameConfig;
304     wuffs_base__pixel_config fPixelConfig;
305     wuffs_base__pixel_buffer fPixelBuffer;
306     wuffs_base__io_buffer    fIOBuffer;
307 
308     // Incremental decoding state.
309     uint8_t*                fIncrDecDst;
310     size_t                  fIncrDecRowBytes;
311     wuffs_base__pixel_blend fIncrDecPixelBlend;
312     bool                    fIncrDecOnePass;
313     bool                    fFirstCallToIncrementalDecode;
314 
315     // Lazily allocated intermediate pixel buffer, for two pass decoding.
316     std::unique_ptr<uint8_t, decltype(&sk_free)> fTwoPassPixbufPtr;
317     size_t                                       fTwoPassPixbufLen;
318 
319     uint64_t                  fNumFullyReceivedFrames;
320     std::vector<SkWuffsFrame> fFrames;
321     bool                      fFramesComplete;
322 
323     // If calling an fDecoder method returns an incomplete status, then
324     // fDecoder is suspended in a coroutine (i.e. waiting on I/O or halted on a
325     // non-recoverable error). To keep its internal proof-of-safety invariants
326     // consistent, there's only two things you can safely do with a suspended
327     // Wuffs object: resume the coroutine, or reset all state (memset to zero
328     // and start again).
329     //
330     // If fDecoderIsSuspended, and we aren't sure that we're going to resume
331     // the coroutine, then we will need to call this->resetDecoder before
332     // calling other fDecoder methods.
333     bool fDecoderIsSuspended;
334 
335     uint8_t fBuffer[SK_WUFFS_CODEC_BUFFER_SIZE];
336 
337     const bool fCanSeek;
338 
339     using INHERITED = SkScalingCodec;
340 };
341 
342 // -------------------------------- SkWuffsFrame implementation
343 
SkWuffsFrame(wuffs_base__frame_config * fc)344 SkWuffsFrame::SkWuffsFrame(wuffs_base__frame_config* fc)
345     : INHERITED(fc->index()),
346       fIOPosition(fc->io_position()),
347       fReportedAlpha(fc->opaque_within_bounds() ? SkEncodedInfo::kOpaque_Alpha
348                                                 : SkEncodedInfo::kUnpremul_Alpha) {
349     wuffs_base__rect_ie_u32 r = fc->bounds();
350     this->setXYWH(r.min_incl_x, r.min_incl_y, r.width(), r.height());
351     this->setDisposalMethod(wuffs_disposal_to_skia_disposal(fc->disposal()));
352     this->setDuration(fc->duration() / WUFFS_BASE__FLICKS_PER_MILLISECOND);
353     this->setBlend(fc->overwrite_instead_of_blend() ? SkCodecAnimation::Blend::kSrc
354                                                     : SkCodecAnimation::Blend::kSrcOver);
355 }
356 
ioPosition() const357 uint64_t SkWuffsFrame::ioPosition() const {
358     return fIOPosition;
359 }
360 
onReportedAlpha() const361 SkEncodedInfo::Alpha SkWuffsFrame::onReportedAlpha() const {
362     return fReportedAlpha;
363 }
364 
365 // -------------------------------- SkWuffsFrameHolder implementation
366 
init(SkWuffsCodec * codec,int width,int height)367 void SkWuffsFrameHolder::init(SkWuffsCodec* codec, int width, int height) {
368     fCodec = codec;
369     // Initialize SkFrameHolder's (the superclass) fields.
370     fScreenWidth = width;
371     fScreenHeight = height;
372 }
373 
onGetFrame(int i) const374 const SkFrame* SkWuffsFrameHolder::onGetFrame(int i) const {
375     return fCodec->frame(i);
376 }
377 
378 // -------------------------------- SkWuffsCodec implementation
379 
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)380 SkWuffsCodec::SkWuffsCodec(SkEncodedInfo&& encodedInfo,
381                            std::unique_ptr<SkStream> stream,
382                            bool canSeek,
383                            std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> dec,
384                            std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr,
385                            size_t workbuf_len,
386                            wuffs_base__image_config imgcfg,
387                            wuffs_base__io_buffer iobuf)
388         : INHERITED(std::move(encodedInfo),
389                     skcms_PixelFormat_RGBA_8888,
390                     // Pass a nullptr SkStream to the SkCodec constructor. We
391                     // manage the stream ourselves, as the default SkCodec behavior
392                     // is too trigger-happy on rewinding the stream.
393                     //
394                     // TODO(https://crbug.com/370522089): See if `SkCodec` can be
395                     // tweaked to avoid the need to hide the stream from it.
396                     nullptr)
397         , fFrameHolder()
398         , fPrivStream(std::move(stream))
399         , fWorkbufPtr(std::move(workbuf_ptr))
400         , fWorkbufLen(workbuf_len)
401         , fDecoder(std::move(dec))
402         , fFirstFrameIOPosition(imgcfg.first_frame_io_position())
403         , fFrameConfig(wuffs_base__null_frame_config())
404         , fPixelConfig(imgcfg.pixcfg)
405         , fPixelBuffer(wuffs_base__null_pixel_buffer())
406         , fIOBuffer(wuffs_base__empty_io_buffer())
407         , fIncrDecDst(nullptr)
408         , fIncrDecRowBytes(0)
409         , fIncrDecPixelBlend(WUFFS_BASE__PIXEL_BLEND__SRC)
410         , fIncrDecOnePass(false)
411         , fFirstCallToIncrementalDecode(false)
412         , fTwoPassPixbufPtr(nullptr, &sk_free)
413         , fTwoPassPixbufLen(0)
414         , fNumFullyReceivedFrames(0)
415         , fFramesComplete(false)
416         , fDecoderIsSuspended(false)
417         , fCanSeek(canSeek) {
418     fFrameHolder.init(this, imgcfg.pixcfg.width(), imgcfg.pixcfg.height());
419 
420     // Initialize fIOBuffer's fields, copying any outstanding data from iobuf to
421     // fIOBuffer, as iobuf's backing array may not be valid for the lifetime of
422     // this SkWuffsCodec object, but fIOBuffer's backing array (fBuffer) is.
423     SkASSERT(iobuf.data.len == SK_WUFFS_CODEC_BUFFER_SIZE);
424     memmove(fBuffer, iobuf.data.ptr, iobuf.meta.wi);
425     fIOBuffer.data = wuffs_base__make_slice_u8(fBuffer, SK_WUFFS_CODEC_BUFFER_SIZE);
426     fIOBuffer.meta = iobuf.meta;
427 }
428 
frame(int i) const429 const SkWuffsFrame* SkWuffsCodec::frame(int i) const {
430     if ((0 <= i) && (static_cast<size_t>(i) < fFrames.size())) {
431         return &fFrames[i];
432     }
433     return nullptr;
434 }
435 
onGetEncodedFormat() const436 SkEncodedImageFormat SkWuffsCodec::onGetEncodedFormat() const {
437     return SkEncodedImageFormat::kGIF;
438 }
439 
onGetPixels(const SkImageInfo & dstInfo,void * dst,size_t rowBytes,const Options & options,int * rowsDecoded)440 SkCodec::Result SkWuffsCodec::onGetPixels(const SkImageInfo& dstInfo,
441                                           void*              dst,
442                                           size_t             rowBytes,
443                                           const Options&     options,
444                                           int*               rowsDecoded) {
445     SkCodec::Result result = this->onStartIncrementalDecode(dstInfo, dst, rowBytes, options);
446     if (result != kSuccess) {
447         return result;
448     }
449     return this->onIncrementalDecode(rowsDecoded);
450 }
451 
getFrameHolder() const452 const SkFrameHolder* SkWuffsCodec::getFrameHolder() const {
453     return &fFrameHolder;
454 }
455 
onStartIncrementalDecode(const SkImageInfo & dstInfo,void * dst,size_t rowBytes,const SkCodec::Options & options)456 SkCodec::Result SkWuffsCodec::onStartIncrementalDecode(const SkImageInfo&      dstInfo,
457                                                        void*                   dst,
458                                                        size_t                  rowBytes,
459                                                        const SkCodec::Options& options) {
460     if (!dst) {
461         return SkCodec::kInvalidParameters;
462     }
463     if (options.fSubset) {
464         return SkCodec::kUnimplemented;
465     }
466     SkCodec::Result result = this->seekFrame(options.fFrameIndex);
467     if (result != SkCodec::kSuccess) {
468         return result;
469     }
470 
471     const char* status = this->decodeFrameConfig();
472     if (status == wuffs_base__suspension__short_read) {
473         return SkCodec::kIncompleteInput;
474     } else if (status != nullptr) {
475         SkCodecPrintf("decodeFrameConfig: %s", status);
476         return SkCodec::kErrorInInput;
477     }
478 
479     uint32_t pixelFormat = WUFFS_BASE__PIXEL_FORMAT__INVALID;
480     size_t   bytesPerPixel = 0;
481 
482     switch (dstInfo.colorType()) {
483         case kRGB_565_SkColorType:
484             pixelFormat = WUFFS_BASE__PIXEL_FORMAT__BGR_565;
485             bytesPerPixel = 2;
486             break;
487         case kBGRA_8888_SkColorType:
488             pixelFormat = WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL;
489             bytesPerPixel = 4;
490             break;
491         case kRGBA_8888_SkColorType:
492             pixelFormat = WUFFS_BASE__PIXEL_FORMAT__RGBA_NONPREMUL;
493             bytesPerPixel = 4;
494             break;
495         default:
496             break;
497     }
498 
499     // We can use "one pass" decoding if we have a Skia pixel format that Wuffs
500     // supports...
501     fIncrDecOnePass = (pixelFormat != WUFFS_BASE__PIXEL_FORMAT__INVALID) &&
502                       // ...and no color profile (as Wuffs does not support them)...
503                       (!getEncodedInfo().profile()) &&
504                       // ...and we use the identity transform (as Wuffs does
505                       // not support scaling).
506                       (this->dimensions() == dstInfo.dimensions());
507 
508     result = fIncrDecOnePass ? this->onStartIncrementalDecodeOnePass(
509                                    dstInfo, static_cast<uint8_t*>(dst), rowBytes, options,
510                                    pixelFormat, bytesPerPixel)
511                              : this->onStartIncrementalDecodeTwoPass();
512     if (result != SkCodec::kSuccess) {
513         return result;
514     }
515 
516     fIncrDecDst = static_cast<uint8_t*>(dst);
517     fIncrDecRowBytes = rowBytes;
518     fFirstCallToIncrementalDecode = true;
519     return SkCodec::kSuccess;
520 }
521 
onStartIncrementalDecodeOnePass(const SkImageInfo & dstInfo,uint8_t * dst,size_t rowBytes,const SkCodec::Options & options,uint32_t pixelFormat,size_t bytesPerPixel)522 SkCodec::Result SkWuffsCodec::onStartIncrementalDecodeOnePass(const SkImageInfo&      dstInfo,
523                                                               uint8_t*                dst,
524                                                               size_t                  rowBytes,
525                                                               const SkCodec::Options& options,
526                                                               uint32_t                pixelFormat,
527                                                               size_t bytesPerPixel) {
528     wuffs_base__pixel_config pixelConfig;
529     pixelConfig.set(pixelFormat, WUFFS_BASE__PIXEL_SUBSAMPLING__NONE, dstInfo.width(),
530                     dstInfo.height());
531 
532     wuffs_base__table_u8 table;
533     table.ptr = dst;
534     table.width = static_cast<size_t>(dstInfo.width()) * bytesPerPixel;
535     table.height = dstInfo.height();
536     table.stride = rowBytes;
537 
538     wuffs_base__status status = fPixelBuffer.set_from_table(&pixelConfig, table);
539     if (status.repr != nullptr) {
540         SkCodecPrintf("set_from_table: %s", status.message());
541         return SkCodec::kInternalError;
542     }
543 
544     // SRC is usually faster than SRC_OVER, but for a dependent frame, dst is
545     // assumed to hold the previous frame's pixels (after processing the
546     // DisposalMethod). For one-pass decoding, we therefore use SRC_OVER.
547     if ((options.fFrameIndex != 0) &&
548         (this->frame(options.fFrameIndex)->getRequiredFrame() != SkCodec::kNoFrame)) {
549         fIncrDecPixelBlend = WUFFS_BASE__PIXEL_BLEND__SRC_OVER;
550     } else {
551         SkSampler::Fill(dstInfo, dst, rowBytes, options.fZeroInitialized);
552         fIncrDecPixelBlend = WUFFS_BASE__PIXEL_BLEND__SRC;
553     }
554 
555     return SkCodec::kSuccess;
556 }
557 
onStartIncrementalDecodeTwoPass()558 SkCodec::Result SkWuffsCodec::onStartIncrementalDecodeTwoPass() {
559     // Either re-use the previously allocated "two pass" pixel buffer (and
560     // memset to zero), or allocate (and zero initialize) a new one.
561     bool already_zeroed = false;
562 
563     if (!fTwoPassPixbufPtr) {
564         uint64_t pixbuf_len = fPixelConfig.pixbuf_len();
565         void*    pixbuf_ptr_raw = (pixbuf_len <= SIZE_MAX)
566                                       ? sk_malloc_flags(pixbuf_len, SK_MALLOC_ZERO_INITIALIZE)
567                                       : nullptr;
568         if (!pixbuf_ptr_raw) {
569             return SkCodec::kInternalError;
570         }
571         fTwoPassPixbufPtr.reset(reinterpret_cast<uint8_t*>(pixbuf_ptr_raw));
572         fTwoPassPixbufLen = SkToSizeT(pixbuf_len);
573         already_zeroed = true;
574     }
575 
576     wuffs_base__status status = fPixelBuffer.set_from_slice(
577         &fPixelConfig, wuffs_base__make_slice_u8(fTwoPassPixbufPtr.get(), fTwoPassPixbufLen));
578     if (status.repr != nullptr) {
579         SkCodecPrintf("set_from_slice: %s", status.message());
580         return SkCodec::kInternalError;
581     }
582 
583     if (!already_zeroed) {
584         uint32_t src_bits_per_pixel = fPixelConfig.pixel_format().bits_per_pixel();
585         if ((src_bits_per_pixel == 0) || (src_bits_per_pixel % 8 != 0)) {
586             return SkCodec::kInternalError;
587         }
588         size_t src_bytes_per_pixel = src_bits_per_pixel / 8;
589 
590         wuffs_base__rect_ie_u32 frame_rect = fFrameConfig.bounds();
591         wuffs_base__table_u8    pixels = fPixelBuffer.plane(0);
592 
593         uint8_t* ptr = pixels.ptr + (frame_rect.min_incl_y * pixels.stride) +
594                        (frame_rect.min_incl_x * src_bytes_per_pixel);
595         size_t len = frame_rect.width() * src_bytes_per_pixel;
596 
597         // As an optimization, issue a single sk_bzero call, if possible.
598         // Otherwise, zero out each row separately.
599         if ((len == pixels.stride) && (frame_rect.min_incl_y < frame_rect.max_excl_y)) {
600             sk_bzero(ptr, len * (frame_rect.max_excl_y - frame_rect.min_incl_y));
601         } else {
602             for (uint32_t y = frame_rect.min_incl_y; y < frame_rect.max_excl_y; y++) {
603                 sk_bzero(ptr, len);
604                 ptr += pixels.stride;
605             }
606         }
607     }
608 
609     fIncrDecPixelBlend = WUFFS_BASE__PIXEL_BLEND__SRC;
610     return SkCodec::kSuccess;
611 }
612 
onIncrementalDecode(int * rowsDecoded)613 SkCodec::Result SkWuffsCodec::onIncrementalDecode(int* rowsDecoded) {
614     if (!fIncrDecDst) {
615         return SkCodec::kInternalError;
616     }
617 
618     if (rowsDecoded) {
619         *rowsDecoded = dstInfo().height();
620     }
621 
622     SkCodec::Result result =
623         fIncrDecOnePass ? this->onIncrementalDecodeOnePass() : this->onIncrementalDecodeTwoPass();
624     if (result == SkCodec::kSuccess) {
625         fIncrDecDst = nullptr;
626         fIncrDecRowBytes = 0;
627         fIncrDecPixelBlend = WUFFS_BASE__PIXEL_BLEND__SRC;
628         fIncrDecOnePass = false;
629     }
630     return result;
631 }
632 
onIncrementalDecodeOnePass()633 SkCodec::Result SkWuffsCodec::onIncrementalDecodeOnePass() {
634     const char* status = this->decodeFrame();
635     if (status != nullptr) {
636         if (status == wuffs_base__suspension__short_read) {
637             return SkCodec::kIncompleteInput;
638         } else {
639             SkCodecPrintf("decodeFrame: %s", status);
640             return SkCodec::kErrorInInput;
641         }
642     }
643     return SkCodec::kSuccess;
644 }
645 
onIncrementalDecodeTwoPass()646 SkCodec::Result SkWuffsCodec::onIncrementalDecodeTwoPass() {
647     SkCodec::Result result = SkCodec::kSuccess;
648     const char*     status = this->decodeFrame();
649     bool            independent;
650     SkAlphaType     alphaType;
651     const int       index = options().fFrameIndex;
652     if (index == 0) {
653         independent = true;
654         alphaType = to_alpha_type(getEncodedInfo().opaque());
655     } else {
656         const SkWuffsFrame* f = this->frame(index);
657         independent = f->getRequiredFrame() == SkCodec::kNoFrame;
658         alphaType = to_alpha_type(f->reportedAlpha() == SkEncodedInfo::kOpaque_Alpha);
659     }
660     if (status != nullptr) {
661         if (status == wuffs_base__suspension__short_read) {
662             result = SkCodec::kIncompleteInput;
663         } else {
664             SkCodecPrintf("decodeFrame: %s", status);
665             result = SkCodec::kErrorInInput;
666         }
667 
668         if (!independent) {
669             // For a dependent frame, we cannot blend the partial result, since
670             // that will overwrite the contribution from prior frames.
671             return result;
672         }
673     }
674 
675     uint32_t src_bits_per_pixel = fPixelBuffer.pixcfg.pixel_format().bits_per_pixel();
676     if ((src_bits_per_pixel == 0) || (src_bits_per_pixel % 8 != 0)) {
677         return SkCodec::kInternalError;
678     }
679     size_t src_bytes_per_pixel = src_bits_per_pixel / 8;
680 
681     wuffs_base__rect_ie_u32 frame_rect = fFrameConfig.bounds();
682     if (fFirstCallToIncrementalDecode) {
683         if (frame_rect.width() > (SIZE_MAX / src_bytes_per_pixel)) {
684             return SkCodec::kInternalError;
685         }
686 
687         auto bounds = SkIRect::MakeLTRB(frame_rect.min_incl_x, frame_rect.min_incl_y,
688                                         frame_rect.max_excl_x, frame_rect.max_excl_y);
689 
690         // If the frame rect does not fill the output, ensure that those pixels are not
691         // left uninitialized.
692         if (independent && (bounds != this->bounds() || result != kSuccess)) {
693             SkSampler::Fill(dstInfo(), fIncrDecDst, fIncrDecRowBytes, options().fZeroInitialized);
694         }
695         fFirstCallToIncrementalDecode = false;
696     } else {
697         // Existing clients intend to only show frames beyond the first if they
698         // are complete (based on FrameInfo::fFullyReceived), since it might
699         // look jarring to draw a partial frame over an existing frame. If they
700         // changed their behavior and expected to continue decoding a partial
701         // frame after the first one, we'll need to update our blending code.
702         // Otherwise, if the frame were interlaced and not independent, the
703         // second pass may have an overlapping dirty_rect with the first,
704         // resulting in blending with the first pass.
705         SkASSERT(index == 0);
706     }
707 
708     // If the frame's dirty rect is empty, no need to swizzle.
709     wuffs_base__rect_ie_u32 dirty_rect = fDecoder->frame_dirty_rect();
710     if (!dirty_rect.is_empty()) {
711         wuffs_base__table_u8 pixels = fPixelBuffer.plane(0);
712 
713         // The Wuffs model is that the dst buffer is the image, not the frame.
714         // The expectation is that you allocate the buffer once, but re-use it
715         // for the N frames, regardless of each frame's top-left co-ordinate.
716         //
717         // To get from the start (in the X-direction) of the image to the start
718         // of the dirty_rect, we adjust s by (dirty_rect.min_incl_x * src_bytes_per_pixel).
719         uint8_t* s = pixels.ptr + (dirty_rect.min_incl_y * pixels.stride) +
720                      (dirty_rect.min_incl_x * src_bytes_per_pixel);
721 
722         // Currently, this is only used for GIF, which will never have an ICC profile. When it is
723         // used for other formats that might have one, we will need to transform from profiles that
724         // do not have corresponding SkColorSpaces.
725         SkASSERT(!getEncodedInfo().profile());
726 
727         auto srcInfo =
728             getInfo().makeWH(dirty_rect.width(), dirty_rect.height()).makeAlphaType(alphaType);
729         SkBitmap src;
730         src.installPixels(srcInfo, s, pixels.stride);
731         SkPaint paint;
732         if (independent) {
733             paint.setBlendMode(SkBlendMode::kSrc);
734         }
735 
736         SkDraw draw;
737         draw.fDst.reset(dstInfo(), fIncrDecDst, fIncrDecRowBytes);
738         SkMatrix matrix = SkMatrix::RectToRect(SkRect::Make(this->dimensions()),
739                                                SkRect::Make(this->dstInfo().dimensions()));
740         draw.fCTM = &matrix;
741         SkRasterClip rc(SkIRect::MakeSize(this->dstInfo().dimensions()));
742         draw.fRC = &rc;
743 
744         SkMatrix translate = SkMatrix::Translate(dirty_rect.min_incl_x, dirty_rect.min_incl_y);
745         draw.drawBitmap(src, translate, nullptr, SkSamplingOptions(), paint);
746     }
747 
748     if (result == SkCodec::kSuccess) {
749         // On success, we are done using the "two pass" pixel buffer for this
750         // frame. We have the option of releasing its memory, but there is a
751         // trade-off. If decoding a subsequent frame will also need "two pass"
752         // decoding, it would have to re-allocate the buffer instead of just
753         // re-using it. On the other hand, if there is no subsequent frame, and
754         // the SkWuffsCodec object isn't deleted soon, then we are holding
755         // megabytes of memory longer than we need to.
756         //
757         // For example, when the Chromium web browser decodes the <img> tags in
758         // a HTML page, the SkCodec object can live until navigating away from
759         // the page, which can be much longer than when the pixels are fully
760         // decoded, especially for a still (non-animated) image. Even for
761         // looping animations, caching the decoded frames (at the higher HTML
762         // renderer layer) may mean that each frame is only decoded once (at
763         // the lower SkCodec layer), in sequence.
764         //
765         // The heuristic we use here is to free the memory if we have decoded
766         // the last frame of the animation (or, for still images, the only
767         // frame). The output of the next decode request (if any) should be the
768         // same either way, but the steady state memory use should hopefully be
769         // lower than always keeping the fTwoPassPixbufPtr buffer up until the
770         // SkWuffsCodec destructor runs.
771         //
772         // This only applies to "two pass" decoding. "One pass" decoding does
773         // not allocate, free or otherwise use fTwoPassPixbufPtr.
774         if (fFramesComplete && (static_cast<size_t>(options().fFrameIndex) == fFrames.size() - 1)) {
775             fTwoPassPixbufPtr.reset(nullptr);
776             fTwoPassPixbufLen = 0;
777         }
778     }
779 
780     return result;
781 }
782 
onGetFrameCount()783 int SkWuffsCodec::onGetFrameCount() {
784     if (!fCanSeek) {
785         return 1;
786     }
787 
788     // It is valid, in terms of the SkCodec API, to call SkCodec::getFrameCount
789     // while in an incremental decode (after onStartIncrementalDecode returns
790     // and before onIncrementalDecode returns kSuccess).
791     //
792     // We should not advance the SkWuffsCodec' stream while doing so, even
793     // though other SkCodec implementations can return increasing values from
794     // onGetFrameCount when given more data. If we tried to do so, the
795     // subsequent resume of the incremental decode would continue reading from
796     // a different position in the I/O stream, leading to an incorrect error.
797     //
798     // Other SkCodec implementations can move the stream forward during
799     // onGetFrameCount because they assume that the stream is rewindable /
800     // seekable. For example, an alternative GIF implementation may choose to
801     // store, for each frame walked past when merely counting the number of
802     // frames, the I/O position of each of the frame's GIF data blocks. (A GIF
803     // frame's compressed data can have multiple data blocks, each at most 255
804     // bytes in length). Obviously, this can require O(numberOfFrames) extra
805     // memory to store these I/O positions. The constant factor is small, but
806     // it's still O(N), not O(1).
807     //
808     // Wuffs and SkWuffsCodec try to minimize relying on the rewindable /
809     // seekable assumption. By design, Wuffs per se aims for O(1) memory use
810     // (after any pixel buffers are allocated) instead of O(N), and its I/O
811     // type, wuffs_base__io_buffer, is not necessarily rewindable or seekable.
812     //
813     // The Wuffs API provides a limited, optional form of seeking, to the start
814     // of an animation frame's data, but does not provide arbitrary save and
815     // load of its internal state whilst in the middle of an animation frame.
816     bool incrementalDecodeIsInProgress = fIncrDecDst != nullptr;
817 
818     if (!fFramesComplete && !incrementalDecodeIsInProgress) {
819         this->onGetFrameCountInternal();
820         this->updateNumFullyReceivedFrames();
821     }
822     return fFrames.size();
823 }
824 
onGetFrameCountInternal()825 void SkWuffsCodec::onGetFrameCountInternal() {
826     size_t n = fFrames.size();
827     int    i = n ? n - 1 : 0;
828     if (this->seekFrame(i) != SkCodec::kSuccess) {
829         return;
830     }
831 
832     // Iterate through the frames, converting from Wuffs'
833     // wuffs_base__frame_config type to Skia's SkWuffsFrame type.
834     for (; i < INT_MAX; i++) {
835         const char* status = this->decodeFrameConfig();
836         if (status == nullptr) {
837             // No-op.
838         } else if (status == wuffs_base__note__end_of_data) {
839             break;
840         } else {
841             return;
842         }
843 
844         if (static_cast<size_t>(i) < fFrames.size()) {
845             continue;
846         }
847         fFrames.emplace_back(&fFrameConfig);
848         SkWuffsFrame* f = &fFrames[fFrames.size() - 1];
849         fFrameHolder.setAlphaAndRequiredFrame(f);
850     }
851 
852     fFramesComplete = true;
853 }
854 
onGetFrameInfo(int i,SkCodec::FrameInfo * frameInfo) const855 bool SkWuffsCodec::onGetFrameInfo(int i, SkCodec::FrameInfo* frameInfo) const {
856     if (!fCanSeek) {
857         // We haven't read forward in the stream, so this info isn't available.
858         return false;
859     }
860 
861     const SkWuffsFrame* f = this->frame(i);
862     if (!f) {
863         return false;
864     }
865     if (frameInfo) {
866         f->fillIn(frameInfo, static_cast<uint64_t>(i) < this->fNumFullyReceivedFrames);
867     }
868     return true;
869 }
870 
onGetRepetitionCount()871 int SkWuffsCodec::onGetRepetitionCount() {
872     // Convert from Wuffs's loop count to Skia's repeat count. Wuffs' uint32_t
873     // number is how many times to play the loop. Skia's int number is how many
874     // times to play the loop *after the first play*. Wuffs and Skia use 0 and
875     // kRepetitionCountInfinite respectively to mean loop forever.
876     uint32_t n = fDecoder->num_animation_loops();
877     if (n == 0) {
878         return SkCodec::kRepetitionCountInfinite;
879     }
880     n--;
881     return n < INT_MAX ? n : INT_MAX;
882 }
883 
seekFrame(int frameIndex)884 SkCodec::Result SkWuffsCodec::seekFrame(int frameIndex) {
885     if (fDecoderIsSuspended) {
886         SkCodec::Result res = this->resetDecoder();
887         if (res != SkCodec::kSuccess) {
888             return res;
889         }
890     }
891 
892     uint64_t pos = 0;
893     if (frameIndex < 0) {
894         return SkCodec::kInternalError;
895     } else if (frameIndex == 0) {
896         pos = fFirstFrameIOPosition;
897     } else if (static_cast<size_t>(frameIndex) < fFrames.size()) {
898         pos = fFrames[frameIndex].ioPosition();
899     } else {
900         return SkCodec::kInternalError;
901     }
902 
903     if (!seek_buffer(&fIOBuffer, fPrivStream.get(), pos)) {
904         return SkCodec::kInternalError;
905     }
906     wuffs_base__status status =
907         fDecoder->restart_frame(frameIndex, fIOBuffer.reader_io_position());
908     if (status.repr != nullptr) {
909         return SkCodec::kInternalError;
910     }
911     return SkCodec::kSuccess;
912 }
913 
resetDecoder()914 SkCodec::Result SkWuffsCodec::resetDecoder() {
915     if (!fPrivStream->rewind()) {
916         return SkCodec::kInternalError;
917     }
918     fIOBuffer.meta = wuffs_base__empty_io_buffer_meta();
919 
920     SkCodec::Result result =
921         reset_and_decode_image_config(fDecoder.get(), nullptr, &fIOBuffer, fPrivStream.get());
922     if (result == SkCodec::kIncompleteInput) {
923         return SkCodec::kInternalError;
924     } else if (result != SkCodec::kSuccess) {
925         return result;
926     }
927 
928     fDecoderIsSuspended = false;
929     return SkCodec::kSuccess;
930 }
931 
decodeFrameConfig()932 const char* SkWuffsCodec::decodeFrameConfig() {
933     while (true) {
934         wuffs_base__status status =
935             fDecoder->decode_frame_config(&fFrameConfig, &fIOBuffer);
936         if ((status.repr == wuffs_base__suspension__short_read) &&
937             fill_buffer(&fIOBuffer, fPrivStream.get())) {
938             continue;
939         }
940         fDecoderIsSuspended = !status.is_complete();
941         this->updateNumFullyReceivedFrames();
942         return status.repr;
943     }
944 }
945 
decodeFrame()946 const char* SkWuffsCodec::decodeFrame() {
947     while (true) {
948         wuffs_base__status status = fDecoder->decode_frame(
949             &fPixelBuffer, &fIOBuffer, fIncrDecPixelBlend,
950             wuffs_base__make_slice_u8(fWorkbufPtr.get(), fWorkbufLen), nullptr);
951         if ((status.repr == wuffs_base__suspension__short_read) &&
952             fill_buffer(&fIOBuffer, fPrivStream.get())) {
953             continue;
954         }
955         fDecoderIsSuspended = !status.is_complete();
956         this->updateNumFullyReceivedFrames();
957         return status.repr;
958     }
959 }
960 
updateNumFullyReceivedFrames()961 void SkWuffsCodec::updateNumFullyReceivedFrames() {
962     // num_decoded_frames's return value, n, can change over time, both up and
963     // down, as we seek back and forth in the underlying stream.
964     // fNumFullyReceivedFrames is the highest n we've seen.
965     uint64_t n = fDecoder->num_decoded_frames();
966     if (fNumFullyReceivedFrames < n) {
967         fNumFullyReceivedFrames = n;
968     }
969 }
970 
971 // We cannot use the SkCodec implementation since we pass nullptr to the superclass out of
972 // an abundance of caution w/r to rewinding the stream.
973 //
974 // TODO(https://crbug.com/370522089): See if `SkCodec` can be tweaked to avoid
975 // the need to hide the stream from it.
getEncodedData() const976 std::unique_ptr<SkStream> SkWuffsCodec::getEncodedData() const {
977     SkASSERT(fPrivStream);
978     return fPrivStream->duplicate();
979 }
980 
981 namespace SkGifDecoder {
982 
IsGif(const void * buf,size_t bytesRead)983 bool IsGif(const void* buf, size_t bytesRead) {
984     constexpr const char* gif_ptr = "GIF8";
985     constexpr size_t      gif_len = 4;
986     return (bytesRead >= gif_len) && (memcmp(buf, gif_ptr, gif_len) == 0);
987 }
988 
MakeFromStream(std::unique_ptr<SkStream> stream,SkCodec::SelectionPolicy selectionPolicy,SkCodec::Result * result)989 std::unique_ptr<SkCodec> MakeFromStream(std::unique_ptr<SkStream> stream,
990                                         SkCodec::SelectionPolicy  selectionPolicy,
991                                         SkCodec::Result*          result) {
992     SkASSERT(result);
993     if (!stream) {
994         *result = SkCodec::kInvalidInput;
995         return nullptr;
996     }
997 
998     bool canSeek = stream->hasPosition() && stream->hasLength();
999 
1000     if (selectionPolicy != SkCodec::SelectionPolicy::kPreferStillImage) {
1001         // Some clients (e.g. Android) need to be able to seek the stream, but may
1002         // not provide a seekable stream. Copy the stream to one that can seek.
1003         if (!canSeek) {
1004             auto data = SkCopyStreamToData(stream.get());
1005             stream = std::make_unique<SkMemoryStream>(std::move(data));
1006             canSeek = true;
1007         }
1008     }
1009 
1010     uint8_t               buffer[SK_WUFFS_CODEC_BUFFER_SIZE];
1011     wuffs_base__io_buffer iobuf =
1012         wuffs_base__make_io_buffer(wuffs_base__make_slice_u8(buffer, SK_WUFFS_CODEC_BUFFER_SIZE),
1013                                    wuffs_base__empty_io_buffer_meta());
1014     wuffs_base__image_config imgcfg = wuffs_base__null_image_config();
1015 
1016     // Wuffs is primarily a C library, not a C++ one. Furthermore, outside of
1017     // the wuffs_base__etc types, the sizeof a file format specific type like
1018     // GIF's wuffs_gif__decoder can vary between Wuffs versions. If p is of
1019     // type wuffs_gif__decoder*, then the supported API treats p as a pointer
1020     // to an opaque type: a private implementation detail. The API is always
1021     // "set_foo(p, etc)" and not "p->foo = etc".
1022     //
1023     // See https://en.wikipedia.org/wiki/Opaque_pointer#C
1024     //
1025     // Thus, we don't use C++'s new operator (which requires knowing the sizeof
1026     // the struct at compile time). Instead, we use sk_malloc_canfail, with
1027     // sizeof__wuffs_gif__decoder returning the appropriate value for the
1028     // (statically or dynamically) linked version of the Wuffs library.
1029     //
1030     // As a C (not C++) library, none of the Wuffs types have constructors or
1031     // destructors.
1032     //
1033     // In RAII style, we can still use std::unique_ptr with these pointers, but
1034     // we pair the pointer with sk_free instead of C++'s delete.
1035     void* decoder_raw = sk_malloc_canfail(sizeof__wuffs_gif__decoder());
1036     if (!decoder_raw) {
1037         *result = SkCodec::kInternalError;
1038         return nullptr;
1039     }
1040     std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> decoder(
1041         reinterpret_cast<wuffs_gif__decoder*>(decoder_raw), &sk_free);
1042 
1043     SkCodec::Result reset_result =
1044         reset_and_decode_image_config(decoder.get(), &imgcfg, &iobuf, stream.get());
1045     if (reset_result != SkCodec::kSuccess) {
1046         *result = reset_result;
1047         return nullptr;
1048     }
1049 
1050     uint32_t width = imgcfg.pixcfg.width();
1051     uint32_t height = imgcfg.pixcfg.height();
1052     if ((width == 0) || (width > INT_MAX) || (height == 0) || (height > INT_MAX)) {
1053         *result = SkCodec::kInvalidInput;
1054         return nullptr;
1055     }
1056 
1057     uint64_t workbuf_len = decoder->workbuf_len().max_incl;
1058     void*    workbuf_ptr_raw = nullptr;
1059     if (workbuf_len) {
1060         workbuf_ptr_raw = workbuf_len <= SIZE_MAX ? sk_malloc_canfail(workbuf_len) : nullptr;
1061         if (!workbuf_ptr_raw) {
1062             *result = SkCodec::kInternalError;
1063             return nullptr;
1064         }
1065     }
1066     std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr(
1067         reinterpret_cast<uint8_t*>(workbuf_ptr_raw), &sk_free);
1068 
1069     SkEncodedInfo::Color color =
1070         (imgcfg.pixcfg.pixel_format().repr == WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL)
1071             ? SkEncodedInfo::kBGRA_Color
1072             : SkEncodedInfo::kRGBA_Color;
1073 
1074     // In Skia's API, the alpha we calculate here and return is only for the
1075     // first frame.
1076     SkEncodedInfo::Alpha alpha = imgcfg.first_frame_is_opaque() ? SkEncodedInfo::kOpaque_Alpha
1077                                                                 : SkEncodedInfo::kBinary_Alpha;
1078 
1079     SkEncodedInfo encodedInfo = SkEncodedInfo::Make(width, height, color, alpha, 8);
1080 
1081     *result = SkCodec::kSuccess;
1082     return std::unique_ptr<SkCodec>(new SkWuffsCodec(std::move(encodedInfo), std::move(stream),
1083                                                      canSeek,
1084                                                      std::move(decoder), std::move(workbuf_ptr),
1085                                                      workbuf_len, imgcfg, iobuf));
1086 }
1087 
Decode(std::unique_ptr<SkStream> stream,SkCodec::Result * outResult,SkCodecs::DecodeContext ctx)1088 std::unique_ptr<SkCodec> Decode(std::unique_ptr<SkStream> stream,
1089                                 SkCodec::Result* outResult,
1090                                 SkCodecs::DecodeContext ctx) {
1091     SkCodec::Result resultStorage;
1092     if (!outResult) {
1093         outResult = &resultStorage;
1094     }
1095     auto policy = SkCodec::SelectionPolicy::kPreferStillImage;
1096     if (ctx) {
1097         policy = *static_cast<SkCodec::SelectionPolicy*>(ctx);
1098     }
1099     return MakeFromStream(std::move(stream), policy, outResult);
1100 }
1101 
Decode(sk_sp<SkData> data,SkCodec::Result * outResult,SkCodecs::DecodeContext ctx)1102 std::unique_ptr<SkCodec> Decode(sk_sp<SkData> data,
1103                                 SkCodec::Result* outResult,
1104                                 SkCodecs::DecodeContext ctx) {
1105     if (!data) {
1106         if (outResult) {
1107             *outResult = SkCodec::kInvalidInput;
1108         }
1109         return nullptr;
1110     }
1111     return Decode(SkMemoryStream::Make(std::move(data)), outResult, ctx);
1112 }
1113 }  // namespace SkGifDecoder
1114 
1115