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