blob: 8ebbf43e5385fb337ba34cc9601762de4b80d076 [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
Hal Canaryc640d0d2018-06-13 09:59:02 -04008#include "SkWebpCodec.h"
9
10#include "../jumper/SkJumper.h"
Leon Scroggins III557fbbe2017-05-23 09:37:21 -040011#include "SkBitmap.h"
12#include "SkCanvas.h"
Leon Scroggins III33deb7e2017-06-07 12:31:51 -040013#include "SkCodecAnimation.h"
14#include "SkCodecAnimationPriv.h"
scroggocc2feb12015-08-14 08:32:46 -070015#include "SkCodecPriv.h"
Mike Reedede7bac2017-07-23 15:30:02 -040016#include "SkMakeUnique.h"
Leon Scroggins III557fbbe2017-05-23 09:37:21 -040017#include "SkRasterPipeline.h"
Matt Sarett5c496172017-02-07 17:01:16 -050018#include "SkSampler.h"
msarettff2a6c82016-09-07 11:23:28 -070019#include "SkStreamPriv.h"
scroggo6f5e6192015-06-18 12:53:43 -070020#include "SkTemplates.h"
Hal Canaryc640d0d2018-06-13 09:59:02 -040021#include "SkTo.h"
scroggo6f5e6192015-06-18 12:53:43 -070022
23// A WebP decoder on top of (subset of) libwebp
24// For more information on WebP image format, and libwebp library, see:
25// https://code.google.com/speed/webp/
26// http://www.webmproject.org/code/#libwebp-webp-image-library
27// https://chromium.googlesource.com/webm/libwebp
28
29// If moving libwebp out of skia source tree, path for webp headers must be
30// updated accordingly. Here, we enforce using local copy in webp sub-directory.
31#include "webp/decode.h"
msarett9d15dab2016-08-24 07:36:06 -070032#include "webp/demux.h"
scroggo6f5e6192015-06-18 12:53:43 -070033#include "webp/encode.h"
34
scroggodb30be22015-12-08 18:54:13 -080035bool SkWebpCodec::IsWebp(const void* buf, size_t bytesRead) {
scroggo6f5e6192015-06-18 12:53:43 -070036 // WEBP starts with the following:
37 // RIFFXXXXWEBPVP
38 // Where XXXX is unspecified.
scroggodb30be22015-12-08 18:54:13 -080039 const char* bytes = static_cast<const char*>(buf);
40 return bytesRead >= 14 && !memcmp(bytes, "RIFF", 4) && !memcmp(&bytes[8], "WEBPVP", 6);
scroggo6f5e6192015-06-18 12:53:43 -070041}
42
scroggo6f5e6192015-06-18 12:53:43 -070043// Parse headers of RIFF container, and check for valid Webp (VP8) content.
Leon Scroggins III557fbbe2017-05-23 09:37:21 -040044// Returns an SkWebpCodec on success
Mike Reedede7bac2017-07-23 15:30:02 -040045std::unique_ptr<SkCodec> SkWebpCodec::MakeFromStream(std::unique_ptr<SkStream> stream,
46 Result* result) {
msarettff2a6c82016-09-07 11:23:28 -070047 // Webp demux needs a contiguous data buffer.
48 sk_sp<SkData> data = nullptr;
49 if (stream->getMemoryBase()) {
50 // It is safe to make without copy because we'll hold onto the stream.
51 data = SkData::MakeWithoutCopy(stream->getMemoryBase(), stream->getLength());
52 } else {
Mike Reedede7bac2017-07-23 15:30:02 -040053 data = SkCopyStreamToData(stream.get());
scroggodb30be22015-12-08 18:54:13 -080054
msarettff2a6c82016-09-07 11:23:28 -070055 // If we are forced to copy the stream to a data, we can go ahead and delete the stream.
Mike Reedede7bac2017-07-23 15:30:02 -040056 stream.reset(nullptr);
msarettff2a6c82016-09-07 11:23:28 -070057 }
58
59 // It's a little strange that the |demux| will outlive |webpData|, though it needs the
60 // pointer in |webpData| to remain valid. This works because the pointer remains valid
61 // until the SkData is freed.
62 WebPData webpData = { data->bytes(), data->size() };
Leon Scroggins III588fb042017-07-14 16:32:31 -040063 WebPDemuxState state;
64 SkAutoTCallVProc<WebPDemuxer, WebPDemuxDelete> demux(WebPDemuxPartial(&webpData, &state));
65 switch (state) {
66 case WEBP_DEMUX_PARSE_ERROR:
67 *result = kInvalidInput;
68 return nullptr;
69 case WEBP_DEMUX_PARSING_HEADER:
70 *result = kIncompleteInput;
71 return nullptr;
72 case WEBP_DEMUX_PARSED_HEADER:
73 case WEBP_DEMUX_DONE:
74 SkASSERT(demux);
75 break;
scroggo6f5e6192015-06-18 12:53:43 -070076 }
77
Matt Sarett5c496172017-02-07 17:01:16 -050078 const int width = WebPDemuxGetI(demux, WEBP_FF_CANVAS_WIDTH);
79 const int height = WebPDemuxGetI(demux, WEBP_FF_CANVAS_HEIGHT);
80
81 // Sanity check for image size that's about to be decoded.
82 {
83 const int64_t size = sk_64_mul(width, height);
Matt Sarett5c496172017-02-07 17:01:16 -050084 // now check that if we are 4-bytes per pixel, we also don't overflow
Herb Derbyc402b772017-09-20 11:56:00 -040085 if (!SkTFitsIn<int32_t>(size) || SkTo<int32_t>(size) > (0x7FFFFFFF >> 2)) {
Leon Scroggins III588fb042017-07-14 16:32:31 -040086 *result = kInvalidInput;
Matt Sarett5c496172017-02-07 17:01:16 -050087 return nullptr;
88 }
89 }
90
Leon Scroggins III36f7e322018-08-27 11:55:46 -040091 std::unique_ptr<SkEncodedInfo::ICCProfile> profile = nullptr;
Leon Scroggins IIIda3e9ad2018-01-26 15:48:26 -050092 {
93 WebPChunkIterator chunkIterator;
94 SkAutoTCallVProc<WebPChunkIterator, WebPDemuxReleaseChunkIterator> autoCI(&chunkIterator);
95 if (WebPDemuxGetChunk(demux, "ICCP", 1, &chunkIterator)) {
Leon Scroggins III36f7e322018-08-27 11:55:46 -040096 // FIXME: I think this could be MakeWithoutCopy
97 auto chunk = SkData::MakeWithCopy(chunkIterator.chunk.bytes, chunkIterator.chunk.size);
98 profile = SkEncodedInfo::ICCProfile::Make(std::move(chunk));
Leon Scroggins IIIda3e9ad2018-01-26 15:48:26 -050099 }
Leon Scroggins III5dd47e42018-09-27 15:26:48 -0400100 if (profile && profile->profile()->data_color_space != skcms_Signature_RGB) {
101 profile = nullptr;
Leon Scroggins IIIda3e9ad2018-01-26 15:48:26 -0500102 }
scroggo6f5e6192015-06-18 12:53:43 -0700103 }
Leon Scroggins IIIda3e9ad2018-01-26 15:48:26 -0500104
105 SkEncodedOrigin origin = kDefault_SkEncodedOrigin;
106 {
107 WebPChunkIterator chunkIterator;
108 SkAutoTCallVProc<WebPChunkIterator, WebPDemuxReleaseChunkIterator> autoCI(&chunkIterator);
109 if (WebPDemuxGetChunk(demux, "EXIF", 1, &chunkIterator)) {
110 is_orientation_marker(chunkIterator.chunk.bytes, chunkIterator.chunk.size, &origin);
111 }
msarettff2a6c82016-09-07 11:23:28 -0700112 }
113
Matt Sarett5c496172017-02-07 17:01:16 -0500114 // Get the first frame and its "features" to determine the color and alpha types.
msarettff2a6c82016-09-07 11:23:28 -0700115 WebPIterator frame;
116 SkAutoTCallVProc<WebPIterator, WebPDemuxReleaseIterator> autoFrame(&frame);
117 if (!WebPDemuxGetFrame(demux, 1, &frame)) {
Leon Scroggins III588fb042017-07-14 16:32:31 -0400118 *result = kIncompleteInput;
msarettff2a6c82016-09-07 11:23:28 -0700119 return nullptr;
120 }
121
msarettff2a6c82016-09-07 11:23:28 -0700122 WebPBitstreamFeatures features;
Leon Scroggins III588fb042017-07-14 16:32:31 -0400123 switch (WebPGetFeatures(frame.fragment.bytes, frame.fragment.size, &features)) {
124 case VP8_STATUS_OK:
125 break;
126 case VP8_STATUS_SUSPENDED:
127 case VP8_STATUS_NOT_ENOUGH_DATA:
128 *result = kIncompleteInput;
129 return nullptr;
130 default:
131 *result = kInvalidInput;
132 return nullptr;
msarettff2a6c82016-09-07 11:23:28 -0700133 }
134
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400135 const bool hasAlpha = SkToBool(frame.has_alpha)
136 || frame.width != width || frame.height != height;
msarettac6c7502016-04-25 09:30:24 -0700137 SkEncodedInfo::Color color;
138 SkEncodedInfo::Alpha alpha;
139 switch (features.format) {
140 case 0:
Matt Sarett5c496172017-02-07 17:01:16 -0500141 // This indicates a "mixed" format. We could see this for
142 // animated webps (multiple fragments).
msarettac6c7502016-04-25 09:30:24 -0700143 // We could also guess kYUV here, but I think it makes more
144 // sense to guess kBGRA which is likely closer to the final
145 // output. Otherwise, we might end up converting
146 // BGRA->YUVA->BGRA.
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400147 // Fallthrough:
148 case 2:
149 // This is the lossless format (BGRA).
150 if (hasAlpha) {
151 color = SkEncodedInfo::kBGRA_Color;
152 alpha = SkEncodedInfo::kUnpremul_Alpha;
153 } else {
154 color = SkEncodedInfo::kBGRX_Color;
155 alpha = SkEncodedInfo::kOpaque_Alpha;
156 }
msarettac6c7502016-04-25 09:30:24 -0700157 break;
158 case 1:
159 // This is the lossy format (YUV).
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400160 if (hasAlpha) {
msarettac6c7502016-04-25 09:30:24 -0700161 color = SkEncodedInfo::kYUVA_Color;
msarettc30c4182016-04-20 11:53:35 -0700162 alpha = SkEncodedInfo::kUnpremul_Alpha;
msarettac6c7502016-04-25 09:30:24 -0700163 } else {
164 color = SkEncodedInfo::kYUV_Color;
165 alpha = SkEncodedInfo::kOpaque_Alpha;
166 }
167 break;
msarettac6c7502016-04-25 09:30:24 -0700168 default:
Leon Scroggins III588fb042017-07-14 16:32:31 -0400169 *result = kInvalidInput;
msarettac6c7502016-04-25 09:30:24 -0700170 return nullptr;
scroggo6f5e6192015-06-18 12:53:43 -0700171 }
scroggo6f5e6192015-06-18 12:53:43 -0700172
Leon Scroggins IIIda3e9ad2018-01-26 15:48:26 -0500173
Leon Scroggins III588fb042017-07-14 16:32:31 -0400174 *result = kSuccess;
Leon Scroggins III36f7e322018-08-27 11:55:46 -0400175 SkEncodedInfo info = SkEncodedInfo::Make(width, height, color, alpha, 8, std::move(profile));
176 return std::unique_ptr<SkCodec>(new SkWebpCodec(std::move(info), std::move(stream),
177 demux.release(), std::move(data), origin));
scroggo6f5e6192015-06-18 12:53:43 -0700178}
179
scroggo6f5e6192015-06-18 12:53:43 -0700180SkISize SkWebpCodec::onGetScaledDimensions(float desiredScale) const {
Leon Scroggins III712476e2018-10-03 15:47:00 -0400181 SkISize dim = this->dimensions();
msaretta0c414d2015-06-19 07:34:30 -0700182 // SkCodec treats zero dimensional images as errors, so the minimum size
183 // that we will recommend is 1x1.
184 dim.fWidth = SkTMax(1, SkScalarRoundToInt(desiredScale * dim.fWidth));
185 dim.fHeight = SkTMax(1, SkScalarRoundToInt(desiredScale * dim.fHeight));
scroggo6f5e6192015-06-18 12:53:43 -0700186 return dim;
187}
188
scroggoe7fc14b2015-10-02 13:14:46 -0700189bool SkWebpCodec::onDimensionsSupported(const SkISize& dim) {
Leon Scroggins III712476e2018-10-03 15:47:00 -0400190 const SkEncodedInfo& info = this->getEncodedInfo();
scroggoe7fc14b2015-10-02 13:14:46 -0700191 return dim.width() >= 1 && dim.width() <= info.width()
192 && dim.height() >= 1 && dim.height() <= info.height();
193}
194
Leon Scroggins III03588412017-11-17 08:07:32 -0500195static WEBP_CSP_MODE webp_decode_mode(SkColorType dstCT, bool premultiply) {
196 switch (dstCT) {
scroggo6f5e6192015-06-18 12:53:43 -0700197 case kBGRA_8888_SkColorType:
198 return premultiply ? MODE_bgrA : MODE_BGRA;
199 case kRGBA_8888_SkColorType:
200 return premultiply ? MODE_rgbA : MODE_RGBA;
scroggo74992b52015-08-06 13:50:15 -0700201 case kRGB_565_SkColorType:
202 return MODE_RGB_565;
scroggo6f5e6192015-06-18 12:53:43 -0700203 default:
204 return MODE_LAST;
205 }
206}
207
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400208SkWebpCodec::Frame* SkWebpCodec::FrameHolder::appendNewFrame(bool hasAlpha) {
209 const int i = this->size();
Leon Scroggins IIIc8037dc2017-12-05 13:55:24 -0500210 fFrames.emplace_back(i, hasAlpha ? SkEncodedInfo::kUnpremul_Alpha
211 : SkEncodedInfo::kOpaque_Alpha);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400212 return &fFrames[i];
213}
214
scroggob636b452015-07-22 07:16:20 -0700215bool SkWebpCodec::onGetValidSubset(SkIRect* desiredSubset) const {
216 if (!desiredSubset) {
217 return false;
218 }
219
Leon Scroggins III712476e2018-10-03 15:47:00 -0400220 if (!this->bounds().contains(*desiredSubset)) {
scroggob636b452015-07-22 07:16:20 -0700221 return false;
222 }
223
224 // As stated below, libwebp snaps to even left and top. Make sure top and left are even, so we
225 // decode this exact subset.
226 // Leave right and bottom unmodified, so we suggest a slightly larger subset than requested.
227 desiredSubset->fLeft = (desiredSubset->fLeft >> 1) << 1;
228 desiredSubset->fTop = (desiredSubset->fTop >> 1) << 1;
229 return true;
230}
231
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400232int SkWebpCodec::onGetRepetitionCount() {
233 auto flags = WebPDemuxGetI(fDemux.get(), WEBP_FF_FORMAT_FLAGS);
234 if (!(flags & ANIMATION_FLAG)) {
235 return 0;
236 }
237
238 const int repCount = WebPDemuxGetI(fDemux.get(), WEBP_FF_LOOP_COUNT);
239 if (0 == repCount) {
240 return kRepetitionCountInfinite;
241 }
242
243 return repCount;
244}
245
246int SkWebpCodec::onGetFrameCount() {
247 auto flags = WebPDemuxGetI(fDemux.get(), WEBP_FF_FORMAT_FLAGS);
248 if (!(flags & ANIMATION_FLAG)) {
249 return 1;
250 }
251
252 const uint32_t oldFrameCount = fFrameHolder.size();
253 if (fFailed) {
254 return oldFrameCount;
255 }
256
257 const uint32_t frameCount = WebPDemuxGetI(fDemux, WEBP_FF_FRAME_COUNT);
258 if (oldFrameCount == frameCount) {
259 // We have already parsed this.
260 return frameCount;
261 }
262
263 fFrameHolder.reserve(frameCount);
264
265 for (uint32_t i = oldFrameCount; i < frameCount; i++) {
266 WebPIterator iter;
267 SkAutoTCallVProc<WebPIterator, WebPDemuxReleaseIterator> autoIter(&iter);
268
269 if (!WebPDemuxGetFrame(fDemux.get(), i + 1, &iter)) {
270 fFailed = true;
271 break;
272 }
273
274 // libwebp only reports complete frames of an animated image.
275 SkASSERT(iter.complete);
276
277 Frame* frame = fFrameHolder.appendNewFrame(iter.has_alpha);
278 frame->setXYWH(iter.x_offset, iter.y_offset, iter.width, iter.height);
279 frame->setDisposalMethod(iter.dispose_method == WEBP_MUX_DISPOSE_BACKGROUND ?
Leon Scroggins III33deb7e2017-06-07 12:31:51 -0400280 SkCodecAnimation::DisposalMethod::kRestoreBGColor :
281 SkCodecAnimation::DisposalMethod::kKeep);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400282 frame->setDuration(iter.duration);
283 if (WEBP_MUX_BLEND != iter.blend_method) {
284 frame->setBlend(SkCodecAnimation::Blend::kBG);
285 }
286 fFrameHolder.setAlphaAndRequiredFrame(frame);
287 }
288
289 return fFrameHolder.size();
290
291}
292
293const SkFrame* SkWebpCodec::FrameHolder::onGetFrame(int i) const {
294 return static_cast<const SkFrame*>(this->frame(i));
295}
296
297const SkWebpCodec::Frame* SkWebpCodec::FrameHolder::frame(int i) const {
298 SkASSERT(i >= 0 && i < this->size());
299 return &fFrames[i];
300}
301
302bool SkWebpCodec::onGetFrameInfo(int i, FrameInfo* frameInfo) const {
303 if (i >= fFrameHolder.size()) {
304 return false;
305 }
306
307 const Frame* frame = fFrameHolder.frame(i);
308 if (!frame) {
309 return false;
310 }
311
312 if (frameInfo) {
313 frameInfo->fRequiredFrame = frame->getRequiredFrame();
314 frameInfo->fDuration = frame->getDuration();
315 // libwebp only reports fully received frames for an
316 // animated image.
317 frameInfo->fFullyReceived = true;
Leon Scroggins IIIc8037dc2017-12-05 13:55:24 -0500318 frameInfo->fAlphaType = frame->hasAlpha() ? kUnpremul_SkAlphaType
319 : kOpaque_SkAlphaType;
Leon Scroggins III33deb7e2017-06-07 12:31:51 -0400320 frameInfo->fDisposalMethod = frame->getDisposalMethod();
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400321 }
322
323 return true;
324}
325
326static bool is_8888(SkColorType colorType) {
327 switch (colorType) {
328 case kRGBA_8888_SkColorType:
329 case kBGRA_8888_SkColorType:
330 return true;
331 default:
332 return false;
333 }
334}
335
Leon Scroggins III03588412017-11-17 08:07:32 -0500336// Requires that the src input be unpremultiplied (or opaque).
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400337static void blend_line(SkColorType dstCT, void* dst,
Mike Klein45c16fa2017-07-18 18:15:13 -0400338 SkColorType srcCT, const void* src,
Leon Scroggins III03588412017-11-17 08:07:32 -0500339 SkAlphaType dstAt,
340 bool srcHasAlpha,
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400341 int width) {
Mike Klein45c16fa2017-07-18 18:15:13 -0400342 SkJumper_MemoryCtx dst_ctx = { (void*)dst, 0 },
343 src_ctx = { (void*)src, 0 };
344
Mike Kleinb24704d2017-05-24 07:53:00 -0400345 SkRasterPipeline_<256> p;
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400346
Mike Klein1a3eb522018-10-18 10:11:00 -0400347 p.append_load_dst(dstCT, &dst_ctx);
Leon Scroggins III03588412017-11-17 08:07:32 -0500348 if (kUnpremul_SkAlphaType == dstAt) {
Mike Klein1a3eb522018-10-18 10:11:00 -0400349 p.append(SkRasterPipeline::premul_dst);
Leon Scroggins III03588412017-11-17 08:07:32 -0500350 }
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400351
Mike Klein1a3eb522018-10-18 10:11:00 -0400352 p.append_load(srcCT, &src_ctx);
Leon Scroggins III03588412017-11-17 08:07:32 -0500353 if (srcHasAlpha) {
354 p.append(SkRasterPipeline::premul);
355 }
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400356
357 p.append(SkRasterPipeline::srcover);
358
Leon Scroggins III03588412017-11-17 08:07:32 -0500359 if (kUnpremul_SkAlphaType == dstAt) {
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400360 p.append(SkRasterPipeline::unpremul);
361 }
Mike Klein1a3eb522018-10-18 10:11:00 -0400362 p.append_store(dstCT, &dst_ctx);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400363
Mike Klein45c16fa2017-07-18 18:15:13 -0400364 p.run(0,0, width,1);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400365}
366
scroggoeb602a52015-07-09 08:16:03 -0700367SkCodec::Result SkWebpCodec::onGetPixels(const SkImageInfo& dstInfo, void* dst, size_t rowBytes,
Leon Scroggins571b30f2017-07-11 17:35:31 +0000368 const Options& options, int* rowsDecodedPtr) {
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400369 const int index = options.fFrameIndex;
Leon Scroggins III1f6af6b2017-06-12 16:41:09 -0400370 SkASSERT(0 == index || index < fFrameHolder.size());
Leon Scroggins III42ee2842018-01-14 14:46:51 -0500371 SkASSERT(0 == index || !options.fSubset);
scroggo6f5e6192015-06-18 12:53:43 -0700372
373 WebPDecoderConfig config;
374 if (0 == WebPInitDecoderConfig(&config)) {
375 // ABI mismatch.
376 // FIXME: New enum for this?
377 return kInvalidInput;
378 }
379
380 // Free any memory associated with the buffer. Must be called last, so we declare it first.
381 SkAutoTCallVProc<WebPDecBuffer, WebPFreeDecBuffer> autoFree(&(config.output));
382
Matt Sarett5c496172017-02-07 17:01:16 -0500383 WebPIterator frame;
384 SkAutoTCallVProc<WebPIterator, WebPDemuxReleaseIterator> autoFrame(&frame);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400385 // If this succeeded in onGetFrameCount(), it should succeed again here.
386 SkAssertResult(WebPDemuxGetFrame(fDemux, index + 1, &frame));
Matt Sarett604971e2017-02-06 09:51:48 -0500387
Leon Scroggins III1f6af6b2017-06-12 16:41:09 -0400388 const bool independent = index == 0 ? true :
Nigel Tao66bc5242018-08-22 10:56:03 +1000389 (fFrameHolder.frame(index)->getRequiredFrame() == kNoFrame);
Matt Sarett5c496172017-02-07 17:01:16 -0500390 // Get the frameRect. libwebp will have already signaled an error if this is not fully
391 // contained by the canvas.
392 auto frameRect = SkIRect::MakeXYWH(frame.x_offset, frame.y_offset, frame.width, frame.height);
Leon Scroggins III712476e2018-10-03 15:47:00 -0400393 SkASSERT(this->bounds().contains(frameRect));
394 const bool frameIsSubset = frameRect != this->bounds();
Leon Scroggins III1f6af6b2017-06-12 16:41:09 -0400395 if (independent && frameIsSubset) {
Leon Scroggins IIIe643a9e2018-08-03 16:15:04 -0400396 SkSampler::Fill(dstInfo, dst, rowBytes, options.fZeroInitialized);
Matt Sarett604971e2017-02-06 09:51:48 -0500397 }
398
Matt Sarett5c496172017-02-07 17:01:16 -0500399 int dstX = frameRect.x();
400 int dstY = frameRect.y();
401 int subsetWidth = frameRect.width();
402 int subsetHeight = frameRect.height();
403 if (options.fSubset) {
404 SkIRect subset = *options.fSubset;
Leon Scroggins III712476e2018-10-03 15:47:00 -0400405 SkASSERT(this->bounds().contains(subset));
Matt Sarett5c496172017-02-07 17:01:16 -0500406 SkASSERT(SkIsAlign2(subset.fLeft) && SkIsAlign2(subset.fTop));
407 SkASSERT(this->getValidSubset(&subset) && subset == *options.fSubset);
408
409 if (!SkIRect::IntersectsNoEmptyCheck(subset, frameRect)) {
410 return kSuccess;
411 }
412
413 int minXOffset = SkTMin(dstX, subset.x());
414 int minYOffset = SkTMin(dstY, subset.y());
415 dstX -= minXOffset;
416 dstY -= minYOffset;
417 frameRect.offset(-minXOffset, -minYOffset);
418 subset.offset(-minXOffset, -minYOffset);
419
420 // Just like we require that the requested subset x and y offset are even, libwebp
421 // guarantees that the frame x and y offset are even (it's actually impossible to specify
422 // an odd frame offset). So we can still guarantee that the adjusted offsets are even.
423 SkASSERT(SkIsAlign2(subset.fLeft) && SkIsAlign2(subset.fTop));
424
425 SkIRect intersection;
426 SkAssertResult(intersection.intersect(frameRect, subset));
427 subsetWidth = intersection.width();
428 subsetHeight = intersection.height();
429
430 config.options.use_cropping = 1;
431 config.options.crop_left = subset.x();
432 config.options.crop_top = subset.y();
433 config.options.crop_width = subsetWidth;
434 config.options.crop_height = subsetHeight;
435 }
436
437 // Ignore the frame size and offset when determining if scaling is necessary.
438 int scaledWidth = subsetWidth;
439 int scaledHeight = subsetHeight;
Leon Scroggins III712476e2018-10-03 15:47:00 -0400440 SkISize srcSize = options.fSubset ? options.fSubset->size() : this->dimensions();
Matt Sarett5c496172017-02-07 17:01:16 -0500441 if (srcSize != dstInfo.dimensions()) {
scroggo6f5e6192015-06-18 12:53:43 -0700442 config.options.use_scaling = 1;
Matt Sarett5c496172017-02-07 17:01:16 -0500443
444 if (frameIsSubset) {
445 float scaleX = ((float) dstInfo.width()) / srcSize.width();
446 float scaleY = ((float) dstInfo.height()) / srcSize.height();
447
448 // We need to be conservative here and floor rather than round.
449 // Otherwise, we may find ourselves decoding off the end of memory.
450 dstX = scaleX * dstX;
451 scaledWidth = scaleX * scaledWidth;
452 dstY = scaleY * dstY;
453 scaledHeight = scaleY * scaledHeight;
454 if (0 == scaledWidth || 0 == scaledHeight) {
455 return kSuccess;
456 }
457 } else {
458 scaledWidth = dstInfo.width();
459 scaledHeight = dstInfo.height();
460 }
461
462 config.options.scaled_width = scaledWidth;
463 config.options.scaled_height = scaledHeight;
scroggo6f5e6192015-06-18 12:53:43 -0700464 }
465
Leon Scroggins III1f6af6b2017-06-12 16:41:09 -0400466 const bool blendWithPrevFrame = !independent && frame.blend_method == WEBP_MUX_BLEND
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400467 && frame.has_alpha;
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400468
469 SkBitmap webpDst;
Leon Scroggins IIIee92f132017-05-23 15:28:46 -0400470 auto webpInfo = dstInfo;
471 if (!frame.has_alpha) {
472 webpInfo = webpInfo.makeAlphaType(kOpaque_SkAlphaType);
473 }
474 if (this->colorXform()) {
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400475 // Swizzling between RGBA and BGRA is zero cost in a color transform. So when we have a
476 // color transform, we should decode to whatever is easiest for libwebp, and then let the
477 // color transform swizzle if necessary.
478 // Lossy webp is encoded as YUV (so RGBA and BGRA are the same cost). Lossless webp is
479 // 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 -0400480 webpInfo = webpInfo.makeColorType(kBGRA_8888_SkColorType);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400481
Leon Scroggins IIIee92f132017-05-23 15:28:46 -0400482 if (webpInfo.alphaType() == kPremul_SkAlphaType) {
483 webpInfo = webpInfo.makeAlphaType(kUnpremul_SkAlphaType);
484 }
485 }
486
487 if ((this->colorXform() && !is_8888(dstInfo.colorType())) || blendWithPrevFrame) {
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400488 // We will decode the entire image and then perform the color transform. libwebp
489 // does not provide a row-by-row API. This is a shame particularly when we do not want
490 // 8888, since we will need to create another image sized buffer.
Leon Scroggins IIIee92f132017-05-23 15:28:46 -0400491 webpDst.allocPixels(webpInfo);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400492 } else {
493 // libwebp can decode directly into the output memory.
Leon Scroggins IIIee92f132017-05-23 15:28:46 -0400494 webpDst.installPixels(webpInfo, dst, rowBytes);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400495 }
496
Leon Scroggins III36f7e322018-08-27 11:55:46 -0400497 config.output.colorspace = webp_decode_mode(webpInfo.colorType(),
498 frame.has_alpha && dstInfo.alphaType() == kPremul_SkAlphaType && !this->colorXform());
scroggo6f5e6192015-06-18 12:53:43 -0700499 config.output.is_external_memory = 1;
500
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400501 config.output.u.RGBA.rgba = reinterpret_cast<uint8_t*>(webpDst.getAddr(dstX, dstY));
502 config.output.u.RGBA.stride = static_cast<int>(webpDst.rowBytes());
Mike Reedf0ffb892017-10-03 14:47:21 -0400503 config.output.u.RGBA.size = webpDst.computeByteSize();
msarettff2a6c82016-09-07 11:23:28 -0700504
halcanary96fcdcc2015-08-27 07:41:13 -0700505 SkAutoTCallVProc<WebPIDecoder, WebPIDelete> idec(WebPIDecode(nullptr, 0, &config));
scroggo6f5e6192015-06-18 12:53:43 -0700506 if (!idec) {
507 return kInvalidInput;
508 }
509
Leon Scroggins IIIe5677462017-09-27 16:31:08 -0400510 int rowsDecoded = 0;
msarette99883f2016-09-08 06:05:35 -0700511 SkCodec::Result result;
msarettff2a6c82016-09-07 11:23:28 -0700512 switch (WebPIUpdate(idec, frame.fragment.bytes, frame.fragment.size)) {
513 case VP8_STATUS_OK:
Matt Sarett5c496172017-02-07 17:01:16 -0500514 rowsDecoded = scaledHeight;
msarette99883f2016-09-08 06:05:35 -0700515 result = kSuccess;
516 break;
msarettff2a6c82016-09-07 11:23:28 -0700517 case VP8_STATUS_SUSPENDED:
Leon Scroggins IIIe5677462017-09-27 16:31:08 -0400518 if (!WebPIDecGetRGB(idec, &rowsDecoded, nullptr, nullptr, nullptr)
519 || rowsDecoded <= 0) {
520 return kInvalidInput;
521 }
Matt Sarett5c496172017-02-07 17:01:16 -0500522 *rowsDecodedPtr = rowsDecoded + dstY;
msarette99883f2016-09-08 06:05:35 -0700523 result = kIncompleteInput;
524 break;
msarettff2a6c82016-09-07 11:23:28 -0700525 default:
526 return kInvalidInput;
scroggo6f5e6192015-06-18 12:53:43 -0700527 }
msarette99883f2016-09-08 06:05:35 -0700528
Mike Reed7fcfb622018-02-09 13:26:46 -0500529 const size_t dstBpp = dstInfo.bytesPerPixel();
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400530 dst = SkTAddOffset<void>(dst, dstBpp * dstX + rowBytes * dstY);
531 const size_t srcRowBytes = config.output.u.RGBA.stride;
532
533 const auto dstCT = dstInfo.colorType();
Matt Sarett313c4632016-10-20 12:35:23 -0400534 if (this->colorXform()) {
Matt Sarett5c496172017-02-07 17:01:16 -0500535 uint32_t* xformSrc = (uint32_t*) config.output.u.RGBA.rgba;
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400536 SkBitmap tmp;
537 void* xformDst;
538
539 if (blendWithPrevFrame) {
540 // Xform into temporary bitmap big enough for one row.
541 tmp.allocPixels(dstInfo.makeWH(scaledWidth, 1));
542 xformDst = tmp.getPixels();
543 } else {
544 xformDst = dst;
545 }
Leon Scroggins III03588412017-11-17 08:07:32 -0500546
Robert Phillipsb3050b92017-02-06 13:12:18 +0000547 for (int y = 0; y < rowsDecoded; y++) {
Leon Scroggins III36f7e322018-08-27 11:55:46 -0400548 this->applyColorXform(xformDst, xformSrc, scaledWidth);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400549 if (blendWithPrevFrame) {
Mike Klein76f57062018-06-08 14:00:19 -0400550 blend_line(dstCT, dst, dstCT, xformDst,
Leon Scroggins III03588412017-11-17 08:07:32 -0500551 dstInfo.alphaType(), frame.has_alpha, scaledWidth);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400552 dst = SkTAddOffset<void>(dst, rowBytes);
553 } else {
554 xformDst = SkTAddOffset<void>(xformDst, rowBytes);
555 }
Matt Sarett5c496172017-02-07 17:01:16 -0500556 xformSrc = SkTAddOffset<uint32_t>(xformSrc, srcRowBytes);
msarette99883f2016-09-08 06:05:35 -0700557 }
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400558 } else if (blendWithPrevFrame) {
559 const uint8_t* src = config.output.u.RGBA.rgba;
560
561 for (int y = 0; y < rowsDecoded; y++) {
Mike Klein76f57062018-06-08 14:00:19 -0400562 blend_line(dstCT, dst, webpDst.colorType(), src,
Leon Scroggins III03588412017-11-17 08:07:32 -0500563 dstInfo.alphaType(), frame.has_alpha, scaledWidth);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400564 src = SkTAddOffset<const uint8_t>(src, srcRowBytes);
565 dst = SkTAddOffset<void>(dst, rowBytes);
566 }
msarette99883f2016-09-08 06:05:35 -0700567 }
568
569 return result;
scroggo6f5e6192015-06-18 12:53:43 -0700570}
571
Leon Scroggins III36f7e322018-08-27 11:55:46 -0400572SkWebpCodec::SkWebpCodec(SkEncodedInfo&& info, std::unique_ptr<SkStream> stream,
Leon Scroggins IIIda3e9ad2018-01-26 15:48:26 -0500573 WebPDemuxer* demux, sk_sp<SkData> data, SkEncodedOrigin origin)
Leon Scroggins III36f7e322018-08-27 11:55:46 -0400574 : INHERITED(std::move(info), skcms_PixelFormat_BGRA_8888, std::move(stream),
575 origin)
msarettff2a6c82016-09-07 11:23:28 -0700576 , fDemux(demux)
577 , fData(std::move(data))
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400578 , fFailed(false)
579{
Leon Scroggins III36f7e322018-08-27 11:55:46 -0400580 const auto& eInfo = this->getEncodedInfo();
581 fFrameHolder.setScreenSize(eInfo.width(), eInfo.height());
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400582}