blob: e40c3f237792fa38454f72c1fb2d5f2e150ae672 [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"
scroggo6f5e6192015-06-18 12:53:43 -07009#include "SkWebpCodec.h"
scroggo6f5e6192015-06-18 12:53:43 -070010#include "SkTemplates.h"
11
12// A WebP decoder on top of (subset of) libwebp
13// For more information on WebP image format, and libwebp library, see:
14// https://code.google.com/speed/webp/
15// http://www.webmproject.org/code/#libwebp-webp-image-library
16// https://chromium.googlesource.com/webm/libwebp
17
18// If moving libwebp out of skia source tree, path for webp headers must be
19// updated accordingly. Here, we enforce using local copy in webp sub-directory.
20#include "webp/decode.h"
21#include "webp/encode.h"
22
scroggodb30be22015-12-08 18:54:13 -080023bool SkWebpCodec::IsWebp(const void* buf, size_t bytesRead) {
scroggo6f5e6192015-06-18 12:53:43 -070024 // WEBP starts with the following:
25 // RIFFXXXXWEBPVP
26 // Where XXXX is unspecified.
scroggodb30be22015-12-08 18:54:13 -080027 const char* bytes = static_cast<const char*>(buf);
28 return bytesRead >= 14 && !memcmp(bytes, "RIFF", 4) && !memcmp(&bytes[8], "WEBPVP", 6);
scroggo6f5e6192015-06-18 12:53:43 -070029}
30
scroggo6f5e6192015-06-18 12:53:43 -070031// Parse headers of RIFF container, and check for valid Webp (VP8) content.
32// NOTE: This calls peek instead of read, since onGetPixels will need these
33// bytes again.
msarettc30c4182016-04-20 11:53:35 -070034static bool webp_parse_header(SkStream* stream, int* width, int* height, SkEncodedInfo* info) {
scroggo6f5e6192015-06-18 12:53:43 -070035 unsigned char buffer[WEBP_VP8_HEADER_SIZE];
scroggodb30be22015-12-08 18:54:13 -080036 SkASSERT(WEBP_VP8_HEADER_SIZE <= SkCodec::MinBufferedBytesNeeded());
37
38 const size_t bytesPeeked = stream->peek(buffer, WEBP_VP8_HEADER_SIZE);
39 if (bytesPeeked != WEBP_VP8_HEADER_SIZE) {
40 // Use read + rewind as a backup
41 if (stream->read(buffer, WEBP_VP8_HEADER_SIZE) != WEBP_VP8_HEADER_SIZE
42 || !stream->rewind())
scroggo6f5e6192015-06-18 12:53:43 -070043 return false;
44 }
45
46 WebPBitstreamFeatures features;
47 VP8StatusCode status = WebPGetFeatures(buffer, WEBP_VP8_HEADER_SIZE, &features);
48 if (VP8_STATUS_OK != status) {
49 return false; // Invalid WebP file.
50 }
51
52 // sanity check for image size that's about to be decoded.
53 {
54 const int64_t size = sk_64_mul(features.width, features.height);
55 if (!sk_64_isS32(size)) {
56 return false;
57 }
58 // now check that if we are 4-bytes per pixel, we also don't overflow
59 if (sk_64_asS32(size) > (0x7FFFFFFF >> 2)) {
60 return false;
61 }
62 }
63
64 if (info) {
msarettc30c4182016-04-20 11:53:35 -070065 SkEncodedInfo::Color color;
66 SkEncodedInfo::Alpha alpha;
67 switch (features.format) {
68 case 0:
69 // This indicates a "mixed" format. We would see this for
70 // animated webps or for webps encoded in multiple fragments.
71 // I believe that this is a rare case.
72 // We could also guess kYUV here, but I think it makes more
73 // sense to guess kBGRA which is likely closer to the final
74 // output. Otherwise, we might end up converting
75 // BGRA->YUVA->BGRA.
76 color = SkEncodedInfo::kBGRA_Color;
77 alpha = SkEncodedInfo::kUnpremul_Alpha;
78 break;
79 case 1:
80 // This is the lossy format (YUV).
81 if (SkToBool(features.has_alpha)) {
82 color = SkEncodedInfo::kYUVA_Color;
83 alpha = SkEncodedInfo::kUnpremul_Alpha;
84 } else {
85 color = SkEncodedInfo::kYUV_Color;
86 alpha = SkEncodedInfo::kOpaque_Alpha;
87 }
88 break;
89 case 2:
90 // This is the lossless format (BGRA).
91 // FIXME: Should we check the has_alpha flag here? It looks
92 // like the image is encoded with an alpha channel
93 // regardless of whether or not the alpha flag is set.
94 color = SkEncodedInfo::kBGRA_Color;
95 alpha = SkEncodedInfo::kUnpremul_Alpha;
96 break;
97 default:
98 return false;
99 }
100
101 *width = features.width;
102 *height = features.height;
103 *info = SkEncodedInfo::Make(color, alpha, 8);
scroggo6f5e6192015-06-18 12:53:43 -0700104 }
105 return true;
106}
107
108SkCodec* SkWebpCodec::NewFromStream(SkStream* stream) {
109 SkAutoTDelete<SkStream> streamDeleter(stream);
msarettc30c4182016-04-20 11:53:35 -0700110 int width, height;
111 SkEncodedInfo info;
112 if (webp_parse_header(stream, &width, &height, &info)) {
113 return new SkWebpCodec(width, height, info, streamDeleter.release());
scroggo6f5e6192015-06-18 12:53:43 -0700114 }
halcanary96fcdcc2015-08-27 07:41:13 -0700115 return nullptr;
scroggo6f5e6192015-06-18 12:53:43 -0700116}
117
scroggocc2feb12015-08-14 08:32:46 -0700118// This version is slightly different from SkCodecPriv's version of conversion_possible. It
119// supports both byte orders for 8888.
120static bool webp_conversion_possible(const SkImageInfo& dst, const SkImageInfo& src) {
msarett6e077e12016-04-06 15:45:41 -0700121 // FIXME: skbug.com/4895
122 // Currently, we ignore the SkColorProfileType on the SkImageInfo. We
123 // will treat the encoded data as linear regardless of what the client
124 // requests.
scroggocc2feb12015-08-14 08:32:46 -0700125
126 if (!valid_alpha(dst.alphaType(), src.alphaType())) {
127 return false;
128 }
129
scroggo6f5e6192015-06-18 12:53:43 -0700130 switch (dst.colorType()) {
131 // Both byte orders are supported.
132 case kBGRA_8888_SkColorType:
133 case kRGBA_8888_SkColorType:
scroggocc2feb12015-08-14 08:32:46 -0700134 return true;
scroggo74992b52015-08-06 13:50:15 -0700135 case kRGB_565_SkColorType:
scroggocc2feb12015-08-14 08:32:46 -0700136 return src.alphaType() == kOpaque_SkAlphaType;
scroggo6f5e6192015-06-18 12:53:43 -0700137 default:
138 return false;
139 }
scroggo6f5e6192015-06-18 12:53:43 -0700140}
141
142SkISize SkWebpCodec::onGetScaledDimensions(float desiredScale) const {
143 SkISize dim = this->getInfo().dimensions();
msaretta0c414d2015-06-19 07:34:30 -0700144 // SkCodec treats zero dimensional images as errors, so the minimum size
145 // that we will recommend is 1x1.
146 dim.fWidth = SkTMax(1, SkScalarRoundToInt(desiredScale * dim.fWidth));
147 dim.fHeight = SkTMax(1, SkScalarRoundToInt(desiredScale * dim.fHeight));
scroggo6f5e6192015-06-18 12:53:43 -0700148 return dim;
149}
150
scroggoe7fc14b2015-10-02 13:14:46 -0700151bool SkWebpCodec::onDimensionsSupported(const SkISize& dim) {
152 const SkImageInfo& info = this->getInfo();
153 return dim.width() >= 1 && dim.width() <= info.width()
154 && dim.height() >= 1 && dim.height() <= info.height();
155}
156
157
scroggo6f5e6192015-06-18 12:53:43 -0700158static WEBP_CSP_MODE webp_decode_mode(SkColorType ct, bool premultiply) {
159 switch (ct) {
160 case kBGRA_8888_SkColorType:
161 return premultiply ? MODE_bgrA : MODE_BGRA;
162 case kRGBA_8888_SkColorType:
163 return premultiply ? MODE_rgbA : MODE_RGBA;
scroggo74992b52015-08-06 13:50:15 -0700164 case kRGB_565_SkColorType:
165 return MODE_RGB_565;
scroggo6f5e6192015-06-18 12:53:43 -0700166 default:
167 return MODE_LAST;
168 }
169}
170
171// The WebP decoding API allows us to incrementally pass chunks of bytes as we receive them to the
172// decoder with WebPIAppend. In order to do so, we need to read chunks from the SkStream. This size
173// is arbitrary.
174static const size_t BUFFER_SIZE = 4096;
175
scroggob636b452015-07-22 07:16:20 -0700176bool SkWebpCodec::onGetValidSubset(SkIRect* desiredSubset) const {
177 if (!desiredSubset) {
178 return false;
179 }
180
msarettfdb47572015-10-13 12:50:14 -0700181 SkIRect dimensions = SkIRect::MakeSize(this->getInfo().dimensions());
182 if (!dimensions.contains(*desiredSubset)) {
scroggob636b452015-07-22 07:16:20 -0700183 return false;
184 }
185
186 // As stated below, libwebp snaps to even left and top. Make sure top and left are even, so we
187 // decode this exact subset.
188 // Leave right and bottom unmodified, so we suggest a slightly larger subset than requested.
189 desiredSubset->fLeft = (desiredSubset->fLeft >> 1) << 1;
190 desiredSubset->fTop = (desiredSubset->fTop >> 1) << 1;
191 return true;
192}
193
scroggoeb602a52015-07-09 08:16:03 -0700194SkCodec::Result SkWebpCodec::onGetPixels(const SkImageInfo& dstInfo, void* dst, size_t rowBytes,
msarette6dd0042015-10-09 11:07:34 -0700195 const Options& options, SkPMColor*, int*,
196 int* rowsDecoded) {
scroggocc2feb12015-08-14 08:32:46 -0700197 if (!webp_conversion_possible(dstInfo, this->getInfo())) {
scroggo6f5e6192015-06-18 12:53:43 -0700198 return kInvalidConversion;
199 }
200
201 WebPDecoderConfig config;
202 if (0 == WebPInitDecoderConfig(&config)) {
203 // ABI mismatch.
204 // FIXME: New enum for this?
205 return kInvalidInput;
206 }
207
208 // Free any memory associated with the buffer. Must be called last, so we declare it first.
209 SkAutoTCallVProc<WebPDecBuffer, WebPFreeDecBuffer> autoFree(&(config.output));
210
scroggob636b452015-07-22 07:16:20 -0700211 SkIRect bounds = SkIRect::MakeSize(this->getInfo().dimensions());
212 if (options.fSubset) {
213 // Caller is requesting a subset.
214 if (!bounds.contains(*options.fSubset)) {
215 // The subset is out of bounds.
216 return kInvalidParameters;
217 }
218
219 bounds = *options.fSubset;
220
221 // This is tricky. libwebp snaps the top and left to even values. We could let libwebp
222 // do the snap, and return a subset which is a different one than requested. The problem
223 // with that approach is that the caller may try to stitch subsets together, and if we
224 // returned different subsets than requested, there would be artifacts at the boundaries.
225 // Instead, we report that we cannot support odd values for top and left..
226 if (!SkIsAlign2(bounds.fLeft) || !SkIsAlign2(bounds.fTop)) {
227 return kInvalidParameters;
228 }
229
230#ifdef SK_DEBUG
231 {
232 // Make a copy, since getValidSubset can change its input.
233 SkIRect subset(bounds);
234 // That said, getValidSubset should *not* change its input, in this case; otherwise
235 // getValidSubset does not match the actual subsets we can do.
236 SkASSERT(this->getValidSubset(&subset) && subset == bounds);
237 }
238#endif
239
240 config.options.use_cropping = 1;
241 config.options.crop_left = bounds.fLeft;
242 config.options.crop_top = bounds.fTop;
243 config.options.crop_width = bounds.width();
244 config.options.crop_height = bounds.height();
245 }
246
247 SkISize dstDimensions = dstInfo.dimensions();
248 if (bounds.size() != dstDimensions) {
scroggo6f5e6192015-06-18 12:53:43 -0700249 // Caller is requesting scaling.
250 config.options.use_scaling = 1;
scroggob636b452015-07-22 07:16:20 -0700251 config.options.scaled_width = dstDimensions.width();
252 config.options.scaled_height = dstDimensions.height();
scroggo6f5e6192015-06-18 12:53:43 -0700253 }
254
255 config.output.colorspace = webp_decode_mode(dstInfo.colorType(),
256 dstInfo.alphaType() == kPremul_SkAlphaType);
257 config.output.u.RGBA.rgba = (uint8_t*) dst;
258 config.output.u.RGBA.stride = (int) rowBytes;
259 config.output.u.RGBA.size = dstInfo.getSafeSize(rowBytes);
260 config.output.is_external_memory = 1;
261
halcanary96fcdcc2015-08-27 07:41:13 -0700262 SkAutoTCallVProc<WebPIDecoder, WebPIDelete> idec(WebPIDecode(nullptr, 0, &config));
scroggo6f5e6192015-06-18 12:53:43 -0700263 if (!idec) {
264 return kInvalidInput;
265 }
266
scroggo565901d2015-12-10 10:44:13 -0800267 SkAutoTMalloc<uint8_t> storage(BUFFER_SIZE);
268 uint8_t* buffer = storage.get();
scroggo6f5e6192015-06-18 12:53:43 -0700269 while (true) {
270 const size_t bytesRead = stream()->read(buffer, BUFFER_SIZE);
271 if (0 == bytesRead) {
msarette6dd0042015-10-09 11:07:34 -0700272 WebPIDecGetRGB(idec, rowsDecoded, NULL, NULL, NULL);
273 return kIncompleteInput;
scroggo6f5e6192015-06-18 12:53:43 -0700274 }
275
276 switch (WebPIAppend(idec, buffer, bytesRead)) {
277 case VP8_STATUS_OK:
278 return kSuccess;
279 case VP8_STATUS_SUSPENDED:
280 // Break out of the switch statement. Continue the loop.
281 break;
282 default:
283 return kInvalidInput;
284 }
285 }
286}
287
msarettc30c4182016-04-20 11:53:35 -0700288SkWebpCodec::SkWebpCodec(int width, int height, const SkEncodedInfo& info, SkStream* stream)
msarett6e077e12016-04-06 15:45:41 -0700289 // The spec says an unmarked image is sRGB, so we return that space here.
290 // TODO: Add support for parsing ICC profiles from webps.
msarettc30c4182016-04-20 11:53:35 -0700291 : INHERITED(width, height, info, stream, SkColorSpace::NewNamed(SkColorSpace::kSRGB_Named)) {}