Home | History | Annotate | Download | only in jpeg
      1 /*
      2  * Copyright (C) 2006 Apple Computer, Inc.
      3  *
      4  * Portions are Copyright (C) 2001-6 mozilla.org
      5  *
      6  * Other contributors:
      7  *   Stuart Parmenter <stuart (at) mozilla.com>
      8  *
      9  * Copyright (C) 2007-2009 Torch Mobile, Inc.
     10  *
     11  * This library is free software; you can redistribute it and/or
     12  * modify it under the terms of the GNU Lesser General Public
     13  * License as published by the Free Software Foundation; either
     14  * version 2.1 of the License, or (at your option) any later version.
     15  *
     16  * This library is distributed in the hope that it will be useful,
     17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
     18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     19  * Lesser General Public License for more details.
     20  *
     21  * You should have received a copy of the GNU Lesser General Public
     22  * License along with this library; if not, write to the Free Software
     23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
     24  *
     25  * Alternatively, the contents of this file may be used under the terms
     26  * of either the Mozilla Public License Version 1.1, found at
     27  * http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
     28  * License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
     29  * (the "GPL"), in which case the provisions of the MPL or the GPL are
     30  * applicable instead of those above.  If you wish to allow use of your
     31  * version of this file only under the terms of one of those two
     32  * licenses (the MPL or the GPL) and not to allow others to use your
     33  * version of this file under the LGPL, indicate your decision by
     34  * deletingthe provisions above and replace them with the notice and
     35  * other provisions required by the MPL or the GPL, as the case may be.
     36  * If you do not delete the provisions above, a recipient may use your
     37  * version of this file under any of the LGPL, the MPL or the GPL.
     38  */
     39 
     40 #include "config.h"
     41 #include "core/platform/image-decoders/jpeg/JPEGImageDecoder.h"
     42 
     43 #include "core/platform/PlatformInstrumentation.h"
     44 #include "wtf/CPU.h"
     45 #include "wtf/PassOwnPtr.h"
     46 
     47 extern "C" {
     48 #include <stdio.h> // jpeglib.h needs stdio FILE.
     49 #include "jpeglib.h"
     50 #if USE(ICCJPEG)
     51 #include "iccjpeg.h"
     52 #endif
     53 #if USE(QCMSLIB)
     54 #include "qcms.h"
     55 #endif
     56 #include <setjmp.h>
     57 }
     58 
     59 #if CPU(BIG_ENDIAN) || CPU(MIDDLE_ENDIAN)
     60 #define ASSUME_LITTLE_ENDIAN 0
     61 #else
     62 #define ASSUME_LITTLE_ENDIAN 1
     63 #endif
     64 
     65 #if defined(JCS_ALPHA_EXTENSIONS) && ASSUME_LITTLE_ENDIAN
     66 #define TURBO_JPEG_RGB_SWIZZLE
     67 #if !SK_R32_SHIFT && SK_G32_SHIFT == 8 && SK_B32_SHIFT == 16
     68 inline J_COLOR_SPACE rgbOutputColorSpace() { return JCS_EXT_RGBA; }
     69 #else
     70 inline J_COLOR_SPACE rgbOutputColorSpace() { return JCS_EXT_BGRA; }
     71 #endif
     72 inline bool turboSwizzled(J_COLOR_SPACE colorSpace) { return colorSpace == JCS_EXT_RGBA || colorSpace == JCS_EXT_BGRA; }
     73 inline bool colorSpaceHasAlpha(J_COLOR_SPACE colorSpace) { return turboSwizzled(colorSpace); }
     74 #else
     75 inline J_COLOR_SPACE rgbOutputColorSpace() { return JCS_RGB; }
     76 inline bool colorSpaceHasAlpha(J_COLOR_SPACE) { return false; }
     77 #endif
     78 
     79 #if USE(LOW_QUALITY_IMAGE_NO_JPEG_DITHERING)
     80 inline J_DCT_METHOD dctMethod() { return JDCT_IFAST; }
     81 inline J_DITHER_MODE ditherMode() { return JDITHER_NONE; }
     82 #else
     83 inline J_DCT_METHOD dctMethod() { return JDCT_ISLOW; }
     84 inline J_DITHER_MODE ditherMode() { return JDITHER_FS; }
     85 #endif
     86 
     87 #if USE(LOW_QUALITY_IMAGE_NO_JPEG_FANCY_UPSAMPLING)
     88 inline bool doFancyUpsampling() { return false; }
     89 #else
     90 inline bool doFancyUpsampling() { return true; }
     91 #endif
     92 
     93 const int exifMarker = JPEG_APP0 + 1;
     94 
     95 namespace WebCore {
     96 
     97 struct decoder_error_mgr {
     98     struct jpeg_error_mgr pub; // "public" fields for IJG library
     99     jmp_buf setjmp_buffer;     // For handling catastropic errors
    100 };
    101 
    102 enum jstate {
    103     JPEG_HEADER,                 // Reading JFIF headers
    104     JPEG_START_DECOMPRESS,
    105     JPEG_DECOMPRESS_PROGRESSIVE, // Output progressive pixels
    106     JPEG_DECOMPRESS_SEQUENTIAL,  // Output sequential pixels
    107     JPEG_DONE,
    108     JPEG_ERROR
    109 };
    110 
    111 void init_source(j_decompress_ptr jd);
    112 boolean fill_input_buffer(j_decompress_ptr jd);
    113 void skip_input_data(j_decompress_ptr jd, long num_bytes);
    114 void term_source(j_decompress_ptr jd);
    115 void error_exit(j_common_ptr cinfo);
    116 
    117 // Implementation of a JPEG src object that understands our state machine
    118 struct decoder_source_mgr {
    119     // public fields; must be first in this struct!
    120     struct jpeg_source_mgr pub;
    121 
    122     JPEGImageReader* decoder;
    123 };
    124 
    125 static unsigned readUint16(JOCTET* data, bool isBigEndian)
    126 {
    127     if (isBigEndian)
    128         return (GETJOCTET(data[0]) << 8) | GETJOCTET(data[1]);
    129     return (GETJOCTET(data[1]) << 8) | GETJOCTET(data[0]);
    130 }
    131 
    132 static unsigned readUint32(JOCTET* data, bool isBigEndian)
    133 {
    134     if (isBigEndian)
    135         return (GETJOCTET(data[0]) << 24) | (GETJOCTET(data[1]) << 16) | (GETJOCTET(data[2]) << 8) | GETJOCTET(data[3]);
    136     return (GETJOCTET(data[3]) << 24) | (GETJOCTET(data[2]) << 16) | (GETJOCTET(data[1]) << 8) | GETJOCTET(data[0]);
    137 }
    138 
    139 static bool checkExifHeader(jpeg_saved_marker_ptr marker, bool& isBigEndian, unsigned& ifdOffset)
    140 {
    141     // For exif data, the APP1 block is followed by 'E', 'x', 'i', 'f', '\0',
    142     // then a fill byte, and then a tiff file that contains the metadata.
    143     // A tiff file starts with 'I', 'I' (intel / little endian byte order) or
    144     // 'M', 'M' (motorola / big endian byte order), followed by (uint16_t)42,
    145     // followed by an uint32_t with the offset to the tag block, relative to the
    146     // tiff file start.
    147     const unsigned exifHeaderSize = 14;
    148     if (!(marker->marker == exifMarker
    149         && marker->data_length >= exifHeaderSize
    150         && marker->data[0] == 'E'
    151         && marker->data[1] == 'x'
    152         && marker->data[2] == 'i'
    153         && marker->data[3] == 'f'
    154         && marker->data[4] == '\0'
    155         // data[5] is a fill byte
    156         && ((marker->data[6] == 'I' && marker->data[7] == 'I')
    157             || (marker->data[6] == 'M' && marker->data[7] == 'M'))))
    158         return false;
    159 
    160     isBigEndian = marker->data[6] == 'M';
    161     if (readUint16(marker->data + 8, isBigEndian) != 42)
    162         return false;
    163 
    164     ifdOffset = readUint32(marker->data + 10, isBigEndian);
    165     return true;
    166 }
    167 
    168 static ImageOrientation readImageOrientation(jpeg_decompress_struct* info)
    169 {
    170     // The JPEG decoder looks at EXIF metadata.
    171     // FIXME: Possibly implement XMP and IPTC support.
    172     const unsigned orientationTag = 0x112;
    173     const unsigned shortType = 3;
    174     for (jpeg_saved_marker_ptr marker = info->marker_list; marker; marker = marker->next) {
    175         bool isBigEndian;
    176         unsigned ifdOffset;
    177         if (!checkExifHeader(marker, isBigEndian, ifdOffset))
    178             continue;
    179         const unsigned offsetToTiffData = 6; // Account for 'Exif\0<fill byte>' header.
    180         if (marker->data_length < offsetToTiffData || ifdOffset >= marker->data_length - offsetToTiffData)
    181             continue;
    182         ifdOffset += offsetToTiffData;
    183 
    184         // The jpeg exif container format contains a tiff block for metadata.
    185         // A tiff image file directory (ifd) consists of a uint16_t describing
    186         // the number of ifd entries, followed by that many entries.
    187         // When touching this code, it's useful to look at the tiff spec:
    188         // http://partners.adobe.com/public/developer/en/tiff/TIFF6.pdf
    189         JOCTET* ifd = marker->data + ifdOffset;
    190         JOCTET* end = marker->data + marker->data_length;
    191         if (end - ifd < 2)
    192             continue;
    193         unsigned tagCount = readUint16(ifd, isBigEndian);
    194         ifd += 2; // Skip over the uint16 that was just read.
    195 
    196         // Every ifd entry is 2 bytes of tag, 2 bytes of contents datatype,
    197         // 4 bytes of number-of-elements, and 4 bytes of either offset to the
    198         // tag data, or if the data is small enough, the inlined data itself.
    199         const int ifdEntrySize = 12;
    200         for (unsigned i = 0; i < tagCount && end - ifd >= ifdEntrySize; ++i, ifd += ifdEntrySize) {
    201             unsigned tag = readUint16(ifd, isBigEndian);
    202             unsigned type = readUint16(ifd + 2, isBigEndian);
    203             unsigned count = readUint32(ifd + 4, isBigEndian);
    204             if (tag == orientationTag && type == shortType && count == 1)
    205                 return ImageOrientation::fromEXIFValue(readUint16(ifd + 8, isBigEndian));
    206         }
    207     }
    208 
    209     return ImageOrientation();
    210 }
    211 
    212 static void readColorProfile(jpeg_decompress_struct* info, ColorProfile& colorProfile)
    213 {
    214 #if USE(ICCJPEG)
    215     JOCTET* profile;
    216     unsigned int profileLength;
    217 
    218     if (!read_icc_profile(info, &profile, &profileLength))
    219         return;
    220 
    221     // Only accept RGB color profiles from input class devices.
    222     bool ignoreProfile = false;
    223     char* profileData = reinterpret_cast<char*>(profile);
    224     if (profileLength < ImageDecoder::iccColorProfileHeaderLength)
    225         ignoreProfile = true;
    226     else if (!ImageDecoder::rgbColorProfile(profileData, profileLength))
    227         ignoreProfile = true;
    228     else if (!ImageDecoder::inputDeviceColorProfile(profileData, profileLength))
    229         ignoreProfile = true;
    230 
    231     ASSERT(colorProfile.isEmpty());
    232     if (!ignoreProfile)
    233         colorProfile.append(profileData, profileLength);
    234     free(profile);
    235 #else
    236     UNUSED_PARAM(info);
    237     UNUSED_PARAM(colorProfile);
    238 #endif
    239 }
    240 
    241 class JPEGImageReader {
    242     WTF_MAKE_FAST_ALLOCATED;
    243 public:
    244     JPEGImageReader(JPEGImageDecoder* decoder)
    245         : m_decoder(decoder)
    246         , m_bufferLength(0)
    247         , m_bytesToSkip(0)
    248         , m_state(JPEG_HEADER)
    249         , m_samples(0)
    250 #if USE(QCMSLIB)
    251         , m_transform(0)
    252 #endif
    253     {
    254         memset(&m_info, 0, sizeof(jpeg_decompress_struct));
    255 
    256         // We set up the normal JPEG error routines, then override error_exit.
    257         m_info.err = jpeg_std_error(&m_err.pub);
    258         m_err.pub.error_exit = error_exit;
    259 
    260         // Allocate and initialize JPEG decompression object.
    261         jpeg_create_decompress(&m_info);
    262 
    263         decoder_source_mgr* src = 0;
    264         if (!m_info.src) {
    265             src = (decoder_source_mgr*)fastCalloc(sizeof(decoder_source_mgr), 1);
    266             if (!src) {
    267                 m_state = JPEG_ERROR;
    268                 return;
    269             }
    270         }
    271 
    272         m_info.src = (jpeg_source_mgr*)src;
    273 
    274         // Set up callback functions.
    275         src->pub.init_source = init_source;
    276         src->pub.fill_input_buffer = fill_input_buffer;
    277         src->pub.skip_input_data = skip_input_data;
    278         src->pub.resync_to_restart = jpeg_resync_to_restart;
    279         src->pub.term_source = term_source;
    280         src->decoder = this;
    281 
    282 #if USE(ICCJPEG)
    283         // Retain ICC color profile markers for color management.
    284         setup_read_icc_profile(&m_info);
    285 #endif
    286 
    287         // Keep APP1 blocks, for obtaining exif data.
    288         jpeg_save_markers(&m_info, exifMarker, 0xFFFF);
    289     }
    290 
    291     ~JPEGImageReader()
    292     {
    293         close();
    294     }
    295 
    296     void close()
    297     {
    298         decoder_source_mgr* src = (decoder_source_mgr*)m_info.src;
    299         if (src)
    300             fastFree(src);
    301         m_info.src = 0;
    302 
    303 #if USE(QCMSLIB)
    304         if (m_transform)
    305             qcms_transform_release(m_transform);
    306         m_transform = 0;
    307 #endif
    308         jpeg_destroy_decompress(&m_info);
    309     }
    310 
    311     void skipBytes(long numBytes)
    312     {
    313         decoder_source_mgr* src = (decoder_source_mgr*)m_info.src;
    314         long bytesToSkip = std::min(numBytes, (long)src->pub.bytes_in_buffer);
    315         src->pub.bytes_in_buffer -= (size_t)bytesToSkip;
    316         src->pub.next_input_byte += bytesToSkip;
    317 
    318         m_bytesToSkip = std::max(numBytes - bytesToSkip, static_cast<long>(0));
    319     }
    320 
    321     bool decode(const SharedBuffer& data, bool onlySize)
    322     {
    323         m_decodingSizeOnly = onlySize;
    324 
    325         unsigned newByteCount = data.size() - m_bufferLength;
    326         unsigned readOffset = m_bufferLength - m_info.src->bytes_in_buffer;
    327 
    328         m_info.src->bytes_in_buffer += newByteCount;
    329         m_info.src->next_input_byte = (JOCTET*)(data.data()) + readOffset;
    330 
    331         // If we still have bytes to skip, try to skip those now.
    332         if (m_bytesToSkip)
    333             skipBytes(m_bytesToSkip);
    334 
    335         m_bufferLength = data.size();
    336 
    337         // We need to do the setjmp here. Otherwise bad things will happen
    338         if (setjmp(m_err.setjmp_buffer))
    339             return m_decoder->setFailed();
    340 
    341         switch (m_state) {
    342         case JPEG_HEADER:
    343             // Read file parameters with jpeg_read_header().
    344             if (jpeg_read_header(&m_info, true) == JPEG_SUSPENDED)
    345                 return false; // I/O suspension.
    346 
    347             switch (m_info.jpeg_color_space) {
    348             case JCS_GRAYSCALE:
    349             case JCS_RGB:
    350             case JCS_YCbCr:
    351                 // libjpeg can convert GRAYSCALE and YCbCr image pixels to RGB.
    352                 m_info.out_color_space = rgbOutputColorSpace();
    353 #if defined(TURBO_JPEG_RGB_SWIZZLE)
    354                 if (m_info.saw_JFIF_marker)
    355                     break;
    356                 // FIXME: Swizzle decoding does not support Adobe transform=0
    357                 // images (yet), so revert to using JSC_RGB in that case.
    358                 if (m_info.saw_Adobe_marker && !m_info.Adobe_transform)
    359                     m_info.out_color_space = JCS_RGB;
    360 #endif
    361                 break;
    362             case JCS_CMYK:
    363             case JCS_YCCK:
    364                 // libjpeg can convert YCCK to CMYK, but neither to RGB, so we
    365                 // manually convert CMKY to RGB.
    366                 m_info.out_color_space = JCS_CMYK;
    367                 break;
    368             default:
    369                 return m_decoder->setFailed();
    370             }
    371 
    372             m_state = JPEG_START_DECOMPRESS;
    373 
    374             // We can fill in the size now that the header is available.
    375             if (!m_decoder->setSize(m_info.image_width, m_info.image_height))
    376                 return false;
    377 
    378             m_decoder->setOrientation(readImageOrientation(info()));
    379 
    380 #if USE(QCMSLIB)
    381             // Allow color management of the decoded RGBA pixels if possible.
    382             if (!m_decoder->ignoresGammaAndColorProfile()) {
    383                 ColorProfile colorProfile;
    384                 readColorProfile(info(), colorProfile);
    385                 createColorTransform(colorProfile, colorSpaceHasAlpha(m_info.out_color_space));
    386 #if defined(TURBO_JPEG_RGB_SWIZZLE)
    387                 // Input RGBA data to qcms. Note: restored to BGRA on output.
    388                 if (m_transform && m_info.out_color_space == JCS_EXT_BGRA)
    389                     m_info.out_color_space = JCS_EXT_RGBA;
    390 #endif
    391             }
    392 #endif
    393             // Don't allocate a giant and superfluous memory buffer when the
    394             // image is a sequential JPEG.
    395             m_info.buffered_image = jpeg_has_multiple_scans(&m_info);
    396 
    397             // Used to set up image size so arrays can be allocated.
    398             jpeg_calc_output_dimensions(&m_info);
    399 
    400             // Make a one-row-high sample array that will go away when done with
    401             // image. Always make it big enough to hold an RGB row. Since this
    402             // uses the IJG memory manager, it must be allocated before the call
    403             // to jpeg_start_compress().
    404             // FIXME: note that some output color spaces do not need the samples
    405             // buffer. Remove this allocation for those color spaces.
    406             m_samples = (*m_info.mem->alloc_sarray)((j_common_ptr) &m_info, JPOOL_IMAGE, m_info.output_width * 4, 1);
    407 
    408             if (m_decodingSizeOnly) {
    409                 // We can stop here. Reduce our buffer length and available data.
    410                 m_bufferLength -= m_info.src->bytes_in_buffer;
    411                 m_info.src->bytes_in_buffer = 0;
    412                 return true;
    413             }
    414         // FALL THROUGH
    415 
    416         case JPEG_START_DECOMPRESS:
    417             // Set parameters for decompression.
    418             // FIXME -- Should reset dct_method and dither mode for final pass
    419             // of progressive JPEG.
    420             m_info.dct_method = dctMethod();
    421             m_info.dither_mode = ditherMode();
    422             m_info.do_fancy_upsampling = doFancyUpsampling();
    423             m_info.enable_2pass_quant = false;
    424             m_info.do_block_smoothing = true;
    425 
    426             // Start decompressor.
    427             if (!jpeg_start_decompress(&m_info))
    428                 return false; // I/O suspension.
    429 
    430             // If this is a progressive JPEG ...
    431             m_state = (m_info.buffered_image) ? JPEG_DECOMPRESS_PROGRESSIVE : JPEG_DECOMPRESS_SEQUENTIAL;
    432         // FALL THROUGH
    433 
    434         case JPEG_DECOMPRESS_SEQUENTIAL:
    435             if (m_state == JPEG_DECOMPRESS_SEQUENTIAL) {
    436 
    437                 if (!m_decoder->outputScanlines())
    438                     return false; // I/O suspension.
    439 
    440                 // If we've completed image output...
    441                 ASSERT(m_info.output_scanline == m_info.output_height);
    442                 m_state = JPEG_DONE;
    443             }
    444         // FALL THROUGH
    445 
    446         case JPEG_DECOMPRESS_PROGRESSIVE:
    447             if (m_state == JPEG_DECOMPRESS_PROGRESSIVE) {
    448                 int status;
    449                 do {
    450                     status = jpeg_consume_input(&m_info);
    451                 } while ((status != JPEG_SUSPENDED) && (status != JPEG_REACHED_EOI));
    452 
    453                 for (;;) {
    454                     if (!m_info.output_scanline) {
    455                         int scan = m_info.input_scan_number;
    456 
    457                         // If we haven't displayed anything yet
    458                         // (output_scan_number == 0) and we have enough data for
    459                         // a complete scan, force output of the last full scan.
    460                         if (!m_info.output_scan_number && (scan > 1) && (status != JPEG_REACHED_EOI))
    461                             --scan;
    462 
    463                         if (!jpeg_start_output(&m_info, scan))
    464                             return false; // I/O suspension.
    465                     }
    466 
    467                     if (m_info.output_scanline == 0xffffff)
    468                         m_info.output_scanline = 0;
    469 
    470                     // If outputScanlines() fails, it deletes |this|. Therefore,
    471                     // copy the decoder pointer and use it to check for failure
    472                     // to avoid member access in the failure case.
    473                     JPEGImageDecoder* decoder = m_decoder;
    474                     if (!decoder->outputScanlines()) {
    475                         if (decoder->failed()) // Careful; |this| is deleted.
    476                             return false;
    477                         if (!m_info.output_scanline)
    478                             // Didn't manage to read any lines - flag so we
    479                             // don't call jpeg_start_output() multiple times for
    480                             // the same scan.
    481                             m_info.output_scanline = 0xffffff;
    482                         return false; // I/O suspension.
    483                     }
    484 
    485                     if (m_info.output_scanline == m_info.output_height) {
    486                         if (!jpeg_finish_output(&m_info))
    487                             return false; // I/O suspension.
    488 
    489                         if (jpeg_input_complete(&m_info) && (m_info.input_scan_number == m_info.output_scan_number))
    490                             break;
    491 
    492                         m_info.output_scanline = 0;
    493                     }
    494                 }
    495 
    496                 m_state = JPEG_DONE;
    497             }
    498         // FALL THROUGH
    499 
    500         case JPEG_DONE:
    501             // Finish decompression.
    502             return jpeg_finish_decompress(&m_info);
    503 
    504         case JPEG_ERROR:
    505             // We can get here if the constructor failed.
    506             return m_decoder->setFailed();
    507         }
    508 
    509         return true;
    510     }
    511 
    512     jpeg_decompress_struct* info() { return &m_info; }
    513     JSAMPARRAY samples() const { return m_samples; }
    514     JPEGImageDecoder* decoder() { return m_decoder; }
    515 #if USE(QCMSLIB)
    516     qcms_transform* colorTransform() const { return m_transform; }
    517 
    518     void createColorTransform(const ColorProfile& colorProfile, bool hasAlpha)
    519     {
    520         if (m_transform)
    521             qcms_transform_release(m_transform);
    522         m_transform = 0;
    523 
    524         if (colorProfile.isEmpty())
    525             return;
    526         qcms_profile* deviceProfile = ImageDecoder::qcmsOutputDeviceProfile();
    527         if (!deviceProfile)
    528             return;
    529         qcms_profile* inputProfile = qcms_profile_from_memory(colorProfile.data(), colorProfile.size());
    530         if (!inputProfile)
    531             return;
    532         // We currently only support color profiles for RGB profiled images.
    533         ASSERT(icSigRgbData == qcms_profile_get_color_space(inputProfile));
    534         qcms_data_type dataFormat = hasAlpha ? QCMS_DATA_RGBA_8 : QCMS_DATA_RGB_8;
    535         // FIXME: Don't force perceptual intent if the image profile contains an intent.
    536         m_transform = qcms_transform_create(inputProfile, dataFormat, deviceProfile, dataFormat, QCMS_INTENT_PERCEPTUAL);
    537         qcms_profile_release(inputProfile);
    538     }
    539 #endif
    540 
    541 private:
    542     JPEGImageDecoder* m_decoder;
    543     unsigned m_bufferLength;
    544     int m_bytesToSkip;
    545     bool m_decodingSizeOnly;
    546 
    547     jpeg_decompress_struct m_info;
    548     decoder_error_mgr m_err;
    549     jstate m_state;
    550 
    551     JSAMPARRAY m_samples;
    552 
    553 #if USE(QCMSLIB)
    554     qcms_transform* m_transform;
    555 #endif
    556 };
    557 
    558 // Override the standard error method in the IJG JPEG decoder code.
    559 void error_exit(j_common_ptr cinfo)
    560 {
    561     // Return control to the setjmp point.
    562     decoder_error_mgr *err = reinterpret_cast_ptr<decoder_error_mgr *>(cinfo->err);
    563     longjmp(err->setjmp_buffer, -1);
    564 }
    565 
    566 void init_source(j_decompress_ptr)
    567 {
    568 }
    569 
    570 void skip_input_data(j_decompress_ptr jd, long num_bytes)
    571 {
    572     decoder_source_mgr *src = (decoder_source_mgr *)jd->src;
    573     src->decoder->skipBytes(num_bytes);
    574 }
    575 
    576 boolean fill_input_buffer(j_decompress_ptr)
    577 {
    578     // Our decode step always sets things up properly, so if this method is ever
    579     // called, then we have hit the end of the buffer.  A return value of false
    580     // indicates that we have no data to supply yet.
    581     return false;
    582 }
    583 
    584 void term_source(j_decompress_ptr jd)
    585 {
    586     decoder_source_mgr *src = (decoder_source_mgr *)jd->src;
    587     src->decoder->decoder()->jpegComplete();
    588 }
    589 
    590 JPEGImageDecoder::JPEGImageDecoder(ImageSource::AlphaOption alphaOption,
    591                                    ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption)
    592     : ImageDecoder(alphaOption, gammaAndColorProfileOption)
    593 {
    594 }
    595 
    596 JPEGImageDecoder::~JPEGImageDecoder()
    597 {
    598 }
    599 
    600 bool JPEGImageDecoder::isSizeAvailable()
    601 {
    602     if (!ImageDecoder::isSizeAvailable())
    603          decode(true);
    604 
    605     return ImageDecoder::isSizeAvailable();
    606 }
    607 
    608 ImageFrame* JPEGImageDecoder::frameBufferAtIndex(size_t index)
    609 {
    610     if (index)
    611         return 0;
    612 
    613     if (m_frameBufferCache.isEmpty()) {
    614         m_frameBufferCache.resize(1);
    615         m_frameBufferCache[0].setPremultiplyAlpha(m_premultiplyAlpha);
    616     }
    617 
    618     ImageFrame& frame = m_frameBufferCache[0];
    619     if (frame.status() != ImageFrame::FrameComplete) {
    620         PlatformInstrumentation::willDecodeImage("JPEG");
    621         decode(false);
    622         PlatformInstrumentation::didDecodeImage();
    623     }
    624     return &frame;
    625 }
    626 
    627 bool JPEGImageDecoder::setFailed()
    628 {
    629     m_reader.clear();
    630     return ImageDecoder::setFailed();
    631 }
    632 
    633 template <J_COLOR_SPACE colorSpace> void setPixel(ImageFrame& buffer, ImageFrame::PixelData* pixel, JSAMPARRAY samples, int column)
    634 {
    635     JSAMPLE* jsample = *samples + column * (colorSpace == JCS_RGB ? 3 : 4);
    636 
    637     switch (colorSpace) {
    638     case JCS_RGB:
    639         buffer.setRGBARaw(pixel, jsample[0], jsample[1], jsample[2], 255);
    640         break;
    641     case JCS_CMYK:
    642         // Source is 'Inverted CMYK', output is RGB.
    643         // See: http://www.easyrgb.com/math.php?MATH=M12#text12
    644         // Or: http://www.ilkeratalay.com/colorspacesfaq.php#rgb
    645         // From CMYK to CMY:
    646         // X =   X    * (1 -   K   ) +   K  [for X = C, M, or Y]
    647         // Thus, from Inverted CMYK to CMY is:
    648         // X = (1-iX) * (1 - (1-iK)) + (1-iK) => 1 - iX*iK
    649         // From CMY (0..1) to RGB (0..1):
    650         // R = 1 - C => 1 - (1 - iC*iK) => iC*iK  [G and B similar]
    651         unsigned k = jsample[3];
    652         buffer.setRGBARaw(pixel, jsample[0] * k / 255, jsample[1] * k / 255, jsample[2] * k / 255, 255);
    653         break;
    654     }
    655 }
    656 
    657 template <J_COLOR_SPACE colorSpace> bool outputRows(JPEGImageReader* reader, ImageFrame& buffer)
    658 {
    659     JSAMPARRAY samples = reader->samples();
    660     jpeg_decompress_struct* info = reader->info();
    661     int width = info->output_width;
    662 
    663     while (info->output_scanline < info->output_height) {
    664         // jpeg_read_scanlines will increase the scanline counter, so we
    665         // save the scanline before calling it.
    666         int y = info->output_scanline;
    667         // Request one scanline: returns 0 or 1 scanlines.
    668         if (jpeg_read_scanlines(info, samples, 1) != 1)
    669             return false;
    670 #if USE(QCMSLIB)
    671         if (reader->colorTransform() && colorSpace == JCS_RGB)
    672             qcms_transform_data(reader->colorTransform(), *samples, *samples, width);
    673 #endif
    674         ImageFrame::PixelData* pixel = buffer.getAddr(0, y);
    675         for (int x = 0; x < width; ++pixel, ++x)
    676             setPixel<colorSpace>(buffer, pixel, samples, x);
    677     }
    678 
    679     return true;
    680 }
    681 
    682 bool JPEGImageDecoder::outputScanlines()
    683 {
    684     if (m_frameBufferCache.isEmpty())
    685         return false;
    686 
    687     // Initialize the framebuffer if needed.
    688     ImageFrame& buffer = m_frameBufferCache[0];
    689     if (buffer.status() == ImageFrame::FrameEmpty) {
    690         if (!buffer.setSize(size().width(), size().height()))
    691             return setFailed();
    692         buffer.setStatus(ImageFrame::FramePartial);
    693         // The buffer is transparent outside the decoded area while the image is
    694         // loading. The completed image will be marked fully opaque in jpegComplete().
    695         buffer.setHasAlpha(true);
    696 
    697         // For JPEGs, the frame always fills the entire image.
    698         buffer.setOriginalFrameRect(IntRect(IntPoint(), size()));
    699     }
    700 
    701     jpeg_decompress_struct* info = m_reader->info();
    702 
    703 #if defined(TURBO_JPEG_RGB_SWIZZLE)
    704     if (turboSwizzled(info->out_color_space)) {
    705         while (info->output_scanline < info->output_height) {
    706             unsigned char* row = reinterpret_cast<unsigned char*>(buffer.getAddr(0, info->output_scanline));
    707             if (jpeg_read_scanlines(info, &row, 1) != 1)
    708                 return false;
    709 #if USE(QCMSLIB)
    710             if (qcms_transform* transform = m_reader->colorTransform())
    711                 qcms_transform_data_type(transform, row, row, info->output_width, rgbOutputColorSpace() == JCS_EXT_BGRA ? QCMS_OUTPUT_BGRX : QCMS_OUTPUT_RGBX);
    712 #endif
    713          }
    714          return true;
    715      }
    716 #endif
    717 
    718     switch (info->out_color_space) {
    719     case JCS_RGB:
    720         return outputRows<JCS_RGB>(m_reader.get(), buffer);
    721     case JCS_CMYK:
    722         return outputRows<JCS_CMYK>(m_reader.get(), buffer);
    723     default:
    724         ASSERT_NOT_REACHED();
    725     }
    726 
    727     return setFailed();
    728 }
    729 
    730 void JPEGImageDecoder::jpegComplete()
    731 {
    732     if (m_frameBufferCache.isEmpty())
    733         return;
    734 
    735     // Hand back an appropriately sized buffer, even if the image ended up being
    736     // empty.
    737     ImageFrame& buffer = m_frameBufferCache[0];
    738     buffer.setHasAlpha(false);
    739     buffer.setStatus(ImageFrame::FrameComplete);
    740 }
    741 
    742 void JPEGImageDecoder::decode(bool onlySize)
    743 {
    744     if (failed())
    745         return;
    746 
    747     if (!m_reader)
    748         m_reader = adoptPtr(new JPEGImageReader(this));
    749 
    750     // If we couldn't decode the image but we've received all the data, decoding
    751     // has failed.
    752     if (!m_reader->decode(*m_data, onlySize) && isAllDataReceived())
    753         setFailed();
    754     // If we're done decoding the image, we don't need the JPEGImageReader
    755     // anymore.  (If we failed, |m_reader| has already been cleared.)
    756     else if (!m_frameBufferCache.isEmpty() && (m_frameBufferCache[0].status() == ImageFrame::FrameComplete))
    757         m_reader.clear();
    758 }
    759 
    760 }
    761