michael@0: /* michael@0: * Copyright 2007 The Android Open Source Project michael@0: * michael@0: * Use of this source code is governed by a BSD-style license that can be michael@0: * found in the LICENSE file. michael@0: */ michael@0: michael@0: michael@0: #include "SkImageDecoder.h" michael@0: #include "SkImageEncoder.h" michael@0: #include "SkJpegUtility.h" michael@0: #include "SkColorPriv.h" michael@0: #include "SkDither.h" michael@0: #include "SkScaledBitmapSampler.h" michael@0: #include "SkStream.h" michael@0: #include "SkTemplates.h" michael@0: #include "SkTime.h" michael@0: #include "SkUtils.h" michael@0: #include "SkRTConf.h" michael@0: #include "SkRect.h" michael@0: #include "SkCanvas.h" michael@0: michael@0: michael@0: #include michael@0: extern "C" { michael@0: #include "jpeglib.h" michael@0: #include "jerror.h" michael@0: } michael@0: michael@0: // These enable timing code that report milliseconds for an encoding/decoding michael@0: //#define TIME_ENCODE michael@0: //#define TIME_DECODE michael@0: michael@0: // this enables our rgb->yuv code, which is faster than libjpeg on ARM michael@0: #define WE_CONVERT_TO_YUV michael@0: michael@0: // If ANDROID_RGB is defined by in the jpeg headers it indicates that jpeg offers michael@0: // support for two additional formats (1) JCS_RGBA_8888 and (2) JCS_RGB_565. michael@0: michael@0: #if defined(SK_DEBUG) michael@0: #define DEFAULT_FOR_SUPPRESS_JPEG_IMAGE_DECODER_WARNINGS false michael@0: #define DEFAULT_FOR_SUPPRESS_JPEG_IMAGE_DECODER_ERRORS false michael@0: #else // !defined(SK_DEBUG) michael@0: #define DEFAULT_FOR_SUPPRESS_JPEG_IMAGE_DECODER_WARNINGS true michael@0: #define DEFAULT_FOR_SUPPRESS_JPEG_IMAGE_DECODER_ERRORS true michael@0: #endif // defined(SK_DEBUG) michael@0: SK_CONF_DECLARE(bool, c_suppressJPEGImageDecoderWarnings, michael@0: "images.jpeg.suppressDecoderWarnings", michael@0: DEFAULT_FOR_SUPPRESS_JPEG_IMAGE_DECODER_WARNINGS, michael@0: "Suppress most JPG warnings when calling decode functions."); michael@0: SK_CONF_DECLARE(bool, c_suppressJPEGImageDecoderErrors, michael@0: "images.jpeg.suppressDecoderErrors", michael@0: DEFAULT_FOR_SUPPRESS_JPEG_IMAGE_DECODER_ERRORS, michael@0: "Suppress most JPG error messages when decode " michael@0: "function fails."); michael@0: michael@0: ////////////////////////////////////////////////////////////////////////// michael@0: ////////////////////////////////////////////////////////////////////////// michael@0: michael@0: static void overwrite_mem_buffer_size(jpeg_decompress_struct* cinfo) { michael@0: #ifdef SK_BUILD_FOR_ANDROID michael@0: /* Check if the device indicates that it has a large amount of system memory michael@0: * if so, increase the memory allocation to 30MB instead of the default 5MB. michael@0: */ michael@0: #ifdef ANDROID_LARGE_MEMORY_DEVICE michael@0: cinfo->mem->max_memory_to_use = 30 * 1024 * 1024; michael@0: #else michael@0: cinfo->mem->max_memory_to_use = 5 * 1024 * 1024; michael@0: #endif michael@0: #endif // SK_BUILD_FOR_ANDROID michael@0: } michael@0: michael@0: ////////////////////////////////////////////////////////////////////////// michael@0: ////////////////////////////////////////////////////////////////////////// michael@0: michael@0: static void do_nothing_emit_message(jpeg_common_struct*, int) { michael@0: /* do nothing */ michael@0: } michael@0: static void do_nothing_output_message(j_common_ptr) { michael@0: /* do nothing */ michael@0: } michael@0: michael@0: static void initialize_info(jpeg_decompress_struct* cinfo, skjpeg_source_mgr* src_mgr) { michael@0: SkASSERT(cinfo != NULL); michael@0: SkASSERT(src_mgr != NULL); michael@0: jpeg_create_decompress(cinfo); michael@0: overwrite_mem_buffer_size(cinfo); michael@0: cinfo->src = src_mgr; michael@0: /* To suppress warnings with a SK_DEBUG binary, set the michael@0: * environment variable "skia_images_jpeg_suppressDecoderWarnings" michael@0: * to "true". Inside a program that links to skia: michael@0: * SK_CONF_SET("images.jpeg.suppressDecoderWarnings", true); */ michael@0: if (c_suppressJPEGImageDecoderWarnings) { michael@0: cinfo->err->emit_message = &do_nothing_emit_message; michael@0: } michael@0: /* To suppress error messages with a SK_DEBUG binary, set the michael@0: * environment variable "skia_images_jpeg_suppressDecoderErrors" michael@0: * to "true". Inside a program that links to skia: michael@0: * SK_CONF_SET("images.jpeg.suppressDecoderErrors", true); */ michael@0: if (c_suppressJPEGImageDecoderErrors) { michael@0: cinfo->err->output_message = &do_nothing_output_message; michael@0: } michael@0: } michael@0: michael@0: #ifdef SK_BUILD_FOR_ANDROID michael@0: class SkJPEGImageIndex { michael@0: public: michael@0: SkJPEGImageIndex(SkStreamRewindable* stream, SkImageDecoder* decoder) michael@0: : fSrcMgr(stream, decoder) michael@0: , fInfoInitialized(false) michael@0: , fHuffmanCreated(false) michael@0: , fDecompressStarted(false) michael@0: { michael@0: SkDEBUGCODE(fReadHeaderSucceeded = false;) michael@0: } michael@0: michael@0: ~SkJPEGImageIndex() { michael@0: if (fHuffmanCreated) { michael@0: // Set to false before calling the libjpeg function, in case michael@0: // the libjpeg function calls longjmp. Our setjmp handler may michael@0: // attempt to delete this SkJPEGImageIndex, thus entering this michael@0: // destructor again. Setting fHuffmanCreated to false first michael@0: // prevents an infinite loop. michael@0: fHuffmanCreated = false; michael@0: jpeg_destroy_huffman_index(&fHuffmanIndex); michael@0: } michael@0: if (fDecompressStarted) { michael@0: // Like fHuffmanCreated, set to false before calling libjpeg michael@0: // function to prevent potential infinite loop. michael@0: fDecompressStarted = false; michael@0: jpeg_finish_decompress(&fCInfo); michael@0: } michael@0: if (fInfoInitialized) { michael@0: this->destroyInfo(); michael@0: } michael@0: } michael@0: michael@0: /** michael@0: * Destroy the cinfo struct. michael@0: * After this call, if a huffman index was already built, it michael@0: * can be used after calling initializeInfoAndReadHeader michael@0: * again. Must not be called after startTileDecompress except michael@0: * in the destructor. michael@0: */ michael@0: void destroyInfo() { michael@0: SkASSERT(fInfoInitialized); michael@0: SkASSERT(!fDecompressStarted); michael@0: // Like fHuffmanCreated, set to false before calling libjpeg michael@0: // function to prevent potential infinite loop. michael@0: fInfoInitialized = false; michael@0: jpeg_destroy_decompress(&fCInfo); michael@0: SkDEBUGCODE(fReadHeaderSucceeded = false;) michael@0: } michael@0: michael@0: /** michael@0: * Initialize the cinfo struct. michael@0: * Calls jpeg_create_decompress, makes customizations, and michael@0: * finally calls jpeg_read_header. Returns true if jpeg_read_header michael@0: * returns JPEG_HEADER_OK. michael@0: * If cinfo was already initialized, destroyInfo must be called to michael@0: * destroy the old one. Must not be called after startTileDecompress. michael@0: */ michael@0: bool initializeInfoAndReadHeader() { michael@0: SkASSERT(!fInfoInitialized && !fDecompressStarted); michael@0: initialize_info(&fCInfo, &fSrcMgr); michael@0: fInfoInitialized = true; michael@0: const bool success = (JPEG_HEADER_OK == jpeg_read_header(&fCInfo, true)); michael@0: SkDEBUGCODE(fReadHeaderSucceeded = success;) michael@0: return success; michael@0: } michael@0: michael@0: jpeg_decompress_struct* cinfo() { return &fCInfo; } michael@0: michael@0: huffman_index* huffmanIndex() { return &fHuffmanIndex; } michael@0: michael@0: /** michael@0: * Build the index to be used for tile based decoding. michael@0: * Must only be called after a successful call to michael@0: * initializeInfoAndReadHeader and must not be called more michael@0: * than once. michael@0: */ michael@0: bool buildHuffmanIndex() { michael@0: SkASSERT(fReadHeaderSucceeded); michael@0: SkASSERT(!fHuffmanCreated); michael@0: jpeg_create_huffman_index(&fCInfo, &fHuffmanIndex); michael@0: SkASSERT(1 == fCInfo.scale_num && 1 == fCInfo.scale_denom); michael@0: fHuffmanCreated = jpeg_build_huffman_index(&fCInfo, &fHuffmanIndex); michael@0: return fHuffmanCreated; michael@0: } michael@0: michael@0: /** michael@0: * Start tile based decoding. Must only be called after a michael@0: * successful call to buildHuffmanIndex, and must only be michael@0: * called once. michael@0: */ michael@0: bool startTileDecompress() { michael@0: SkASSERT(fHuffmanCreated); michael@0: SkASSERT(fReadHeaderSucceeded); michael@0: SkASSERT(!fDecompressStarted); michael@0: if (jpeg_start_tile_decompress(&fCInfo)) { michael@0: fDecompressStarted = true; michael@0: return true; michael@0: } michael@0: return false; michael@0: } michael@0: michael@0: private: michael@0: skjpeg_source_mgr fSrcMgr; michael@0: jpeg_decompress_struct fCInfo; michael@0: huffman_index fHuffmanIndex; michael@0: bool fInfoInitialized; michael@0: bool fHuffmanCreated; michael@0: bool fDecompressStarted; michael@0: SkDEBUGCODE(bool fReadHeaderSucceeded;) michael@0: }; michael@0: #endif michael@0: michael@0: class SkJPEGImageDecoder : public SkImageDecoder { michael@0: public: michael@0: #ifdef SK_BUILD_FOR_ANDROID michael@0: SkJPEGImageDecoder() { michael@0: fImageIndex = NULL; michael@0: fImageWidth = 0; michael@0: fImageHeight = 0; michael@0: } michael@0: michael@0: virtual ~SkJPEGImageDecoder() { michael@0: SkDELETE(fImageIndex); michael@0: } michael@0: #endif michael@0: michael@0: virtual Format getFormat() const { michael@0: return kJPEG_Format; michael@0: } michael@0: michael@0: protected: michael@0: #ifdef SK_BUILD_FOR_ANDROID michael@0: virtual bool onBuildTileIndex(SkStreamRewindable *stream, int *width, int *height) SK_OVERRIDE; michael@0: virtual bool onDecodeSubset(SkBitmap* bitmap, const SkIRect& rect) SK_OVERRIDE; michael@0: #endif michael@0: virtual bool onDecode(SkStream* stream, SkBitmap* bm, Mode) SK_OVERRIDE; michael@0: michael@0: private: michael@0: #ifdef SK_BUILD_FOR_ANDROID michael@0: SkJPEGImageIndex* fImageIndex; michael@0: int fImageWidth; michael@0: int fImageHeight; michael@0: #endif michael@0: michael@0: /** michael@0: * Determine the appropriate bitmap config and out_color_space based on michael@0: * both the preference of the caller and the jpeg_color_space on the michael@0: * jpeg_decompress_struct passed in. michael@0: * Must be called after jpeg_read_header. michael@0: */ michael@0: SkBitmap::Config getBitmapConfig(jpeg_decompress_struct*); michael@0: michael@0: typedef SkImageDecoder INHERITED; michael@0: }; michael@0: michael@0: ////////////////////////////////////////////////////////////////////////// michael@0: michael@0: /* Automatically clean up after throwing an exception */ michael@0: class JPEGAutoClean { michael@0: public: michael@0: JPEGAutoClean(): cinfo_ptr(NULL) {} michael@0: ~JPEGAutoClean() { michael@0: if (cinfo_ptr) { michael@0: jpeg_destroy_decompress(cinfo_ptr); michael@0: } michael@0: } michael@0: void set(jpeg_decompress_struct* info) { michael@0: cinfo_ptr = info; michael@0: } michael@0: private: michael@0: jpeg_decompress_struct* cinfo_ptr; michael@0: }; michael@0: michael@0: /////////////////////////////////////////////////////////////////////////////// michael@0: michael@0: /* If we need to better match the request, we might examine the image and michael@0: output dimensions, and determine if the downsampling jpeg provided is michael@0: not sufficient. If so, we can recompute a modified sampleSize value to michael@0: make up the difference. michael@0: michael@0: To skip this additional scaling, just set sampleSize = 1; below. michael@0: */ michael@0: static int recompute_sampleSize(int sampleSize, michael@0: const jpeg_decompress_struct& cinfo) { michael@0: return sampleSize * cinfo.output_width / cinfo.image_width; michael@0: } michael@0: michael@0: static bool valid_output_dimensions(const jpeg_decompress_struct& cinfo) { michael@0: /* These are initialized to 0, so if they have non-zero values, we assume michael@0: they are "valid" (i.e. have been computed by libjpeg) michael@0: */ michael@0: return 0 != cinfo.output_width && 0 != cinfo.output_height; michael@0: } michael@0: michael@0: static bool skip_src_rows(jpeg_decompress_struct* cinfo, void* buffer, int count) { michael@0: for (int i = 0; i < count; i++) { michael@0: JSAMPLE* rowptr = (JSAMPLE*)buffer; michael@0: int row_count = jpeg_read_scanlines(cinfo, &rowptr, 1); michael@0: if (1 != row_count) { michael@0: return false; michael@0: } michael@0: } michael@0: return true; michael@0: } michael@0: michael@0: #ifdef SK_BUILD_FOR_ANDROID michael@0: static bool skip_src_rows_tile(jpeg_decompress_struct* cinfo, michael@0: huffman_index *index, void* buffer, int count) { michael@0: for (int i = 0; i < count; i++) { michael@0: JSAMPLE* rowptr = (JSAMPLE*)buffer; michael@0: int row_count = jpeg_read_tile_scanline(cinfo, index, &rowptr); michael@0: if (1 != row_count) { michael@0: return false; michael@0: } michael@0: } michael@0: return true; michael@0: } michael@0: #endif michael@0: michael@0: // This guy exists just to aid in debugging, as it allows debuggers to just michael@0: // set a break-point in one place to see all error exists. michael@0: static bool return_false(const jpeg_decompress_struct& cinfo, michael@0: const SkBitmap& bm, const char caller[]) { michael@0: if (!(c_suppressJPEGImageDecoderErrors)) { michael@0: char buffer[JMSG_LENGTH_MAX]; michael@0: cinfo.err->format_message((const j_common_ptr)&cinfo, buffer); michael@0: SkDebugf("libjpeg error %d <%s> from %s [%d %d]\n", michael@0: cinfo.err->msg_code, buffer, caller, bm.width(), bm.height()); michael@0: } michael@0: return false; // must always return false michael@0: } michael@0: michael@0: // Convert a scanline of CMYK samples to RGBX in place. Note that this michael@0: // method moves the "scanline" pointer in its processing michael@0: static void convert_CMYK_to_RGB(uint8_t* scanline, unsigned int width) { michael@0: // At this point we've received CMYK pixels from libjpeg. We michael@0: // perform a crude conversion to RGB (based on the formulae michael@0: // from easyrgb.com): michael@0: // CMYK -> CMY michael@0: // C = ( C * (1 - K) + K ) // for each CMY component michael@0: // CMY -> RGB michael@0: // R = ( 1 - C ) * 255 // for each RGB component michael@0: // Unfortunately we are seeing inverted CMYK so all the original terms michael@0: // are 1-. This yields: michael@0: // CMYK -> CMY michael@0: // C = ( (1-C) * (1 - (1-K) + (1-K) ) -> C = 1 - C*K michael@0: // The conversion from CMY->RGB remains the same michael@0: for (unsigned int x = 0; x < width; ++x, scanline += 4) { michael@0: scanline[0] = SkMulDiv255Round(scanline[0], scanline[3]); michael@0: scanline[1] = SkMulDiv255Round(scanline[1], scanline[3]); michael@0: scanline[2] = SkMulDiv255Round(scanline[2], scanline[3]); michael@0: scanline[3] = 255; michael@0: } michael@0: } michael@0: michael@0: /** michael@0: * Common code for setting the error manager. michael@0: */ michael@0: static void set_error_mgr(jpeg_decompress_struct* cinfo, skjpeg_error_mgr* errorManager) { michael@0: SkASSERT(cinfo != NULL); michael@0: SkASSERT(errorManager != NULL); michael@0: cinfo->err = jpeg_std_error(errorManager); michael@0: errorManager->error_exit = skjpeg_error_exit; michael@0: } michael@0: michael@0: /** michael@0: * Common code for turning off upsampling and smoothing. Turning these michael@0: * off helps performance without showing noticable differences in the michael@0: * resulting bitmap. michael@0: */ michael@0: static void turn_off_visual_optimizations(jpeg_decompress_struct* cinfo) { michael@0: SkASSERT(cinfo != NULL); michael@0: /* this gives about 30% performance improvement. In theory it may michael@0: reduce the visual quality, in practice I'm not seeing a difference michael@0: */ michael@0: cinfo->do_fancy_upsampling = 0; michael@0: michael@0: /* this gives another few percents */ michael@0: cinfo->do_block_smoothing = 0; michael@0: } michael@0: michael@0: /** michael@0: * Common code for setting the dct method. michael@0: */ michael@0: static void set_dct_method(const SkImageDecoder& decoder, jpeg_decompress_struct* cinfo) { michael@0: SkASSERT(cinfo != NULL); michael@0: #ifdef DCT_IFAST_SUPPORTED michael@0: if (decoder.getPreferQualityOverSpeed()) { michael@0: cinfo->dct_method = JDCT_ISLOW; michael@0: } else { michael@0: cinfo->dct_method = JDCT_IFAST; michael@0: } michael@0: #else michael@0: cinfo->dct_method = JDCT_ISLOW; michael@0: #endif michael@0: } michael@0: michael@0: SkBitmap::Config SkJPEGImageDecoder::getBitmapConfig(jpeg_decompress_struct* cinfo) { michael@0: SkASSERT(cinfo != NULL); michael@0: michael@0: SrcDepth srcDepth = k32Bit_SrcDepth; michael@0: if (JCS_GRAYSCALE == cinfo->jpeg_color_space) { michael@0: srcDepth = k8BitGray_SrcDepth; michael@0: } michael@0: michael@0: SkBitmap::Config config = this->getPrefConfig(srcDepth, /*hasAlpha*/ false); michael@0: switch (config) { michael@0: case SkBitmap::kA8_Config: michael@0: // Only respect A8 config if the original is grayscale, michael@0: // in which case we will treat the grayscale as alpha michael@0: // values. michael@0: if (cinfo->jpeg_color_space != JCS_GRAYSCALE) { michael@0: config = SkBitmap::kARGB_8888_Config; michael@0: } michael@0: break; michael@0: case SkBitmap::kARGB_8888_Config: michael@0: // Fall through. michael@0: case SkBitmap::kARGB_4444_Config: michael@0: // Fall through. michael@0: case SkBitmap::kRGB_565_Config: michael@0: // These are acceptable destination configs. michael@0: break; michael@0: default: michael@0: // Force all other configs to 8888. michael@0: config = SkBitmap::kARGB_8888_Config; michael@0: break; michael@0: } michael@0: michael@0: switch (cinfo->jpeg_color_space) { michael@0: case JCS_CMYK: michael@0: // Fall through. michael@0: case JCS_YCCK: michael@0: // libjpeg cannot convert from CMYK or YCCK to RGB - here we set up michael@0: // so libjpeg will give us CMYK samples back and we will later michael@0: // manually convert them to RGB michael@0: cinfo->out_color_space = JCS_CMYK; michael@0: break; michael@0: case JCS_GRAYSCALE: michael@0: if (SkBitmap::kA8_Config == config) { michael@0: cinfo->out_color_space = JCS_GRAYSCALE; michael@0: break; michael@0: } michael@0: // The data is JCS_GRAYSCALE, but the caller wants some sort of RGB michael@0: // config. Fall through to set to the default. michael@0: default: michael@0: cinfo->out_color_space = JCS_RGB; michael@0: break; michael@0: } michael@0: return config; michael@0: } michael@0: michael@0: #ifdef ANDROID_RGB michael@0: /** michael@0: * Based on the config and dither mode, adjust out_color_space and michael@0: * dither_mode of cinfo. michael@0: */ michael@0: static void adjust_out_color_space_and_dither(jpeg_decompress_struct* cinfo, michael@0: SkBitmap::Config config, michael@0: const SkImageDecoder& decoder) { michael@0: SkASSERT(cinfo != NULL); michael@0: cinfo->dither_mode = JDITHER_NONE; michael@0: if (JCS_CMYK == cinfo->out_color_space) { michael@0: return; michael@0: } michael@0: switch(config) { michael@0: case SkBitmap::kARGB_8888_Config: michael@0: cinfo->out_color_space = JCS_RGBA_8888; michael@0: break; michael@0: case SkBitmap::kRGB_565_Config: michael@0: cinfo->out_color_space = JCS_RGB_565; michael@0: if (decoder.getDitherImage()) { michael@0: cinfo->dither_mode = JDITHER_ORDERED; michael@0: } michael@0: break; michael@0: default: michael@0: break; michael@0: } michael@0: } michael@0: #endif michael@0: michael@0: michael@0: /** michael@0: Sets all pixels in given bitmap to SK_ColorWHITE for all rows >= y. michael@0: Used when decoding fails partway through reading scanlines to fill michael@0: remaining lines. */ michael@0: static void fill_below_level(int y, SkBitmap* bitmap) { michael@0: SkIRect rect = SkIRect::MakeLTRB(0, y, bitmap->width(), bitmap->height()); michael@0: SkCanvas canvas(*bitmap); michael@0: canvas.clipRect(SkRect::Make(rect)); michael@0: canvas.drawColor(SK_ColorWHITE); michael@0: } michael@0: michael@0: /** michael@0: * Get the config and bytes per pixel of the source data. Return michael@0: * whether the data is supported. michael@0: */ michael@0: static bool get_src_config(const jpeg_decompress_struct& cinfo, michael@0: SkScaledBitmapSampler::SrcConfig* sc, michael@0: int* srcBytesPerPixel) { michael@0: SkASSERT(sc != NULL && srcBytesPerPixel != NULL); michael@0: if (JCS_CMYK == cinfo.out_color_space) { michael@0: // In this case we will manually convert the CMYK values to RGB michael@0: *sc = SkScaledBitmapSampler::kRGBX; michael@0: // The CMYK work-around relies on 4 components per pixel here michael@0: *srcBytesPerPixel = 4; michael@0: } else if (3 == cinfo.out_color_components && JCS_RGB == cinfo.out_color_space) { michael@0: *sc = SkScaledBitmapSampler::kRGB; michael@0: *srcBytesPerPixel = 3; michael@0: #ifdef ANDROID_RGB michael@0: } else if (JCS_RGBA_8888 == cinfo.out_color_space) { michael@0: *sc = SkScaledBitmapSampler::kRGBX; michael@0: *srcBytesPerPixel = 4; michael@0: } else if (JCS_RGB_565 == cinfo.out_color_space) { michael@0: *sc = SkScaledBitmapSampler::kRGB_565; michael@0: *srcBytesPerPixel = 2; michael@0: #endif michael@0: } else if (1 == cinfo.out_color_components && michael@0: JCS_GRAYSCALE == cinfo.out_color_space) { michael@0: *sc = SkScaledBitmapSampler::kGray; michael@0: *srcBytesPerPixel = 1; michael@0: } else { michael@0: return false; michael@0: } michael@0: return true; michael@0: } michael@0: michael@0: bool SkJPEGImageDecoder::onDecode(SkStream* stream, SkBitmap* bm, Mode mode) { michael@0: #ifdef TIME_DECODE michael@0: SkAutoTime atm("JPEG Decode"); michael@0: #endif michael@0: michael@0: JPEGAutoClean autoClean; michael@0: michael@0: jpeg_decompress_struct cinfo; michael@0: skjpeg_source_mgr srcManager(stream, this); michael@0: michael@0: skjpeg_error_mgr errorManager; michael@0: set_error_mgr(&cinfo, &errorManager); michael@0: michael@0: // All objects need to be instantiated before this setjmp call so that michael@0: // they will be cleaned up properly if an error occurs. michael@0: if (setjmp(errorManager.fJmpBuf)) { michael@0: return return_false(cinfo, *bm, "setjmp"); michael@0: } michael@0: michael@0: initialize_info(&cinfo, &srcManager); michael@0: autoClean.set(&cinfo); michael@0: michael@0: int status = jpeg_read_header(&cinfo, true); michael@0: if (status != JPEG_HEADER_OK) { michael@0: return return_false(cinfo, *bm, "read_header"); michael@0: } michael@0: michael@0: /* Try to fulfill the requested sampleSize. Since jpeg can do it (when it michael@0: can) much faster that we, just use their num/denom api to approximate michael@0: the size. michael@0: */ michael@0: int sampleSize = this->getSampleSize(); michael@0: michael@0: set_dct_method(*this, &cinfo); michael@0: michael@0: SkASSERT(1 == cinfo.scale_num); michael@0: cinfo.scale_denom = sampleSize; michael@0: michael@0: turn_off_visual_optimizations(&cinfo); michael@0: michael@0: const SkBitmap::Config config = this->getBitmapConfig(&cinfo); michael@0: michael@0: #ifdef ANDROID_RGB michael@0: adjust_out_color_space_and_dither(&cinfo, config, *this); michael@0: #endif michael@0: michael@0: if (1 == sampleSize && SkImageDecoder::kDecodeBounds_Mode == mode) { michael@0: // Assume an A8 bitmap is not opaque to avoid the check of each michael@0: // individual pixel. It is very unlikely to be opaque, since michael@0: // an opaque A8 bitmap would not be very interesting. michael@0: // Otherwise, a jpeg image is opaque. michael@0: return bm->setConfig(config, cinfo.image_width, cinfo.image_height, 0, michael@0: SkBitmap::kA8_Config == config ? michael@0: kPremul_SkAlphaType : kOpaque_SkAlphaType); michael@0: } michael@0: michael@0: /* image_width and image_height are the original dimensions, available michael@0: after jpeg_read_header(). To see the scaled dimensions, we have to call michael@0: jpeg_start_decompress(), and then read output_width and output_height. michael@0: */ michael@0: if (!jpeg_start_decompress(&cinfo)) { michael@0: /* If we failed here, we may still have enough information to return michael@0: to the caller if they just wanted (subsampled bounds). If sampleSize michael@0: was 1, then we would have already returned. Thus we just check if michael@0: we're in kDecodeBounds_Mode, and that we have valid output sizes. michael@0: michael@0: One reason to fail here is that we have insufficient stream data michael@0: to complete the setup. However, output dimensions seem to get michael@0: computed very early, which is why this special check can pay off. michael@0: */ michael@0: if (SkImageDecoder::kDecodeBounds_Mode == mode && valid_output_dimensions(cinfo)) { michael@0: SkScaledBitmapSampler smpl(cinfo.output_width, cinfo.output_height, michael@0: recompute_sampleSize(sampleSize, cinfo)); michael@0: // Assume an A8 bitmap is not opaque to avoid the check of each michael@0: // individual pixel. It is very unlikely to be opaque, since michael@0: // an opaque A8 bitmap would not be very interesting. michael@0: // Otherwise, a jpeg image is opaque. michael@0: return bm->setConfig(config, smpl.scaledWidth(), smpl.scaledHeight(), michael@0: 0, SkBitmap::kA8_Config == config ? michael@0: kPremul_SkAlphaType : kOpaque_SkAlphaType); michael@0: } else { michael@0: return return_false(cinfo, *bm, "start_decompress"); michael@0: } michael@0: } michael@0: sampleSize = recompute_sampleSize(sampleSize, cinfo); michael@0: michael@0: // should we allow the Chooser (if present) to pick a config for us??? michael@0: if (!this->chooseFromOneChoice(config, cinfo.output_width, cinfo.output_height)) { michael@0: return return_false(cinfo, *bm, "chooseFromOneChoice"); michael@0: } michael@0: michael@0: SkScaledBitmapSampler sampler(cinfo.output_width, cinfo.output_height, sampleSize); michael@0: // Assume an A8 bitmap is not opaque to avoid the check of each michael@0: // individual pixel. It is very unlikely to be opaque, since michael@0: // an opaque A8 bitmap would not be very interesting. michael@0: // Otherwise, a jpeg image is opaque. michael@0: bm->setConfig(config, sampler.scaledWidth(), sampler.scaledHeight(), 0, michael@0: SkBitmap::kA8_Config != config ? kOpaque_SkAlphaType : kPremul_SkAlphaType); michael@0: if (SkImageDecoder::kDecodeBounds_Mode == mode) { michael@0: return true; michael@0: } michael@0: if (!this->allocPixelRef(bm, NULL)) { michael@0: return return_false(cinfo, *bm, "allocPixelRef"); michael@0: } michael@0: michael@0: SkAutoLockPixels alp(*bm); michael@0: michael@0: #ifdef ANDROID_RGB michael@0: /* short-circuit the SkScaledBitmapSampler when possible, as this gives michael@0: a significant performance boost. michael@0: */ michael@0: if (sampleSize == 1 && michael@0: ((config == SkBitmap::kARGB_8888_Config && michael@0: cinfo.out_color_space == JCS_RGBA_8888) || michael@0: (config == SkBitmap::kRGB_565_Config && michael@0: cinfo.out_color_space == JCS_RGB_565))) michael@0: { michael@0: JSAMPLE* rowptr = (JSAMPLE*)bm->getPixels(); michael@0: INT32 const bpr = bm->rowBytes(); michael@0: michael@0: while (cinfo.output_scanline < cinfo.output_height) { michael@0: int row_count = jpeg_read_scanlines(&cinfo, &rowptr, 1); michael@0: if (0 == row_count) { michael@0: // if row_count == 0, then we didn't get a scanline, michael@0: // so return early. We will return a partial image. michael@0: fill_below_level(cinfo.output_scanline, bm); michael@0: cinfo.output_scanline = cinfo.output_height; michael@0: break; // Skip to jpeg_finish_decompress() michael@0: } michael@0: if (this->shouldCancelDecode()) { michael@0: return return_false(cinfo, *bm, "shouldCancelDecode"); michael@0: } michael@0: rowptr += bpr; michael@0: } michael@0: jpeg_finish_decompress(&cinfo); michael@0: return true; michael@0: } michael@0: #endif michael@0: michael@0: // check for supported formats michael@0: SkScaledBitmapSampler::SrcConfig sc; michael@0: int srcBytesPerPixel; michael@0: michael@0: if (!get_src_config(cinfo, &sc, &srcBytesPerPixel)) { michael@0: return return_false(cinfo, *bm, "jpeg colorspace"); michael@0: } michael@0: michael@0: if (!sampler.begin(bm, sc, *this)) { michael@0: return return_false(cinfo, *bm, "sampler.begin"); michael@0: } michael@0: michael@0: SkAutoMalloc srcStorage(cinfo.output_width * srcBytesPerPixel); michael@0: uint8_t* srcRow = (uint8_t*)srcStorage.get(); michael@0: michael@0: // Possibly skip initial rows [sampler.srcY0] michael@0: if (!skip_src_rows(&cinfo, srcRow, sampler.srcY0())) { michael@0: return return_false(cinfo, *bm, "skip rows"); michael@0: } michael@0: michael@0: // now loop through scanlines until y == bm->height() - 1 michael@0: for (int y = 0;; y++) { michael@0: JSAMPLE* rowptr = (JSAMPLE*)srcRow; michael@0: int row_count = jpeg_read_scanlines(&cinfo, &rowptr, 1); michael@0: if (0 == row_count) { michael@0: // if row_count == 0, then we didn't get a scanline, michael@0: // so return early. We will return a partial image. michael@0: fill_below_level(y, bm); michael@0: cinfo.output_scanline = cinfo.output_height; michael@0: break; // Skip to jpeg_finish_decompress() michael@0: } michael@0: if (this->shouldCancelDecode()) { michael@0: return return_false(cinfo, *bm, "shouldCancelDecode"); michael@0: } michael@0: michael@0: if (JCS_CMYK == cinfo.out_color_space) { michael@0: convert_CMYK_to_RGB(srcRow, cinfo.output_width); michael@0: } michael@0: michael@0: sampler.next(srcRow); michael@0: if (bm->height() - 1 == y) { michael@0: // we're done michael@0: break; michael@0: } michael@0: michael@0: if (!skip_src_rows(&cinfo, srcRow, sampler.srcDY() - 1)) { michael@0: return return_false(cinfo, *bm, "skip rows"); michael@0: } michael@0: } michael@0: michael@0: // we formally skip the rest, so we don't get a complaint from libjpeg michael@0: if (!skip_src_rows(&cinfo, srcRow, michael@0: cinfo.output_height - cinfo.output_scanline)) { michael@0: return return_false(cinfo, *bm, "skip rows"); michael@0: } michael@0: jpeg_finish_decompress(&cinfo); michael@0: michael@0: return true; michael@0: } michael@0: michael@0: #ifdef SK_BUILD_FOR_ANDROID michael@0: bool SkJPEGImageDecoder::onBuildTileIndex(SkStreamRewindable* stream, int *width, int *height) { michael@0: michael@0: SkAutoTDelete imageIndex(SkNEW_ARGS(SkJPEGImageIndex, (stream, this))); michael@0: jpeg_decompress_struct* cinfo = imageIndex->cinfo(); michael@0: michael@0: skjpeg_error_mgr sk_err; michael@0: set_error_mgr(cinfo, &sk_err); michael@0: michael@0: // All objects need to be instantiated before this setjmp call so that michael@0: // they will be cleaned up properly if an error occurs. michael@0: if (setjmp(sk_err.fJmpBuf)) { michael@0: return false; michael@0: } michael@0: michael@0: // create the cinfo used to create/build the huffmanIndex michael@0: if (!imageIndex->initializeInfoAndReadHeader()) { michael@0: return false; michael@0: } michael@0: michael@0: if (!imageIndex->buildHuffmanIndex()) { michael@0: return false; michael@0: } michael@0: michael@0: // destroy the cinfo used to create/build the huffman index michael@0: imageIndex->destroyInfo(); michael@0: michael@0: // Init decoder to image decode mode michael@0: if (!imageIndex->initializeInfoAndReadHeader()) { michael@0: return false; michael@0: } michael@0: michael@0: // FIXME: This sets cinfo->out_color_space, which we may change later michael@0: // based on the config in onDecodeSubset. This should be fine, since michael@0: // jpeg_init_read_tile_scanline will check out_color_space again after michael@0: // that change (when it calls jinit_color_deconverter). michael@0: (void) this->getBitmapConfig(cinfo); michael@0: michael@0: turn_off_visual_optimizations(cinfo); michael@0: michael@0: // instead of jpeg_start_decompress() we start a tiled decompress michael@0: if (!imageIndex->startTileDecompress()) { michael@0: return false; michael@0: } michael@0: michael@0: SkASSERT(1 == cinfo->scale_num); michael@0: fImageWidth = cinfo->output_width; michael@0: fImageHeight = cinfo->output_height; michael@0: michael@0: if (width) { michael@0: *width = fImageWidth; michael@0: } michael@0: if (height) { michael@0: *height = fImageHeight; michael@0: } michael@0: michael@0: SkDELETE(fImageIndex); michael@0: fImageIndex = imageIndex.detach(); michael@0: michael@0: return true; michael@0: } michael@0: michael@0: bool SkJPEGImageDecoder::onDecodeSubset(SkBitmap* bm, const SkIRect& region) { michael@0: if (NULL == fImageIndex) { michael@0: return false; michael@0: } michael@0: jpeg_decompress_struct* cinfo = fImageIndex->cinfo(); michael@0: michael@0: SkIRect rect = SkIRect::MakeWH(fImageWidth, fImageHeight); michael@0: if (!rect.intersect(region)) { michael@0: // If the requested region is entirely outside the image return false michael@0: return false; michael@0: } michael@0: michael@0: michael@0: skjpeg_error_mgr errorManager; michael@0: set_error_mgr(cinfo, &errorManager); michael@0: michael@0: if (setjmp(errorManager.fJmpBuf)) { michael@0: return false; michael@0: } michael@0: michael@0: int requestedSampleSize = this->getSampleSize(); michael@0: cinfo->scale_denom = requestedSampleSize; michael@0: michael@0: set_dct_method(*this, cinfo); michael@0: michael@0: const SkBitmap::Config config = this->getBitmapConfig(cinfo); michael@0: #ifdef ANDROID_RGB michael@0: adjust_out_color_space_and_dither(cinfo, config, *this); michael@0: #endif michael@0: michael@0: int startX = rect.fLeft; michael@0: int startY = rect.fTop; michael@0: int width = rect.width(); michael@0: int height = rect.height(); michael@0: michael@0: jpeg_init_read_tile_scanline(cinfo, fImageIndex->huffmanIndex(), michael@0: &startX, &startY, &width, &height); michael@0: int skiaSampleSize = recompute_sampleSize(requestedSampleSize, *cinfo); michael@0: int actualSampleSize = skiaSampleSize * (DCTSIZE / cinfo->min_DCT_scaled_size); michael@0: michael@0: SkScaledBitmapSampler sampler(width, height, skiaSampleSize); michael@0: michael@0: SkBitmap bitmap; michael@0: bitmap.setConfig(config, sampler.scaledWidth(), sampler.scaledHeight()); michael@0: // Assume an A8 bitmap is not opaque to avoid the check of each michael@0: // individual pixel. It is very unlikely to be opaque, since michael@0: // an opaque A8 bitmap would not be very interesting. michael@0: // Otherwise, a jpeg image is opaque. michael@0: bitmap.setConfig(config, sampler.scaledWidth(), sampler.scaledHeight(), 0, michael@0: config == SkBitmap::kA8_Config ? kPremul_SkAlphaType : michael@0: kOpaque_SkAlphaType); michael@0: michael@0: // Check ahead of time if the swap(dest, src) is possible or not. michael@0: // If yes, then we will stick to AllocPixelRef since it's cheaper with the michael@0: // swap happening. If no, then we will use alloc to allocate pixels to michael@0: // prevent garbage collection. michael@0: int w = rect.width() / actualSampleSize; michael@0: int h = rect.height() / actualSampleSize; michael@0: bool swapOnly = (rect == region) && bm->isNull() && michael@0: (w == bitmap.width()) && (h == bitmap.height()) && michael@0: ((startX - rect.x()) / actualSampleSize == 0) && michael@0: ((startY - rect.y()) / actualSampleSize == 0); michael@0: if (swapOnly) { michael@0: if (!this->allocPixelRef(&bitmap, NULL)) { michael@0: return return_false(*cinfo, bitmap, "allocPixelRef"); michael@0: } michael@0: } else { michael@0: if (!bitmap.allocPixels()) { michael@0: return return_false(*cinfo, bitmap, "allocPixels"); michael@0: } michael@0: } michael@0: michael@0: SkAutoLockPixels alp(bitmap); michael@0: michael@0: #ifdef ANDROID_RGB michael@0: /* short-circuit the SkScaledBitmapSampler when possible, as this gives michael@0: a significant performance boost. michael@0: */ michael@0: if (skiaSampleSize == 1 && michael@0: ((config == SkBitmap::kARGB_8888_Config && michael@0: cinfo->out_color_space == JCS_RGBA_8888) || michael@0: (config == SkBitmap::kRGB_565_Config && michael@0: cinfo->out_color_space == JCS_RGB_565))) michael@0: { michael@0: JSAMPLE* rowptr = (JSAMPLE*)bitmap.getPixels(); michael@0: INT32 const bpr = bitmap.rowBytes(); michael@0: int rowTotalCount = 0; michael@0: michael@0: while (rowTotalCount < height) { michael@0: int rowCount = jpeg_read_tile_scanline(cinfo, michael@0: fImageIndex->huffmanIndex(), michael@0: &rowptr); michael@0: // if rowCount == 0, then we didn't get a scanline, so abort. michael@0: // onDecodeSubset() relies on onBuildTileIndex(), which michael@0: // needs a complete image to succeed. michael@0: if (0 == rowCount) { michael@0: return return_false(*cinfo, bitmap, "read_scanlines"); michael@0: } michael@0: if (this->shouldCancelDecode()) { michael@0: return return_false(*cinfo, bitmap, "shouldCancelDecode"); michael@0: } michael@0: rowTotalCount += rowCount; michael@0: rowptr += bpr; michael@0: } michael@0: michael@0: if (swapOnly) { michael@0: bm->swap(bitmap); michael@0: } else { michael@0: cropBitmap(bm, &bitmap, actualSampleSize, region.x(), region.y(), michael@0: region.width(), region.height(), startX, startY); michael@0: } michael@0: return true; michael@0: } michael@0: #endif michael@0: michael@0: // check for supported formats michael@0: SkScaledBitmapSampler::SrcConfig sc; michael@0: int srcBytesPerPixel; michael@0: michael@0: if (!get_src_config(*cinfo, &sc, &srcBytesPerPixel)) { michael@0: return return_false(*cinfo, *bm, "jpeg colorspace"); michael@0: } michael@0: michael@0: if (!sampler.begin(&bitmap, sc, *this)) { michael@0: return return_false(*cinfo, bitmap, "sampler.begin"); michael@0: } michael@0: michael@0: SkAutoMalloc srcStorage(width * srcBytesPerPixel); michael@0: uint8_t* srcRow = (uint8_t*)srcStorage.get(); michael@0: michael@0: // Possibly skip initial rows [sampler.srcY0] michael@0: if (!skip_src_rows_tile(cinfo, fImageIndex->huffmanIndex(), srcRow, sampler.srcY0())) { michael@0: return return_false(*cinfo, bitmap, "skip rows"); michael@0: } michael@0: michael@0: // now loop through scanlines until y == bitmap->height() - 1 michael@0: for (int y = 0;; y++) { michael@0: JSAMPLE* rowptr = (JSAMPLE*)srcRow; michael@0: int row_count = jpeg_read_tile_scanline(cinfo, fImageIndex->huffmanIndex(), &rowptr); michael@0: // if row_count == 0, then we didn't get a scanline, so abort. michael@0: // onDecodeSubset() relies on onBuildTileIndex(), which michael@0: // needs a complete image to succeed. michael@0: if (0 == row_count) { michael@0: return return_false(*cinfo, bitmap, "read_scanlines"); michael@0: } michael@0: if (this->shouldCancelDecode()) { michael@0: return return_false(*cinfo, bitmap, "shouldCancelDecode"); michael@0: } michael@0: michael@0: if (JCS_CMYK == cinfo->out_color_space) { michael@0: convert_CMYK_to_RGB(srcRow, width); michael@0: } michael@0: michael@0: sampler.next(srcRow); michael@0: if (bitmap.height() - 1 == y) { michael@0: // we're done michael@0: break; michael@0: } michael@0: michael@0: if (!skip_src_rows_tile(cinfo, fImageIndex->huffmanIndex(), srcRow, michael@0: sampler.srcDY() - 1)) { michael@0: return return_false(*cinfo, bitmap, "skip rows"); michael@0: } michael@0: } michael@0: if (swapOnly) { michael@0: bm->swap(bitmap); michael@0: } else { michael@0: cropBitmap(bm, &bitmap, actualSampleSize, region.x(), region.y(), michael@0: region.width(), region.height(), startX, startY); michael@0: } michael@0: return true; michael@0: } michael@0: #endif michael@0: michael@0: /////////////////////////////////////////////////////////////////////////////// michael@0: michael@0: #include "SkColorPriv.h" michael@0: michael@0: // taken from jcolor.c in libjpeg michael@0: #if 0 // 16bit - precise but slow michael@0: #define CYR 19595 // 0.299 michael@0: #define CYG 38470 // 0.587 michael@0: #define CYB 7471 // 0.114 michael@0: michael@0: #define CUR -11059 // -0.16874 michael@0: #define CUG -21709 // -0.33126 michael@0: #define CUB 32768 // 0.5 michael@0: michael@0: #define CVR 32768 // 0.5 michael@0: #define CVG -27439 // -0.41869 michael@0: #define CVB -5329 // -0.08131 michael@0: michael@0: #define CSHIFT 16 michael@0: #else // 8bit - fast, slightly less precise michael@0: #define CYR 77 // 0.299 michael@0: #define CYG 150 // 0.587 michael@0: #define CYB 29 // 0.114 michael@0: michael@0: #define CUR -43 // -0.16874 michael@0: #define CUG -85 // -0.33126 michael@0: #define CUB 128 // 0.5 michael@0: michael@0: #define CVR 128 // 0.5 michael@0: #define CVG -107 // -0.41869 michael@0: #define CVB -21 // -0.08131 michael@0: michael@0: #define CSHIFT 8 michael@0: #endif michael@0: michael@0: static void rgb2yuv_32(uint8_t dst[], SkPMColor c) { michael@0: int r = SkGetPackedR32(c); michael@0: int g = SkGetPackedG32(c); michael@0: int b = SkGetPackedB32(c); michael@0: michael@0: int y = ( CYR*r + CYG*g + CYB*b ) >> CSHIFT; michael@0: int u = ( CUR*r + CUG*g + CUB*b ) >> CSHIFT; michael@0: int v = ( CVR*r + CVG*g + CVB*b ) >> CSHIFT; michael@0: michael@0: dst[0] = SkToU8(y); michael@0: dst[1] = SkToU8(u + 128); michael@0: dst[2] = SkToU8(v + 128); michael@0: } michael@0: michael@0: static void rgb2yuv_4444(uint8_t dst[], U16CPU c) { michael@0: int r = SkGetPackedR4444(c); michael@0: int g = SkGetPackedG4444(c); michael@0: int b = SkGetPackedB4444(c); michael@0: michael@0: int y = ( CYR*r + CYG*g + CYB*b ) >> (CSHIFT - 4); michael@0: int u = ( CUR*r + CUG*g + CUB*b ) >> (CSHIFT - 4); michael@0: int v = ( CVR*r + CVG*g + CVB*b ) >> (CSHIFT - 4); michael@0: michael@0: dst[0] = SkToU8(y); michael@0: dst[1] = SkToU8(u + 128); michael@0: dst[2] = SkToU8(v + 128); michael@0: } michael@0: michael@0: static void rgb2yuv_16(uint8_t dst[], U16CPU c) { michael@0: int r = SkGetPackedR16(c); michael@0: int g = SkGetPackedG16(c); michael@0: int b = SkGetPackedB16(c); michael@0: michael@0: int y = ( 2*CYR*r + CYG*g + 2*CYB*b ) >> (CSHIFT - 2); michael@0: int u = ( 2*CUR*r + CUG*g + 2*CUB*b ) >> (CSHIFT - 2); michael@0: int v = ( 2*CVR*r + CVG*g + 2*CVB*b ) >> (CSHIFT - 2); michael@0: michael@0: dst[0] = SkToU8(y); michael@0: dst[1] = SkToU8(u + 128); michael@0: dst[2] = SkToU8(v + 128); michael@0: } michael@0: michael@0: /////////////////////////////////////////////////////////////////////////////// michael@0: michael@0: typedef void (*WriteScanline)(uint8_t* SK_RESTRICT dst, michael@0: const void* SK_RESTRICT src, int width, michael@0: const SkPMColor* SK_RESTRICT ctable); michael@0: michael@0: static void Write_32_YUV(uint8_t* SK_RESTRICT dst, michael@0: const void* SK_RESTRICT srcRow, int width, michael@0: const SkPMColor*) { michael@0: const uint32_t* SK_RESTRICT src = (const uint32_t*)srcRow; michael@0: while (--width >= 0) { michael@0: #ifdef WE_CONVERT_TO_YUV michael@0: rgb2yuv_32(dst, *src++); michael@0: #else michael@0: uint32_t c = *src++; michael@0: dst[0] = SkGetPackedR32(c); michael@0: dst[1] = SkGetPackedG32(c); michael@0: dst[2] = SkGetPackedB32(c); michael@0: #endif michael@0: dst += 3; michael@0: } michael@0: } michael@0: michael@0: static void Write_4444_YUV(uint8_t* SK_RESTRICT dst, michael@0: const void* SK_RESTRICT srcRow, int width, michael@0: const SkPMColor*) { michael@0: const SkPMColor16* SK_RESTRICT src = (const SkPMColor16*)srcRow; michael@0: while (--width >= 0) { michael@0: #ifdef WE_CONVERT_TO_YUV michael@0: rgb2yuv_4444(dst, *src++); michael@0: #else michael@0: SkPMColor16 c = *src++; michael@0: dst[0] = SkPacked4444ToR32(c); michael@0: dst[1] = SkPacked4444ToG32(c); michael@0: dst[2] = SkPacked4444ToB32(c); michael@0: #endif michael@0: dst += 3; michael@0: } michael@0: } michael@0: michael@0: static void Write_16_YUV(uint8_t* SK_RESTRICT dst, michael@0: const void* SK_RESTRICT srcRow, int width, michael@0: const SkPMColor*) { michael@0: const uint16_t* SK_RESTRICT src = (const uint16_t*)srcRow; michael@0: while (--width >= 0) { michael@0: #ifdef WE_CONVERT_TO_YUV michael@0: rgb2yuv_16(dst, *src++); michael@0: #else michael@0: uint16_t c = *src++; michael@0: dst[0] = SkPacked16ToR32(c); michael@0: dst[1] = SkPacked16ToG32(c); michael@0: dst[2] = SkPacked16ToB32(c); michael@0: #endif michael@0: dst += 3; michael@0: } michael@0: } michael@0: michael@0: static void Write_Index_YUV(uint8_t* SK_RESTRICT dst, michael@0: const void* SK_RESTRICT srcRow, int width, michael@0: const SkPMColor* SK_RESTRICT ctable) { michael@0: const uint8_t* SK_RESTRICT src = (const uint8_t*)srcRow; michael@0: while (--width >= 0) { michael@0: #ifdef WE_CONVERT_TO_YUV michael@0: rgb2yuv_32(dst, ctable[*src++]); michael@0: #else michael@0: uint32_t c = ctable[*src++]; michael@0: dst[0] = SkGetPackedR32(c); michael@0: dst[1] = SkGetPackedG32(c); michael@0: dst[2] = SkGetPackedB32(c); michael@0: #endif michael@0: dst += 3; michael@0: } michael@0: } michael@0: michael@0: static WriteScanline ChooseWriter(const SkBitmap& bm) { michael@0: switch (bm.config()) { michael@0: case SkBitmap::kARGB_8888_Config: michael@0: return Write_32_YUV; michael@0: case SkBitmap::kRGB_565_Config: michael@0: return Write_16_YUV; michael@0: case SkBitmap::kARGB_4444_Config: michael@0: return Write_4444_YUV; michael@0: case SkBitmap::kIndex8_Config: michael@0: return Write_Index_YUV; michael@0: default: michael@0: return NULL; michael@0: } michael@0: } michael@0: michael@0: class SkJPEGImageEncoder : public SkImageEncoder { michael@0: protected: michael@0: virtual bool onEncode(SkWStream* stream, const SkBitmap& bm, int quality) { michael@0: #ifdef TIME_ENCODE michael@0: SkAutoTime atm("JPEG Encode"); michael@0: #endif michael@0: michael@0: SkAutoLockPixels alp(bm); michael@0: if (NULL == bm.getPixels()) { michael@0: return false; michael@0: } michael@0: michael@0: jpeg_compress_struct cinfo; michael@0: skjpeg_error_mgr sk_err; michael@0: skjpeg_destination_mgr sk_wstream(stream); michael@0: michael@0: // allocate these before set call setjmp michael@0: SkAutoMalloc oneRow; michael@0: SkAutoLockColors ctLocker; michael@0: michael@0: cinfo.err = jpeg_std_error(&sk_err); michael@0: sk_err.error_exit = skjpeg_error_exit; michael@0: if (setjmp(sk_err.fJmpBuf)) { michael@0: return false; michael@0: } michael@0: michael@0: // Keep after setjmp or mark volatile. michael@0: const WriteScanline writer = ChooseWriter(bm); michael@0: if (NULL == writer) { michael@0: return false; michael@0: } michael@0: michael@0: jpeg_create_compress(&cinfo); michael@0: cinfo.dest = &sk_wstream; michael@0: cinfo.image_width = bm.width(); michael@0: cinfo.image_height = bm.height(); michael@0: cinfo.input_components = 3; michael@0: #ifdef WE_CONVERT_TO_YUV michael@0: cinfo.in_color_space = JCS_YCbCr; michael@0: #else michael@0: cinfo.in_color_space = JCS_RGB; michael@0: #endif michael@0: cinfo.input_gamma = 1; michael@0: michael@0: jpeg_set_defaults(&cinfo); michael@0: jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */); michael@0: #ifdef DCT_IFAST_SUPPORTED michael@0: cinfo.dct_method = JDCT_IFAST; michael@0: #endif michael@0: michael@0: jpeg_start_compress(&cinfo, TRUE); michael@0: michael@0: const int width = bm.width(); michael@0: uint8_t* oneRowP = (uint8_t*)oneRow.reset(width * 3); michael@0: michael@0: const SkPMColor* colors = ctLocker.lockColors(bm); michael@0: const void* srcRow = bm.getPixels(); michael@0: michael@0: while (cinfo.next_scanline < cinfo.image_height) { michael@0: JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */ michael@0: michael@0: writer(oneRowP, srcRow, width, colors); michael@0: row_pointer[0] = oneRowP; michael@0: (void) jpeg_write_scanlines(&cinfo, row_pointer, 1); michael@0: srcRow = (const void*)((const char*)srcRow + bm.rowBytes()); michael@0: } michael@0: michael@0: jpeg_finish_compress(&cinfo); michael@0: jpeg_destroy_compress(&cinfo); michael@0: michael@0: return true; michael@0: } michael@0: }; michael@0: michael@0: /////////////////////////////////////////////////////////////////////////////// michael@0: DEFINE_DECODER_CREATOR(JPEGImageDecoder); michael@0: DEFINE_ENCODER_CREATOR(JPEGImageEncoder); michael@0: /////////////////////////////////////////////////////////////////////////////// michael@0: michael@0: static bool is_jpeg(SkStreamRewindable* stream) { michael@0: static const unsigned char gHeader[] = { 0xFF, 0xD8, 0xFF }; michael@0: static const size_t HEADER_SIZE = sizeof(gHeader); michael@0: michael@0: char buffer[HEADER_SIZE]; michael@0: size_t len = stream->read(buffer, HEADER_SIZE); michael@0: michael@0: if (len != HEADER_SIZE) { michael@0: return false; // can't read enough michael@0: } michael@0: if (memcmp(buffer, gHeader, HEADER_SIZE)) { michael@0: return false; michael@0: } michael@0: return true; michael@0: } michael@0: michael@0: michael@0: static SkImageDecoder* sk_libjpeg_dfactory(SkStreamRewindable* stream) { michael@0: if (is_jpeg(stream)) { michael@0: return SkNEW(SkJPEGImageDecoder); michael@0: } michael@0: return NULL; michael@0: } michael@0: michael@0: static SkImageDecoder::Format get_format_jpeg(SkStreamRewindable* stream) { michael@0: if (is_jpeg(stream)) { michael@0: return SkImageDecoder::kJPEG_Format; michael@0: } michael@0: return SkImageDecoder::kUnknown_Format; michael@0: } michael@0: michael@0: static SkImageEncoder* sk_libjpeg_efactory(SkImageEncoder::Type t) { michael@0: return (SkImageEncoder::kJPEG_Type == t) ? SkNEW(SkJPEGImageEncoder) : NULL; michael@0: } michael@0: michael@0: static SkImageDecoder_DecodeReg gDReg(sk_libjpeg_dfactory); michael@0: static SkImageDecoder_FormatReg gFormatReg(get_format_jpeg); michael@0: static SkImageEncoder_EncodeReg gEReg(sk_libjpeg_efactory);