blob: 1f69b4f712b8a7402b15a745ca62d625ba26777b [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
23bool SkWebpCodec::IsWebp(SkStream* stream) {
24 // WEBP starts with the following:
25 // RIFFXXXXWEBPVP
26 // Where XXXX is unspecified.
27 const char LENGTH = 14;
28 char bytes[LENGTH];
29 if (stream->read(&bytes, LENGTH) != LENGTH) {
30 return false;
31 }
32 return !memcmp(bytes, "RIFF", 4) && !memcmp(&bytes[8], "WEBPVP", 6);
33}
34
35static const size_t WEBP_VP8_HEADER_SIZE = 30;
36
37// Parse headers of RIFF container, and check for valid Webp (VP8) content.
38// NOTE: This calls peek instead of read, since onGetPixels will need these
39// bytes again.
40static bool webp_parse_header(SkStream* stream, SkImageInfo* info) {
41 unsigned char buffer[WEBP_VP8_HEADER_SIZE];
42 if (!stream->peek(buffer, WEBP_VP8_HEADER_SIZE)) {
43 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) {
65 // FIXME: Is N32 the right type?
scroggoeb602a52015-07-09 08:16:03 -070066 // Is unpremul the right type? Clients of SkCodec may assume it's the
scroggo6f5e6192015-06-18 12:53:43 -070067 // best type, when Skia currently cannot draw unpremul (and raster is faster
68 // with premul).
69 *info = SkImageInfo::Make(features.width, features.height, kN32_SkColorType,
70 SkToBool(features.has_alpha) ? kUnpremul_SkAlphaType
71 : kOpaque_SkAlphaType);
72 }
73 return true;
74}
75
76SkCodec* SkWebpCodec::NewFromStream(SkStream* stream) {
77 SkAutoTDelete<SkStream> streamDeleter(stream);
78 SkImageInfo info;
79 if (webp_parse_header(stream, &info)) {
80 return SkNEW_ARGS(SkWebpCodec, (info, streamDeleter.detach()));
81 }
82 return NULL;
83}
84
scroggocc2feb12015-08-14 08:32:46 -070085// This version is slightly different from SkCodecPriv's version of conversion_possible. It
86// supports both byte orders for 8888.
87static bool webp_conversion_possible(const SkImageInfo& dst, const SkImageInfo& src) {
scroggo74992b52015-08-06 13:50:15 -070088 if (dst.profileType() != src.profileType()) {
89 return false;
90 }
scroggocc2feb12015-08-14 08:32:46 -070091
92 if (!valid_alpha(dst.alphaType(), src.alphaType())) {
93 return false;
94 }
95
scroggo6f5e6192015-06-18 12:53:43 -070096 switch (dst.colorType()) {
97 // Both byte orders are supported.
98 case kBGRA_8888_SkColorType:
99 case kRGBA_8888_SkColorType:
scroggocc2feb12015-08-14 08:32:46 -0700100 return true;
scroggo74992b52015-08-06 13:50:15 -0700101 case kRGB_565_SkColorType:
scroggocc2feb12015-08-14 08:32:46 -0700102 return src.alphaType() == kOpaque_SkAlphaType;
scroggo6f5e6192015-06-18 12:53:43 -0700103 default:
104 return false;
105 }
scroggo6f5e6192015-06-18 12:53:43 -0700106}
107
108SkISize SkWebpCodec::onGetScaledDimensions(float desiredScale) const {
109 SkISize dim = this->getInfo().dimensions();
msaretta0c414d2015-06-19 07:34:30 -0700110 // SkCodec treats zero dimensional images as errors, so the minimum size
111 // that we will recommend is 1x1.
112 dim.fWidth = SkTMax(1, SkScalarRoundToInt(desiredScale * dim.fWidth));
113 dim.fHeight = SkTMax(1, SkScalarRoundToInt(desiredScale * dim.fHeight));
scroggo6f5e6192015-06-18 12:53:43 -0700114 return dim;
115}
116
117static WEBP_CSP_MODE webp_decode_mode(SkColorType ct, bool premultiply) {
118 switch (ct) {
119 case kBGRA_8888_SkColorType:
120 return premultiply ? MODE_bgrA : MODE_BGRA;
121 case kRGBA_8888_SkColorType:
122 return premultiply ? MODE_rgbA : MODE_RGBA;
scroggo74992b52015-08-06 13:50:15 -0700123 case kRGB_565_SkColorType:
124 return MODE_RGB_565;
scroggo6f5e6192015-06-18 12:53:43 -0700125 default:
126 return MODE_LAST;
127 }
128}
129
130// The WebP decoding API allows us to incrementally pass chunks of bytes as we receive them to the
131// decoder with WebPIAppend. In order to do so, we need to read chunks from the SkStream. This size
132// is arbitrary.
133static const size_t BUFFER_SIZE = 4096;
134
scroggob636b452015-07-22 07:16:20 -0700135bool SkWebpCodec::onGetValidSubset(SkIRect* desiredSubset) const {
136 if (!desiredSubset) {
137 return false;
138 }
139
140 SkIRect bounds = SkIRect::MakeSize(this->getInfo().dimensions());
141 if (!desiredSubset->intersect(bounds)) {
142 return false;
143 }
144
145 // As stated below, libwebp snaps to even left and top. Make sure top and left are even, so we
146 // decode this exact subset.
147 // Leave right and bottom unmodified, so we suggest a slightly larger subset than requested.
148 desiredSubset->fLeft = (desiredSubset->fLeft >> 1) << 1;
149 desiredSubset->fTop = (desiredSubset->fTop >> 1) << 1;
150 return true;
151}
152
scroggoeb602a52015-07-09 08:16:03 -0700153SkCodec::Result SkWebpCodec::onGetPixels(const SkImageInfo& dstInfo, void* dst, size_t rowBytes,
scroggob636b452015-07-22 07:16:20 -0700154 const Options& options, SkPMColor*, int*) {
scroggob427db12015-08-12 07:24:13 -0700155 if (!this->rewindIfNeeded()) {
156 return kCouldNotRewind;
scroggo6f5e6192015-06-18 12:53:43 -0700157 }
158
scroggocc2feb12015-08-14 08:32:46 -0700159 if (!webp_conversion_possible(dstInfo, this->getInfo())) {
scroggo6f5e6192015-06-18 12:53:43 -0700160 return kInvalidConversion;
161 }
162
163 WebPDecoderConfig config;
164 if (0 == WebPInitDecoderConfig(&config)) {
165 // ABI mismatch.
166 // FIXME: New enum for this?
167 return kInvalidInput;
168 }
169
170 // Free any memory associated with the buffer. Must be called last, so we declare it first.
171 SkAutoTCallVProc<WebPDecBuffer, WebPFreeDecBuffer> autoFree(&(config.output));
172
scroggob636b452015-07-22 07:16:20 -0700173 SkIRect bounds = SkIRect::MakeSize(this->getInfo().dimensions());
174 if (options.fSubset) {
175 // Caller is requesting a subset.
176 if (!bounds.contains(*options.fSubset)) {
177 // The subset is out of bounds.
178 return kInvalidParameters;
179 }
180
181 bounds = *options.fSubset;
182
183 // This is tricky. libwebp snaps the top and left to even values. We could let libwebp
184 // do the snap, and return a subset which is a different one than requested. The problem
185 // with that approach is that the caller may try to stitch subsets together, and if we
186 // returned different subsets than requested, there would be artifacts at the boundaries.
187 // Instead, we report that we cannot support odd values for top and left..
188 if (!SkIsAlign2(bounds.fLeft) || !SkIsAlign2(bounds.fTop)) {
189 return kInvalidParameters;
190 }
191
192#ifdef SK_DEBUG
193 {
194 // Make a copy, since getValidSubset can change its input.
195 SkIRect subset(bounds);
196 // That said, getValidSubset should *not* change its input, in this case; otherwise
197 // getValidSubset does not match the actual subsets we can do.
198 SkASSERT(this->getValidSubset(&subset) && subset == bounds);
199 }
200#endif
201
202 config.options.use_cropping = 1;
203 config.options.crop_left = bounds.fLeft;
204 config.options.crop_top = bounds.fTop;
205 config.options.crop_width = bounds.width();
206 config.options.crop_height = bounds.height();
207 }
208
209 SkISize dstDimensions = dstInfo.dimensions();
210 if (bounds.size() != dstDimensions) {
scroggo6f5e6192015-06-18 12:53:43 -0700211 // Caller is requesting scaling.
212 config.options.use_scaling = 1;
scroggob636b452015-07-22 07:16:20 -0700213 config.options.scaled_width = dstDimensions.width();
214 config.options.scaled_height = dstDimensions.height();
scroggo6f5e6192015-06-18 12:53:43 -0700215 }
216
217 config.output.colorspace = webp_decode_mode(dstInfo.colorType(),
218 dstInfo.alphaType() == kPremul_SkAlphaType);
219 config.output.u.RGBA.rgba = (uint8_t*) dst;
220 config.output.u.RGBA.stride = (int) rowBytes;
221 config.output.u.RGBA.size = dstInfo.getSafeSize(rowBytes);
222 config.output.is_external_memory = 1;
223
224 SkAutoTCallVProc<WebPIDecoder, WebPIDelete> idec(WebPIDecode(NULL, 0, &config));
225 if (!idec) {
226 return kInvalidInput;
227 }
228
229 SkAutoMalloc storage(BUFFER_SIZE);
230 uint8_t* buffer = static_cast<uint8_t*>(storage.get());
231 while (true) {
232 const size_t bytesRead = stream()->read(buffer, BUFFER_SIZE);
233 if (0 == bytesRead) {
234 // FIXME: Maybe this is an incomplete image? How to decide? Based
235 // on the number of rows decoded? We can know the number of rows
236 // decoded using WebPIDecGetRGB.
237 return kInvalidInput;
238 }
239
240 switch (WebPIAppend(idec, buffer, bytesRead)) {
241 case VP8_STATUS_OK:
242 return kSuccess;
243 case VP8_STATUS_SUSPENDED:
244 // Break out of the switch statement. Continue the loop.
245 break;
246 default:
247 return kInvalidInput;
248 }
249 }
250}
251
252SkWebpCodec::SkWebpCodec(const SkImageInfo& info, SkStream* stream)
253 : INHERITED(info, stream) {}