• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2015 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 "src/codec/SkWebpCodec.h"
9 
10 #include "include/codec/SkCodec.h"
11 #include "include/codec/SkCodecAnimation.h"
12 #include "include/codec/SkWebpDecoder.h"
13 #include "include/core/SkAlphaType.h"
14 #include "include/core/SkBitmap.h"
15 #include "include/core/SkColorType.h"
16 #include "include/core/SkImageInfo.h"
17 #include "include/core/SkRect.h"
18 #include "include/core/SkSize.h"
19 #include "include/core/SkStream.h"
20 #include "include/private/base/SkAlign.h"
21 #include "include/private/base/SkMath.h"
22 #include "include/private/base/SkNoncopyable.h"
23 #include "include/private/base/SkTFitsIn.h"
24 #include "include/private/base/SkTemplates.h"
25 #include "include/private/base/SkTo.h"
26 #include "modules/skcms/skcms.h"
27 #include "src/codec/SkParseEncodedOrigin.h"
28 #include "src/codec/SkSampler.h"
29 #include "src/core/SkRasterPipeline.h"
30 #include "src/core/SkRasterPipelineOpContexts.h"
31 #include "src/core/SkRasterPipelineOpList.h"
32 #include "src/core/SkStreamPriv.h"
33 
34 #include <algorithm>
35 #include <cstdint>
36 #include <cstring>
37 #include <optional>
38 #include <utility>
39 
40 // A WebP decoder on top of (subset of) libwebp
41 // For more information on WebP image format, and libwebp library, see:
42 //   https://code.google.com/speed/webp/
43 //   http://www.webmproject.org/code/#libwebp-webp-image-library
44 //   https://chromium.googlesource.com/webm/libwebp
45 
46 // If moving libwebp out of skia source tree, path for webp headers must be
47 // updated accordingly. Here, we enforce using local copy in webp sub-directory.
48 #include "webp/decode.h"  // NO_G3_REWRITE
49 #include "webp/demux.h"  // NO_G3_REWRITE
50 #include "webp/mux_types.h"  // NO_G3_REWRITE
51 #include "plugin/hispeed_plugin.h"
52 
53 #ifdef USE_HISPEED_PLUGIN
54 
55 struct HispeedPluginLoader {
HispeedPluginLoaderHispeedPluginLoader56     HispeedPluginLoader() {
57         WebPLoadHispeedPlugin();
58     }
59 
~HispeedPluginLoaderHispeedPluginLoader60     ~HispeedPluginLoader() {
61         WebPUnloadHispeedPlugin();
62     }
63 };
64 
65 static HispeedPluginLoader hispeedPluginLoader;
66 #endif
67 
IsWebp(const void * buf,size_t bytesRead)68 bool SkWebpCodec::IsWebp(const void* buf, size_t bytesRead) {
69     // WEBP starts with the following:
70     // RIFFXXXXWEBPVP
71     // Where XXXX is unspecified.
72     const char* bytes = static_cast<const char*>(buf);
73     return bytesRead >= 14 && !memcmp(bytes, "RIFF", 4) && !memcmp(&bytes[8], "WEBPVP", 6);
74 }
75 
76 // Parse headers of RIFF container, and check for valid Webp (VP8) content.
77 // Returns an SkWebpCodec on success
MakeFromStream(std::unique_ptr<SkStream> stream,Result * result)78 std::unique_ptr<SkCodec> SkWebpCodec::MakeFromStream(std::unique_ptr<SkStream> stream,
79                                                      Result* result) {
80     SkASSERT(result);
81     if (!stream) {
82         *result = SkCodec::kInvalidInput;
83         return nullptr;
84     }
85     // Webp demux needs a contiguous data buffer.
86     sk_sp<SkData> data = nullptr;
87     if (stream->getMemoryBase()) {
88         // It is safe to make without copy because we'll hold onto the stream.
89         data = SkData::MakeWithoutCopy(stream->getMemoryBase(), stream->getLength());
90     } else {
91         data = SkCopyStreamToData(stream.get());
92 
93         // If we are forced to copy the stream to a data, we can go ahead and delete the stream.
94         stream.reset(nullptr);
95     }
96 
97     // It's a little strange that the |demux| will outlive |webpData|, though it needs the
98     // pointer in |webpData| to remain valid.  This works because the pointer remains valid
99     // until the SkData is freed.
100     WebPData webpData = { data->bytes(), data->size() };
101     WebPDemuxState state;
102     SkAutoTCallVProc<WebPDemuxer, WebPDemuxDelete> demux(WebPDemuxPartial(&webpData, &state));
103     switch (state) {
104         case WEBP_DEMUX_PARSE_ERROR:
105             *result = kInvalidInput;
106             return nullptr;
107         case WEBP_DEMUX_PARSING_HEADER:
108             *result = kIncompleteInput;
109             return nullptr;
110         case WEBP_DEMUX_PARSED_HEADER:
111         case WEBP_DEMUX_DONE:
112             SkASSERT(demux);
113             break;
114     }
115 
116     const int width = WebPDemuxGetI(demux, WEBP_FF_CANVAS_WIDTH);
117     const int height = WebPDemuxGetI(demux, WEBP_FF_CANVAS_HEIGHT);
118 
119     // Validate the image size that's about to be decoded.
120     {
121         const int64_t size = sk_64_mul(width, height);
122         // now check that if we are 4-bytes per pixel, we also don't overflow
123         if (!SkTFitsIn<int32_t>(size) || SkTo<int32_t>(size) > (0x7FFFFFFF >> 2)) {
124             *result = kInvalidInput;
125             return nullptr;
126         }
127     }
128 
129     std::unique_ptr<SkEncodedInfo::ICCProfile> profile = nullptr;
130     {
131         WebPChunkIterator chunkIterator;
132         SkAutoTCallVProc<WebPChunkIterator, WebPDemuxReleaseChunkIterator> autoCI(&chunkIterator);
133         if (WebPDemuxGetChunk(demux, "ICCP", 1, &chunkIterator)) {
134             // FIXME: I think this could be MakeWithoutCopy
135             auto chunk = SkData::MakeWithCopy(chunkIterator.chunk.bytes, chunkIterator.chunk.size);
136             profile = SkEncodedInfo::ICCProfile::Make(std::move(chunk));
137         }
138         if (profile && profile->profile()->data_color_space != skcms_Signature_RGB) {
139             profile = nullptr;
140         }
141     }
142 
143     SkEncodedOrigin origin = kDefault_SkEncodedOrigin;
144     {
145         WebPChunkIterator chunkIterator;
146         SkAutoTCallVProc<WebPChunkIterator, WebPDemuxReleaseChunkIterator> autoCI(&chunkIterator);
147         if (WebPDemuxGetChunk(demux, "EXIF", 1, &chunkIterator)) {
148             SkParseEncodedOrigin(chunkIterator.chunk.bytes, chunkIterator.chunk.size, &origin);
149         }
150     }
151 
152     // Get the first frame and its "features" to determine the color and alpha types.
153     WebPIterator frame;
154     SkAutoTCallVProc<WebPIterator, WebPDemuxReleaseIterator> autoFrame(&frame);
155     if (!WebPDemuxGetFrame(demux, 1, &frame)) {
156         *result = kIncompleteInput;
157         return nullptr;
158     }
159 
160     WebPBitstreamFeatures features;
161     switch (WebPGetFeatures(frame.fragment.bytes, frame.fragment.size, &features)) {
162         case VP8_STATUS_OK:
163             break;
164         case VP8_STATUS_SUSPENDED:
165         case VP8_STATUS_NOT_ENOUGH_DATA:
166             *result = kIncompleteInput;
167             return nullptr;
168         default:
169             *result = kInvalidInput;
170             return nullptr;
171     }
172 
173     const bool hasAlpha = SkToBool(frame.has_alpha)
174             || frame.width != width || frame.height != height;
175     SkEncodedInfo::Color color;
176     SkEncodedInfo::Alpha alpha;
177     switch (features.format) {
178         case 0:
179             // This indicates a "mixed" format.  We could see this for
180             // animated webps (multiple fragments).
181             // We could also guess kYUV here, but I think it makes more
182             // sense to guess kBGRA which is likely closer to the final
183             // output.  Otherwise, we might end up converting
184             // BGRA->YUVA->BGRA.
185             [[fallthrough]];
186         case 2:
187             // This is the lossless format (BGRA).
188             if (hasAlpha) {
189                 color = SkEncodedInfo::kBGRA_Color;
190                 alpha = SkEncodedInfo::kUnpremul_Alpha;
191             } else {
192                 color = SkEncodedInfo::kBGRX_Color;
193                 alpha = SkEncodedInfo::kOpaque_Alpha;
194             }
195             break;
196         case 1:
197             // This is the lossy format (YUV).
198             if (hasAlpha) {
199                 color = SkEncodedInfo::kYUVA_Color;
200                 alpha = SkEncodedInfo::kUnpremul_Alpha;
201             } else {
202                 color = SkEncodedInfo::kYUV_Color;
203                 alpha = SkEncodedInfo::kOpaque_Alpha;
204             }
205             break;
206         default:
207             *result = kInvalidInput;
208             return nullptr;
209     }
210 
211 
212     *result = kSuccess;
213     SkEncodedInfo info = SkEncodedInfo::Make(width, height, color, alpha, 8, std::move(profile));
214     return std::unique_ptr<SkCodec>(new SkWebpCodec(std::move(info), std::move(stream),
215                                                     demux.release(), std::move(data), origin));
216 }
217 
webp_decode_mode(SkColorType dstCT,bool premultiply)218 static WEBP_CSP_MODE webp_decode_mode(SkColorType dstCT, bool premultiply) {
219     switch (dstCT) {
220         case kBGRA_8888_SkColorType:
221             return premultiply ? MODE_bgrA : MODE_BGRA;
222         case kRGBA_8888_SkColorType:
223             return premultiply ? MODE_rgbA : MODE_RGBA;
224         case kRGB_565_SkColorType:
225             return MODE_RGB_565;
226         default:
227             return MODE_LAST;
228     }
229 }
230 
appendNewFrame(bool hasAlpha)231 SkWebpCodec::Frame* SkWebpCodec::FrameHolder::appendNewFrame(bool hasAlpha) {
232     const int i = this->size();
233     fFrames.emplace_back(i, hasAlpha ? SkEncodedInfo::kUnpremul_Alpha
234                                      : SkEncodedInfo::kOpaque_Alpha);
235     return &fFrames[i];
236 }
237 
onGetValidSubset(SkIRect * desiredSubset) const238 bool SkWebpCodec::onGetValidSubset(SkIRect* desiredSubset) const {
239     if (!desiredSubset) {
240         return false;
241     }
242 
243     if (!this->bounds().contains(*desiredSubset)) {
244         return false;
245     }
246 
247     // As stated below, libwebp snaps to even left and top. Make sure top and left are even, so we
248     // decode this exact subset.
249     // Leave right and bottom unmodified, so we suggest a slightly larger subset than requested.
250     desiredSubset->fLeft = (desiredSubset->fLeft >> 1) << 1;
251     desiredSubset->fTop = (desiredSubset->fTop >> 1) << 1;
252     return true;
253 }
254 
onGetRepetitionCount()255 int SkWebpCodec::onGetRepetitionCount() {
256     auto flags = WebPDemuxGetI(fDemux.get(), WEBP_FF_FORMAT_FLAGS);
257     if (!(flags & ANIMATION_FLAG)) {
258         return 0;
259     }
260 
261     int loopCount = WebPDemuxGetI(fDemux.get(), WEBP_FF_LOOP_COUNT);
262     if (0 == loopCount) {
263         return kRepetitionCountInfinite;
264     }
265 
266     loopCount--;
267     return loopCount;
268 }
269 
onGetFrameCount()270 int SkWebpCodec::onGetFrameCount() {
271     auto flags = WebPDemuxGetI(fDemux.get(), WEBP_FF_FORMAT_FLAGS);
272     if (!(flags & ANIMATION_FLAG)) {
273         return 1;
274     }
275 
276     const uint32_t oldFrameCount = fFrameHolder.size();
277     if (fFailed) {
278         return oldFrameCount;
279     }
280 
281     const uint32_t frameCount = WebPDemuxGetI(fDemux, WEBP_FF_FRAME_COUNT);
282     if (oldFrameCount == frameCount) {
283         // We have already parsed this.
284         return frameCount;
285     }
286 
287     fFrameHolder.reserve(frameCount);
288 
289     for (uint32_t i = oldFrameCount; i < frameCount; i++) {
290         WebPIterator iter;
291         SkAutoTCallVProc<WebPIterator, WebPDemuxReleaseIterator> autoIter(&iter);
292 
293         if (!WebPDemuxGetFrame(fDemux.get(), i + 1, &iter)) {
294             fFailed = true;
295             break;
296         }
297 
298         // libwebp only reports complete frames of an animated image.
299         SkASSERT(iter.complete);
300 
301         Frame* frame = fFrameHolder.appendNewFrame(iter.has_alpha);
302         frame->setXYWH(iter.x_offset, iter.y_offset, iter.width, iter.height);
303         frame->setDisposalMethod(iter.dispose_method == WEBP_MUX_DISPOSE_BACKGROUND ?
304                 SkCodecAnimation::DisposalMethod::kRestoreBGColor :
305                 SkCodecAnimation::DisposalMethod::kKeep);
306         frame->setDuration(iter.duration);
307         if (WEBP_MUX_BLEND != iter.blend_method) {
308             frame->setBlend(SkCodecAnimation::Blend::kSrc);
309         }
310         fFrameHolder.setAlphaAndRequiredFrame(frame);
311     }
312 
313     return fFrameHolder.size();
314 
315 }
316 
onGetFrame(int i) const317 const SkFrame* SkWebpCodec::FrameHolder::onGetFrame(int i) const {
318     return static_cast<const SkFrame*>(this->frame(i));
319 }
320 
frame(int i) const321 const SkWebpCodec::Frame* SkWebpCodec::FrameHolder::frame(int i) const {
322     SkASSERT(i >= 0 && i < this->size());
323     return &fFrames[i];
324 }
325 
onGetFrameInfo(int i,FrameInfo * frameInfo) const326 bool SkWebpCodec::onGetFrameInfo(int i, FrameInfo* frameInfo) const {
327     if (i >= fFrameHolder.size()) {
328         return false;
329     }
330 
331     const Frame* frame = fFrameHolder.frame(i);
332     if (!frame) {
333         return false;
334     }
335 
336     if (frameInfo) {
337         // libwebp only reports fully received frames for an
338         // animated image.
339         frame->fillIn(frameInfo, true);
340     }
341 
342     return true;
343 }
344 
is_8888(SkColorType colorType)345 static bool is_8888(SkColorType colorType) {
346     switch (colorType) {
347         case kRGBA_8888_SkColorType:
348         case kBGRA_8888_SkColorType:
349             return true;
350         default:
351             return false;
352     }
353 }
354 
355 namespace {
356 
357 // Requires that the src input be unpremultiplied (or opaque).
358 class RPBlender final : SkNoncopyable {
359 public:
RPBlender(SkColorType dstCT,SkColorType srcCT,SkAlphaType dstAt,bool srcHasAlpha)360     RPBlender(SkColorType dstCT, SkColorType srcCT, SkAlphaType dstAt, bool srcHasAlpha)
361     {
362         fRP.appendLoadDst(dstCT, &fDstCtx);
363         if (kUnpremul_SkAlphaType == dstAt) {
364             fRP.append(SkRasterPipelineOp::premul_dst);
365         }
366 
367         fRP.appendLoad(srcCT, &fSrcCtx);
368         if (srcHasAlpha) {
369             fRP.append(SkRasterPipelineOp::premul);
370         }
371 
372         fRP.append(SkRasterPipelineOp::srcover);
373 
374         if (kUnpremul_SkAlphaType == dstAt) {
375             fRP.append(SkRasterPipelineOp::unpremul);
376         }
377         fRP.appendStore(dstCT, &fDstCtx);
378     }
379 
blendLine(void * dst,const void * src,int width)380     void blendLine(void* dst, const void* src, int width) {
381         fDstCtx = {                    dst, 0 };
382         fSrcCtx = { const_cast<void*>(src), 0 };
383 
384         fRP.run(0, 0, width, 1);
385     }
386 
387 private:
388     SkRasterPipeline_MemoryCtx fDstCtx, fSrcCtx;
389 
390     SkRasterPipeline_<256> fRP;
391 };
392 
393 }  // namespace
394 
onGetPixels(const SkImageInfo & dstInfo,void * dst,size_t rowBytes,const Options & options,int * rowsDecodedPtr)395 SkCodec::Result SkWebpCodec::onGetPixels(const SkImageInfo& dstInfo, void* dst, size_t rowBytes,
396                                          const Options& options, int* rowsDecodedPtr) {
397     const int index = options.fFrameIndex;
398     SkASSERT(0 == index || index < fFrameHolder.size());
399     SkASSERT(0 == index || !options.fSubset);
400 
401     WebPDecoderConfig config;
402     if (0 == WebPInitDecoderConfig(&config)) {
403         // ABI mismatch.
404         // FIXME: New enum for this?
405         return kInvalidInput;
406     }
407 
408     // Free any memory associated with the buffer. Must be called last, so we declare it first.
409     SkAutoTCallVProc<WebPDecBuffer, WebPFreeDecBuffer> autoFree(&(config.output));
410 
411     WebPIterator frame;
412     SkAutoTCallVProc<WebPIterator, WebPDemuxReleaseIterator> autoFrame(&frame);
413     // If this succeeded in onGetFrameCount(), it should succeed again here.
414     SkAssertResult(WebPDemuxGetFrame(fDemux, index + 1, &frame));
415 
416     const bool independent = index == 0 ? true :
417             (fFrameHolder.frame(index)->getRequiredFrame() == kNoFrame);
418     // Get the frameRect.  libwebp will have already signaled an error if this is not fully
419     // contained by the canvas.
420     auto frameRect = SkIRect::MakeXYWH(frame.x_offset, frame.y_offset, frame.width, frame.height);
421     SkASSERT(this->bounds().contains(frameRect));
422     const bool frameIsSubset = frameRect != this->bounds();
423     if (independent && frameIsSubset) {
424         SkSampler::Fill(dstInfo, dst, rowBytes, options.fZeroInitialized);
425     }
426 
427     int dstX = frameRect.x();
428     int dstY = frameRect.y();
429     int subsetWidth = frameRect.width();
430     int subsetHeight = frameRect.height();
431     if (options.fSubset) {
432         SkIRect subset = *options.fSubset;
433         SkASSERT(this->bounds().contains(subset));
434         SkASSERT(SkIsAlign2(subset.fLeft) && SkIsAlign2(subset.fTop));
435         SkASSERT(this->getValidSubset(&subset) && subset == *options.fSubset);
436 
437         if (!SkIRect::Intersects(subset, frameRect)) {
438             return kSuccess;
439         }
440 
441         int minXOffset = std::min(dstX, subset.x());
442         int minYOffset = std::min(dstY, subset.y());
443         dstX -= minXOffset;
444         dstY -= minYOffset;
445         frameRect.offset(-minXOffset, -minYOffset);
446         subset.offset(-minXOffset, -minYOffset);
447 
448         // Just like we require that the requested subset x and y offset are even, libwebp
449         // guarantees that the frame x and y offset are even (it's actually impossible to specify
450         // an odd frame offset).  So we can still guarantee that the adjusted offsets are even.
451         SkASSERT(SkIsAlign2(subset.fLeft) && SkIsAlign2(subset.fTop));
452 
453         SkIRect intersection;
454         SkAssertResult(intersection.intersect(frameRect, subset));
455         subsetWidth = intersection.width();
456         subsetHeight = intersection.height();
457 
458         config.options.use_cropping = 1;
459         config.options.crop_left = subset.x();
460         config.options.crop_top = subset.y();
461         config.options.crop_width = subsetWidth;
462         config.options.crop_height = subsetHeight;
463     }
464 
465     // Ignore the frame size and offset when determining if scaling is necessary.
466     int scaledWidth = subsetWidth;
467     int scaledHeight = subsetHeight;
468     SkISize srcSize = options.fSubset ? options.fSubset->size() : this->dimensions();
469     if (srcSize != dstInfo.dimensions()) {
470         config.options.use_scaling = 1;
471 
472         if (frameIsSubset) {
473             float scaleX = ((float) dstInfo.width()) / srcSize.width();
474             float scaleY = ((float) dstInfo.height()) / srcSize.height();
475 
476             // We need to be conservative here and floor rather than round.
477             // Otherwise, we may find ourselves decoding off the end of memory.
478             dstX = scaleX * dstX;
479             scaledWidth = scaleX * scaledWidth;
480             dstY = scaleY * dstY;
481             scaledHeight = scaleY * scaledHeight;
482             if (0 == scaledWidth || 0 == scaledHeight) {
483                 return kSuccess;
484             }
485         } else {
486             scaledWidth = dstInfo.width();
487             scaledHeight = dstInfo.height();
488         }
489 
490         config.options.scaled_width = scaledWidth;
491         config.options.scaled_height = scaledHeight;
492     }
493 
494     const bool blendWithPrevFrame = !independent && frame.blend_method == WEBP_MUX_BLEND
495         && frame.has_alpha;
496 
497     auto webpInfo = dstInfo;
498     if (!frame.has_alpha) {
499         webpInfo = webpInfo.makeAlphaType(kOpaque_SkAlphaType);
500     } else if (this->colorXform() || blendWithPrevFrame) {
501         // the colorXform and blend_line expect unpremul.
502         webpInfo = webpInfo.makeAlphaType(kUnpremul_SkAlphaType);
503     }
504     if (this->colorXform()) {
505         // Swizzling between RGBA and BGRA is zero cost in a color transform.  So when we have a
506         // color transform, we should decode to whatever is easiest for libwebp, and then let the
507         // color transform swizzle if necessary.
508         // Lossy webp is encoded as YUV (so RGBA and BGRA are the same cost).  Lossless webp is
509         // encoded as BGRA. This means decoding to BGRA is either faster or the same cost as RGBA.
510         webpInfo = webpInfo.makeColorType(kBGRA_8888_SkColorType);
511     }
512 
513     SkBitmap webpDst;
514     if ((this->colorXform() && !is_8888(dstInfo.colorType())) || blendWithPrevFrame) {
515         // We will decode the entire image and then perform the color transform.  libwebp
516         // does not provide a row-by-row API.  This is a shame particularly when we do not want
517         // 8888, since we will need to create another image sized buffer.
518         webpDst.allocPixels(webpInfo);
519     } else {
520         // libwebp can decode directly into the output memory.
521         webpDst.installPixels(webpInfo, dst, rowBytes);
522     }
523 
524     config.output.colorspace = webp_decode_mode(webpInfo.colorType(),
525             webpInfo.alphaType() == kPremul_SkAlphaType);
526     config.output.is_external_memory = 1;
527 
528     config.output.u.RGBA.rgba = reinterpret_cast<uint8_t*>(webpDst.getAddr(dstX, dstY));
529     config.output.u.RGBA.stride = static_cast<int>(webpDst.rowBytes());
530     config.output.u.RGBA.size = webpDst.computeByteSize();
531 
532     SkAutoTCallVProc<WebPIDecoder, WebPIDelete> idec(WebPIDecode(nullptr, 0, &config));
533     if (!idec) {
534         return kInvalidInput;
535     }
536 
537     int rowsDecoded = 0;
538     SkCodec::Result result;
539     switch (WebPIUpdate(idec, frame.fragment.bytes, frame.fragment.size)) {
540         case VP8_STATUS_OK:
541             rowsDecoded = scaledHeight;
542             result = kSuccess;
543             break;
544         case VP8_STATUS_SUSPENDED:
545             if (!WebPIDecGetRGB(idec, &rowsDecoded, nullptr, nullptr, nullptr)
546                     || rowsDecoded <= 0) {
547                 return kInvalidInput;
548             }
549             *rowsDecodedPtr = rowsDecoded + dstY;
550             result = kIncompleteInput;
551             break;
552         default:
553             return kInvalidInput;
554     }
555 
556     const size_t dstBpp = dstInfo.bytesPerPixel();
557     dst = SkTAddOffset<void>(dst, dstBpp * dstX + rowBytes * dstY);
558     const size_t srcRowBytes = config.output.u.RGBA.stride;
559 
560     const auto dstCT = dstInfo.colorType();
561     if (this->colorXform()) {
562         uint32_t* xformSrc = (uint32_t*) config.output.u.RGBA.rgba;
563         SkBitmap tmp;
564         void* xformDst;
565 
566         if (blendWithPrevFrame) {
567             // Xform into temporary bitmap big enough for one row.
568             tmp.allocPixels(dstInfo.makeWH(scaledWidth, 1));
569             xformDst = tmp.getPixels();
570         } else {
571             xformDst = dst;
572         }
573 
574         std::optional<RPBlender> blender;
575         if (blendWithPrevFrame) {
576             blender.emplace(dstCT, dstCT, dstInfo.alphaType(), frame.has_alpha);
577         }
578 
579         for (int y = 0; y < rowsDecoded; y++) {
580             this->applyColorXform(xformDst, xformSrc, scaledWidth);
581             if (blendWithPrevFrame) {
582                 blender->blendLine(dst, xformDst, scaledWidth);
583                 dst = SkTAddOffset<void>(dst, rowBytes);
584             } else {
585                 xformDst = SkTAddOffset<void>(xformDst, rowBytes);
586             }
587             xformSrc = SkTAddOffset<uint32_t>(xformSrc, srcRowBytes);
588         }
589     } else if (blendWithPrevFrame) {
590         RPBlender blender(dstCT, webpDst.colorType(), dstInfo.alphaType(), frame.has_alpha);
591 
592         const uint8_t* src = config.output.u.RGBA.rgba;
593 
594         for (int y = 0; y < rowsDecoded; y++) {
595             blender.blendLine(dst, src, scaledWidth);
596             src = SkTAddOffset<const uint8_t>(src, srcRowBytes);
597             dst = SkTAddOffset<void>(dst, rowBytes);
598         }
599     }
600 
601     return result;
602 }
603 
SkWebpCodec(SkEncodedInfo && info,std::unique_ptr<SkStream> stream,WebPDemuxer * demux,sk_sp<SkData> data,SkEncodedOrigin origin)604 SkWebpCodec::SkWebpCodec(SkEncodedInfo&& info, std::unique_ptr<SkStream> stream,
605                          WebPDemuxer* demux, sk_sp<SkData> data, SkEncodedOrigin origin)
606     : INHERITED(std::move(info), skcms_PixelFormat_BGRA_8888, std::move(stream),
607                 origin)
608     , fDemux(demux)
609     , fData(std::move(data))
610     , fFailed(false)
611 {
612     const auto& eInfo = this->getEncodedInfo();
613     fFrameHolder.setScreenSize(eInfo.width(), eInfo.height());
614 }
615 
616 namespace SkWebpDecoder {
IsWebp(const void * data,size_t len)617 bool IsWebp(const void* data, size_t len) {
618     return SkWebpCodec::IsWebp(data, len);
619 }
620 
Decode(std::unique_ptr<SkStream> stream,SkCodec::Result * outResult,SkCodecs::DecodeContext)621 std::unique_ptr<SkCodec> Decode(std::unique_ptr<SkStream> stream,
622                                 SkCodec::Result* outResult,
623                                 SkCodecs::DecodeContext) {
624     SkCodec::Result resultStorage;
625     if (!outResult) {
626         outResult = &resultStorage;
627     }
628     return SkWebpCodec::MakeFromStream(std::move(stream), outResult);
629 }
630 
Decode(sk_sp<SkData> data,SkCodec::Result * outResult,SkCodecs::DecodeContext)631 std::unique_ptr<SkCodec> Decode(sk_sp<SkData> data,
632                                 SkCodec::Result* outResult,
633                                 SkCodecs::DecodeContext) {
634     if (!data) {
635         if (outResult) {
636             *outResult = SkCodec::kInvalidInput;
637         }
638         return nullptr;
639     }
640     return Decode(SkMemoryStream::Make(std::move(data)), outResult, nullptr);
641 }
642 }  // namespace SkWebpDecoder
643