blob: d5614d6213e91db01707d0bdbbe851fb0d2035f0 [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"
Mike Reedede7bac2017-07-23 15:30:02 -040014#include "SkMakeUnique.h"
Leon Scroggins III557fbbe2017-05-23 09:37:21 -040015#include "SkRasterPipeline.h"
Matt Sarett5c496172017-02-07 17:01:16 -050016#include "SkSampler.h"
msarettff2a6c82016-09-07 11:23:28 -070017#include "SkStreamPriv.h"
scroggo6f5e6192015-06-18 12:53:43 -070018#include "SkTemplates.h"
Matt Sarett5c496172017-02-07 17:01:16 -050019#include "SkWebpCodec.h"
Mike Klein45c16fa2017-07-18 18:15:13 -040020#include "../jumper/SkJumper.h"
scroggo6f5e6192015-06-18 12:53:43 -070021
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"
msarett9d15dab2016-08-24 07:36:06 -070031#include "webp/demux.h"
scroggo6f5e6192015-06-18 12:53:43 -070032#include "webp/encode.h"
33
scroggodb30be22015-12-08 18:54:13 -080034bool SkWebpCodec::IsWebp(const void* buf, size_t bytesRead) {
scroggo6f5e6192015-06-18 12:53:43 -070035 // WEBP starts with the following:
36 // RIFFXXXXWEBPVP
37 // Where XXXX is unspecified.
scroggodb30be22015-12-08 18:54:13 -080038 const char* bytes = static_cast<const char*>(buf);
39 return bytesRead >= 14 && !memcmp(bytes, "RIFF", 4) && !memcmp(&bytes[8], "WEBPVP", 6);
scroggo6f5e6192015-06-18 12:53:43 -070040}
41
scroggo6f5e6192015-06-18 12:53:43 -070042// Parse headers of RIFF container, and check for valid Webp (VP8) content.
Leon Scroggins III557fbbe2017-05-23 09:37:21 -040043// Returns an SkWebpCodec on success
Mike Reedede7bac2017-07-23 15:30:02 -040044std::unique_ptr<SkCodec> SkWebpCodec::MakeFromStream(std::unique_ptr<SkStream> stream,
45 Result* result) {
msarettff2a6c82016-09-07 11:23:28 -070046 // 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 {
Mike Reedede7bac2017-07-23 15:30:02 -040052 data = SkCopyStreamToData(stream.get());
scroggodb30be22015-12-08 18:54:13 -080053
msarettff2a6c82016-09-07 11:23:28 -070054 // 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 -040055 stream.reset(nullptr);
msarettff2a6c82016-09-07 11:23:28 -070056 }
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() };
Leon Scroggins III588fb042017-07-14 16:32:31 -040062 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;
scroggo6f5e6192015-06-18 12:53:43 -070075 }
76
Matt Sarett5c496172017-02-07 17:01:16 -050077 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);
Matt Sarett5c496172017-02-07 17:01:16 -050083 // now check that if we are 4-bytes per pixel, we also don't overflow
Leon Scroggins III588fb042017-07-14 16:32:31 -040084 if (!sk_64_isS32(size) || sk_64_asS32(size) > (0x7FFFFFFF >> 2)) {
85 *result = kInvalidInput;
Matt Sarett5c496172017-02-07 17:01:16 -050086 return nullptr;
87 }
88 }
89
msarettff2a6c82016-09-07 11:23:28 -070090 WebPChunkIterator chunkIterator;
91 SkAutoTCallVProc<WebPChunkIterator, WebPDemuxReleaseChunkIterator> autoCI(&chunkIterator);
92 sk_sp<SkColorSpace> colorSpace = nullptr;
93 if (WebPDemuxGetChunk(demux, "ICCP", 1, &chunkIterator)) {
Brian Osman526972e2016-10-24 09:24:02 -040094 colorSpace = SkColorSpace::MakeICC(chunkIterator.chunk.bytes, chunkIterator.chunk.size);
scroggo6f5e6192015-06-18 12:53:43 -070095 }
Leon Scroggins IIIf78b55c2017-10-31 13:49:14 -040096 if (!colorSpace || colorSpace->type() != SkColorSpace::kRGB_Type) {
Matt Sarett77a7a1b2017-02-07 13:56:11 -050097 colorSpace = SkColorSpace::MakeSRGB();
msarettff2a6c82016-09-07 11:23:28 -070098 }
99
Matt Sarett5c496172017-02-07 17:01:16 -0500100 // Get the first frame and its "features" to determine the color and alpha types.
msarettff2a6c82016-09-07 11:23:28 -0700101 WebPIterator frame;
102 SkAutoTCallVProc<WebPIterator, WebPDemuxReleaseIterator> autoFrame(&frame);
103 if (!WebPDemuxGetFrame(demux, 1, &frame)) {
Leon Scroggins III588fb042017-07-14 16:32:31 -0400104 *result = kIncompleteInput;
msarettff2a6c82016-09-07 11:23:28 -0700105 return nullptr;
106 }
107
msarettff2a6c82016-09-07 11:23:28 -0700108 WebPBitstreamFeatures features;
Leon Scroggins III588fb042017-07-14 16:32:31 -0400109 switch (WebPGetFeatures(frame.fragment.bytes, frame.fragment.size, &features)) {
110 case VP8_STATUS_OK:
111 break;
112 case VP8_STATUS_SUSPENDED:
113 case VP8_STATUS_NOT_ENOUGH_DATA:
114 *result = kIncompleteInput;
115 return nullptr;
116 default:
117 *result = kInvalidInput;
118 return nullptr;
msarettff2a6c82016-09-07 11:23:28 -0700119 }
120
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400121 const bool hasAlpha = SkToBool(frame.has_alpha)
122 || frame.width != width || frame.height != height;
msarettac6c7502016-04-25 09:30:24 -0700123 SkEncodedInfo::Color color;
124 SkEncodedInfo::Alpha alpha;
125 switch (features.format) {
126 case 0:
Matt Sarett5c496172017-02-07 17:01:16 -0500127 // This indicates a "mixed" format. We could see this for
128 // animated webps (multiple fragments).
msarettac6c7502016-04-25 09:30:24 -0700129 // We could also guess kYUV here, but I think it makes more
130 // sense to guess kBGRA which is likely closer to the final
131 // output. Otherwise, we might end up converting
132 // BGRA->YUVA->BGRA.
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400133 // Fallthrough:
134 case 2:
135 // This is the lossless format (BGRA).
136 if (hasAlpha) {
137 color = SkEncodedInfo::kBGRA_Color;
138 alpha = SkEncodedInfo::kUnpremul_Alpha;
139 } else {
140 color = SkEncodedInfo::kBGRX_Color;
141 alpha = SkEncodedInfo::kOpaque_Alpha;
142 }
msarettac6c7502016-04-25 09:30:24 -0700143 break;
144 case 1:
145 // This is the lossy format (YUV).
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400146 if (hasAlpha) {
msarettac6c7502016-04-25 09:30:24 -0700147 color = SkEncodedInfo::kYUVA_Color;
msarettc30c4182016-04-20 11:53:35 -0700148 alpha = SkEncodedInfo::kUnpremul_Alpha;
msarettac6c7502016-04-25 09:30:24 -0700149 } else {
150 color = SkEncodedInfo::kYUV_Color;
151 alpha = SkEncodedInfo::kOpaque_Alpha;
152 }
153 break;
msarettac6c7502016-04-25 09:30:24 -0700154 default:
Leon Scroggins III588fb042017-07-14 16:32:31 -0400155 *result = kInvalidInput;
msarettac6c7502016-04-25 09:30:24 -0700156 return nullptr;
scroggo6f5e6192015-06-18 12:53:43 -0700157 }
scroggo6f5e6192015-06-18 12:53:43 -0700158
Leon Scroggins III588fb042017-07-14 16:32:31 -0400159 *result = kSuccess;
msarettac6c7502016-04-25 09:30:24 -0700160 SkEncodedInfo info = SkEncodedInfo::Make(color, alpha, 8);
Mike Reedede7bac2017-07-23 15:30:02 -0400161 return std::unique_ptr<SkCodec>(new SkWebpCodec(width, height, info, std::move(colorSpace),
162 std::move(stream), demux.release(), std::move(data)));
scroggo6f5e6192015-06-18 12:53:43 -0700163}
164
scroggo6f5e6192015-06-18 12:53:43 -0700165SkISize SkWebpCodec::onGetScaledDimensions(float desiredScale) const {
166 SkISize dim = this->getInfo().dimensions();
msaretta0c414d2015-06-19 07:34:30 -0700167 // SkCodec treats zero dimensional images as errors, so the minimum size
168 // that we will recommend is 1x1.
169 dim.fWidth = SkTMax(1, SkScalarRoundToInt(desiredScale * dim.fWidth));
170 dim.fHeight = SkTMax(1, SkScalarRoundToInt(desiredScale * dim.fHeight));
scroggo6f5e6192015-06-18 12:53:43 -0700171 return dim;
172}
173
scroggoe7fc14b2015-10-02 13:14:46 -0700174bool SkWebpCodec::onDimensionsSupported(const SkISize& dim) {
175 const SkImageInfo& info = this->getInfo();
176 return dim.width() >= 1 && dim.width() <= info.width()
177 && dim.height() >= 1 && dim.height() <= info.height();
178}
179
Leon Scroggins III03588412017-11-17 08:07:32 -0500180static WEBP_CSP_MODE webp_decode_mode(SkColorType dstCT, bool premultiply) {
181 switch (dstCT) {
scroggo6f5e6192015-06-18 12:53:43 -0700182 case kBGRA_8888_SkColorType:
183 return premultiply ? MODE_bgrA : MODE_BGRA;
184 case kRGBA_8888_SkColorType:
185 return premultiply ? MODE_rgbA : MODE_RGBA;
scroggo74992b52015-08-06 13:50:15 -0700186 case kRGB_565_SkColorType:
187 return MODE_RGB_565;
scroggo6f5e6192015-06-18 12:53:43 -0700188 default:
189 return MODE_LAST;
190 }
191}
192
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400193SkWebpCodec::Frame* SkWebpCodec::FrameHolder::appendNewFrame(bool hasAlpha) {
194 const int i = this->size();
195 fFrames.emplace_back(i, hasAlpha);
196 return &fFrames[i];
197}
198
scroggob636b452015-07-22 07:16:20 -0700199bool SkWebpCodec::onGetValidSubset(SkIRect* desiredSubset) const {
200 if (!desiredSubset) {
201 return false;
202 }
203
msarettfdb47572015-10-13 12:50:14 -0700204 SkIRect dimensions = SkIRect::MakeSize(this->getInfo().dimensions());
205 if (!dimensions.contains(*desiredSubset)) {
scroggob636b452015-07-22 07:16:20 -0700206 return false;
207 }
208
209 // As stated below, libwebp snaps to even left and top. Make sure top and left are even, so we
210 // decode this exact subset.
211 // Leave right and bottom unmodified, so we suggest a slightly larger subset than requested.
212 desiredSubset->fLeft = (desiredSubset->fLeft >> 1) << 1;
213 desiredSubset->fTop = (desiredSubset->fTop >> 1) << 1;
214 return true;
215}
216
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400217int SkWebpCodec::onGetRepetitionCount() {
218 auto flags = WebPDemuxGetI(fDemux.get(), WEBP_FF_FORMAT_FLAGS);
219 if (!(flags & ANIMATION_FLAG)) {
220 return 0;
221 }
222
223 const int repCount = WebPDemuxGetI(fDemux.get(), WEBP_FF_LOOP_COUNT);
224 if (0 == repCount) {
225 return kRepetitionCountInfinite;
226 }
227
228 return repCount;
229}
230
231int SkWebpCodec::onGetFrameCount() {
232 auto flags = WebPDemuxGetI(fDemux.get(), WEBP_FF_FORMAT_FLAGS);
233 if (!(flags & ANIMATION_FLAG)) {
234 return 1;
235 }
236
237 const uint32_t oldFrameCount = fFrameHolder.size();
238 if (fFailed) {
239 return oldFrameCount;
240 }
241
242 const uint32_t frameCount = WebPDemuxGetI(fDemux, WEBP_FF_FRAME_COUNT);
243 if (oldFrameCount == frameCount) {
244 // We have already parsed this.
245 return frameCount;
246 }
247
248 fFrameHolder.reserve(frameCount);
249
250 for (uint32_t i = oldFrameCount; i < frameCount; i++) {
251 WebPIterator iter;
252 SkAutoTCallVProc<WebPIterator, WebPDemuxReleaseIterator> autoIter(&iter);
253
254 if (!WebPDemuxGetFrame(fDemux.get(), i + 1, &iter)) {
255 fFailed = true;
256 break;
257 }
258
259 // libwebp only reports complete frames of an animated image.
260 SkASSERT(iter.complete);
261
262 Frame* frame = fFrameHolder.appendNewFrame(iter.has_alpha);
263 frame->setXYWH(iter.x_offset, iter.y_offset, iter.width, iter.height);
264 frame->setDisposalMethod(iter.dispose_method == WEBP_MUX_DISPOSE_BACKGROUND ?
Leon Scroggins III33deb7e2017-06-07 12:31:51 -0400265 SkCodecAnimation::DisposalMethod::kRestoreBGColor :
266 SkCodecAnimation::DisposalMethod::kKeep);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400267 frame->setDuration(iter.duration);
268 if (WEBP_MUX_BLEND != iter.blend_method) {
269 frame->setBlend(SkCodecAnimation::Blend::kBG);
270 }
271 fFrameHolder.setAlphaAndRequiredFrame(frame);
272 }
273
274 return fFrameHolder.size();
275
276}
277
278const SkFrame* SkWebpCodec::FrameHolder::onGetFrame(int i) const {
279 return static_cast<const SkFrame*>(this->frame(i));
280}
281
282const SkWebpCodec::Frame* SkWebpCodec::FrameHolder::frame(int i) const {
283 SkASSERT(i >= 0 && i < this->size());
284 return &fFrames[i];
285}
286
287bool SkWebpCodec::onGetFrameInfo(int i, FrameInfo* frameInfo) const {
288 if (i >= fFrameHolder.size()) {
289 return false;
290 }
291
292 const Frame* frame = fFrameHolder.frame(i);
293 if (!frame) {
294 return false;
295 }
296
297 if (frameInfo) {
298 frameInfo->fRequiredFrame = frame->getRequiredFrame();
299 frameInfo->fDuration = frame->getDuration();
300 // libwebp only reports fully received frames for an
301 // animated image.
302 frameInfo->fFullyReceived = true;
Leon Scroggins IIIae79f322017-08-18 10:53:24 -0400303 frameInfo->fAlpha = frame->hasAlpha() ? SkEncodedInfo::kUnpremul_Alpha
304 : SkEncodedInfo::kOpaque_Alpha;
Leon Scroggins III33deb7e2017-06-07 12:31:51 -0400305 frameInfo->fDisposalMethod = frame->getDisposalMethod();
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400306 }
307
308 return true;
309}
310
311static bool is_8888(SkColorType colorType) {
312 switch (colorType) {
313 case kRGBA_8888_SkColorType:
314 case kBGRA_8888_SkColorType:
315 return true;
316 default:
317 return false;
318 }
319}
320
321static void pick_memory_stages(SkColorType ct, SkRasterPipeline::StockStage* load,
322 SkRasterPipeline::StockStage* store) {
323 switch(ct) {
324 case kUnknown_SkColorType:
325 case kAlpha_8_SkColorType:
326 case kARGB_4444_SkColorType:
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400327 case kGray_8_SkColorType:
328 SkASSERT(false);
329 break;
330 case kRGB_565_SkColorType:
331 if (load) *load = SkRasterPipeline::load_565;
332 if (store) *store = SkRasterPipeline::store_565;
333 break;
334 case kRGBA_8888_SkColorType:
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400335 if (load) *load = SkRasterPipeline::load_8888;
336 if (store) *store = SkRasterPipeline::store_8888;
337 break;
Mike Kleinc2d20762017-06-27 19:53:21 -0400338 case kBGRA_8888_SkColorType:
339 if (load) *load = SkRasterPipeline::load_bgra;
340 if (store) *store = SkRasterPipeline::store_bgra;
341 break;
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400342 case kRGBA_F16_SkColorType:
343 if (load) *load = SkRasterPipeline::load_f16;
344 if (store) *store = SkRasterPipeline::store_f16;
345 break;
346 }
347}
348
Leon Scroggins III03588412017-11-17 08:07:32 -0500349// Requires that the src input be unpremultiplied (or opaque).
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400350static void blend_line(SkColorType dstCT, void* dst,
Mike Klein45c16fa2017-07-18 18:15:13 -0400351 SkColorType srcCT, const void* src,
Leon Scroggins III03588412017-11-17 08:07:32 -0500352 bool needsSrgbToLinear,
353 SkAlphaType dstAt,
354 bool srcHasAlpha,
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400355 int width) {
Mike Klein45c16fa2017-07-18 18:15:13 -0400356 SkJumper_MemoryCtx dst_ctx = { (void*)dst, 0 },
357 src_ctx = { (void*)src, 0 };
358
Mike Kleinb24704d2017-05-24 07:53:00 -0400359 SkRasterPipeline_<256> p;
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400360 SkRasterPipeline::StockStage load_dst, store_dst;
361 pick_memory_stages(dstCT, &load_dst, &store_dst);
362
363 // Load the final dst.
Mike Klein45c16fa2017-07-18 18:15:13 -0400364 p.append(load_dst, &dst_ctx);
Leon Scroggins III03588412017-11-17 08:07:32 -0500365 if (needsSrgbToLinear) {
366 p.append_from_srgb(dstAt);
367 }
368 if (kUnpremul_SkAlphaType == dstAt) {
369 p.append(SkRasterPipeline::premul);
370 }
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400371 p.append(SkRasterPipeline::move_src_dst);
372
373 // Load the src.
374 SkRasterPipeline::StockStage load_src;
375 pick_memory_stages(srcCT, &load_src, nullptr);
Mike Klein45c16fa2017-07-18 18:15:13 -0400376 p.append(load_src, &src_ctx);
Leon Scroggins III03588412017-11-17 08:07:32 -0500377 if (needsSrgbToLinear) {
378 p.append_from_srgb(kUnpremul_SkAlphaType);
379 }
380 if (srcHasAlpha) {
381 p.append(SkRasterPipeline::premul);
382 }
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400383
384 p.append(SkRasterPipeline::srcover);
385
386 // Convert back to dst.
Leon Scroggins III03588412017-11-17 08:07:32 -0500387 if (kUnpremul_SkAlphaType == dstAt) {
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400388 p.append(SkRasterPipeline::unpremul);
389 }
390 if (needsSrgbToLinear) {
391 p.append(SkRasterPipeline::to_srgb);
392 }
Mike Klein45c16fa2017-07-18 18:15:13 -0400393 p.append(store_dst, &dst_ctx);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400394
Mike Klein45c16fa2017-07-18 18:15:13 -0400395 p.run(0,0, width,1);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400396}
397
scroggoeb602a52015-07-09 08:16:03 -0700398SkCodec::Result SkWebpCodec::onGetPixels(const SkImageInfo& dstInfo, void* dst, size_t rowBytes,
Leon Scroggins571b30f2017-07-11 17:35:31 +0000399 const Options& options, int* rowsDecodedPtr) {
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400400 const int index = options.fFrameIndex;
Leon Scroggins III1f6af6b2017-06-12 16:41:09 -0400401 SkASSERT(0 == index || index < fFrameHolder.size());
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400402
403 const auto& srcInfo = this->getInfo();
Leon Scroggins III1f6af6b2017-06-12 16:41:09 -0400404 SkASSERT(0 == index || (!options.fSubset && dstInfo.dimensions() == srcInfo.dimensions()));
scroggo6f5e6192015-06-18 12:53:43 -0700405
406 WebPDecoderConfig config;
407 if (0 == WebPInitDecoderConfig(&config)) {
408 // ABI mismatch.
409 // FIXME: New enum for this?
410 return kInvalidInput;
411 }
412
413 // Free any memory associated with the buffer. Must be called last, so we declare it first.
414 SkAutoTCallVProc<WebPDecBuffer, WebPFreeDecBuffer> autoFree(&(config.output));
415
Matt Sarett5c496172017-02-07 17:01:16 -0500416 WebPIterator frame;
417 SkAutoTCallVProc<WebPIterator, WebPDemuxReleaseIterator> autoFrame(&frame);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400418 // If this succeeded in onGetFrameCount(), it should succeed again here.
419 SkAssertResult(WebPDemuxGetFrame(fDemux, index + 1, &frame));
Matt Sarett604971e2017-02-06 09:51:48 -0500420
Leon Scroggins III1f6af6b2017-06-12 16:41:09 -0400421 const bool independent = index == 0 ? true :
422 (fFrameHolder.frame(index)->getRequiredFrame() == kNone);
Matt Sarett5c496172017-02-07 17:01:16 -0500423 // Get the frameRect. libwebp will have already signaled an error if this is not fully
424 // contained by the canvas.
425 auto frameRect = SkIRect::MakeXYWH(frame.x_offset, frame.y_offset, frame.width, frame.height);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400426 SkASSERT(srcInfo.bounds().contains(frameRect));
427 const bool frameIsSubset = frameRect != srcInfo.bounds();
Leon Scroggins III1f6af6b2017-06-12 16:41:09 -0400428 if (independent && frameIsSubset) {
429 SkSampler::Fill(dstInfo, dst, rowBytes, 0, options.fZeroInitialized);
Matt Sarett604971e2017-02-06 09:51:48 -0500430 }
431
Matt Sarett5c496172017-02-07 17:01:16 -0500432 int dstX = frameRect.x();
433 int dstY = frameRect.y();
434 int subsetWidth = frameRect.width();
435 int subsetHeight = frameRect.height();
436 if (options.fSubset) {
437 SkIRect subset = *options.fSubset;
438 SkASSERT(this->getInfo().bounds().contains(subset));
439 SkASSERT(SkIsAlign2(subset.fLeft) && SkIsAlign2(subset.fTop));
440 SkASSERT(this->getValidSubset(&subset) && subset == *options.fSubset);
441
442 if (!SkIRect::IntersectsNoEmptyCheck(subset, frameRect)) {
443 return kSuccess;
444 }
445
446 int minXOffset = SkTMin(dstX, subset.x());
447 int minYOffset = SkTMin(dstY, subset.y());
448 dstX -= minXOffset;
449 dstY -= minYOffset;
450 frameRect.offset(-minXOffset, -minYOffset);
451 subset.offset(-minXOffset, -minYOffset);
452
453 // Just like we require that the requested subset x and y offset are even, libwebp
454 // guarantees that the frame x and y offset are even (it's actually impossible to specify
455 // an odd frame offset). So we can still guarantee that the adjusted offsets are even.
456 SkASSERT(SkIsAlign2(subset.fLeft) && SkIsAlign2(subset.fTop));
457
458 SkIRect intersection;
459 SkAssertResult(intersection.intersect(frameRect, subset));
460 subsetWidth = intersection.width();
461 subsetHeight = intersection.height();
462
463 config.options.use_cropping = 1;
464 config.options.crop_left = subset.x();
465 config.options.crop_top = subset.y();
466 config.options.crop_width = subsetWidth;
467 config.options.crop_height = subsetHeight;
468 }
469
470 // Ignore the frame size and offset when determining if scaling is necessary.
471 int scaledWidth = subsetWidth;
472 int scaledHeight = subsetHeight;
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400473 SkISize srcSize = options.fSubset ? options.fSubset->size() : srcInfo.dimensions();
Matt Sarett5c496172017-02-07 17:01:16 -0500474 if (srcSize != dstInfo.dimensions()) {
scroggo6f5e6192015-06-18 12:53:43 -0700475 config.options.use_scaling = 1;
Matt Sarett5c496172017-02-07 17:01:16 -0500476
477 if (frameIsSubset) {
478 float scaleX = ((float) dstInfo.width()) / srcSize.width();
479 float scaleY = ((float) dstInfo.height()) / srcSize.height();
480
481 // We need to be conservative here and floor rather than round.
482 // Otherwise, we may find ourselves decoding off the end of memory.
483 dstX = scaleX * dstX;
484 scaledWidth = scaleX * scaledWidth;
485 dstY = scaleY * dstY;
486 scaledHeight = scaleY * scaledHeight;
487 if (0 == scaledWidth || 0 == scaledHeight) {
488 return kSuccess;
489 }
490 } else {
491 scaledWidth = dstInfo.width();
492 scaledHeight = dstInfo.height();
493 }
494
495 config.options.scaled_width = scaledWidth;
496 config.options.scaled_height = scaledHeight;
scroggo6f5e6192015-06-18 12:53:43 -0700497 }
498
Leon Scroggins III1f6af6b2017-06-12 16:41:09 -0400499 const bool blendWithPrevFrame = !independent && frame.blend_method == WEBP_MUX_BLEND
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400500 && frame.has_alpha;
501 if (blendWithPrevFrame && options.fPremulBehavior == SkTransferFunctionBehavior::kRespect) {
502 // Blending is done with SkRasterPipeline, which requires a color space that is valid for
503 // rendering.
504 const auto* cs = dstInfo.colorSpace();
505 if (!cs || (!cs->gammaCloseToSRGB() && !cs->gammaIsLinear())) {
506 return kInvalidConversion;
507 }
508 }
509
510 SkBitmap webpDst;
Leon Scroggins IIIee92f132017-05-23 15:28:46 -0400511 auto webpInfo = dstInfo;
512 if (!frame.has_alpha) {
513 webpInfo = webpInfo.makeAlphaType(kOpaque_SkAlphaType);
514 }
515 if (this->colorXform()) {
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400516 // Swizzling between RGBA and BGRA is zero cost in a color transform. So when we have a
517 // color transform, we should decode to whatever is easiest for libwebp, and then let the
518 // color transform swizzle if necessary.
519 // Lossy webp is encoded as YUV (so RGBA and BGRA are the same cost). Lossless webp is
520 // 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 -0400521 webpInfo = webpInfo.makeColorType(kBGRA_8888_SkColorType);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400522
Leon Scroggins IIIee92f132017-05-23 15:28:46 -0400523 if (webpInfo.alphaType() == kPremul_SkAlphaType) {
524 webpInfo = webpInfo.makeAlphaType(kUnpremul_SkAlphaType);
525 }
526 }
527
528 if ((this->colorXform() && !is_8888(dstInfo.colorType())) || blendWithPrevFrame) {
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400529 // We will decode the entire image and then perform the color transform. libwebp
530 // does not provide a row-by-row API. This is a shame particularly when we do not want
531 // 8888, since we will need to create another image sized buffer.
Leon Scroggins IIIee92f132017-05-23 15:28:46 -0400532 webpDst.allocPixels(webpInfo);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400533 } else {
534 // libwebp can decode directly into the output memory.
Leon Scroggins IIIee92f132017-05-23 15:28:46 -0400535 webpDst.installPixels(webpInfo, dst, rowBytes);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400536 }
537
Leon Scroggins III03588412017-11-17 08:07:32 -0500538 // Choose the step when we will perform premultiplication.
539 enum {
540 kNone,
541 kBlendLine,
542 kColorXform,
543 kLibwebp,
544 };
545 auto choose_premul_step = [&]() {
546 if (!frame.has_alpha) {
547 // None necessary.
548 return kNone;
549 }
550 if (blendWithPrevFrame) {
551 // Premultiply in blend_line, in a linear space.
552 return kBlendLine;
553 }
554 if (dstInfo.alphaType() != kPremul_SkAlphaType) {
555 // No blending is necessary, so we only need to premultiply if the
556 // client requested it.
557 return kNone;
558 }
559 if (this->colorXform()) {
560 // Premultiply in the colorXform, in a linear space.
561 return kColorXform;
562 }
563 return kLibwebp;
564 };
565 const auto premulStep = choose_premul_step();
566 config.output.colorspace = webp_decode_mode(webpInfo.colorType(), premulStep == kLibwebp);
scroggo6f5e6192015-06-18 12:53:43 -0700567 config.output.is_external_memory = 1;
568
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400569 config.output.u.RGBA.rgba = reinterpret_cast<uint8_t*>(webpDst.getAddr(dstX, dstY));
570 config.output.u.RGBA.stride = static_cast<int>(webpDst.rowBytes());
Mike Reedf0ffb892017-10-03 14:47:21 -0400571 config.output.u.RGBA.size = webpDst.computeByteSize();
msarettff2a6c82016-09-07 11:23:28 -0700572
halcanary96fcdcc2015-08-27 07:41:13 -0700573 SkAutoTCallVProc<WebPIDecoder, WebPIDelete> idec(WebPIDecode(nullptr, 0, &config));
scroggo6f5e6192015-06-18 12:53:43 -0700574 if (!idec) {
575 return kInvalidInput;
576 }
577
Leon Scroggins IIIe5677462017-09-27 16:31:08 -0400578 int rowsDecoded = 0;
msarette99883f2016-09-08 06:05:35 -0700579 SkCodec::Result result;
msarettff2a6c82016-09-07 11:23:28 -0700580 switch (WebPIUpdate(idec, frame.fragment.bytes, frame.fragment.size)) {
581 case VP8_STATUS_OK:
Matt Sarett5c496172017-02-07 17:01:16 -0500582 rowsDecoded = scaledHeight;
msarette99883f2016-09-08 06:05:35 -0700583 result = kSuccess;
584 break;
msarettff2a6c82016-09-07 11:23:28 -0700585 case VP8_STATUS_SUSPENDED:
Leon Scroggins IIIe5677462017-09-27 16:31:08 -0400586 if (!WebPIDecGetRGB(idec, &rowsDecoded, nullptr, nullptr, nullptr)
587 || rowsDecoded <= 0) {
588 return kInvalidInput;
589 }
Matt Sarett5c496172017-02-07 17:01:16 -0500590 *rowsDecodedPtr = rowsDecoded + dstY;
msarette99883f2016-09-08 06:05:35 -0700591 result = kIncompleteInput;
592 break;
msarettff2a6c82016-09-07 11:23:28 -0700593 default:
594 return kInvalidInput;
scroggo6f5e6192015-06-18 12:53:43 -0700595 }
msarette99883f2016-09-08 06:05:35 -0700596
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400597 const bool needsSrgbToLinear = dstInfo.gammaCloseToSRGB() &&
598 options.fPremulBehavior == SkTransferFunctionBehavior::kRespect;
599
600 const size_t dstBpp = SkColorTypeBytesPerPixel(dstInfo.colorType());
601 dst = SkTAddOffset<void>(dst, dstBpp * dstX + rowBytes * dstY);
602 const size_t srcRowBytes = config.output.u.RGBA.stride;
603
604 const auto dstCT = dstInfo.colorType();
Matt Sarett313c4632016-10-20 12:35:23 -0400605 if (this->colorXform()) {
Matt Sarett5c496172017-02-07 17:01:16 -0500606 uint32_t* xformSrc = (uint32_t*) config.output.u.RGBA.rgba;
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400607 SkBitmap tmp;
608 void* xformDst;
609
610 if (blendWithPrevFrame) {
611 // Xform into temporary bitmap big enough for one row.
612 tmp.allocPixels(dstInfo.makeWH(scaledWidth, 1));
613 xformDst = tmp.getPixels();
614 } else {
615 xformDst = dst;
616 }
Leon Scroggins III03588412017-11-17 08:07:32 -0500617
618 const auto xformAlphaType = (premulStep == kColorXform) ? kPremul_SkAlphaType :
619 ( frame.has_alpha) ? kUnpremul_SkAlphaType :
620 kOpaque_SkAlphaType ;
Robert Phillipsb3050b92017-02-06 13:12:18 +0000621 for (int y = 0; y < rowsDecoded; y++) {
Leon Scroggins2009c202017-11-15 13:49:19 +0000622 this->applyColorXform(xformDst, xformSrc, scaledWidth, xformAlphaType);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400623 if (blendWithPrevFrame) {
Leon Scroggins III03588412017-11-17 08:07:32 -0500624 blend_line(dstCT, dst, dstCT, xformDst, needsSrgbToLinear,
625 dstInfo.alphaType(), frame.has_alpha, scaledWidth);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400626 dst = SkTAddOffset<void>(dst, rowBytes);
627 } else {
628 xformDst = SkTAddOffset<void>(xformDst, rowBytes);
629 }
Matt Sarett5c496172017-02-07 17:01:16 -0500630 xformSrc = SkTAddOffset<uint32_t>(xformSrc, srcRowBytes);
msarette99883f2016-09-08 06:05:35 -0700631 }
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400632 } else if (blendWithPrevFrame) {
633 const uint8_t* src = config.output.u.RGBA.rgba;
634
635 for (int y = 0; y < rowsDecoded; y++) {
Mike Klein45c16fa2017-07-18 18:15:13 -0400636 blend_line(dstCT, dst, webpDst.colorType(), src, needsSrgbToLinear,
Leon Scroggins III03588412017-11-17 08:07:32 -0500637 dstInfo.alphaType(), frame.has_alpha, scaledWidth);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400638 src = SkTAddOffset<const uint8_t>(src, srcRowBytes);
639 dst = SkTAddOffset<void>(dst, rowBytes);
640 }
msarette99883f2016-09-08 06:05:35 -0700641 }
642
643 return result;
scroggo6f5e6192015-06-18 12:53:43 -0700644}
645
msarett9d15dab2016-08-24 07:36:06 -0700646SkWebpCodec::SkWebpCodec(int width, int height, const SkEncodedInfo& info,
Mike Reedede7bac2017-07-23 15:30:02 -0400647 sk_sp<SkColorSpace> colorSpace, std::unique_ptr<SkStream> stream,
648 WebPDemuxer* demux, sk_sp<SkData> data)
649 : INHERITED(width, height, info, SkColorSpaceXform::kBGRA_8888_ColorFormat, std::move(stream),
Leon Scroggins IIIc6e6a5f2017-06-05 15:53:38 -0400650 std::move(colorSpace))
msarettff2a6c82016-09-07 11:23:28 -0700651 , fDemux(demux)
652 , fData(std::move(data))
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400653 , fFailed(false)
654{
655 fFrameHolder.setScreenSize(width, height);
656}