blob: 746e9b79ad46ed22d436ec8604827476ccae6c6c [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
scroggocc2feb12015-08-14 08:32:46 -07008#include "SkCodecPriv.h"
msarette99883f2016-09-08 06:05:35 -07009#include "SkColorSpaceXform.h"
scroggo6f5e6192015-06-18 12:53:43 -070010#include "SkWebpCodec.h"
msarettff2a6c82016-09-07 11:23:28 -070011#include "SkStreamPriv.h"
scroggo6f5e6192015-06-18 12:53:43 -070012#include "SkTemplates.h"
13
14// A WebP decoder on top of (subset of) libwebp
15// For more information on WebP image format, and libwebp library, see:
16// https://code.google.com/speed/webp/
17// http://www.webmproject.org/code/#libwebp-webp-image-library
18// https://chromium.googlesource.com/webm/libwebp
19
20// If moving libwebp out of skia source tree, path for webp headers must be
21// updated accordingly. Here, we enforce using local copy in webp sub-directory.
22#include "webp/decode.h"
msarett9d15dab2016-08-24 07:36:06 -070023#include "webp/demux.h"
scroggo6f5e6192015-06-18 12:53:43 -070024#include "webp/encode.h"
25
scroggodb30be22015-12-08 18:54:13 -080026bool SkWebpCodec::IsWebp(const void* buf, size_t bytesRead) {
scroggo6f5e6192015-06-18 12:53:43 -070027 // WEBP starts with the following:
28 // RIFFXXXXWEBPVP
29 // Where XXXX is unspecified.
scroggodb30be22015-12-08 18:54:13 -080030 const char* bytes = static_cast<const char*>(buf);
31 return bytesRead >= 14 && !memcmp(bytes, "RIFF", 4) && !memcmp(&bytes[8], "WEBPVP", 6);
scroggo6f5e6192015-06-18 12:53:43 -070032}
33
scroggo6f5e6192015-06-18 12:53:43 -070034// Parse headers of RIFF container, and check for valid Webp (VP8) content.
35// NOTE: This calls peek instead of read, since onGetPixels will need these
36// bytes again.
msarettac6c7502016-04-25 09:30:24 -070037// Returns an SkWebpCodec on success;
38SkCodec* SkWebpCodec::NewFromStream(SkStream* stream) {
39 SkAutoTDelete<SkStream> streamDeleter(stream);
40
msarettff2a6c82016-09-07 11:23:28 -070041 // Webp demux needs a contiguous data buffer.
42 sk_sp<SkData> data = nullptr;
43 if (stream->getMemoryBase()) {
44 // It is safe to make without copy because we'll hold onto the stream.
45 data = SkData::MakeWithoutCopy(stream->getMemoryBase(), stream->getLength());
46 } else {
47 data = SkCopyStreamToData(stream);
scroggodb30be22015-12-08 18:54:13 -080048
msarettff2a6c82016-09-07 11:23:28 -070049 // If we are forced to copy the stream to a data, we can go ahead and delete the stream.
50 streamDeleter.reset(nullptr);
51 }
52
53 // It's a little strange that the |demux| will outlive |webpData|, though it needs the
54 // pointer in |webpData| to remain valid. This works because the pointer remains valid
55 // until the SkData is freed.
56 WebPData webpData = { data->bytes(), data->size() };
57 SkAutoTCallVProc<WebPDemuxer, WebPDemuxDelete> demux(WebPDemuxPartial(&webpData, nullptr));
58 if (nullptr == demux) {
msarettac6c7502016-04-25 09:30:24 -070059 return nullptr;
scroggo6f5e6192015-06-18 12:53:43 -070060 }
61
msarettff2a6c82016-09-07 11:23:28 -070062 WebPChunkIterator chunkIterator;
63 SkAutoTCallVProc<WebPChunkIterator, WebPDemuxReleaseChunkIterator> autoCI(&chunkIterator);
64 sk_sp<SkColorSpace> colorSpace = nullptr;
65 if (WebPDemuxGetChunk(demux, "ICCP", 1, &chunkIterator)) {
66 colorSpace = SkColorSpace::NewICC(chunkIterator.chunk.bytes, chunkIterator.chunk.size);
scroggo6f5e6192015-06-18 12:53:43 -070067 }
68
msarettff2a6c82016-09-07 11:23:28 -070069 if (!colorSpace) {
70 colorSpace = SkColorSpace::NewNamed(SkColorSpace::kSRGB_Named);
71 }
72
73 // Since we do not yet support animation, we get the |width|, |height|, |color|, and |alpha|
74 // from the first frame. It's the only frame we will decode.
75 //
76 // TODO:
77 // When we support animation, we'll want to report the canvas width and canvas height instead.
78 // We can get these from the |demux| directly.
79 // What |color| and |alpha| will we want to report though? WebP allows different frames
80 // to be encoded in different ways, making the encoded format difficult to describe.
81 WebPIterator frame;
82 SkAutoTCallVProc<WebPIterator, WebPDemuxReleaseIterator> autoFrame(&frame);
83 if (!WebPDemuxGetFrame(demux, 1, &frame)) {
84 return nullptr;
85 }
86
87 // Sanity check for image size that's about to be decoded.
scroggo6f5e6192015-06-18 12:53:43 -070088 {
msarettff2a6c82016-09-07 11:23:28 -070089 const int64_t size = sk_64_mul(frame.width, frame.height);
scroggo6f5e6192015-06-18 12:53:43 -070090 if (!sk_64_isS32(size)) {
msarettac6c7502016-04-25 09:30:24 -070091 return nullptr;
scroggo6f5e6192015-06-18 12:53:43 -070092 }
93 // now check that if we are 4-bytes per pixel, we also don't overflow
94 if (sk_64_asS32(size) > (0x7FFFFFFF >> 2)) {
msarettac6c7502016-04-25 09:30:24 -070095 return nullptr;
scroggo6f5e6192015-06-18 12:53:43 -070096 }
97 }
98
msarettff2a6c82016-09-07 11:23:28 -070099 // TODO:
100 // The only reason we actually need to call WebPGetFeatures() is to get the |features.format|.
101 // This call actually re-reads the frame header. Should we suggest that libwebp expose
102 // the format on the |frame|?
103 WebPBitstreamFeatures features;
104 VP8StatusCode status = WebPGetFeatures(frame.fragment.bytes, frame.fragment.size, &features);
105 if (VP8_STATUS_OK != status) {
106 return nullptr;
107 }
108
msarettac6c7502016-04-25 09:30:24 -0700109 SkEncodedInfo::Color color;
110 SkEncodedInfo::Alpha alpha;
111 switch (features.format) {
112 case 0:
113 // This indicates a "mixed" format. We would see this for
114 // animated webps or for webps encoded in multiple fragments.
115 // I believe that this is a rare case.
116 // 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.
120 color = SkEncodedInfo::kBGRA_Color;
121 alpha = SkEncodedInfo::kUnpremul_Alpha;
122 break;
123 case 1:
124 // This is the lossy format (YUV).
125 if (SkToBool(features.has_alpha)) {
126 color = SkEncodedInfo::kYUVA_Color;
msarettc30c4182016-04-20 11:53:35 -0700127 alpha = SkEncodedInfo::kUnpremul_Alpha;
msarettac6c7502016-04-25 09:30:24 -0700128 } else {
129 color = SkEncodedInfo::kYUV_Color;
130 alpha = SkEncodedInfo::kOpaque_Alpha;
131 }
132 break;
133 case 2:
134 // This is the lossless format (BGRA).
msarettac6c7502016-04-25 09:30:24 -0700135 color = SkEncodedInfo::kBGRA_Color;
136 alpha = SkEncodedInfo::kUnpremul_Alpha;
137 break;
138 default:
139 return nullptr;
scroggo6f5e6192015-06-18 12:53:43 -0700140 }
scroggo6f5e6192015-06-18 12:53:43 -0700141
msarettac6c7502016-04-25 09:30:24 -0700142 SkEncodedInfo info = SkEncodedInfo::Make(color, alpha, 8);
msarettff2a6c82016-09-07 11:23:28 -0700143 return new SkWebpCodec(features.width, features.height, info, std::move(colorSpace),
144 streamDeleter.release(), demux.release(), std::move(data));
scroggo6f5e6192015-06-18 12:53:43 -0700145}
146
scroggo6f5e6192015-06-18 12:53:43 -0700147SkISize SkWebpCodec::onGetScaledDimensions(float desiredScale) const {
148 SkISize dim = this->getInfo().dimensions();
msaretta0c414d2015-06-19 07:34:30 -0700149 // SkCodec treats zero dimensional images as errors, so the minimum size
150 // that we will recommend is 1x1.
151 dim.fWidth = SkTMax(1, SkScalarRoundToInt(desiredScale * dim.fWidth));
152 dim.fHeight = SkTMax(1, SkScalarRoundToInt(desiredScale * dim.fHeight));
scroggo6f5e6192015-06-18 12:53:43 -0700153 return dim;
154}
155
scroggoe7fc14b2015-10-02 13:14:46 -0700156bool SkWebpCodec::onDimensionsSupported(const SkISize& dim) {
157 const SkImageInfo& info = this->getInfo();
158 return dim.width() >= 1 && dim.width() <= info.width()
159 && dim.height() >= 1 && dim.height() <= info.height();
160}
161
scroggo6f5e6192015-06-18 12:53:43 -0700162static WEBP_CSP_MODE webp_decode_mode(SkColorType ct, bool premultiply) {
163 switch (ct) {
164 case kBGRA_8888_SkColorType:
165 return premultiply ? MODE_bgrA : MODE_BGRA;
166 case kRGBA_8888_SkColorType:
167 return premultiply ? MODE_rgbA : MODE_RGBA;
scroggo74992b52015-08-06 13:50:15 -0700168 case kRGB_565_SkColorType:
169 return MODE_RGB_565;
scroggo6f5e6192015-06-18 12:53:43 -0700170 default:
171 return MODE_LAST;
172 }
173}
174
scroggob636b452015-07-22 07:16:20 -0700175bool SkWebpCodec::onGetValidSubset(SkIRect* desiredSubset) const {
176 if (!desiredSubset) {
177 return false;
178 }
179
msarettfdb47572015-10-13 12:50:14 -0700180 SkIRect dimensions = SkIRect::MakeSize(this->getInfo().dimensions());
181 if (!dimensions.contains(*desiredSubset)) {
scroggob636b452015-07-22 07:16:20 -0700182 return false;
183 }
184
185 // As stated below, libwebp snaps to even left and top. Make sure top and left are even, so we
186 // decode this exact subset.
187 // Leave right and bottom unmodified, so we suggest a slightly larger subset than requested.
188 desiredSubset->fLeft = (desiredSubset->fLeft >> 1) << 1;
189 desiredSubset->fTop = (desiredSubset->fTop >> 1) << 1;
190 return true;
191}
192
scroggoeb602a52015-07-09 08:16:03 -0700193SkCodec::Result SkWebpCodec::onGetPixels(const SkImageInfo& dstInfo, void* dst, size_t rowBytes,
msarette6dd0042015-10-09 11:07:34 -0700194 const Options& options, SkPMColor*, int*,
msarette99883f2016-09-08 06:05:35 -0700195 int* rowsDecodedPtr) {
msarett2ecc35f2016-09-08 11:55:16 -0700196 if (!conversion_possible(dstInfo, this->getInfo())) {
197 return kInvalidConversion;
198 }
msarette99883f2016-09-08 06:05:35 -0700199
Matt Sarett313c4632016-10-20 12:35:23 -0400200 if (!this->initializeColorXform(dstInfo)) {
201 return kInvalidConversion;
scroggo6f5e6192015-06-18 12:53:43 -0700202 }
203
204 WebPDecoderConfig config;
205 if (0 == WebPInitDecoderConfig(&config)) {
206 // ABI mismatch.
207 // FIXME: New enum for this?
208 return kInvalidInput;
209 }
210
211 // Free any memory associated with the buffer. Must be called last, so we declare it first.
212 SkAutoTCallVProc<WebPDecBuffer, WebPFreeDecBuffer> autoFree(&(config.output));
213
scroggob636b452015-07-22 07:16:20 -0700214 SkIRect bounds = SkIRect::MakeSize(this->getInfo().dimensions());
215 if (options.fSubset) {
216 // Caller is requesting a subset.
217 if (!bounds.contains(*options.fSubset)) {
218 // The subset is out of bounds.
219 return kInvalidParameters;
220 }
221
222 bounds = *options.fSubset;
223
224 // This is tricky. libwebp snaps the top and left to even values. We could let libwebp
225 // do the snap, and return a subset which is a different one than requested. The problem
226 // with that approach is that the caller may try to stitch subsets together, and if we
227 // returned different subsets than requested, there would be artifacts at the boundaries.
228 // Instead, we report that we cannot support odd values for top and left..
229 if (!SkIsAlign2(bounds.fLeft) || !SkIsAlign2(bounds.fTop)) {
230 return kInvalidParameters;
231 }
232
233#ifdef SK_DEBUG
234 {
235 // Make a copy, since getValidSubset can change its input.
236 SkIRect subset(bounds);
237 // That said, getValidSubset should *not* change its input, in this case; otherwise
238 // getValidSubset does not match the actual subsets we can do.
239 SkASSERT(this->getValidSubset(&subset) && subset == bounds);
240 }
241#endif
242
243 config.options.use_cropping = 1;
244 config.options.crop_left = bounds.fLeft;
245 config.options.crop_top = bounds.fTop;
246 config.options.crop_width = bounds.width();
247 config.options.crop_height = bounds.height();
248 }
249
250 SkISize dstDimensions = dstInfo.dimensions();
251 if (bounds.size() != dstDimensions) {
scroggo6f5e6192015-06-18 12:53:43 -0700252 // Caller is requesting scaling.
253 config.options.use_scaling = 1;
scroggob636b452015-07-22 07:16:20 -0700254 config.options.scaled_width = dstDimensions.width();
255 config.options.scaled_height = dstDimensions.height();
scroggo6f5e6192015-06-18 12:53:43 -0700256 }
257
msarettcf7b8772016-09-22 12:37:04 -0700258 // Swizzling between RGBA and BGRA is zero cost in a color transform. So when we have a
259 // color transform, we should decode to whatever is easiest for libwebp, and then let the
260 // color transform swizzle if necessary.
261 // Lossy webp is encoded as YUV (so RGBA and BGRA are the same cost). Lossless webp is
262 // encoded as BGRA. This means decoding to BGRA is either faster or the same cost as RGBA.
Matt Sarett313c4632016-10-20 12:35:23 -0400263 config.output.colorspace = this->colorXform() ? MODE_BGRA :
msarette99883f2016-09-08 06:05:35 -0700264 webp_decode_mode(dstInfo.colorType(), dstInfo.alphaType() == kPremul_SkAlphaType);
scroggo6f5e6192015-06-18 12:53:43 -0700265 config.output.is_external_memory = 1;
266
msarette99883f2016-09-08 06:05:35 -0700267 // We will decode the entire image and then perform the color transform. libwebp
268 // does not provide a row-by-row API. This is a shame particularly in the F16 case,
269 // where we need to allocate an extra image-sized buffer.
270 SkAutoTMalloc<uint32_t> pixels;
271 if (kRGBA_F16_SkColorType == dstInfo.colorType()) {
272 pixels.reset(dstDimensions.width() * dstDimensions.height());
273 config.output.u.RGBA.rgba = (uint8_t*) pixels.get();
274 config.output.u.RGBA.stride = (int) dstDimensions.width() * sizeof(uint32_t);
275 config.output.u.RGBA.size = config.output.u.RGBA.stride * dstDimensions.height();
276 } else {
277 config.output.u.RGBA.rgba = (uint8_t*) dst;
278 config.output.u.RGBA.stride = (int) rowBytes;
279 config.output.u.RGBA.size = dstInfo.getSafeSize(rowBytes);
280 }
281
msarettff2a6c82016-09-07 11:23:28 -0700282 WebPIterator frame;
283 SkAutoTCallVProc<WebPIterator, WebPDemuxReleaseIterator> autoFrame(&frame);
284 // If this succeeded in NewFromStream(), it should succeed again here.
285 SkAssertResult(WebPDemuxGetFrame(fDemux, 1, &frame));
286
halcanary96fcdcc2015-08-27 07:41:13 -0700287 SkAutoTCallVProc<WebPIDecoder, WebPIDelete> idec(WebPIDecode(nullptr, 0, &config));
scroggo6f5e6192015-06-18 12:53:43 -0700288 if (!idec) {
289 return kInvalidInput;
290 }
291
msarette99883f2016-09-08 06:05:35 -0700292 int rowsDecoded;
293 SkCodec::Result result;
msarettff2a6c82016-09-07 11:23:28 -0700294 switch (WebPIUpdate(idec, frame.fragment.bytes, frame.fragment.size)) {
295 case VP8_STATUS_OK:
msarette99883f2016-09-08 06:05:35 -0700296 rowsDecoded = dstInfo.height();
297 result = kSuccess;
298 break;
msarettff2a6c82016-09-07 11:23:28 -0700299 case VP8_STATUS_SUSPENDED:
msarette99883f2016-09-08 06:05:35 -0700300 WebPIDecGetRGB(idec, rowsDecodedPtr, nullptr, nullptr, nullptr);
301 rowsDecoded = *rowsDecodedPtr;
302 result = kIncompleteInput;
303 break;
msarettff2a6c82016-09-07 11:23:28 -0700304 default:
305 return kInvalidInput;
scroggo6f5e6192015-06-18 12:53:43 -0700306 }
msarette99883f2016-09-08 06:05:35 -0700307
Matt Sarett313c4632016-10-20 12:35:23 -0400308 if (this->colorXform()) {
msarettcf7b8772016-09-22 12:37:04 -0700309 SkColorSpaceXform::ColorFormat dstColorFormat = select_xform_format(dstInfo.colorType());
msarettc0444612016-09-16 11:45:58 -0700310 SkAlphaType xformAlphaType = select_xform_alpha(dstInfo.alphaType(),
msarette99883f2016-09-08 06:05:35 -0700311 this->getInfo().alphaType());
312
313 uint32_t* src = (uint32_t*) config.output.u.RGBA.rgba;
314 size_t srcRowBytes = config.output.u.RGBA.stride;
315 for (int y = 0; y < rowsDecoded; y++) {
Matt Sarett313c4632016-10-20 12:35:23 -0400316 SkAssertResult(this->colorXform()->apply(dstColorFormat, dst,
317 SkColorSpaceXform::kBGRA_8888_ColorFormat, src, dstInfo.width(),
318 xformAlphaType));
msarette99883f2016-09-08 06:05:35 -0700319 dst = SkTAddOffset<void>(dst, rowBytes);
320 src = SkTAddOffset<uint32_t>(src, srcRowBytes);
321 }
322 }
323
324 return result;
scroggo6f5e6192015-06-18 12:53:43 -0700325}
326
msarett9d15dab2016-08-24 07:36:06 -0700327SkWebpCodec::SkWebpCodec(int width, int height, const SkEncodedInfo& info,
msarettff2a6c82016-09-07 11:23:28 -0700328 sk_sp<SkColorSpace> colorSpace, SkStream* stream, WebPDemuxer* demux,
329 sk_sp<SkData> data)
330 : INHERITED(width, height, info, stream, std::move(colorSpace))
331 , fDemux(demux)
332 , fData(std::move(data))
msarett9d15dab2016-08-24 07:36:06 -0700333{}