blob: d94011a8670ad2db7daf914dc19e5f362d06f89b [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:
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400323 if (load) *load = SkRasterPipeline::load_8888;
324 if (store) *store = SkRasterPipeline::store_8888;
325 break;
Mike Kleinc2d20762017-06-27 19:53:21 -0400326 case kBGRA_8888_SkColorType:
327 if (load) *load = SkRasterPipeline::load_bgra;
328 if (store) *store = SkRasterPipeline::store_bgra;
329 break;
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400330 case kRGBA_F16_SkColorType:
331 if (load) *load = SkRasterPipeline::load_f16;
332 if (store) *store = SkRasterPipeline::store_f16;
333 break;
334 }
335}
336
337static void blend_line(SkColorType dstCT, void* dst,
338 SkColorType srcCT, void* src,
339 bool needsSrgbToLinear, SkAlphaType at,
340 int width) {
341 // Setup conversion from the source and dest, which will be the same.
Mike Kleinb24704d2017-05-24 07:53:00 -0400342 SkRasterPipeline_<256> convert_to_linear_premul;
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400343 if (needsSrgbToLinear) {
344 convert_to_linear_premul.append_from_srgb(at);
345 }
346 if (kUnpremul_SkAlphaType == at) {
347 // srcover assumes premultiplied inputs.
348 convert_to_linear_premul.append(SkRasterPipeline::premul);
349 }
350
Mike Kleinb24704d2017-05-24 07:53:00 -0400351 SkRasterPipeline_<256> p;
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400352 SkRasterPipeline::StockStage load_dst, store_dst;
353 pick_memory_stages(dstCT, &load_dst, &store_dst);
354
355 // Load the final dst.
356 p.append(load_dst, dst);
357 p.extend(convert_to_linear_premul);
358 p.append(SkRasterPipeline::move_src_dst);
359
360 // Load the src.
361 SkRasterPipeline::StockStage load_src;
362 pick_memory_stages(srcCT, &load_src, nullptr);
363 p.append(load_src, src);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400364 p.extend(convert_to_linear_premul);
365
366 p.append(SkRasterPipeline::srcover);
367
368 // Convert back to dst.
369 if (kUnpremul_SkAlphaType == at) {
370 p.append(SkRasterPipeline::unpremul);
371 }
372 if (needsSrgbToLinear) {
373 p.append(SkRasterPipeline::to_srgb);
374 }
375 p.append(store_dst, dst);
376
Mike Klein761d27c2017-06-01 12:37:08 -0400377 p.run(0,0, width);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400378}
379
scroggoeb602a52015-07-09 08:16:03 -0700380SkCodec::Result SkWebpCodec::onGetPixels(const SkImageInfo& dstInfo, void* dst, size_t rowBytes,
msarette6dd0042015-10-09 11:07:34 -0700381 const Options& options, SkPMColor*, int*,
msarette99883f2016-09-08 06:05:35 -0700382 int* rowsDecodedPtr) {
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400383 const int index = options.fFrameIndex;
Leon Scroggins III1f6af6b2017-06-12 16:41:09 -0400384 SkASSERT(0 == index || index < fFrameHolder.size());
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400385
386 const auto& srcInfo = this->getInfo();
Matt Sarettcf3f2342017-03-23 15:32:25 -0400387 {
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400388 auto info = srcInfo;
389 if (index > 0) {
390 auto alphaType = alpha_type(fFrameHolder.frame(index)->hasAlpha());
391 info = info.makeAlphaType(alphaType);
392 }
393 if (!conversion_possible(dstInfo, info) ||
394 !this->initializeColorXform(dstInfo, options.fPremulBehavior))
395 {
396 return kInvalidConversion;
397 }
398 }
399
Leon Scroggins III1f6af6b2017-06-12 16:41:09 -0400400 SkASSERT(0 == index || (!options.fSubset && dstInfo.dimensions() == srcInfo.dimensions()));
scroggo6f5e6192015-06-18 12:53:43 -0700401
402 WebPDecoderConfig config;
403 if (0 == WebPInitDecoderConfig(&config)) {
404 // ABI mismatch.
405 // FIXME: New enum for this?
406 return kInvalidInput;
407 }
408
409 // Free any memory associated with the buffer. Must be called last, so we declare it first.
410 SkAutoTCallVProc<WebPDecBuffer, WebPFreeDecBuffer> autoFree(&(config.output));
411
Matt Sarett5c496172017-02-07 17:01:16 -0500412 WebPIterator frame;
413 SkAutoTCallVProc<WebPIterator, WebPDemuxReleaseIterator> autoFrame(&frame);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400414 // If this succeeded in onGetFrameCount(), it should succeed again here.
415 SkAssertResult(WebPDemuxGetFrame(fDemux, index + 1, &frame));
Matt Sarett604971e2017-02-06 09:51:48 -0500416
Leon Scroggins III1f6af6b2017-06-12 16:41:09 -0400417 const bool independent = index == 0 ? true :
418 (fFrameHolder.frame(index)->getRequiredFrame() == kNone);
Matt Sarett5c496172017-02-07 17:01:16 -0500419 // Get the frameRect. libwebp will have already signaled an error if this is not fully
420 // contained by the canvas.
421 auto frameRect = SkIRect::MakeXYWH(frame.x_offset, frame.y_offset, frame.width, frame.height);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400422 SkASSERT(srcInfo.bounds().contains(frameRect));
423 const bool frameIsSubset = frameRect != srcInfo.bounds();
Leon Scroggins III1f6af6b2017-06-12 16:41:09 -0400424 if (independent && frameIsSubset) {
425 SkSampler::Fill(dstInfo, dst, rowBytes, 0, options.fZeroInitialized);
Matt Sarett604971e2017-02-06 09:51:48 -0500426 }
427
Matt Sarett5c496172017-02-07 17:01:16 -0500428 int dstX = frameRect.x();
429 int dstY = frameRect.y();
430 int subsetWidth = frameRect.width();
431 int subsetHeight = frameRect.height();
432 if (options.fSubset) {
433 SkIRect subset = *options.fSubset;
434 SkASSERT(this->getInfo().bounds().contains(subset));
435 SkASSERT(SkIsAlign2(subset.fLeft) && SkIsAlign2(subset.fTop));
436 SkASSERT(this->getValidSubset(&subset) && subset == *options.fSubset);
437
438 if (!SkIRect::IntersectsNoEmptyCheck(subset, frameRect)) {
439 return kSuccess;
440 }
441
442 int minXOffset = SkTMin(dstX, subset.x());
443 int minYOffset = SkTMin(dstY, subset.y());
444 dstX -= minXOffset;
445 dstY -= minYOffset;
446 frameRect.offset(-minXOffset, -minYOffset);
447 subset.offset(-minXOffset, -minYOffset);
448
449 // Just like we require that the requested subset x and y offset are even, libwebp
450 // guarantees that the frame x and y offset are even (it's actually impossible to specify
451 // an odd frame offset). So we can still guarantee that the adjusted offsets are even.
452 SkASSERT(SkIsAlign2(subset.fLeft) && SkIsAlign2(subset.fTop));
453
454 SkIRect intersection;
455 SkAssertResult(intersection.intersect(frameRect, subset));
456 subsetWidth = intersection.width();
457 subsetHeight = intersection.height();
458
459 config.options.use_cropping = 1;
460 config.options.crop_left = subset.x();
461 config.options.crop_top = subset.y();
462 config.options.crop_width = subsetWidth;
463 config.options.crop_height = subsetHeight;
464 }
465
466 // Ignore the frame size and offset when determining if scaling is necessary.
467 int scaledWidth = subsetWidth;
468 int scaledHeight = subsetHeight;
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400469 SkISize srcSize = options.fSubset ? options.fSubset->size() : srcInfo.dimensions();
Matt Sarett5c496172017-02-07 17:01:16 -0500470 if (srcSize != dstInfo.dimensions()) {
scroggo6f5e6192015-06-18 12:53:43 -0700471 config.options.use_scaling = 1;
Matt Sarett5c496172017-02-07 17:01:16 -0500472
473 if (frameIsSubset) {
474 float scaleX = ((float) dstInfo.width()) / srcSize.width();
475 float scaleY = ((float) dstInfo.height()) / srcSize.height();
476
477 // We need to be conservative here and floor rather than round.
478 // Otherwise, we may find ourselves decoding off the end of memory.
479 dstX = scaleX * dstX;
480 scaledWidth = scaleX * scaledWidth;
481 dstY = scaleY * dstY;
482 scaledHeight = scaleY * scaledHeight;
483 if (0 == scaledWidth || 0 == scaledHeight) {
484 return kSuccess;
485 }
486 } else {
487 scaledWidth = dstInfo.width();
488 scaledHeight = dstInfo.height();
489 }
490
491 config.options.scaled_width = scaledWidth;
492 config.options.scaled_height = scaledHeight;
scroggo6f5e6192015-06-18 12:53:43 -0700493 }
494
Leon Scroggins III1f6af6b2017-06-12 16:41:09 -0400495 const bool blendWithPrevFrame = !independent && frame.blend_method == WEBP_MUX_BLEND
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400496 && frame.has_alpha;
497 if (blendWithPrevFrame && options.fPremulBehavior == SkTransferFunctionBehavior::kRespect) {
498 // Blending is done with SkRasterPipeline, which requires a color space that is valid for
499 // rendering.
500 const auto* cs = dstInfo.colorSpace();
501 if (!cs || (!cs->gammaCloseToSRGB() && !cs->gammaIsLinear())) {
502 return kInvalidConversion;
503 }
504 }
505
506 SkBitmap webpDst;
Leon Scroggins IIIee92f132017-05-23 15:28:46 -0400507 auto webpInfo = dstInfo;
508 if (!frame.has_alpha) {
509 webpInfo = webpInfo.makeAlphaType(kOpaque_SkAlphaType);
510 }
511 if (this->colorXform()) {
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400512 // Swizzling between RGBA and BGRA is zero cost in a color transform. So when we have a
513 // color transform, we should decode to whatever is easiest for libwebp, and then let the
514 // color transform swizzle if necessary.
515 // Lossy webp is encoded as YUV (so RGBA and BGRA are the same cost). Lossless webp is
516 // 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 -0400517 webpInfo = webpInfo.makeColorType(kBGRA_8888_SkColorType);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400518
Leon Scroggins IIIee92f132017-05-23 15:28:46 -0400519 if (webpInfo.alphaType() == kPremul_SkAlphaType) {
520 webpInfo = webpInfo.makeAlphaType(kUnpremul_SkAlphaType);
521 }
522 }
523
524 if ((this->colorXform() && !is_8888(dstInfo.colorType())) || blendWithPrevFrame) {
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400525 // We will decode the entire image and then perform the color transform. libwebp
526 // does not provide a row-by-row API. This is a shame particularly when we do not want
527 // 8888, since we will need to create another image sized buffer.
Leon Scroggins IIIee92f132017-05-23 15:28:46 -0400528 webpDst.allocPixels(webpInfo);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400529 } else {
530 // libwebp can decode directly into the output memory.
Leon Scroggins IIIee92f132017-05-23 15:28:46 -0400531 webpDst.installPixels(webpInfo, dst, rowBytes);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400532 }
533
Leon Scroggins IIIee92f132017-05-23 15:28:46 -0400534 config.output.colorspace = webp_decode_mode(webpInfo);
scroggo6f5e6192015-06-18 12:53:43 -0700535 config.output.is_external_memory = 1;
536
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400537 config.output.u.RGBA.rgba = reinterpret_cast<uint8_t*>(webpDst.getAddr(dstX, dstY));
538 config.output.u.RGBA.stride = static_cast<int>(webpDst.rowBytes());
539 config.output.u.RGBA.size = webpDst.getSafeSize();
msarettff2a6c82016-09-07 11:23:28 -0700540
halcanary96fcdcc2015-08-27 07:41:13 -0700541 SkAutoTCallVProc<WebPIDecoder, WebPIDelete> idec(WebPIDecode(nullptr, 0, &config));
scroggo6f5e6192015-06-18 12:53:43 -0700542 if (!idec) {
543 return kInvalidInput;
544 }
545
msarette99883f2016-09-08 06:05:35 -0700546 int rowsDecoded;
547 SkCodec::Result result;
msarettff2a6c82016-09-07 11:23:28 -0700548 switch (WebPIUpdate(idec, frame.fragment.bytes, frame.fragment.size)) {
549 case VP8_STATUS_OK:
Matt Sarett5c496172017-02-07 17:01:16 -0500550 rowsDecoded = scaledHeight;
msarette99883f2016-09-08 06:05:35 -0700551 result = kSuccess;
552 break;
msarettff2a6c82016-09-07 11:23:28 -0700553 case VP8_STATUS_SUSPENDED:
Matt Sarett5c496172017-02-07 17:01:16 -0500554 WebPIDecGetRGB(idec, &rowsDecoded, nullptr, nullptr, nullptr);
555 *rowsDecodedPtr = rowsDecoded + dstY;
msarette99883f2016-09-08 06:05:35 -0700556 result = kIncompleteInput;
557 break;
msarettff2a6c82016-09-07 11:23:28 -0700558 default:
559 return kInvalidInput;
scroggo6f5e6192015-06-18 12:53:43 -0700560 }
msarette99883f2016-09-08 06:05:35 -0700561
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400562 // We're only transforming the new part of the frame, so no need to worry about the
563 // final composited alpha.
564 const auto srcAlpha = 0 == index ? srcInfo.alphaType() : alpha_type(frame.has_alpha);
565 const auto xformAlphaType = select_xform_alpha(dstInfo.alphaType(), srcAlpha);
566 const bool needsSrgbToLinear = dstInfo.gammaCloseToSRGB() &&
567 options.fPremulBehavior == SkTransferFunctionBehavior::kRespect;
568
569 const size_t dstBpp = SkColorTypeBytesPerPixel(dstInfo.colorType());
570 dst = SkTAddOffset<void>(dst, dstBpp * dstX + rowBytes * dstY);
571 const size_t srcRowBytes = config.output.u.RGBA.stride;
572
573 const auto dstCT = dstInfo.colorType();
Matt Sarett313c4632016-10-20 12:35:23 -0400574 if (this->colorXform()) {
Matt Sarett5c496172017-02-07 17:01:16 -0500575 uint32_t* xformSrc = (uint32_t*) config.output.u.RGBA.rgba;
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400576 SkBitmap tmp;
577 void* xformDst;
578
579 if (blendWithPrevFrame) {
580 // Xform into temporary bitmap big enough for one row.
581 tmp.allocPixels(dstInfo.makeWH(scaledWidth, 1));
582 xformDst = tmp.getPixels();
583 } else {
584 xformDst = dst;
585 }
Robert Phillipsb3050b92017-02-06 13:12:18 +0000586 for (int y = 0; y < rowsDecoded; y++) {
Leon Scroggins IIIc6e6a5f2017-06-05 15:53:38 -0400587 this->applyColorXform(xformDst, xformSrc, scaledWidth, xformAlphaType);
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400588 if (blendWithPrevFrame) {
589 blend_line(dstCT, &dst, dstCT, &xformDst, needsSrgbToLinear, xformAlphaType,
590 scaledWidth);
591 dst = SkTAddOffset<void>(dst, rowBytes);
592 } else {
593 xformDst = SkTAddOffset<void>(xformDst, rowBytes);
594 }
Matt Sarett5c496172017-02-07 17:01:16 -0500595 xformSrc = SkTAddOffset<uint32_t>(xformSrc, srcRowBytes);
msarette99883f2016-09-08 06:05:35 -0700596 }
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400597 } else if (blendWithPrevFrame) {
598 const uint8_t* src = config.output.u.RGBA.rgba;
599
600 for (int y = 0; y < rowsDecoded; y++) {
601 blend_line(dstCT, &dst, webpDst.colorType(), &src, needsSrgbToLinear,
602 xformAlphaType, scaledWidth);
603 src = SkTAddOffset<const uint8_t>(src, srcRowBytes);
604 dst = SkTAddOffset<void>(dst, rowBytes);
605 }
msarette99883f2016-09-08 06:05:35 -0700606 }
607
608 return result;
scroggo6f5e6192015-06-18 12:53:43 -0700609}
610
msarett9d15dab2016-08-24 07:36:06 -0700611SkWebpCodec::SkWebpCodec(int width, int height, const SkEncodedInfo& info,
msarettff2a6c82016-09-07 11:23:28 -0700612 sk_sp<SkColorSpace> colorSpace, SkStream* stream, WebPDemuxer* demux,
613 sk_sp<SkData> data)
Leon Scroggins IIIc6e6a5f2017-06-05 15:53:38 -0400614 : INHERITED(width, height, info, SkColorSpaceXform::kBGRA_8888_ColorFormat, stream,
615 std::move(colorSpace))
msarettff2a6c82016-09-07 11:23:28 -0700616 , fDemux(demux)
617 , fData(std::move(data))
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400618 , fFailed(false)
619{
620 fFrameHolder.setScreenSize(width, height);
621}