blob: fea557d21ed9ddb8e9a86ff475a2c996a8fa749d [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
8#include "SkWebpCodec.h"
scroggo6f5e6192015-06-18 12:53:43 -07009#include "SkTemplates.h"
10
11// A WebP decoder on top of (subset of) libwebp
12// For more information on WebP image format, and libwebp library, see:
13// https://code.google.com/speed/webp/
14// http://www.webmproject.org/code/#libwebp-webp-image-library
15// https://chromium.googlesource.com/webm/libwebp
16
17// If moving libwebp out of skia source tree, path for webp headers must be
18// updated accordingly. Here, we enforce using local copy in webp sub-directory.
19#include "webp/decode.h"
20#include "webp/encode.h"
21
22bool SkWebpCodec::IsWebp(SkStream* stream) {
23 // WEBP starts with the following:
24 // RIFFXXXXWEBPVP
25 // Where XXXX is unspecified.
26 const char LENGTH = 14;
27 char bytes[LENGTH];
28 if (stream->read(&bytes, LENGTH) != LENGTH) {
29 return false;
30 }
31 return !memcmp(bytes, "RIFF", 4) && !memcmp(&bytes[8], "WEBPVP", 6);
32}
33
34static const size_t WEBP_VP8_HEADER_SIZE = 30;
35
36// Parse headers of RIFF container, and check for valid Webp (VP8) content.
37// NOTE: This calls peek instead of read, since onGetPixels will need these
38// bytes again.
39static bool webp_parse_header(SkStream* stream, SkImageInfo* info) {
40 unsigned char buffer[WEBP_VP8_HEADER_SIZE];
41 if (!stream->peek(buffer, WEBP_VP8_HEADER_SIZE)) {
42 return false;
43 }
44
45 WebPBitstreamFeatures features;
46 VP8StatusCode status = WebPGetFeatures(buffer, WEBP_VP8_HEADER_SIZE, &features);
47 if (VP8_STATUS_OK != status) {
48 return false; // Invalid WebP file.
49 }
50
51 // sanity check for image size that's about to be decoded.
52 {
53 const int64_t size = sk_64_mul(features.width, features.height);
54 if (!sk_64_isS32(size)) {
55 return false;
56 }
57 // now check that if we are 4-bytes per pixel, we also don't overflow
58 if (sk_64_asS32(size) > (0x7FFFFFFF >> 2)) {
59 return false;
60 }
61 }
62
63 if (info) {
64 // FIXME: Is N32 the right type?
scroggoeb602a52015-07-09 08:16:03 -070065 // Is unpremul the right type? Clients of SkCodec may assume it's the
scroggo6f5e6192015-06-18 12:53:43 -070066 // best type, when Skia currently cannot draw unpremul (and raster is faster
67 // with premul).
68 *info = SkImageInfo::Make(features.width, features.height, kN32_SkColorType,
69 SkToBool(features.has_alpha) ? kUnpremul_SkAlphaType
70 : kOpaque_SkAlphaType);
71 }
72 return true;
73}
74
75SkCodec* SkWebpCodec::NewFromStream(SkStream* stream) {
76 SkAutoTDelete<SkStream> streamDeleter(stream);
77 SkImageInfo info;
78 if (webp_parse_header(stream, &info)) {
79 return SkNEW_ARGS(SkWebpCodec, (info, streamDeleter.detach()));
80 }
81 return NULL;
82}
83
84static bool conversion_possible(const SkImageInfo& dst, const SkImageInfo& src) {
85 switch (dst.colorType()) {
86 // Both byte orders are supported.
87 case kBGRA_8888_SkColorType:
88 case kRGBA_8888_SkColorType:
89 break;
90 default:
91 return false;
92 }
93 if (dst.profileType() != src.profileType()) {
94 return false;
95 }
96 if (dst.alphaType() == src.alphaType()) {
97 return true;
98 }
99 return kPremul_SkAlphaType == dst.alphaType() &&
100 kUnpremul_SkAlphaType == src.alphaType();
101}
102
103SkISize SkWebpCodec::onGetScaledDimensions(float desiredScale) const {
104 SkISize dim = this->getInfo().dimensions();
msaretta0c414d2015-06-19 07:34:30 -0700105 // SkCodec treats zero dimensional images as errors, so the minimum size
106 // that we will recommend is 1x1.
107 dim.fWidth = SkTMax(1, SkScalarRoundToInt(desiredScale * dim.fWidth));
108 dim.fHeight = SkTMax(1, SkScalarRoundToInt(desiredScale * dim.fHeight));
scroggo6f5e6192015-06-18 12:53:43 -0700109 return dim;
110}
111
112static WEBP_CSP_MODE webp_decode_mode(SkColorType ct, bool premultiply) {
113 switch (ct) {
114 case kBGRA_8888_SkColorType:
115 return premultiply ? MODE_bgrA : MODE_BGRA;
116 case kRGBA_8888_SkColorType:
117 return premultiply ? MODE_rgbA : MODE_RGBA;
118 default:
119 return MODE_LAST;
120 }
121}
122
123// The WebP decoding API allows us to incrementally pass chunks of bytes as we receive them to the
124// decoder with WebPIAppend. In order to do so, we need to read chunks from the SkStream. This size
125// is arbitrary.
126static const size_t BUFFER_SIZE = 4096;
127
scroggob636b452015-07-22 07:16:20 -0700128bool SkWebpCodec::onGetValidSubset(SkIRect* desiredSubset) const {
129 if (!desiredSubset) {
130 return false;
131 }
132
133 SkIRect bounds = SkIRect::MakeSize(this->getInfo().dimensions());
134 if (!desiredSubset->intersect(bounds)) {
135 return false;
136 }
137
138 // As stated below, libwebp snaps to even left and top. Make sure top and left are even, so we
139 // decode this exact subset.
140 // Leave right and bottom unmodified, so we suggest a slightly larger subset than requested.
141 desiredSubset->fLeft = (desiredSubset->fLeft >> 1) << 1;
142 desiredSubset->fTop = (desiredSubset->fTop >> 1) << 1;
143 return true;
144}
145
scroggoeb602a52015-07-09 08:16:03 -0700146SkCodec::Result SkWebpCodec::onGetPixels(const SkImageInfo& dstInfo, void* dst, size_t rowBytes,
scroggob636b452015-07-22 07:16:20 -0700147 const Options& options, SkPMColor*, int*) {
scroggo6f5e6192015-06-18 12:53:43 -0700148 switch (this->rewindIfNeeded()) {
149 case kCouldNotRewind_RewindState:
150 return kCouldNotRewind;
151 case kRewound_RewindState:
152 // Rewound to the beginning. Since creation only does a peek, the stream is at the
153 // correct position.
154 break;
155 case kNoRewindNecessary_RewindState:
156 // Already at the right spot for decoding.
157 break;
158 }
159
160 if (!conversion_possible(dstInfo, this->getInfo())) {
161 return kInvalidConversion;
162 }
163
164 WebPDecoderConfig config;
165 if (0 == WebPInitDecoderConfig(&config)) {
166 // ABI mismatch.
167 // FIXME: New enum for this?
168 return kInvalidInput;
169 }
170
171 // Free any memory associated with the buffer. Must be called last, so we declare it first.
172 SkAutoTCallVProc<WebPDecBuffer, WebPFreeDecBuffer> autoFree(&(config.output));
173
scroggob636b452015-07-22 07:16:20 -0700174 SkIRect bounds = SkIRect::MakeSize(this->getInfo().dimensions());
175 if (options.fSubset) {
176 // Caller is requesting a subset.
177 if (!bounds.contains(*options.fSubset)) {
178 // The subset is out of bounds.
179 return kInvalidParameters;
180 }
181
182 bounds = *options.fSubset;
183
184 // This is tricky. libwebp snaps the top and left to even values. We could let libwebp
185 // do the snap, and return a subset which is a different one than requested. The problem
186 // with that approach is that the caller may try to stitch subsets together, and if we
187 // returned different subsets than requested, there would be artifacts at the boundaries.
188 // Instead, we report that we cannot support odd values for top and left..
189 if (!SkIsAlign2(bounds.fLeft) || !SkIsAlign2(bounds.fTop)) {
190 return kInvalidParameters;
191 }
192
193#ifdef SK_DEBUG
194 {
195 // Make a copy, since getValidSubset can change its input.
196 SkIRect subset(bounds);
197 // That said, getValidSubset should *not* change its input, in this case; otherwise
198 // getValidSubset does not match the actual subsets we can do.
199 SkASSERT(this->getValidSubset(&subset) && subset == bounds);
200 }
201#endif
202
203 config.options.use_cropping = 1;
204 config.options.crop_left = bounds.fLeft;
205 config.options.crop_top = bounds.fTop;
206 config.options.crop_width = bounds.width();
207 config.options.crop_height = bounds.height();
208 }
209
210 SkISize dstDimensions = dstInfo.dimensions();
211 if (bounds.size() != dstDimensions) {
scroggo6f5e6192015-06-18 12:53:43 -0700212 // Caller is requesting scaling.
213 config.options.use_scaling = 1;
scroggob636b452015-07-22 07:16:20 -0700214 config.options.scaled_width = dstDimensions.width();
215 config.options.scaled_height = dstDimensions.height();
scroggo6f5e6192015-06-18 12:53:43 -0700216 }
217
218 config.output.colorspace = webp_decode_mode(dstInfo.colorType(),
219 dstInfo.alphaType() == kPremul_SkAlphaType);
220 config.output.u.RGBA.rgba = (uint8_t*) dst;
221 config.output.u.RGBA.stride = (int) rowBytes;
222 config.output.u.RGBA.size = dstInfo.getSafeSize(rowBytes);
223 config.output.is_external_memory = 1;
224
225 SkAutoTCallVProc<WebPIDecoder, WebPIDelete> idec(WebPIDecode(NULL, 0, &config));
226 if (!idec) {
227 return kInvalidInput;
228 }
229
230 SkAutoMalloc storage(BUFFER_SIZE);
231 uint8_t* buffer = static_cast<uint8_t*>(storage.get());
232 while (true) {
233 const size_t bytesRead = stream()->read(buffer, BUFFER_SIZE);
234 if (0 == bytesRead) {
235 // FIXME: Maybe this is an incomplete image? How to decide? Based
236 // on the number of rows decoded? We can know the number of rows
237 // decoded using WebPIDecGetRGB.
238 return kInvalidInput;
239 }
240
241 switch (WebPIAppend(idec, buffer, bytesRead)) {
242 case VP8_STATUS_OK:
243 return kSuccess;
244 case VP8_STATUS_SUSPENDED:
245 // Break out of the switch statement. Continue the loop.
246 break;
247 default:
248 return kInvalidInput;
249 }
250 }
251}
252
253SkWebpCodec::SkWebpCodec(const SkImageInfo& info, SkStream* stream)
254 : INHERITED(info, stream) {}