blob: 7a3c65875c18191730838bba29d5e576d67eb90a [file] [log] [blame]
commit-bot@chromium.orga936e372013-03-14 14:42:18 +00001/*
2 * Copyright 2010, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "SkImageDecoder.h"
18#include "SkImageEncoder.h"
19#include "SkColorPriv.h"
20#include "SkScaledBitmapSampler.h"
21#include "SkStream.h"
22#include "SkTemplates.h"
23#include "SkUtils.h"
commit-bot@chromium.orga936e372013-03-14 14:42:18 +000024
25// A WebP decoder only, on top of (subset of) libwebp
26// For more information on WebP image format, and libwebp library, see:
27// http://code.google.com/speed/webp/
28// http://www.webmproject.org/code/#libwebp_webp_image_decoder_library
29// http://review.webmproject.org/gitweb?p=libwebp.git
30
31#include <stdio.h>
32extern "C" {
33// If moving libwebp out of skia source tree, path for webp headers must be
34// updated accordingly. Here, we enforce using local copy in webp sub-directory.
35#include "webp/decode.h"
36#include "webp/encode.h"
37}
38
commit-bot@chromium.orga936e372013-03-14 14:42:18 +000039// this enables timing code to report milliseconds for a decode
40//#define TIME_DECODE
41
42//////////////////////////////////////////////////////////////////////////
43//////////////////////////////////////////////////////////////////////////
44
45// Define VP8 I/O on top of Skia stream
46
47//////////////////////////////////////////////////////////////////////////
48//////////////////////////////////////////////////////////////////////////
49
50static const size_t WEBP_VP8_HEADER_SIZE = 64;
51static const size_t WEBP_IDECODE_BUFFER_SZ = (1 << 16);
52
53// Parse headers of RIFF container, and check for valid Webp (VP8) content.
54static bool webp_parse_header(SkStream* stream, int* width, int* height, int* alpha) {
55 unsigned char buffer[WEBP_VP8_HEADER_SIZE];
scroggo@google.com3c8730a2013-08-21 14:56:09 +000056 size_t bytesToRead = WEBP_VP8_HEADER_SIZE;
57 size_t totalBytesRead = 0;
58 do {
59 unsigned char* dst = buffer + totalBytesRead;
60 const size_t bytesRead = stream->read(dst, bytesToRead);
61 if (0 == bytesRead) {
62 // Could not read any bytes. Check to see if we are at the end (exit
63 // condition), and continue reading if not. Important for streams
64 // that do not have all the data ready.
65 continue;
66 }
67 bytesToRead -= bytesRead;
68 totalBytesRead += bytesRead;
69 SkASSERT(bytesToRead + totalBytesRead == WEBP_VP8_HEADER_SIZE);
70 } while (!stream->isAtEnd() && bytesToRead > 0);
commit-bot@chromium.orga936e372013-03-14 14:42:18 +000071
72 WebPBitstreamFeatures features;
scroggo@google.com3c8730a2013-08-21 14:56:09 +000073 VP8StatusCode status = WebPGetFeatures(buffer, totalBytesRead, &features);
commit-bot@chromium.orga936e372013-03-14 14:42:18 +000074 if (VP8_STATUS_OK != status) {
75 return false; // Invalid WebP file.
76 }
77 *width = features.width;
78 *height = features.height;
79 *alpha = features.has_alpha;
80
81 // sanity check for image size that's about to be decoded.
82 {
reed@google.com57212f92013-12-30 14:40:38 +000083 int64_t size = sk_64_mul(*width, *height);
84 if (!sk_64_isS32(size)) {
commit-bot@chromium.orga936e372013-03-14 14:42:18 +000085 return false;
86 }
87 // now check that if we are 4-bytes per pixel, we also don't overflow
reed@google.com57212f92013-12-30 14:40:38 +000088 if (sk_64_asS32(size) > (0x7FFFFFFF >> 2)) {
commit-bot@chromium.orga936e372013-03-14 14:42:18 +000089 return false;
90 }
91 }
92 return true;
93}
94
95class SkWEBPImageDecoder: public SkImageDecoder {
96public:
97 SkWEBPImageDecoder() {
98 fInputStream = NULL;
99 fOrigWidth = 0;
100 fOrigHeight = 0;
101 fHasAlpha = 0;
102 }
103 virtual ~SkWEBPImageDecoder() {
104 SkSafeUnref(fInputStream);
105 }
106
107 virtual Format getFormat() const SK_OVERRIDE {
108 return kWEBP_Format;
109 }
110
111protected:
scroggo@google.comb5571b32013-09-25 21:34:24 +0000112 virtual bool onBuildTileIndex(SkStreamRewindable *stream, int *width, int *height) SK_OVERRIDE;
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000113 virtual bool onDecodeSubset(SkBitmap* bitmap, const SkIRect& rect) SK_OVERRIDE;
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000114 virtual bool onDecode(SkStream* stream, SkBitmap* bm, Mode) SK_OVERRIDE;
115
116private:
scroggo@google.com2bbc2c92013-06-14 15:33:20 +0000117 /**
118 * Called when determining the output config to request to webp.
119 * If the image does not have alpha, there is no need to premultiply.
120 * If the caller wants unpremultiplied colors, that is respected.
121 */
122 bool shouldPremultiply() const {
123 return SkToBool(fHasAlpha) && !this->getRequireUnpremultipliedColors();
124 }
125
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000126 bool setDecodeConfig(SkBitmap* decodedBitmap, int width, int height);
scroggo@google.com2bbc2c92013-06-14 15:33:20 +0000127
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000128 SkStream* fInputStream;
129 int fOrigWidth;
130 int fOrigHeight;
131 int fHasAlpha;
132
133 typedef SkImageDecoder INHERITED;
134};
135
136//////////////////////////////////////////////////////////////////////////
137
138#ifdef TIME_DECODE
139
140#include "SkTime.h"
141
142class AutoTimeMillis {
143public:
144 AutoTimeMillis(const char label[]) :
145 fLabel(label) {
146 if (NULL == fLabel) {
147 fLabel = "";
148 }
149 fNow = SkTime::GetMSecs();
150 }
151 ~AutoTimeMillis() {
152 SkDebugf("---- Time (ms): %s %d\n", fLabel, SkTime::GetMSecs() - fNow);
153 }
154private:
155 const char* fLabel;
156 SkMSec fNow;
157};
158
159#endif
160
161///////////////////////////////////////////////////////////////////////////////
162
163// This guy exists just to aid in debugging, as it allows debuggers to just
164// set a break-point in one place to see all error exists.
165static bool return_false(const SkBitmap& bm, const char msg[]) {
166 SkDEBUGF(("libwebp error %s [%d %d]", msg, bm.width(), bm.height()));
167 return false; // must always return false
168}
169
scroggo@google.com2bbc2c92013-06-14 15:33:20 +0000170static WEBP_CSP_MODE webp_decode_mode(const SkBitmap* decodedBitmap, bool premultiply) {
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000171 WEBP_CSP_MODE mode = MODE_LAST;
172 SkBitmap::Config config = decodedBitmap->config();
scroggo@google.com2bbc2c92013-06-14 15:33:20 +0000173
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000174 if (config == SkBitmap::kARGB_8888_Config) {
halcanary@google.comdedd44a2013-12-20 16:35:22 +0000175 #if SK_PMCOLOR_BYTE_ORDER(B,G,R,A)
176 mode = premultiply ? MODE_bgrA : MODE_BGRA;
177 #elif SK_PMCOLOR_BYTE_ORDER(R,G,B,A)
178 mode = premultiply ? MODE_rgbA : MODE_RGBA;
179 #else
180 #error "Skia uses BGRA or RGBA byte order"
181 #endif
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000182 } else if (config == SkBitmap::kARGB_4444_Config) {
scroggo@google.com2bbc2c92013-06-14 15:33:20 +0000183 mode = premultiply ? MODE_rgbA_4444 : MODE_RGBA_4444;
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000184 } else if (config == SkBitmap::kRGB_565_Config) {
scroggo@google.com2bbc2c92013-06-14 15:33:20 +0000185 mode = MODE_RGB_565;
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000186 }
187 SkASSERT(MODE_LAST != mode);
188 return mode;
189}
190
191// Incremental WebP image decoding. Reads input buffer of 64K size iteratively
192// and decodes this block to appropriate color-space as per config object.
193static bool webp_idecode(SkStream* stream, WebPDecoderConfig* config) {
194 WebPIDecoder* idec = WebPIDecode(NULL, 0, config);
195 if (NULL == idec) {
196 WebPFreeDecBuffer(&config->output);
197 return false;
198 }
199
scroggo@google.com4d213ab2013-08-28 13:08:54 +0000200 if (!stream->rewind()) {
201 SkDebugf("Failed to rewind webp stream!");
202 return false;
203 }
scroggo@google.com3c8730a2013-08-21 14:56:09 +0000204 const size_t readBufferSize = stream->hasLength() ?
205 SkTMin(stream->getLength(), WEBP_IDECODE_BUFFER_SZ) : WEBP_IDECODE_BUFFER_SZ;
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000206 SkAutoMalloc srcStorage(readBufferSize);
207 unsigned char* input = (uint8_t*)srcStorage.get();
208 if (NULL == input) {
209 WebPIDelete(idec);
210 WebPFreeDecBuffer(&config->output);
211 return false;
212 }
213
scroggo@google.com80e18c92013-08-09 19:22:00 +0000214 bool success = true;
215 VP8StatusCode status = VP8_STATUS_SUSPENDED;
216 do {
217 const size_t bytesRead = stream->read(input, readBufferSize);
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000218 if (0 == bytesRead) {
scroggo@google.com80e18c92013-08-09 19:22:00 +0000219 success = false;
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000220 break;
221 }
222
scroggo@google.com80e18c92013-08-09 19:22:00 +0000223 status = WebPIAppend(idec, input, bytesRead);
224 if (VP8_STATUS_OK != status && VP8_STATUS_SUSPENDED != status) {
225 success = false;
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000226 break;
227 }
scroggo@google.com80e18c92013-08-09 19:22:00 +0000228 } while (VP8_STATUS_OK != status);
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000229 srcStorage.free();
230 WebPIDelete(idec);
231 WebPFreeDecBuffer(&config->output);
232
scroggo@google.com80e18c92013-08-09 19:22:00 +0000233 return success;
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000234}
235
236static bool webp_get_config_resize(WebPDecoderConfig* config,
237 SkBitmap* decodedBitmap,
scroggo@google.com2bbc2c92013-06-14 15:33:20 +0000238 int width, int height, bool premultiply) {
239 WEBP_CSP_MODE mode = webp_decode_mode(decodedBitmap, premultiply);
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000240 if (MODE_LAST == mode) {
241 return false;
242 }
243
244 if (0 == WebPInitDecoderConfig(config)) {
245 return false;
246 }
247
248 config->output.colorspace = mode;
249 config->output.u.RGBA.rgba = (uint8_t*)decodedBitmap->getPixels();
robertphillips@google.com8b169312013-10-15 17:47:36 +0000250 config->output.u.RGBA.stride = (int) decodedBitmap->rowBytes();
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000251 config->output.u.RGBA.size = decodedBitmap->getSize();
252 config->output.is_external_memory = 1;
253
254 if (width != decodedBitmap->width() || height != decodedBitmap->height()) {
255 config->options.use_scaling = 1;
256 config->options.scaled_width = decodedBitmap->width();
257 config->options.scaled_height = decodedBitmap->height();
258 }
259
260 return true;
261}
262
263static bool webp_get_config_resize_crop(WebPDecoderConfig* config,
264 SkBitmap* decodedBitmap,
scroggo@google.com2bbc2c92013-06-14 15:33:20 +0000265 const SkIRect& region, bool premultiply) {
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000266
267 if (!webp_get_config_resize(config, decodedBitmap, region.width(),
scroggo@google.com2bbc2c92013-06-14 15:33:20 +0000268 region.height(), premultiply)) {
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000269 return false;
270 }
271
272 config->options.use_cropping = 1;
273 config->options.crop_left = region.fLeft;
274 config->options.crop_top = region.fTop;
275 config->options.crop_width = region.width();
276 config->options.crop_height = region.height();
277
278 return true;
279}
280
reed6c225732014-06-09 19:52:07 -0700281bool SkWEBPImageDecoder::setDecodeConfig(SkBitmap* decodedBitmap, int width, int height) {
282 SkColorType colorType = this->getPrefColorType(k32Bit_SrcDepth, SkToBool(fHasAlpha));
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000283
284 // YUV converter supports output in RGB565, RGBA4444 and RGBA8888 formats.
285 if (fHasAlpha) {
reed6c225732014-06-09 19:52:07 -0700286 if (colorType != kARGB_4444_SkColorType) {
287 colorType = kN32_SkColorType;
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000288 }
289 } else {
reed6c225732014-06-09 19:52:07 -0700290 if (colorType != kRGB_565_SkColorType && colorType != kARGB_4444_SkColorType) {
291 colorType = kN32_SkColorType;
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000292 }
293 }
294
reed5926b862014-06-11 10:33:13 -0700295#ifdef SK_SUPPORT_LEGACY_IMAGEDECODER_CHOOSER
reed6c225732014-06-09 19:52:07 -0700296 if (!this->chooseFromOneChoice(colorType, width, height)) {
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000297 return false;
298 }
reed5926b862014-06-11 10:33:13 -0700299#endif
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000300
reed6c225732014-06-09 19:52:07 -0700301 SkAlphaType alphaType = kOpaque_SkAlphaType;
commit-bot@chromium.org915b9722014-04-24 18:55:13 +0000302 if (SkToBool(fHasAlpha)) {
303 if (this->getRequireUnpremultipliedColors()) {
reed6c225732014-06-09 19:52:07 -0700304 alphaType = kUnpremul_SkAlphaType;
commit-bot@chromium.org915b9722014-04-24 18:55:13 +0000305 } else {
reed6c225732014-06-09 19:52:07 -0700306 alphaType = kPremul_SkAlphaType;
commit-bot@chromium.org915b9722014-04-24 18:55:13 +0000307 }
commit-bot@chromium.org915b9722014-04-24 18:55:13 +0000308 }
reed6c225732014-06-09 19:52:07 -0700309 return decodedBitmap->setInfo(SkImageInfo::Make(width, height, colorType, alphaType));
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000310}
311
scroggo@google.comb5571b32013-09-25 21:34:24 +0000312bool SkWEBPImageDecoder::onBuildTileIndex(SkStreamRewindable* stream,
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000313 int *width, int *height) {
314 int origWidth, origHeight, hasAlpha;
315 if (!webp_parse_header(stream, &origWidth, &origHeight, &hasAlpha)) {
316 return false;
317 }
318
scroggo@google.com4d213ab2013-08-28 13:08:54 +0000319 if (!stream->rewind()) {
320 SkDebugf("Failed to rewind webp stream!");
321 return false;
322 }
323
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000324 *width = origWidth;
325 *height = origHeight;
326
327 SkRefCnt_SafeAssign(this->fInputStream, stream);
328 this->fOrigWidth = origWidth;
329 this->fOrigHeight = origHeight;
330 this->fHasAlpha = hasAlpha;
331
332 return true;
333}
334
335static bool is_config_compatible(const SkBitmap& bitmap) {
336 SkBitmap::Config config = bitmap.config();
337 return config == SkBitmap::kARGB_4444_Config ||
338 config == SkBitmap::kRGB_565_Config ||
339 config == SkBitmap::kARGB_8888_Config;
340}
341
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000342bool SkWEBPImageDecoder::onDecodeSubset(SkBitmap* decodedBitmap,
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000343 const SkIRect& region) {
344 SkIRect rect = SkIRect::MakeWH(fOrigWidth, fOrigHeight);
345
346 if (!rect.intersect(region)) {
347 // If the requested region is entirely outsides the image, return false
348 return false;
349 }
350
351 const int sampleSize = this->getSampleSize();
352 SkScaledBitmapSampler sampler(rect.width(), rect.height(), sampleSize);
353 const int width = sampler.scaledWidth();
354 const int height = sampler.scaledHeight();
355
356 // The image can be decoded directly to decodedBitmap if
357 // 1. the region is within the image range
358 // 2. bitmap's config is compatible
359 // 3. bitmap's size is same as the required region (after sampled)
360 bool directDecode = (rect == region) &&
361 (decodedBitmap->isNull() ||
362 (is_config_compatible(*decodedBitmap) &&
363 (decodedBitmap->width() == width) &&
364 (decodedBitmap->height() == height)));
commit-bot@chromium.orga9f142e2013-05-09 16:15:20 +0000365
366 SkBitmap tmpBitmap;
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000367 SkBitmap *bitmap = decodedBitmap;
368
369 if (!directDecode) {
commit-bot@chromium.orga9f142e2013-05-09 16:15:20 +0000370 bitmap = &tmpBitmap;
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000371 }
372
373 if (bitmap->isNull()) {
374 if (!setDecodeConfig(bitmap, width, height)) {
375 return false;
376 }
377 // alloc from native heap if it is a temp bitmap. (prevent GC)
378 bool allocResult = (bitmap == decodedBitmap)
379 ? allocPixelRef(bitmap, NULL)
380 : bitmap->allocPixels();
381 if (!allocResult) {
382 return return_false(*decodedBitmap, "allocPixelRef");
383 }
reed5926b862014-06-11 10:33:13 -0700384#ifdef SK_SUPPORT_LEGACY_IMAGEDECODER_CHOOSER
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000385 } else {
386 // This is also called in setDecodeConfig in above block.
387 // i.e., when bitmap->isNull() is true.
reed6c225732014-06-09 19:52:07 -0700388 if (!chooseFromOneChoice(bitmap->colorType(), width, height)) {
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000389 return false;
390 }
reed5926b862014-06-11 10:33:13 -0700391#endif
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000392 }
393
394 SkAutoLockPixels alp(*bitmap);
395 WebPDecoderConfig config;
scroggo@google.com2bbc2c92013-06-14 15:33:20 +0000396 if (!webp_get_config_resize_crop(&config, bitmap, rect,
397 this->shouldPremultiply())) {
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000398 return false;
399 }
400
401 // Decode the WebP image data stream using WebP incremental decoding for
402 // the specified cropped image-region.
403 if (!webp_idecode(this->fInputStream, &config)) {
404 return false;
405 }
406
407 if (!directDecode) {
408 cropBitmap(decodedBitmap, bitmap, sampleSize, region.x(), region.y(),
409 region.width(), region.height(), rect.x(), rect.y());
410 }
411 return true;
412}
413
414bool SkWEBPImageDecoder::onDecode(SkStream* stream, SkBitmap* decodedBitmap,
415 Mode mode) {
416#ifdef TIME_DECODE
417 AutoTimeMillis atm("WEBP Decode");
418#endif
419
420 int origWidth, origHeight, hasAlpha;
421 if (!webp_parse_header(stream, &origWidth, &origHeight, &hasAlpha)) {
422 return false;
423 }
424 this->fHasAlpha = hasAlpha;
425
426 const int sampleSize = this->getSampleSize();
427 SkScaledBitmapSampler sampler(origWidth, origHeight, sampleSize);
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000428 if (!setDecodeConfig(decodedBitmap, sampler.scaledWidth(),
429 sampler.scaledHeight())) {
430 return false;
431 }
432
scroggo@google.combc69ce92013-07-09 15:45:14 +0000433 // If only bounds are requested, done
434 if (SkImageDecoder::kDecodeBounds_Mode == mode) {
435 return true;
436 }
437
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000438 if (!this->allocPixelRef(decodedBitmap, NULL)) {
439 return return_false(*decodedBitmap, "allocPixelRef");
440 }
441
442 SkAutoLockPixels alp(*decodedBitmap);
443
444 WebPDecoderConfig config;
445 if (!webp_get_config_resize(&config, decodedBitmap, origWidth, origHeight,
scroggo@google.com2bbc2c92013-06-14 15:33:20 +0000446 this->shouldPremultiply())) {
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000447 return false;
448 }
449
450 // Decode the WebP image data stream using WebP incremental decoding.
451 return webp_idecode(stream, &config);
452}
453
454///////////////////////////////////////////////////////////////////////////////
455
commit-bot@chromium.org5007aab2014-02-26 21:35:17 +0000456#include "SkUnPreMultiply.h"
457
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000458typedef void (*ScanlineImporter)(const uint8_t* in, uint8_t* out, int width,
459 const SkPMColor* SK_RESTRICT ctable);
460
461static void ARGB_8888_To_RGB(const uint8_t* in, uint8_t* rgb, int width,
462 const SkPMColor*) {
463 const uint32_t* SK_RESTRICT src = (const uint32_t*)in;
464 for (int i = 0; i < width; ++i) {
465 const uint32_t c = *src++;
466 rgb[0] = SkGetPackedR32(c);
467 rgb[1] = SkGetPackedG32(c);
468 rgb[2] = SkGetPackedB32(c);
469 rgb += 3;
470 }
471}
472
commit-bot@chromium.org5007aab2014-02-26 21:35:17 +0000473static void ARGB_8888_To_RGBA(const uint8_t* in, uint8_t* rgb, int width,
474 const SkPMColor*) {
475 const uint32_t* SK_RESTRICT src = (const uint32_t*)in;
476 const SkUnPreMultiply::Scale* SK_RESTRICT table =
477 SkUnPreMultiply::GetScaleTable();
478 for (int i = 0; i < width; ++i) {
479 const uint32_t c = *src++;
480 uint8_t a = SkGetPackedA32(c);
481 uint8_t r = SkGetPackedR32(c);
482 uint8_t g = SkGetPackedG32(c);
483 uint8_t b = SkGetPackedB32(c);
484 if (0 != a && 255 != a) {
485 SkUnPreMultiply::Scale scale = table[a];
486 r = SkUnPreMultiply::ApplyScale(scale, r);
487 g = SkUnPreMultiply::ApplyScale(scale, g);
488 b = SkUnPreMultiply::ApplyScale(scale, b);
489 }
490 rgb[0] = r;
491 rgb[1] = g;
492 rgb[2] = b;
493 rgb[3] = a;
494 rgb += 4;
495 }
496}
497
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000498static void RGB_565_To_RGB(const uint8_t* in, uint8_t* rgb, int width,
499 const SkPMColor*) {
500 const uint16_t* SK_RESTRICT src = (const uint16_t*)in;
501 for (int i = 0; i < width; ++i) {
502 const uint16_t c = *src++;
503 rgb[0] = SkPacked16ToR32(c);
504 rgb[1] = SkPacked16ToG32(c);
505 rgb[2] = SkPacked16ToB32(c);
506 rgb += 3;
507 }
508}
509
510static void ARGB_4444_To_RGB(const uint8_t* in, uint8_t* rgb, int width,
511 const SkPMColor*) {
512 const SkPMColor16* SK_RESTRICT src = (const SkPMColor16*)in;
513 for (int i = 0; i < width; ++i) {
514 const SkPMColor16 c = *src++;
515 rgb[0] = SkPacked4444ToR32(c);
516 rgb[1] = SkPacked4444ToG32(c);
517 rgb[2] = SkPacked4444ToB32(c);
518 rgb += 3;
519 }
520}
521
commit-bot@chromium.org5007aab2014-02-26 21:35:17 +0000522static void ARGB_4444_To_RGBA(const uint8_t* in, uint8_t* rgb, int width,
523 const SkPMColor*) {
524 const SkPMColor16* SK_RESTRICT src = (const SkPMColor16*)in;
525 const SkUnPreMultiply::Scale* SK_RESTRICT table =
526 SkUnPreMultiply::GetScaleTable();
527 for (int i = 0; i < width; ++i) {
528 const SkPMColor16 c = *src++;
529 uint8_t a = SkPacked4444ToA32(c);
530 uint8_t r = SkPacked4444ToR32(c);
531 uint8_t g = SkPacked4444ToG32(c);
532 uint8_t b = SkPacked4444ToB32(c);
533 if (0 != a && 255 != a) {
534 SkUnPreMultiply::Scale scale = table[a];
535 r = SkUnPreMultiply::ApplyScale(scale, r);
536 g = SkUnPreMultiply::ApplyScale(scale, g);
537 b = SkUnPreMultiply::ApplyScale(scale, b);
538 }
539 rgb[0] = r;
540 rgb[1] = g;
541 rgb[2] = b;
542 rgb[3] = a;
543 rgb += 4;
544 }
545}
546
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000547static void Index8_To_RGB(const uint8_t* in, uint8_t* rgb, int width,
548 const SkPMColor* SK_RESTRICT ctable) {
549 const uint8_t* SK_RESTRICT src = (const uint8_t*)in;
550 for (int i = 0; i < width; ++i) {
551 const uint32_t c = ctable[*src++];
552 rgb[0] = SkGetPackedR32(c);
553 rgb[1] = SkGetPackedG32(c);
554 rgb[2] = SkGetPackedB32(c);
555 rgb += 3;
556 }
557}
558
commit-bot@chromium.org5007aab2014-02-26 21:35:17 +0000559static ScanlineImporter ChooseImporter(const SkBitmap::Config& config,
560 bool hasAlpha,
561 int* bpp) {
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000562 switch (config) {
563 case SkBitmap::kARGB_8888_Config:
commit-bot@chromium.org5007aab2014-02-26 21:35:17 +0000564 if (hasAlpha) {
565 *bpp = 4;
566 return ARGB_8888_To_RGBA;
567 } else {
568 *bpp = 3;
569 return ARGB_8888_To_RGB;
570 }
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000571 case SkBitmap::kARGB_4444_Config:
commit-bot@chromium.org5007aab2014-02-26 21:35:17 +0000572 if (hasAlpha) {
573 *bpp = 4;
574 return ARGB_4444_To_RGBA;
575 } else {
576 *bpp = 3;
577 return ARGB_4444_To_RGB;
578 }
579 case SkBitmap::kRGB_565_Config:
580 *bpp = 3;
581 return RGB_565_To_RGB;
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000582 case SkBitmap::kIndex8_Config:
commit-bot@chromium.org5007aab2014-02-26 21:35:17 +0000583 *bpp = 3;
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000584 return Index8_To_RGB;
585 default:
586 return NULL;
587 }
588}
589
590static int stream_writer(const uint8_t* data, size_t data_size,
591 const WebPPicture* const picture) {
592 SkWStream* const stream = (SkWStream*)picture->custom_ptr;
593 return stream->write(data, data_size) ? 1 : 0;
594}
595
596class SkWEBPImageEncoder : public SkImageEncoder {
597protected:
598 virtual bool onEncode(SkWStream* stream, const SkBitmap& bm, int quality) SK_OVERRIDE;
599
600private:
601 typedef SkImageEncoder INHERITED;
602};
603
604bool SkWEBPImageEncoder::onEncode(SkWStream* stream, const SkBitmap& bm,
605 int quality) {
reed@google.com44699382013-10-31 17:28:30 +0000606 const SkBitmap::Config config = bm.config();
commit-bot@chromium.org5007aab2014-02-26 21:35:17 +0000607 const bool hasAlpha = !bm.isOpaque();
608 int bpp = -1;
609 const ScanlineImporter scanline_import = ChooseImporter(config, hasAlpha,
610 &bpp);
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000611 if (NULL == scanline_import) {
612 return false;
613 }
commit-bot@chromium.org5007aab2014-02-26 21:35:17 +0000614 if (-1 == bpp) {
615 return false;
616 }
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000617
618 SkAutoLockPixels alp(bm);
619 SkAutoLockColors ctLocker;
620 if (NULL == bm.getPixels()) {
621 return false;
622 }
623
624 WebPConfig webp_config;
commit-bot@chromium.orgbff83f62013-03-14 15:18:08 +0000625 if (!WebPConfigPreset(&webp_config, WEBP_PRESET_DEFAULT, (float) quality)) {
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000626 return false;
627 }
628
629 WebPPicture pic;
630 WebPPictureInit(&pic);
631 pic.width = bm.width();
632 pic.height = bm.height();
633 pic.writer = stream_writer;
634 pic.custom_ptr = (void*)stream;
635
636 const SkPMColor* colors = ctLocker.lockColors(bm);
637 const uint8_t* src = (uint8_t*)bm.getPixels();
commit-bot@chromium.org5007aab2014-02-26 21:35:17 +0000638 const int rgbStride = pic.width * bpp;
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000639
640 // Import (for each scanline) the bit-map image (in appropriate color-space)
641 // to RGB color space.
642 uint8_t* rgb = new uint8_t[rgbStride * pic.height];
643 for (int y = 0; y < pic.height; ++y) {
644 scanline_import(src + y * bm.rowBytes(), rgb + y * rgbStride,
645 pic.width, colors);
646 }
647
commit-bot@chromium.org5007aab2014-02-26 21:35:17 +0000648 bool ok;
649 if (bpp == 3) {
650 ok = SkToBool(WebPPictureImportRGB(&pic, rgb, rgbStride));
651 } else {
652 ok = SkToBool(WebPPictureImportRGBA(&pic, rgb, rgbStride));
653 }
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000654 delete[] rgb;
655
656 ok = ok && WebPEncode(&webp_config, &pic);
657 WebPPictureFree(&pic);
658
659 return ok;
660}
661
662
663///////////////////////////////////////////////////////////////////////////////
664DEFINE_DECODER_CREATOR(WEBPImageDecoder);
665DEFINE_ENCODER_CREATOR(WEBPImageEncoder);
666///////////////////////////////////////////////////////////////////////////////
667
scroggo@google.comb5571b32013-09-25 21:34:24 +0000668static SkImageDecoder* sk_libwebp_dfactory(SkStreamRewindable* stream) {
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000669 int width, height, hasAlpha;
670 if (!webp_parse_header(stream, &width, &height, &hasAlpha)) {
671 return NULL;
672 }
673
674 // Magic matches, call decoder
675 return SkNEW(SkWEBPImageDecoder);
676}
677
scroggo@google.comb5571b32013-09-25 21:34:24 +0000678static SkImageDecoder::Format get_format_webp(SkStreamRewindable* stream) {
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000679 int width, height, hasAlpha;
680 if (webp_parse_header(stream, &width, &height, &hasAlpha)) {
681 return SkImageDecoder::kWEBP_Format;
682 }
683 return SkImageDecoder::kUnknown_Format;
684}
685
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000686static SkImageEncoder* sk_libwebp_efactory(SkImageEncoder::Type t) {
687 return (SkImageEncoder::kWEBP_Type == t) ? SkNEW(SkWEBPImageEncoder) : NULL;
688}
689
mtklein@google.combd6343b2013-09-04 17:20:18 +0000690static SkImageDecoder_DecodeReg gDReg(sk_libwebp_dfactory);
691static SkImageDecoder_FormatReg gFormatReg(get_format_webp);
692static SkImageEncoder_EncodeReg gEReg(sk_libwebp_efactory);