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