blob: 68301b93f836ca8f78e0b78fb45ffbb3447e2bca [file] [log] [blame]
scroggo6f5e6192015-06-18 12:53:43 -07001/*
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
Leon Scroggins III557fbbe2017-05-23 09:37:21 -04008#include "SkBitmap.h"
9#include "SkCanvas.h"
Leon Scroggins III33deb7e2017-06-07 12:31:51 -040010#include "SkCodecAnimation.h"
11#include "SkCodecAnimationPriv.h"
scroggocc2feb12015-08-14 08:32:46 -070012#include "SkCodecPriv.h"
msarette99883f2016-09-08 06:05:35 -070013#include "SkColorSpaceXform.h"
Leon Scroggins III557fbbe2017-05-23 09:37:21 -040014#include "SkRasterPipeline.h"
Matt Sarett5c496172017-02-07 17:01:16 -050015#include "SkSampler.h"
msarettff2a6c82016-09-07 11:23:28 -070016#include "SkStreamPriv.h"
scroggo6f5e6192015-06-18 12:53:43 -070017#include "SkTemplates.h"
Matt Sarett5c496172017-02-07 17:01:16 -050018#include "SkWebpCodec.h"
scroggo6f5e6192015-06-18 12:53:43 -070019
20// A WebP decoder on top of (subset of) libwebp
21// For more information on WebP image format, and libwebp library, see:
22// https://code.google.com/speed/webp/
23// http://www.webmproject.org/code/#libwebp-webp-image-library
24// https://chromium.googlesource.com/webm/libwebp
25
26// If moving libwebp out of skia source tree, path for webp headers must be
27// updated accordingly. Here, we enforce using local copy in webp sub-directory.
28#include "webp/decode.h"
msarett9d15dab2016-08-24 07:36:06 -070029#include "webp/demux.h"
scroggo6f5e6192015-06-18 12:53:43 -070030#include "webp/encode.h"
31
scroggodb30be22015-12-08 18:54:13 -080032bool SkWebpCodec::IsWebp(const void* buf, size_t bytesRead) {
scroggo6f5e6192015-06-18 12:53:43 -070033 // WEBP starts with the following:
34 // RIFFXXXXWEBPVP
35 // Where XXXX is unspecified.
scroggodb30be22015-12-08 18:54:13 -080036 const char* bytes = static_cast<const char*>(buf);
37 return bytesRead >= 14 && !memcmp(bytes, "RIFF", 4) && !memcmp(&bytes[8], "WEBPVP", 6);
scroggo6f5e6192015-06-18 12:53:43 -070038}
39
Leon Scroggins III557fbbe2017-05-23 09:37:21 -040040static SkAlphaType alpha_type(bool hasAlpha) {
41 return hasAlpha ? kUnpremul_SkAlphaType : kOpaque_SkAlphaType;
42}
43
scroggo6f5e6192015-06-18 12:53:43 -070044// Parse headers of RIFF container, and check for valid Webp (VP8) content.
Leon Scroggins III557fbbe2017-05-23 09:37:21 -040045// Returns an SkWebpCodec on success
msarettac6c7502016-04-25 09:30:24 -070046SkCodec* SkWebpCodec::NewFromStream(SkStream* stream) {
Ben Wagner145dbcd2016-11-03 14:40:50 -040047 std::unique_ptr<SkStream> streamDeleter(stream);
msarettac6c7502016-04-25 09:30:24 -070048
msarettff2a6c82016-09-07 11:23:28 -070049 // Webp demux needs a contiguous data buffer.
50 sk_sp<SkData> data = nullptr;
51 if (stream->getMemoryBase()) {
52 // It is safe to make without copy because we'll hold onto the stream.
53 data = SkData::MakeWithoutCopy(stream->getMemoryBase(), stream->getLength());
54 } else {
55 data = SkCopyStreamToData(stream);
scroggodb30be22015-12-08 18:54:13 -080056
msarettff2a6c82016-09-07 11:23:28 -070057 // If we are forced to copy the stream to a data, we can go ahead and delete the stream.
58 streamDeleter.reset(nullptr);
59 }
60
61 // It's a little strange that the |demux| will outlive |webpData|, though it needs the
62 // pointer in |webpData| to remain valid. This works because the pointer remains valid
63 // until the SkData is freed.
64 WebPData webpData = { data->bytes(), data->size() };
65 SkAutoTCallVProc<WebPDemuxer, WebPDemuxDelete> demux(WebPDemuxPartial(&webpData, nullptr));
66 if (nullptr == demux) {
msarettac6c7502016-04-25 09:30:24 -070067 return nullptr;
scroggo6f5e6192015-06-18 12:53:43 -070068 }
69
Matt Sarett5c496172017-02-07 17:01:16 -050070 const int width = WebPDemuxGetI(demux, WEBP_FF_CANVAS_WIDTH);
71 const int height = WebPDemuxGetI(demux, WEBP_FF_CANVAS_HEIGHT);
72
73 // Sanity check for image size that's about to be decoded.
74 {
75 const int64_t size = sk_64_mul(width, height);
76 if (!sk_64_isS32(size)) {
77 return nullptr;
78 }
79 // now check that if we are 4-bytes per pixel, we also don't overflow
80 if (sk_64_asS32(size) > (0x7FFFFFFF >> 2)) {
81 return nullptr;
82 }
83 }
84
msarettff2a6c82016-09-07 11:23:28 -070085 WebPChunkIterator chunkIterator;
86 SkAutoTCallVProc<WebPChunkIterator, WebPDemuxReleaseChunkIterator> autoCI(&chunkIterator);
87 sk_sp<SkColorSpace> colorSpace = nullptr;
88 if (WebPDemuxGetChunk(demux, "ICCP", 1, &chunkIterator)) {
Brian Osman526972e2016-10-24 09:24:02 -040089 colorSpace = SkColorSpace::MakeICC(chunkIterator.chunk.bytes, chunkIterator.chunk.size);
scroggo6f5e6192015-06-18 12:53:43 -070090 }
msarettff2a6c82016-09-07 11:23:28 -070091 if (!colorSpace) {
Matt Sarett77a7a1b2017-02-07 13:56:11 -050092 colorSpace = SkColorSpace::MakeSRGB();
msarettff2a6c82016-09-07 11:23:28 -070093 }
94
Matt Sarett5c496172017-02-07 17:01:16 -050095 // Get the first frame and its "features" to determine the color and alpha types.
msarettff2a6c82016-09-07 11:23:28 -070096 WebPIterator frame;
97 SkAutoTCallVProc<WebPIterator, WebPDemuxReleaseIterator> autoFrame(&frame);
98 if (!WebPDemuxGetFrame(demux, 1, &frame)) {
99 return nullptr;
100 }
101
msarettff2a6c82016-09-07 11:23:28 -0700102 WebPBitstreamFeatures features;
103 VP8StatusCode status = WebPGetFeatures(frame.fragment.bytes, frame.fragment.size, &features);
104 if (VP8_STATUS_OK != status) {
105 return nullptr;
106 }
107
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400108 const bool hasAlpha = SkToBool(frame.has_alpha)
109 || frame.width != width || frame.height != height;
msarettac6c7502016-04-25 09:30:24 -0700110 SkEncodedInfo::Color color;
111 SkEncodedInfo::Alpha alpha;
112 switch (features.format) {
113 case 0:
Matt Sarett5c496172017-02-07 17:01:16 -0500114 // This indicates a "mixed" format. We could see this for
115 // animated webps (multiple fragments).
msarettac6c7502016-04-25 09:30:24 -0700116 // We could also guess kYUV here, but I think it makes more
117 // sense to guess kBGRA which is likely closer to the final
118 // output. Otherwise, we might end up converting
119 // BGRA->YUVA->BGRA.
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400120 // Fallthrough:
121 case 2:
122 // This is the lossless format (BGRA).
123 if (hasAlpha) {
124 color = SkEncodedInfo::kBGRA_Color;
125 alpha = SkEncodedInfo::kUnpremul_Alpha;
126 } else {
127 color = SkEncodedInfo::kBGRX_Color;
128 alpha = SkEncodedInfo::kOpaque_Alpha;
129 }
msarettac6c7502016-04-25 09:30:24 -0700130 break;
131 case 1:
132 // This is the lossy format (YUV).
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400133 if (hasAlpha) {
msarettac6c7502016-04-25 09:30:24 -0700134 color = SkEncodedInfo::kYUVA_Color;
msarettc30c4182016-04-20 11:53:35 -0700135 alpha = SkEncodedInfo::kUnpremul_Alpha;
msarettac6c7502016-04-25 09:30:24 -0700136 } else {
137 color = SkEncodedInfo::kYUV_Color;
138 alpha = SkEncodedInfo::kOpaque_Alpha;
139 }
140 break;
msarettac6c7502016-04-25 09:30:24 -0700141 default:
142 return nullptr;
scroggo6f5e6192015-06-18 12:53:43 -0700143 }
scroggo6f5e6192015-06-18 12:53:43 -0700144
msarettac6c7502016-04-25 09:30:24 -0700145 SkEncodedInfo info = SkEncodedInfo::Make(color, alpha, 8);
Matt Sarett5c496172017-02-07 17:01:16 -0500146 SkWebpCodec* codecOut = new SkWebpCodec(width, height, info, std::move(colorSpace),
147 streamDeleter.release(), demux.release(),
148 std::move(data));
raftiasd737bee2016-12-08 10:53:24 -0500149 return codecOut;
scroggo6f5e6192015-06-18 12:53:43 -0700150}
151
scroggo6f5e6192015-06-18 12:53:43 -0700152SkISize SkWebpCodec::onGetScaledDimensions(float desiredScale) const {
153 SkISize dim = this->getInfo().dimensions();
msaretta0c414d2015-06-19 07:34:30 -0700154 // SkCodec treats zero dimensional images as errors, so the minimum size
155 // that we will recommend is 1x1.
156 dim.fWidth = SkTMax(1, SkScalarRoundToInt(desiredScale * dim.fWidth));
157 dim.fHeight = SkTMax(1, SkScalarRoundToInt(desiredScale * dim.fHeight));
scroggo6f5e6192015-06-18 12:53:43 -0700158 return dim;
159}
160
scroggoe7fc14b2015-10-02 13:14:46 -0700161bool SkWebpCodec::onDimensionsSupported(const SkISize& dim) {
162 const SkImageInfo& info = this->getInfo();
163 return dim.width() >= 1 && dim.width() <= info.width()
164 && dim.height() >= 1 && dim.height() <= info.height();
165}
166
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400167static WEBP_CSP_MODE webp_decode_mode(const SkImageInfo& info) {
168 const bool premultiply = info.alphaType() == kPremul_SkAlphaType;
169 switch (info.colorType()) {
scroggo6f5e6192015-06-18 12:53:43 -0700170 case kBGRA_8888_SkColorType:
171 return premultiply ? MODE_bgrA : MODE_BGRA;
172 case kRGBA_8888_SkColorType:
173 return premultiply ? MODE_rgbA : MODE_RGBA;
scroggo74992b52015-08-06 13:50:15 -0700174 case kRGB_565_SkColorType:
175 return MODE_RGB_565;
scroggo6f5e6192015-06-18 12:53:43 -0700176 default:
177 return MODE_LAST;
178 }
179}
180
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400181SkWebpCodec::Frame* SkWebpCodec::FrameHolder::appendNewFrame(bool hasAlpha) {
182 const int i = this->size();
183 fFrames.emplace_back(i, hasAlpha);
184 return &fFrames[i];
185}
186
scroggob636b452015-07-22 07:16:20 -0700187bool SkWebpCodec::onGetValidSubset(SkIRect* desiredSubset) const {
188 if (!desiredSubset) {
189 return false;
190 }
191
msarettfdb47572015-10-13 12:50:14 -0700192 SkIRect dimensions = SkIRect::MakeSize(this->getInfo().dimensions());
193 if (!dimensions.contains(*desiredSubset)) {
scroggob636b452015-07-22 07:16:20 -0700194 return false;
195 }
196
197 // As stated below, libwebp snaps to even left and top. Make sure top and left are even, so we
198 // decode this exact subset.
199 // Leave right and bottom unmodified, so we suggest a slightly larger subset than requested.
200 desiredSubset->fLeft = (desiredSubset->fLeft >> 1) << 1;
201 desiredSubset->fTop = (desiredSubset->fTop >> 1) << 1;
202 return true;
203}
204
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400205int SkWebpCodec::onGetRepetitionCount() {
206 auto flags = WebPDemuxGetI(fDemux.get(), WEBP_FF_FORMAT_FLAGS);
207 if (!(flags & ANIMATION_FLAG)) {
208 return 0;
209 }
210
211 const int repCount = WebPDemuxGetI(fDemux.get(), WEBP_FF_LOOP_COUNT);
212 if (0 == repCount) {
213 return kRepetitionCountInfinite;
214 }
215
216 return repCount;
217}
218
219int SkWebpCodec::onGetFrameCount() {
220 auto flags = WebPDemuxGetI(fDemux.get(), WEBP_FF_FORMAT_FLAGS);
221 if (!(flags & ANIMATION_FLAG)) {
222 return 1;
223 }
224
225 const uint32_t oldFrameCount = fFrameHolder.size();
226 if (fFailed) {
227 return oldFrameCount;
228 }
229
230 const uint32_t frameCount = WebPDemuxGetI(fDemux, WEBP_FF_FRAME_COUNT);
231 if (oldFrameCount == frameCount) {
232 // We have already parsed this.
233 return frameCount;
234 }
235
236 fFrameHolder.reserve(frameCount);
237
238 for (uint32_t i = oldFrameCount; i < frameCount; i++) {
239 WebPIterator iter;
240 SkAutoTCallVProc<WebPIterator, WebPDemuxReleaseIterator> autoIter(&iter);
241
242 if (!WebPDemuxGetFrame(fDemux.get(), i + 1, &iter)) {
243 fFailed = true;
244 break;
245 }
246
247 // libwebp only reports complete frames of an animated image.
248 SkASSERT(iter.complete);
249
250 Frame* frame = fFrameHolder.appendNewFrame(iter.has_alpha);
251 frame->setXYWH(iter.x_offset, iter.y_offset, iter.width, iter.height);
252 frame->setDisposalMethod(iter.dispose_method == WEBP_MUX_DISPOSE_BACKGROUND ?
Leon Scroggins III33deb7e2017-06-07 12:31:51 -0400253 SkCodecAnimation::DisposalMethod::kRestoreBGColor :
254 SkCodecAnimation::DisposalMethod::kKeep);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400255 frame->setDuration(iter.duration);
256 if (WEBP_MUX_BLEND != iter.blend_method) {
257 frame->setBlend(SkCodecAnimation::Blend::kBG);
258 }
259 fFrameHolder.setAlphaAndRequiredFrame(frame);
260 }
261
262 return fFrameHolder.size();
263
264}
265
266const SkFrame* SkWebpCodec::FrameHolder::onGetFrame(int i) const {
267 return static_cast<const SkFrame*>(this->frame(i));
268}
269
270const SkWebpCodec::Frame* SkWebpCodec::FrameHolder::frame(int i) const {
271 SkASSERT(i >= 0 && i < this->size());
272 return &fFrames[i];
273}
274
275bool SkWebpCodec::onGetFrameInfo(int i, FrameInfo* frameInfo) const {
276 if (i >= fFrameHolder.size()) {
277 return false;
278 }
279
280 const Frame* frame = fFrameHolder.frame(i);
281 if (!frame) {
282 return false;
283 }
284
285 if (frameInfo) {
286 frameInfo->fRequiredFrame = frame->getRequiredFrame();
287 frameInfo->fDuration = frame->getDuration();
288 // libwebp only reports fully received frames for an
289 // animated image.
290 frameInfo->fFullyReceived = true;
291 frameInfo->fAlphaType = alpha_type(frame->hasAlpha());
Leon Scroggins III33deb7e2017-06-07 12:31:51 -0400292 frameInfo->fDisposalMethod = frame->getDisposalMethod();
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400293 }
294
295 return true;
296}
297
298static bool is_8888(SkColorType colorType) {
299 switch (colorType) {
300 case kRGBA_8888_SkColorType:
301 case kBGRA_8888_SkColorType:
302 return true;
303 default:
304 return false;
305 }
306}
307
308static void pick_memory_stages(SkColorType ct, SkRasterPipeline::StockStage* load,
309 SkRasterPipeline::StockStage* store) {
310 switch(ct) {
311 case kUnknown_SkColorType:
312 case kAlpha_8_SkColorType:
313 case kARGB_4444_SkColorType:
314 case kIndex_8_SkColorType:
315 case kGray_8_SkColorType:
316 SkASSERT(false);
317 break;
318 case kRGB_565_SkColorType:
319 if (load) *load = SkRasterPipeline::load_565;
320 if (store) *store = SkRasterPipeline::store_565;
321 break;
322 case kRGBA_8888_SkColorType:
323 case kBGRA_8888_SkColorType:
324 if (load) *load = SkRasterPipeline::load_8888;
325 if (store) *store = SkRasterPipeline::store_8888;
326 break;
327 case kRGBA_F16_SkColorType:
328 if (load) *load = SkRasterPipeline::load_f16;
329 if (store) *store = SkRasterPipeline::store_f16;
330 break;
331 }
332}
333
334static void blend_line(SkColorType dstCT, void* dst,
335 SkColorType srcCT, void* src,
336 bool needsSrgbToLinear, SkAlphaType at,
337 int width) {
338 // Setup conversion from the source and dest, which will be the same.
Mike Kleinb24704d2017-05-24 07:53:00 -0400339 SkRasterPipeline_<256> convert_to_linear_premul;
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400340 if (needsSrgbToLinear) {
341 convert_to_linear_premul.append_from_srgb(at);
342 }
343 if (kUnpremul_SkAlphaType == at) {
344 // srcover assumes premultiplied inputs.
345 convert_to_linear_premul.append(SkRasterPipeline::premul);
346 }
347
Mike Kleinb24704d2017-05-24 07:53:00 -0400348 SkRasterPipeline_<256> p;
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400349 SkRasterPipeline::StockStage load_dst, store_dst;
350 pick_memory_stages(dstCT, &load_dst, &store_dst);
351
352 // Load the final dst.
353 p.append(load_dst, dst);
354 p.extend(convert_to_linear_premul);
355 p.append(SkRasterPipeline::move_src_dst);
356
357 // Load the src.
358 SkRasterPipeline::StockStage load_src;
359 pick_memory_stages(srcCT, &load_src, nullptr);
360 p.append(load_src, src);
361 if (dstCT != srcCT) {
362 SkASSERT(kBGRA_8888_SkColorType == srcCT);
363 p.append(SkRasterPipeline::swap_rb);
364 }
365 p.extend(convert_to_linear_premul);
366
367 p.append(SkRasterPipeline::srcover);
368
369 // Convert back to dst.
370 if (kUnpremul_SkAlphaType == at) {
371 p.append(SkRasterPipeline::unpremul);
372 }
373 if (needsSrgbToLinear) {
374 p.append(SkRasterPipeline::to_srgb);
375 }
376 p.append(store_dst, dst);
377
Mike Klein761d27c2017-06-01 12:37:08 -0400378 p.run(0,0, width);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400379}
380
scroggoeb602a52015-07-09 08:16:03 -0700381SkCodec::Result SkWebpCodec::onGetPixels(const SkImageInfo& dstInfo, void* dst, size_t rowBytes,
msarette6dd0042015-10-09 11:07:34 -0700382 const Options& options, SkPMColor*, int*,
msarette99883f2016-09-08 06:05:35 -0700383 int* rowsDecodedPtr) {
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400384 const int index = options.fFrameIndex;
Leon Scroggins III1f6af6b2017-06-12 16:41:09 -0400385 SkASSERT(0 == index || index < fFrameHolder.size());
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400386
387 const auto& srcInfo = this->getInfo();
Matt Sarettcf3f2342017-03-23 15:32:25 -0400388 {
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400389 auto info = srcInfo;
390 if (index > 0) {
391 auto alphaType = alpha_type(fFrameHolder.frame(index)->hasAlpha());
392 info = info.makeAlphaType(alphaType);
393 }
394 if (!conversion_possible(dstInfo, info) ||
395 !this->initializeColorXform(dstInfo, options.fPremulBehavior))
396 {
397 return kInvalidConversion;
398 }
399 }
400
Leon Scroggins III1f6af6b2017-06-12 16:41:09 -0400401 SkASSERT(0 == index || (!options.fSubset && dstInfo.dimensions() == srcInfo.dimensions()));
scroggo6f5e6192015-06-18 12:53:43 -0700402
403 WebPDecoderConfig config;
404 if (0 == WebPInitDecoderConfig(&config)) {
405 // ABI mismatch.
406 // FIXME: New enum for this?
407 return kInvalidInput;
408 }
409
410 // Free any memory associated with the buffer. Must be called last, so we declare it first.
411 SkAutoTCallVProc<WebPDecBuffer, WebPFreeDecBuffer> autoFree(&(config.output));
412
Matt Sarett5c496172017-02-07 17:01:16 -0500413 WebPIterator frame;
414 SkAutoTCallVProc<WebPIterator, WebPDemuxReleaseIterator> autoFrame(&frame);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400415 // If this succeeded in onGetFrameCount(), it should succeed again here.
416 SkAssertResult(WebPDemuxGetFrame(fDemux, index + 1, &frame));
Matt Sarett604971e2017-02-06 09:51:48 -0500417
Leon Scroggins III1f6af6b2017-06-12 16:41:09 -0400418 const bool independent = index == 0 ? true :
419 (fFrameHolder.frame(index)->getRequiredFrame() == kNone);
Matt Sarett5c496172017-02-07 17:01:16 -0500420 // Get the frameRect. libwebp will have already signaled an error if this is not fully
421 // contained by the canvas.
422 auto frameRect = SkIRect::MakeXYWH(frame.x_offset, frame.y_offset, frame.width, frame.height);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400423 SkASSERT(srcInfo.bounds().contains(frameRect));
424 const bool frameIsSubset = frameRect != srcInfo.bounds();
Leon Scroggins III1f6af6b2017-06-12 16:41:09 -0400425 if (independent && frameIsSubset) {
426 SkSampler::Fill(dstInfo, dst, rowBytes, 0, options.fZeroInitialized);
Matt Sarett604971e2017-02-06 09:51:48 -0500427 }
428
Matt Sarett5c496172017-02-07 17:01:16 -0500429 int dstX = frameRect.x();
430 int dstY = frameRect.y();
431 int subsetWidth = frameRect.width();
432 int subsetHeight = frameRect.height();
433 if (options.fSubset) {
434 SkIRect subset = *options.fSubset;
435 SkASSERT(this->getInfo().bounds().contains(subset));
436 SkASSERT(SkIsAlign2(subset.fLeft) && SkIsAlign2(subset.fTop));
437 SkASSERT(this->getValidSubset(&subset) && subset == *options.fSubset);
438
439 if (!SkIRect::IntersectsNoEmptyCheck(subset, frameRect)) {
440 return kSuccess;
441 }
442
443 int minXOffset = SkTMin(dstX, subset.x());
444 int minYOffset = SkTMin(dstY, subset.y());
445 dstX -= minXOffset;
446 dstY -= minYOffset;
447 frameRect.offset(-minXOffset, -minYOffset);
448 subset.offset(-minXOffset, -minYOffset);
449
450 // Just like we require that the requested subset x and y offset are even, libwebp
451 // guarantees that the frame x and y offset are even (it's actually impossible to specify
452 // an odd frame offset). So we can still guarantee that the adjusted offsets are even.
453 SkASSERT(SkIsAlign2(subset.fLeft) && SkIsAlign2(subset.fTop));
454
455 SkIRect intersection;
456 SkAssertResult(intersection.intersect(frameRect, subset));
457 subsetWidth = intersection.width();
458 subsetHeight = intersection.height();
459
460 config.options.use_cropping = 1;
461 config.options.crop_left = subset.x();
462 config.options.crop_top = subset.y();
463 config.options.crop_width = subsetWidth;
464 config.options.crop_height = subsetHeight;
465 }
466
467 // Ignore the frame size and offset when determining if scaling is necessary.
468 int scaledWidth = subsetWidth;
469 int scaledHeight = subsetHeight;
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400470 SkISize srcSize = options.fSubset ? options.fSubset->size() : srcInfo.dimensions();
Matt Sarett5c496172017-02-07 17:01:16 -0500471 if (srcSize != dstInfo.dimensions()) {
scroggo6f5e6192015-06-18 12:53:43 -0700472 config.options.use_scaling = 1;
Matt Sarett5c496172017-02-07 17:01:16 -0500473
474 if (frameIsSubset) {
475 float scaleX = ((float) dstInfo.width()) / srcSize.width();
476 float scaleY = ((float) dstInfo.height()) / srcSize.height();
477
478 // We need to be conservative here and floor rather than round.
479 // Otherwise, we may find ourselves decoding off the end of memory.
480 dstX = scaleX * dstX;
481 scaledWidth = scaleX * scaledWidth;
482 dstY = scaleY * dstY;
483 scaledHeight = scaleY * scaledHeight;
484 if (0 == scaledWidth || 0 == scaledHeight) {
485 return kSuccess;
486 }
487 } else {
488 scaledWidth = dstInfo.width();
489 scaledHeight = dstInfo.height();
490 }
491
492 config.options.scaled_width = scaledWidth;
493 config.options.scaled_height = scaledHeight;
scroggo6f5e6192015-06-18 12:53:43 -0700494 }
495
Leon Scroggins III1f6af6b2017-06-12 16:41:09 -0400496 const bool blendWithPrevFrame = !independent && frame.blend_method == WEBP_MUX_BLEND
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400497 && frame.has_alpha;
498 if (blendWithPrevFrame && options.fPremulBehavior == SkTransferFunctionBehavior::kRespect) {
499 // Blending is done with SkRasterPipeline, which requires a color space that is valid for
500 // rendering.
501 const auto* cs = dstInfo.colorSpace();
502 if (!cs || (!cs->gammaCloseToSRGB() && !cs->gammaIsLinear())) {
503 return kInvalidConversion;
504 }
505 }
506
507 SkBitmap webpDst;
Leon Scroggins IIIee92f132017-05-23 15:28:46 -0400508 auto webpInfo = dstInfo;
509 if (!frame.has_alpha) {
510 webpInfo = webpInfo.makeAlphaType(kOpaque_SkAlphaType);
511 }
512 if (this->colorXform()) {
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400513 // Swizzling between RGBA and BGRA is zero cost in a color transform. So when we have a
514 // color transform, we should decode to whatever is easiest for libwebp, and then let the
515 // color transform swizzle if necessary.
516 // Lossy webp is encoded as YUV (so RGBA and BGRA are the same cost). Lossless webp is
517 // encoded as BGRA. This means decoding to BGRA is either faster or the same cost as RGBA.
Leon Scroggins IIIee92f132017-05-23 15:28:46 -0400518 webpInfo = webpInfo.makeColorType(kBGRA_8888_SkColorType);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400519
Leon Scroggins IIIee92f132017-05-23 15:28:46 -0400520 if (webpInfo.alphaType() == kPremul_SkAlphaType) {
521 webpInfo = webpInfo.makeAlphaType(kUnpremul_SkAlphaType);
522 }
523 }
524
525 if ((this->colorXform() && !is_8888(dstInfo.colorType())) || blendWithPrevFrame) {
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400526 // We will decode the entire image and then perform the color transform. libwebp
527 // does not provide a row-by-row API. This is a shame particularly when we do not want
528 // 8888, since we will need to create another image sized buffer.
Leon Scroggins IIIee92f132017-05-23 15:28:46 -0400529 webpDst.allocPixels(webpInfo);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400530 } else {
531 // libwebp can decode directly into the output memory.
Leon Scroggins IIIee92f132017-05-23 15:28:46 -0400532 webpDst.installPixels(webpInfo, dst, rowBytes);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400533 }
534
Leon Scroggins IIIee92f132017-05-23 15:28:46 -0400535 config.output.colorspace = webp_decode_mode(webpInfo);
scroggo6f5e6192015-06-18 12:53:43 -0700536 config.output.is_external_memory = 1;
537
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400538 config.output.u.RGBA.rgba = reinterpret_cast<uint8_t*>(webpDst.getAddr(dstX, dstY));
539 config.output.u.RGBA.stride = static_cast<int>(webpDst.rowBytes());
540 config.output.u.RGBA.size = webpDst.getSafeSize();
msarettff2a6c82016-09-07 11:23:28 -0700541
halcanary96fcdcc2015-08-27 07:41:13 -0700542 SkAutoTCallVProc<WebPIDecoder, WebPIDelete> idec(WebPIDecode(nullptr, 0, &config));
scroggo6f5e6192015-06-18 12:53:43 -0700543 if (!idec) {
544 return kInvalidInput;
545 }
546
msarette99883f2016-09-08 06:05:35 -0700547 int rowsDecoded;
548 SkCodec::Result result;
msarettff2a6c82016-09-07 11:23:28 -0700549 switch (WebPIUpdate(idec, frame.fragment.bytes, frame.fragment.size)) {
550 case VP8_STATUS_OK:
Matt Sarett5c496172017-02-07 17:01:16 -0500551 rowsDecoded = scaledHeight;
msarette99883f2016-09-08 06:05:35 -0700552 result = kSuccess;
553 break;
msarettff2a6c82016-09-07 11:23:28 -0700554 case VP8_STATUS_SUSPENDED:
Matt Sarett5c496172017-02-07 17:01:16 -0500555 WebPIDecGetRGB(idec, &rowsDecoded, nullptr, nullptr, nullptr);
556 *rowsDecodedPtr = rowsDecoded + dstY;
msarette99883f2016-09-08 06:05:35 -0700557 result = kIncompleteInput;
558 break;
msarettff2a6c82016-09-07 11:23:28 -0700559 default:
560 return kInvalidInput;
scroggo6f5e6192015-06-18 12:53:43 -0700561 }
msarette99883f2016-09-08 06:05:35 -0700562
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400563 // We're only transforming the new part of the frame, so no need to worry about the
564 // final composited alpha.
565 const auto srcAlpha = 0 == index ? srcInfo.alphaType() : alpha_type(frame.has_alpha);
566 const auto xformAlphaType = select_xform_alpha(dstInfo.alphaType(), srcAlpha);
567 const bool needsSrgbToLinear = dstInfo.gammaCloseToSRGB() &&
568 options.fPremulBehavior == SkTransferFunctionBehavior::kRespect;
569
570 const size_t dstBpp = SkColorTypeBytesPerPixel(dstInfo.colorType());
571 dst = SkTAddOffset<void>(dst, dstBpp * dstX + rowBytes * dstY);
572 const size_t srcRowBytes = config.output.u.RGBA.stride;
573
574 const auto dstCT = dstInfo.colorType();
Matt Sarett313c4632016-10-20 12:35:23 -0400575 if (this->colorXform()) {
Matt Sarett5c496172017-02-07 17:01:16 -0500576 uint32_t* xformSrc = (uint32_t*) config.output.u.RGBA.rgba;
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400577 SkBitmap tmp;
578 void* xformDst;
579
580 if (blendWithPrevFrame) {
581 // Xform into temporary bitmap big enough for one row.
582 tmp.allocPixels(dstInfo.makeWH(scaledWidth, 1));
583 xformDst = tmp.getPixels();
584 } else {
585 xformDst = dst;
586 }
Robert Phillipsb3050b92017-02-06 13:12:18 +0000587 for (int y = 0; y < rowsDecoded; y++) {
Leon Scroggins IIIc6e6a5f2017-06-05 15:53:38 -0400588 this->applyColorXform(xformDst, xformSrc, scaledWidth, xformAlphaType);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400589 if (blendWithPrevFrame) {
590 blend_line(dstCT, &dst, dstCT, &xformDst, needsSrgbToLinear, xformAlphaType,
591 scaledWidth);
592 dst = SkTAddOffset<void>(dst, rowBytes);
593 } else {
594 xformDst = SkTAddOffset<void>(xformDst, rowBytes);
595 }
Matt Sarett5c496172017-02-07 17:01:16 -0500596 xformSrc = SkTAddOffset<uint32_t>(xformSrc, srcRowBytes);
msarette99883f2016-09-08 06:05:35 -0700597 }
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400598 } else if (blendWithPrevFrame) {
599 const uint8_t* src = config.output.u.RGBA.rgba;
600
601 for (int y = 0; y < rowsDecoded; y++) {
602 blend_line(dstCT, &dst, webpDst.colorType(), &src, needsSrgbToLinear,
603 xformAlphaType, scaledWidth);
604 src = SkTAddOffset<const uint8_t>(src, srcRowBytes);
605 dst = SkTAddOffset<void>(dst, rowBytes);
606 }
msarette99883f2016-09-08 06:05:35 -0700607 }
608
609 return result;
scroggo6f5e6192015-06-18 12:53:43 -0700610}
611
msarett9d15dab2016-08-24 07:36:06 -0700612SkWebpCodec::SkWebpCodec(int width, int height, const SkEncodedInfo& info,
msarettff2a6c82016-09-07 11:23:28 -0700613 sk_sp<SkColorSpace> colorSpace, SkStream* stream, WebPDemuxer* demux,
614 sk_sp<SkData> data)
Leon Scroggins IIIc6e6a5f2017-06-05 15:53:38 -0400615 : INHERITED(width, height, info, SkColorSpaceXform::kBGRA_8888_ColorFormat, stream,
616 std::move(colorSpace))
msarettff2a6c82016-09-07 11:23:28 -0700617 , fDemux(demux)
618 , fData(std::move(data))
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400619 , fFailed(false)
620{
621 fFrameHolder.setScreenSize(width, height);
622}