blob: 95b9a97878f381c6244279f6c7e4833c5afc81a5 [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
39#ifdef ANDROID
40#include <cutils/properties.h>
41
42// Key to lookup the size of memory buffer set in system property
43static const char KEY_MEM_CAP[] = "ro.media.dec.webp.memcap";
44#endif
45
46// this enables timing code to report milliseconds for a decode
47//#define TIME_DECODE
48
49//////////////////////////////////////////////////////////////////////////
50//////////////////////////////////////////////////////////////////////////
51
52// Define VP8 I/O on top of Skia stream
53
54//////////////////////////////////////////////////////////////////////////
55//////////////////////////////////////////////////////////////////////////
56
57static const size_t WEBP_VP8_HEADER_SIZE = 64;
58static const size_t WEBP_IDECODE_BUFFER_SZ = (1 << 16);
59
60// Parse headers of RIFF container, and check for valid Webp (VP8) content.
61static bool webp_parse_header(SkStream* stream, int* width, int* height, int* alpha) {
62 unsigned char buffer[WEBP_VP8_HEADER_SIZE];
63 const uint32_t contentSize = stream->getLength();
64 const size_t len = stream->read(buffer, WEBP_VP8_HEADER_SIZE);
65 const uint32_t read_bytes =
66 (contentSize < WEBP_VP8_HEADER_SIZE) ? contentSize : WEBP_VP8_HEADER_SIZE;
67 if (len != read_bytes) {
68 return false; // can't read enough
69 }
70
71 WebPBitstreamFeatures features;
72 VP8StatusCode status = WebPGetFeatures(buffer, read_bytes, &features);
73 if (VP8_STATUS_OK != status) {
74 return false; // Invalid WebP file.
75 }
76 *width = features.width;
77 *height = features.height;
78 *alpha = features.has_alpha;
79
80 // sanity check for image size that's about to be decoded.
81 {
82 Sk64 size;
83 size.setMul(*width, *height);
84 if (size.isNeg() || !size.is32()) {
85 return false;
86 }
87 // now check that if we are 4-bytes per pixel, we also don't overflow
88 if (size.get32() > (0x7FFFFFFF >> 2)) {
89 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:
112 virtual bool onBuildTileIndex(SkStream *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:
117 bool setDecodeConfig(SkBitmap* decodedBitmap, int width, int height);
118 SkStream* fInputStream;
119 int fOrigWidth;
120 int fOrigHeight;
121 int fHasAlpha;
122
123 typedef SkImageDecoder INHERITED;
124};
125
126//////////////////////////////////////////////////////////////////////////
127
128#ifdef TIME_DECODE
129
130#include "SkTime.h"
131
132class AutoTimeMillis {
133public:
134 AutoTimeMillis(const char label[]) :
135 fLabel(label) {
136 if (NULL == fLabel) {
137 fLabel = "";
138 }
139 fNow = SkTime::GetMSecs();
140 }
141 ~AutoTimeMillis() {
142 SkDebugf("---- Time (ms): %s %d\n", fLabel, SkTime::GetMSecs() - fNow);
143 }
144private:
145 const char* fLabel;
146 SkMSec fNow;
147};
148
149#endif
150
151///////////////////////////////////////////////////////////////////////////////
152
153// This guy exists just to aid in debugging, as it allows debuggers to just
154// set a break-point in one place to see all error exists.
155static bool return_false(const SkBitmap& bm, const char msg[]) {
156 SkDEBUGF(("libwebp error %s [%d %d]", msg, bm.width(), bm.height()));
157 return false; // must always return false
158}
159
160static WEBP_CSP_MODE webp_decode_mode(const SkBitmap* decodedBitmap, int hasAlpha) {
161 WEBP_CSP_MODE mode = MODE_LAST;
162 SkBitmap::Config config = decodedBitmap->config();
163 // For images that have alpha, choose appropriate color mode (MODE_rgbA,
164 // MODE_rgbA_4444) that pre-multiplies RGB pixel values with transparency
165 // factor (alpha).
166 if (config == SkBitmap::kARGB_8888_Config) {
167 mode = hasAlpha ? MODE_rgbA : MODE_RGBA;
168 } else if (config == SkBitmap::kARGB_4444_Config) {
169 mode = hasAlpha ? MODE_rgbA_4444 : MODE_RGBA_4444;
170 } else if (config == SkBitmap::kRGB_565_Config) {
171 mode = MODE_RGB_565;
172 }
173 SkASSERT(MODE_LAST != mode);
174 return mode;
175}
176
177// Incremental WebP image decoding. Reads input buffer of 64K size iteratively
178// and decodes this block to appropriate color-space as per config object.
179static bool webp_idecode(SkStream* stream, WebPDecoderConfig* config) {
180 WebPIDecoder* idec = WebPIDecode(NULL, 0, config);
181 if (NULL == idec) {
182 WebPFreeDecBuffer(&config->output);
183 return false;
184 }
185
186 stream->rewind();
187 const uint32_t contentSize = stream->getLength();
188 const uint32_t readBufferSize = (contentSize < WEBP_IDECODE_BUFFER_SZ) ?
189 contentSize : WEBP_IDECODE_BUFFER_SZ;
190 SkAutoMalloc srcStorage(readBufferSize);
191 unsigned char* input = (uint8_t*)srcStorage.get();
192 if (NULL == input) {
193 WebPIDelete(idec);
194 WebPFreeDecBuffer(&config->output);
195 return false;
196 }
197
198 uint32_t bytesRemaining = contentSize;
199 while (bytesRemaining > 0) {
200 const uint32_t bytesToRead = (bytesRemaining < WEBP_IDECODE_BUFFER_SZ) ?
201 bytesRemaining : WEBP_IDECODE_BUFFER_SZ;
202 const size_t bytesRead = stream->read(input, bytesToRead);
203 if (0 == bytesRead) {
204 break;
205 }
206
207 VP8StatusCode status = WebPIAppend(idec, input, bytesRead);
208 if (VP8_STATUS_OK == status || VP8_STATUS_SUSPENDED == status) {
209 bytesRemaining -= bytesRead;
210 } else {
211 break;
212 }
213 }
214 srcStorage.free();
215 WebPIDelete(idec);
216 WebPFreeDecBuffer(&config->output);
217
218 if (bytesRemaining > 0) {
219 return false;
220 } else {
221 return true;
222 }
223}
224
225static bool webp_get_config_resize(WebPDecoderConfig* config,
226 SkBitmap* decodedBitmap,
227 int width, int height, int hasAlpha) {
228 WEBP_CSP_MODE mode = webp_decode_mode(decodedBitmap, hasAlpha);
229 if (MODE_LAST == mode) {
230 return false;
231 }
232
233 if (0 == WebPInitDecoderConfig(config)) {
234 return false;
235 }
236
237 config->output.colorspace = mode;
238 config->output.u.RGBA.rgba = (uint8_t*)decodedBitmap->getPixels();
239 config->output.u.RGBA.stride = decodedBitmap->rowBytes();
240 config->output.u.RGBA.size = decodedBitmap->getSize();
241 config->output.is_external_memory = 1;
242
243 if (width != decodedBitmap->width() || height != decodedBitmap->height()) {
244 config->options.use_scaling = 1;
245 config->options.scaled_width = decodedBitmap->width();
246 config->options.scaled_height = decodedBitmap->height();
247 }
248
249 return true;
250}
251
252static bool webp_get_config_resize_crop(WebPDecoderConfig* config,
253 SkBitmap* decodedBitmap,
254 const SkIRect& region, int hasAlpha) {
255
256 if (!webp_get_config_resize(config, decodedBitmap, region.width(),
257 region.height(), hasAlpha)) {
258 return false;
259 }
260
261 config->options.use_cropping = 1;
262 config->options.crop_left = region.fLeft;
263 config->options.crop_top = region.fTop;
264 config->options.crop_width = region.width();
265 config->options.crop_height = region.height();
266
267 return true;
268}
269
270bool SkWEBPImageDecoder::setDecodeConfig(SkBitmap* decodedBitmap,
271 int width, int height) {
commit-bot@chromium.orgbff83f62013-03-14 15:18:08 +0000272 SkBitmap::Config config = this->getPrefConfig(k32Bit_SrcDepth, SkToBool(fHasAlpha));
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000273
274 // YUV converter supports output in RGB565, RGBA4444 and RGBA8888 formats.
275 if (fHasAlpha) {
276 if (config != SkBitmap::kARGB_4444_Config) {
277 config = SkBitmap::kARGB_8888_Config;
278 }
279 } else {
280 if (config != SkBitmap::kRGB_565_Config &&
281 config != SkBitmap::kARGB_4444_Config) {
282 config = SkBitmap::kARGB_8888_Config;
283 }
284 }
285
286 if (!this->chooseFromOneChoice(config, width, height)) {
287 return false;
288 }
289
290 decodedBitmap->setConfig(config, width, height, 0);
291
292 decodedBitmap->setIsOpaque(!fHasAlpha);
293
294 return true;
295}
296
297bool SkWEBPImageDecoder::onBuildTileIndex(SkStream* stream,
298 int *width, int *height) {
299 int origWidth, origHeight, hasAlpha;
300 if (!webp_parse_header(stream, &origWidth, &origHeight, &hasAlpha)) {
301 return false;
302 }
303
304 stream->rewind();
305 *width = origWidth;
306 *height = origHeight;
307
308 SkRefCnt_SafeAssign(this->fInputStream, stream);
309 this->fOrigWidth = origWidth;
310 this->fOrigHeight = origHeight;
311 this->fHasAlpha = hasAlpha;
312
313 return true;
314}
315
316static bool is_config_compatible(const SkBitmap& bitmap) {
317 SkBitmap::Config config = bitmap.config();
318 return config == SkBitmap::kARGB_4444_Config ||
319 config == SkBitmap::kRGB_565_Config ||
320 config == SkBitmap::kARGB_8888_Config;
321}
322
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000323bool SkWEBPImageDecoder::onDecodeSubset(SkBitmap* decodedBitmap,
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000324 const SkIRect& region) {
325 SkIRect rect = SkIRect::MakeWH(fOrigWidth, fOrigHeight);
326
327 if (!rect.intersect(region)) {
328 // If the requested region is entirely outsides the image, return false
329 return false;
330 }
331
332 const int sampleSize = this->getSampleSize();
333 SkScaledBitmapSampler sampler(rect.width(), rect.height(), sampleSize);
334 const int width = sampler.scaledWidth();
335 const int height = sampler.scaledHeight();
336
337 // The image can be decoded directly to decodedBitmap if
338 // 1. the region is within the image range
339 // 2. bitmap's config is compatible
340 // 3. bitmap's size is same as the required region (after sampled)
341 bool directDecode = (rect == region) &&
342 (decodedBitmap->isNull() ||
343 (is_config_compatible(*decodedBitmap) &&
344 (decodedBitmap->width() == width) &&
345 (decodedBitmap->height() == height)));
commit-bot@chromium.orga9f142e2013-05-09 16:15:20 +0000346
347 SkBitmap tmpBitmap;
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000348 SkBitmap *bitmap = decodedBitmap;
349
350 if (!directDecode) {
commit-bot@chromium.orga9f142e2013-05-09 16:15:20 +0000351 bitmap = &tmpBitmap;
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000352 }
353
354 if (bitmap->isNull()) {
355 if (!setDecodeConfig(bitmap, width, height)) {
356 return false;
357 }
358 // alloc from native heap if it is a temp bitmap. (prevent GC)
359 bool allocResult = (bitmap == decodedBitmap)
360 ? allocPixelRef(bitmap, NULL)
361 : bitmap->allocPixels();
362 if (!allocResult) {
363 return return_false(*decodedBitmap, "allocPixelRef");
364 }
365 } else {
366 // This is also called in setDecodeConfig in above block.
367 // i.e., when bitmap->isNull() is true.
368 if (!chooseFromOneChoice(bitmap->config(), width, height)) {
369 return false;
370 }
371 }
372
373 SkAutoLockPixels alp(*bitmap);
374 WebPDecoderConfig config;
375 if (!webp_get_config_resize_crop(&config, bitmap, rect, fHasAlpha)) {
376 return false;
377 }
378
379 // Decode the WebP image data stream using WebP incremental decoding for
380 // the specified cropped image-region.
381 if (!webp_idecode(this->fInputStream, &config)) {
382 return false;
383 }
384
385 if (!directDecode) {
386 cropBitmap(decodedBitmap, bitmap, sampleSize, region.x(), region.y(),
387 region.width(), region.height(), rect.x(), rect.y());
388 }
389 return true;
390}
391
392bool SkWEBPImageDecoder::onDecode(SkStream* stream, SkBitmap* decodedBitmap,
393 Mode mode) {
394#ifdef TIME_DECODE
395 AutoTimeMillis atm("WEBP Decode");
396#endif
397
398 int origWidth, origHeight, hasAlpha;
399 if (!webp_parse_header(stream, &origWidth, &origHeight, &hasAlpha)) {
400 return false;
401 }
402 this->fHasAlpha = hasAlpha;
403
404 const int sampleSize = this->getSampleSize();
405 SkScaledBitmapSampler sampler(origWidth, origHeight, sampleSize);
406
407 // If only bounds are requested, done
408 if (SkImageDecoder::kDecodeBounds_Mode == mode) {
409 if (!setDecodeConfig(decodedBitmap, sampler.scaledWidth(),
410 sampler.scaledHeight())) {
411 return false;
412 }
413 return true;
414 }
415
416 // No Bitmap reuse supported for this format
417 if (!decodedBitmap->isNull()) {
418 return false;
419 }
420 if (!setDecodeConfig(decodedBitmap, sampler.scaledWidth(),
421 sampler.scaledHeight())) {
422 return false;
423 }
424
425 if (!this->allocPixelRef(decodedBitmap, NULL)) {
426 return return_false(*decodedBitmap, "allocPixelRef");
427 }
428
429 SkAutoLockPixels alp(*decodedBitmap);
430
431 WebPDecoderConfig config;
432 if (!webp_get_config_resize(&config, decodedBitmap, origWidth, origHeight,
433 hasAlpha)) {
434 return false;
435 }
436
437 // Decode the WebP image data stream using WebP incremental decoding.
438 return webp_idecode(stream, &config);
439}
440
441///////////////////////////////////////////////////////////////////////////////
442
443typedef void (*ScanlineImporter)(const uint8_t* in, uint8_t* out, int width,
444 const SkPMColor* SK_RESTRICT ctable);
445
446static void ARGB_8888_To_RGB(const uint8_t* in, uint8_t* rgb, int width,
447 const SkPMColor*) {
448 const uint32_t* SK_RESTRICT src = (const uint32_t*)in;
449 for (int i = 0; i < width; ++i) {
450 const uint32_t c = *src++;
451 rgb[0] = SkGetPackedR32(c);
452 rgb[1] = SkGetPackedG32(c);
453 rgb[2] = SkGetPackedB32(c);
454 rgb += 3;
455 }
456}
457
458static void RGB_565_To_RGB(const uint8_t* in, uint8_t* rgb, int width,
459 const SkPMColor*) {
460 const uint16_t* SK_RESTRICT src = (const uint16_t*)in;
461 for (int i = 0; i < width; ++i) {
462 const uint16_t c = *src++;
463 rgb[0] = SkPacked16ToR32(c);
464 rgb[1] = SkPacked16ToG32(c);
465 rgb[2] = SkPacked16ToB32(c);
466 rgb += 3;
467 }
468}
469
470static void ARGB_4444_To_RGB(const uint8_t* in, uint8_t* rgb, int width,
471 const SkPMColor*) {
472 const SkPMColor16* SK_RESTRICT src = (const SkPMColor16*)in;
473 for (int i = 0; i < width; ++i) {
474 const SkPMColor16 c = *src++;
475 rgb[0] = SkPacked4444ToR32(c);
476 rgb[1] = SkPacked4444ToG32(c);
477 rgb[2] = SkPacked4444ToB32(c);
478 rgb += 3;
479 }
480}
481
482static void Index8_To_RGB(const uint8_t* in, uint8_t* rgb, int width,
483 const SkPMColor* SK_RESTRICT ctable) {
484 const uint8_t* SK_RESTRICT src = (const uint8_t*)in;
485 for (int i = 0; i < width; ++i) {
486 const uint32_t c = ctable[*src++];
487 rgb[0] = SkGetPackedR32(c);
488 rgb[1] = SkGetPackedG32(c);
489 rgb[2] = SkGetPackedB32(c);
490 rgb += 3;
491 }
492}
493
494static ScanlineImporter ChooseImporter(const SkBitmap::Config& config) {
495 switch (config) {
496 case SkBitmap::kARGB_8888_Config:
497 return ARGB_8888_To_RGB;
498 case SkBitmap::kRGB_565_Config:
499 return RGB_565_To_RGB;
500 case SkBitmap::kARGB_4444_Config:
501 return ARGB_4444_To_RGB;
502 case SkBitmap::kIndex8_Config:
503 return Index8_To_RGB;
504 default:
505 return NULL;
506 }
507}
508
509static int stream_writer(const uint8_t* data, size_t data_size,
510 const WebPPicture* const picture) {
511 SkWStream* const stream = (SkWStream*)picture->custom_ptr;
512 return stream->write(data, data_size) ? 1 : 0;
513}
514
515class SkWEBPImageEncoder : public SkImageEncoder {
516protected:
517 virtual bool onEncode(SkWStream* stream, const SkBitmap& bm, int quality) SK_OVERRIDE;
518
519private:
520 typedef SkImageEncoder INHERITED;
521};
522
523bool SkWEBPImageEncoder::onEncode(SkWStream* stream, const SkBitmap& bm,
524 int quality) {
525 const SkBitmap::Config config = bm.getConfig();
526 const ScanlineImporter scanline_import = ChooseImporter(config);
527 if (NULL == scanline_import) {
528 return false;
529 }
530
531 SkAutoLockPixels alp(bm);
532 SkAutoLockColors ctLocker;
533 if (NULL == bm.getPixels()) {
534 return false;
535 }
536
537 WebPConfig webp_config;
commit-bot@chromium.orgbff83f62013-03-14 15:18:08 +0000538 if (!WebPConfigPreset(&webp_config, WEBP_PRESET_DEFAULT, (float) quality)) {
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000539 return false;
540 }
541
542 WebPPicture pic;
543 WebPPictureInit(&pic);
544 pic.width = bm.width();
545 pic.height = bm.height();
546 pic.writer = stream_writer;
547 pic.custom_ptr = (void*)stream;
548
549 const SkPMColor* colors = ctLocker.lockColors(bm);
550 const uint8_t* src = (uint8_t*)bm.getPixels();
551 const int rgbStride = pic.width * 3;
552
553 // Import (for each scanline) the bit-map image (in appropriate color-space)
554 // to RGB color space.
555 uint8_t* rgb = new uint8_t[rgbStride * pic.height];
556 for (int y = 0; y < pic.height; ++y) {
557 scanline_import(src + y * bm.rowBytes(), rgb + y * rgbStride,
558 pic.width, colors);
559 }
560
reed@google.combda74d32013-03-14 15:25:45 +0000561 bool ok = SkToBool(WebPPictureImportRGB(&pic, rgb, rgbStride));
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000562 delete[] rgb;
563
564 ok = ok && WebPEncode(&webp_config, &pic);
565 WebPPictureFree(&pic);
566
567 return ok;
568}
569
570
571///////////////////////////////////////////////////////////////////////////////
572DEFINE_DECODER_CREATOR(WEBPImageDecoder);
573DEFINE_ENCODER_CREATOR(WEBPImageEncoder);
574///////////////////////////////////////////////////////////////////////////////
575
576#include "SkTRegistry.h"
577
578static SkImageDecoder* sk_libwebp_dfactory(SkStream* stream) {
579 int width, height, hasAlpha;
580 if (!webp_parse_header(stream, &width, &height, &hasAlpha)) {
581 return NULL;
582 }
583
584 // Magic matches, call decoder
585 return SkNEW(SkWEBPImageDecoder);
586}
587
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000588static SkImageDecoder::Format get_format_webp(SkStream* stream) {
589 int width, height, hasAlpha;
590 if (webp_parse_header(stream, &width, &height, &hasAlpha)) {
591 return SkImageDecoder::kWEBP_Format;
592 }
593 return SkImageDecoder::kUnknown_Format;
594}
595
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000596static SkImageEncoder* sk_libwebp_efactory(SkImageEncoder::Type t) {
597 return (SkImageEncoder::kWEBP_Type == t) ? SkNEW(SkWEBPImageEncoder) : NULL;
598}
599
600static SkTRegistry<SkImageDecoder*, SkStream*> gDReg(sk_libwebp_dfactory);
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000601static SkTRegistry<SkImageDecoder::Format, SkStream*> gFormatReg(get_format_webp);
commit-bot@chromium.orga936e372013-03-14 14:42:18 +0000602static SkTRegistry<SkImageEncoder*, SkImageEncoder::Type> gEReg(sk_libwebp_efactory);