blob: 32a8b78b14f2487e69305c6d90c89533319435bb [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
scroggoeb602a52015-07-09 08:16:03 -0700128SkCodec::Result SkWebpCodec::onGetPixels(const SkImageInfo& dstInfo, void* dst, size_t rowBytes,
129 const Options&, SkPMColor*, int*) {
scroggo6f5e6192015-06-18 12:53:43 -0700130 switch (this->rewindIfNeeded()) {
131 case kCouldNotRewind_RewindState:
132 return kCouldNotRewind;
133 case kRewound_RewindState:
134 // Rewound to the beginning. Since creation only does a peek, the stream is at the
135 // correct position.
136 break;
137 case kNoRewindNecessary_RewindState:
138 // Already at the right spot for decoding.
139 break;
140 }
141
142 if (!conversion_possible(dstInfo, this->getInfo())) {
143 return kInvalidConversion;
144 }
145
146 WebPDecoderConfig config;
147 if (0 == WebPInitDecoderConfig(&config)) {
148 // ABI mismatch.
149 // FIXME: New enum for this?
150 return kInvalidInput;
151 }
152
153 // Free any memory associated with the buffer. Must be called last, so we declare it first.
154 SkAutoTCallVProc<WebPDecBuffer, WebPFreeDecBuffer> autoFree(&(config.output));
155
156 SkISize dimensions = dstInfo.dimensions();
157 if (this->getInfo().dimensions() != dimensions) {
158 // Caller is requesting scaling.
159 config.options.use_scaling = 1;
160 config.options.scaled_width = dimensions.width();
161 config.options.scaled_height = dimensions.height();
162 }
163
164 config.output.colorspace = webp_decode_mode(dstInfo.colorType(),
165 dstInfo.alphaType() == kPremul_SkAlphaType);
166 config.output.u.RGBA.rgba = (uint8_t*) dst;
167 config.output.u.RGBA.stride = (int) rowBytes;
168 config.output.u.RGBA.size = dstInfo.getSafeSize(rowBytes);
169 config.output.is_external_memory = 1;
170
171 SkAutoTCallVProc<WebPIDecoder, WebPIDelete> idec(WebPIDecode(NULL, 0, &config));
172 if (!idec) {
173 return kInvalidInput;
174 }
175
176 SkAutoMalloc storage(BUFFER_SIZE);
177 uint8_t* buffer = static_cast<uint8_t*>(storage.get());
178 while (true) {
179 const size_t bytesRead = stream()->read(buffer, BUFFER_SIZE);
180 if (0 == bytesRead) {
181 // FIXME: Maybe this is an incomplete image? How to decide? Based
182 // on the number of rows decoded? We can know the number of rows
183 // decoded using WebPIDecGetRGB.
184 return kInvalidInput;
185 }
186
187 switch (WebPIAppend(idec, buffer, bytesRead)) {
188 case VP8_STATUS_OK:
189 return kSuccess;
190 case VP8_STATUS_SUSPENDED:
191 // Break out of the switch statement. Continue the loop.
192 break;
193 default:
194 return kInvalidInput;
195 }
196 }
197}
198
199SkWebpCodec::SkWebpCodec(const SkImageInfo& info, SkStream* stream)
200 : INHERITED(info, stream) {}