blob: 5ffdd34eae81a81eeb0a77bee135831489eb0601 [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"
9#include "SkImageGenerator.h"
10#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?
66 // Is unpremul the right type? Clients of SkImageGenerator may assume it's the
67 // 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
85static bool conversion_possible(const SkImageInfo& dst, const SkImageInfo& src) {
86 switch (dst.colorType()) {
87 // Both byte orders are supported.
88 case kBGRA_8888_SkColorType:
89 case kRGBA_8888_SkColorType:
90 break;
91 default:
92 return false;
93 }
94 if (dst.profileType() != src.profileType()) {
95 return false;
96 }
97 if (dst.alphaType() == src.alphaType()) {
98 return true;
99 }
100 return kPremul_SkAlphaType == dst.alphaType() &&
101 kUnpremul_SkAlphaType == src.alphaType();
102}
103
104SkISize SkWebpCodec::onGetScaledDimensions(float desiredScale) const {
105 SkISize dim = this->getInfo().dimensions();
msaretta0c414d2015-06-19 07:34:30 -0700106 // SkCodec treats zero dimensional images as errors, so the minimum size
107 // that we will recommend is 1x1.
108 dim.fWidth = SkTMax(1, SkScalarRoundToInt(desiredScale * dim.fWidth));
109 dim.fHeight = SkTMax(1, SkScalarRoundToInt(desiredScale * dim.fHeight));
scroggo6f5e6192015-06-18 12:53:43 -0700110 return dim;
111}
112
113static WEBP_CSP_MODE webp_decode_mode(SkColorType ct, bool premultiply) {
114 switch (ct) {
115 case kBGRA_8888_SkColorType:
116 return premultiply ? MODE_bgrA : MODE_BGRA;
117 case kRGBA_8888_SkColorType:
118 return premultiply ? MODE_rgbA : MODE_RGBA;
119 default:
120 return MODE_LAST;
121 }
122}
123
124// The WebP decoding API allows us to incrementally pass chunks of bytes as we receive them to the
125// decoder with WebPIAppend. In order to do so, we need to read chunks from the SkStream. This size
126// is arbitrary.
127static const size_t BUFFER_SIZE = 4096;
128
129SkImageGenerator::Result SkWebpCodec::onGetPixels(const SkImageInfo& dstInfo, void* dst,
130 size_t rowBytes, const Options&, SkPMColor*,
131 int*) {
132 switch (this->rewindIfNeeded()) {
133 case kCouldNotRewind_RewindState:
134 return kCouldNotRewind;
135 case kRewound_RewindState:
136 // Rewound to the beginning. Since creation only does a peek, the stream is at the
137 // correct position.
138 break;
139 case kNoRewindNecessary_RewindState:
140 // Already at the right spot for decoding.
141 break;
142 }
143
144 if (!conversion_possible(dstInfo, this->getInfo())) {
145 return kInvalidConversion;
146 }
147
148 WebPDecoderConfig config;
149 if (0 == WebPInitDecoderConfig(&config)) {
150 // ABI mismatch.
151 // FIXME: New enum for this?
152 return kInvalidInput;
153 }
154
155 // Free any memory associated with the buffer. Must be called last, so we declare it first.
156 SkAutoTCallVProc<WebPDecBuffer, WebPFreeDecBuffer> autoFree(&(config.output));
157
158 SkISize dimensions = dstInfo.dimensions();
159 if (this->getInfo().dimensions() != dimensions) {
160 // Caller is requesting scaling.
161 config.options.use_scaling = 1;
162 config.options.scaled_width = dimensions.width();
163 config.options.scaled_height = dimensions.height();
164 }
165
166 config.output.colorspace = webp_decode_mode(dstInfo.colorType(),
167 dstInfo.alphaType() == kPremul_SkAlphaType);
168 config.output.u.RGBA.rgba = (uint8_t*) dst;
169 config.output.u.RGBA.stride = (int) rowBytes;
170 config.output.u.RGBA.size = dstInfo.getSafeSize(rowBytes);
171 config.output.is_external_memory = 1;
172
173 SkAutoTCallVProc<WebPIDecoder, WebPIDelete> idec(WebPIDecode(NULL, 0, &config));
174 if (!idec) {
175 return kInvalidInput;
176 }
177
178 SkAutoMalloc storage(BUFFER_SIZE);
179 uint8_t* buffer = static_cast<uint8_t*>(storage.get());
180 while (true) {
181 const size_t bytesRead = stream()->read(buffer, BUFFER_SIZE);
182 if (0 == bytesRead) {
183 // FIXME: Maybe this is an incomplete image? How to decide? Based
184 // on the number of rows decoded? We can know the number of rows
185 // decoded using WebPIDecGetRGB.
186 return kInvalidInput;
187 }
188
189 switch (WebPIAppend(idec, buffer, bytesRead)) {
190 case VP8_STATUS_OK:
191 return kSuccess;
192 case VP8_STATUS_SUSPENDED:
193 // Break out of the switch statement. Continue the loop.
194 break;
195 default:
196 return kInvalidInput;
197 }
198 }
199}
200
201SkWebpCodec::SkWebpCodec(const SkImageInfo& info, SkStream* stream)
202 : INHERITED(info, stream) {}