1/*
2 * Copyright (C) 2006 Apple 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 <wtf/PassOwnPtr.h>
43
44extern "C" {
45#if USE(ICCJPEG)
46#include "iccjpeg.h"
47#endif
48#if USE(QCMSLIB)
49#include "qcms.h"
50#endif
51#include <setjmp.h>
52}
53
54#if CPU(BIG_ENDIAN) || CPU(MIDDLE_ENDIAN)
55#define ASSUME_LITTLE_ENDIAN 0
56#else
57#define ASSUME_LITTLE_ENDIAN 1
58#endif
59
60#if defined(JCS_ALPHA_EXTENSIONS) && ASSUME_LITTLE_ENDIAN
61#define TURBO_JPEG_RGB_SWIZZLE
62inline J_COLOR_SPACE rgbOutputColorSpace() { return JCS_EXT_BGRA; }
63inline bool turboSwizzled(J_COLOR_SPACE colorSpace) { return colorSpace == JCS_EXT_RGBA || colorSpace == JCS_EXT_BGRA; }
64inline bool colorSpaceHasAlpha(J_COLOR_SPACE colorSpace) { return turboSwizzled(colorSpace); }
65#else
66inline J_COLOR_SPACE rgbOutputColorSpace() { return JCS_RGB; }
67inline bool colorSpaceHasAlpha(J_COLOR_SPACE) { return false; }
68#endif
69
70#if USE(LOW_QUALITY_IMAGE_NO_JPEG_DITHERING)
71inline J_DCT_METHOD dctMethod() { return JDCT_IFAST; }
72inline J_DITHER_MODE ditherMode() { return JDITHER_NONE; }
73#else
74inline J_DCT_METHOD dctMethod() { return JDCT_ISLOW; }
75inline J_DITHER_MODE ditherMode() { return JDITHER_FS; }
76#endif
77
78#if USE(LOW_QUALITY_IMAGE_NO_JPEG_FANCY_UPSAMPLING)
79inline bool doFancyUpsampling() { return false; }
80#else
81inline bool doFancyUpsampling() { return true; }
82#endif
83
84const int exifMarker = JPEG_APP0 + 1;
85
86namespace WebCore {
87
88struct decoder_error_mgr {
89    struct jpeg_error_mgr pub; // "public" fields for IJG library
90    jmp_buf setjmp_buffer;     // For handling catastropic errors
91};
92
93enum jstate {
94    JPEG_HEADER,                 // Reading JFIF headers
95    JPEG_START_DECOMPRESS,
96    JPEG_DECOMPRESS_PROGRESSIVE, // Output progressive pixels
97    JPEG_DECOMPRESS_SEQUENTIAL,  // Output sequential pixels
98    JPEG_DONE,
99    JPEG_ERROR
100};
101
102void init_source(j_decompress_ptr jd);
103boolean fill_input_buffer(j_decompress_ptr jd);
104void skip_input_data(j_decompress_ptr jd, long num_bytes);
105void term_source(j_decompress_ptr jd);
106void error_exit(j_common_ptr cinfo);
107
108// Implementation of a JPEG src object that understands our state machine
109struct decoder_source_mgr {
110    // public fields; must be first in this struct!
111    struct jpeg_source_mgr pub;
112
113    JPEGImageReader* decoder;
114};
115
116static unsigned readUint16(JOCTET* data, bool isBigEndian)
117{
118    if (isBigEndian)
119        return (GETJOCTET(data[0]) << 8) | GETJOCTET(data[1]);
120    return (GETJOCTET(data[1]) << 8) | GETJOCTET(data[0]);
121}
122
123static unsigned readUint32(JOCTET* data, bool isBigEndian)
124{
125    if (isBigEndian)
126        return (GETJOCTET(data[0]) << 24) | (GETJOCTET(data[1]) << 16) | (GETJOCTET(data[2]) << 8) | GETJOCTET(data[3]);
127    return (GETJOCTET(data[3]) << 24) | (GETJOCTET(data[2]) << 16) | (GETJOCTET(data[1]) << 8) | GETJOCTET(data[0]);
128}
129
130static bool checkExifHeader(jpeg_saved_marker_ptr marker, bool& isBigEndian, unsigned& ifdOffset)
131{
132    // For exif data, the APP1 block is followed by 'E', 'x', 'i', 'f', '\0',
133    // then a fill byte, and then a tiff file that contains the metadata.
134    // A tiff file starts with 'I', 'I' (intel / little endian byte order) or
135    // 'M', 'M' (motorola / big endian byte order), followed by (uint16_t)42,
136    // followed by an uint32_t with the offset to the tag block, relative to the
137    // tiff file start.
138    const unsigned exifHeaderSize = 14;
139    if (!(marker->marker == exifMarker
140        && marker->data_length >= exifHeaderSize
141        && marker->data[0] == 'E'
142        && marker->data[1] == 'x'
143        && marker->data[2] == 'i'
144        && marker->data[3] == 'f'
145        && marker->data[4] == '\0'
146        // data[5] is a fill byte
147        && ((marker->data[6] == 'I' && marker->data[7] == 'I')
148            || (marker->data[6] == 'M' && marker->data[7] == 'M'))))
149        return false;
150
151    isBigEndian = marker->data[6] == 'M';
152    if (readUint16(marker->data + 8, isBigEndian) != 42)
153        return false;
154
155    ifdOffset = readUint32(marker->data + 10, isBigEndian);
156    return true;
157}
158
159static ImageOrientation readImageOrientation(jpeg_decompress_struct* info)
160{
161    // The JPEG decoder looks at EXIF metadata.
162    // FIXME: Possibly implement XMP and IPTC support.
163    const unsigned orientationTag = 0x112;
164    const unsigned shortType = 3;
165    for (jpeg_saved_marker_ptr marker = info->marker_list; marker; marker = marker->next) {
166        bool isBigEndian;
167        unsigned ifdOffset;
168        if (!checkExifHeader(marker, isBigEndian, ifdOffset))
169            continue;
170        const unsigned offsetToTiffData = 6; // Account for 'Exif\0<fill byte>' header.
171        if (marker->data_length < offsetToTiffData || ifdOffset >= marker->data_length - offsetToTiffData)
172            continue;
173        ifdOffset += offsetToTiffData;
174
175        // The jpeg exif container format contains a tiff block for metadata.
176        // A tiff image file directory (ifd) consists of a uint16_t describing
177        // the number of ifd entries, followed by that many entries.
178        // When touching this code, it's useful to look at the tiff spec:
179        // http://partners.adobe.com/public/developer/en/tiff/TIFF6.pdf
180        JOCTET* ifd = marker->data + ifdOffset;
181        JOCTET* end = marker->data + marker->data_length;
182        if (end - ifd < 2)
183            continue;
184        unsigned tagCount = readUint16(ifd, isBigEndian);
185        ifd += 2; // Skip over the uint16 that was just read.
186
187        // Every ifd entry is 2 bytes of tag, 2 bytes of contents datatype,
188        // 4 bytes of number-of-elements, and 4 bytes of either offset to the
189        // tag data, or if the data is small enough, the inlined data itself.
190        const int ifdEntrySize = 12;
191        for (unsigned i = 0; i < tagCount && end - ifd >= ifdEntrySize; ++i, ifd += ifdEntrySize) {
192            unsigned tag = readUint16(ifd, isBigEndian);
193            unsigned type = readUint16(ifd + 2, isBigEndian);
194            unsigned count = readUint32(ifd + 4, isBigEndian);
195            if (tag == orientationTag && type == shortType && count == 1)
196                return ImageOrientation::fromEXIFValue(readUint16(ifd + 8, isBigEndian));
197        }
198    }
199
200    return ImageOrientation();
201}
202
203static ColorProfile readColorProfile(jpeg_decompress_struct* info)
204{
205#if USE(ICCJPEG)
206    JOCTET* profile;
207    unsigned int profileLength;
208
209    if (!read_icc_profile(info, &profile, &profileLength))
210        return ColorProfile();
211
212    // Only accept RGB color profiles from input class devices.
213    bool ignoreProfile = false;
214    char* profileData = reinterpret_cast<char*>(profile);
215    if (profileLength < ImageDecoder::iccColorProfileHeaderLength)
216        ignoreProfile = true;
217    else if (!ImageDecoder::rgbColorProfile(profileData, profileLength))
218        ignoreProfile = true;
219    else if (!ImageDecoder::inputDeviceColorProfile(profileData, profileLength))
220        ignoreProfile = true;
221
222    ColorProfile colorProfile;
223    if (!ignoreProfile)
224        colorProfile.append(profileData, profileLength);
225    free(profile);
226    return colorProfile;
227#else
228    UNUSED_PARAM(info);
229    return ColorProfile();
230#endif
231}
232
233class JPEGImageReader {
234    WTF_MAKE_FAST_ALLOCATED;
235public:
236    JPEGImageReader(JPEGImageDecoder* decoder)
237        : m_decoder(decoder)
238        , m_bufferLength(0)
239        , m_bytesToSkip(0)
240        , m_state(JPEG_HEADER)
241        , m_samples(0)
242#if USE(QCMSLIB)
243        , m_transform(0)
244#endif
245    {
246        memset(&m_info, 0, sizeof(jpeg_decompress_struct));
247
248        // We set up the normal JPEG error routines, then override error_exit.
249        m_info.err = jpeg_std_error(&m_err.pub);
250        m_err.pub.error_exit = error_exit;
251
252        // Allocate and initialize JPEG decompression object.
253        jpeg_create_decompress(&m_info);
254
255        decoder_source_mgr* src = 0;
256        if (!m_info.src) {
257            src = (decoder_source_mgr*)fastCalloc(sizeof(decoder_source_mgr), 1);
258            if (!src) {
259                m_state = JPEG_ERROR;
260                return;
261            }
262        }
263
264        m_info.src = (jpeg_source_mgr*)src;
265
266        // Set up callback functions.
267        src->pub.init_source = init_source;
268        src->pub.fill_input_buffer = fill_input_buffer;
269        src->pub.skip_input_data = skip_input_data;
270        src->pub.resync_to_restart = jpeg_resync_to_restart;
271        src->pub.term_source = term_source;
272        src->decoder = this;
273
274#if USE(ICCJPEG)
275        // Retain ICC color profile markers for color management.
276        setup_read_icc_profile(&m_info);
277#endif
278
279        // Keep APP1 blocks, for obtaining exif data.
280        jpeg_save_markers(&m_info, exifMarker, 0xFFFF);
281    }
282
283    ~JPEGImageReader()
284    {
285        close();
286    }
287
288    void close()
289    {
290        decoder_source_mgr* src = (decoder_source_mgr*)m_info.src;
291        if (src)
292            fastFree(src);
293        m_info.src = 0;
294
295#if USE(QCMSLIB)
296        if (m_transform)
297            qcms_transform_release(m_transform);
298        m_transform = 0;
299#endif
300        jpeg_destroy_decompress(&m_info);
301    }
302
303    void skipBytes(long numBytes)
304    {
305        decoder_source_mgr* src = (decoder_source_mgr*)m_info.src;
306        long bytesToSkip = std::min(numBytes, (long)src->pub.bytes_in_buffer);
307        src->pub.bytes_in_buffer -= (size_t)bytesToSkip;
308        src->pub.next_input_byte += bytesToSkip;
309
310        m_bytesToSkip = std::max(numBytes - bytesToSkip, static_cast<long>(0));
311    }
312
313    bool decode(const SharedBuffer& data, bool onlySize)
314    {
315        m_decodingSizeOnly = onlySize;
316
317        unsigned newByteCount = data.size() - m_bufferLength;
318        unsigned readOffset = m_bufferLength - m_info.src->bytes_in_buffer;
319
320        m_info.src->bytes_in_buffer += newByteCount;
321        m_info.src->next_input_byte = (JOCTET*)(data.data()) + readOffset;
322
323        // If we still have bytes to skip, try to skip those now.
324        if (m_bytesToSkip)
325            skipBytes(m_bytesToSkip);
326
327        m_bufferLength = data.size();
328
329        // We need to do the setjmp here. Otherwise bad things will happen
330        if (setjmp(m_err.setjmp_buffer))
331            return m_decoder->setFailed();
332
333        switch (m_state) {
334        case JPEG_HEADER:
335            // Read file parameters with jpeg_read_header().
336            if (jpeg_read_header(&m_info, TRUE) == JPEG_SUSPENDED)
337                return false; // I/O suspension.
338
339            switch (m_info.jpeg_color_space) {
340            case JCS_GRAYSCALE:
341            case JCS_RGB:
342            case JCS_YCbCr:
343                // libjpeg can convert GRAYSCALE and YCbCr image pixels to RGB.
344                m_info.out_color_space = rgbOutputColorSpace();
345#if defined(TURBO_JPEG_RGB_SWIZZLE)
346                if (m_info.saw_JFIF_marker)
347                    break;
348                // FIXME: Swizzle decoding does not support Adobe transform=0
349                // images (yet), so revert to using JSC_RGB in that case.
350                if (m_info.saw_Adobe_marker && !m_info.Adobe_transform)
351                    m_info.out_color_space = JCS_RGB;
352#endif
353                break;
354            case JCS_CMYK:
355            case JCS_YCCK:
356                // libjpeg can convert YCCK to CMYK, but neither to RGB, so we
357                // manually convert CMKY to RGB.
358                m_info.out_color_space = JCS_CMYK;
359                break;
360            default:
361                return m_decoder->setFailed();
362            }
363
364            m_state = JPEG_START_DECOMPRESS;
365
366            // We can fill in the size now that the header is available.
367            if (!m_decoder->setSize(m_info.image_width, m_info.image_height))
368                return false;
369
370            m_decoder->setOrientation(readImageOrientation(info()));
371
372#if ENABLE(IMAGE_DECODER_DOWN_SAMPLING) && defined(TURBO_JPEG_RGB_SWIZZLE)
373            // There's no point swizzle decoding if image down sampling will
374            // be applied. Revert to using JSC_RGB in that case.
375            if (m_decoder->willDownSample() && turboSwizzled(m_info.out_color_space))
376                m_info.out_color_space = JCS_RGB;
377#endif
378            // Allow color management of the decoded RGBA pixels if possible.
379            if (!m_decoder->ignoresGammaAndColorProfile()) {
380                ColorProfile rgbInputDeviceColorProfile = readColorProfile(info());
381                if (!rgbInputDeviceColorProfile.isEmpty())
382                    m_decoder->setColorProfile(rgbInputDeviceColorProfile);
383#if USE(QCMSLIB)
384                createColorTransform(rgbInputDeviceColorProfile, colorSpaceHasAlpha(m_info.out_color_space));
385#if defined(TURBO_JPEG_RGB_SWIZZLE)
386                // Input RGBA data to qcms. Note: restored to BGRA on output.
387                if (m_transform && m_info.out_color_space == JCS_EXT_BGRA)
388                    m_info.out_color_space = JCS_EXT_RGBA;
389#endif
390#endif
391            }
392
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() ? TRUE : FALSE;
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
541private:
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.
559void 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
566void init_source(j_decompress_ptr)
567{
568}
569
570void 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
576boolean 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
584void term_source(j_decompress_ptr jd)
585{
586    decoder_source_mgr *src = (decoder_source_mgr *)jd->src;
587    src->decoder->decoder()->jpegComplete();
588}
589
590JPEGImageDecoder::JPEGImageDecoder(ImageSource::AlphaOption alphaOption,
591                                   ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption)
592    : ImageDecoder(alphaOption, gammaAndColorProfileOption)
593{
594}
595
596JPEGImageDecoder::~JPEGImageDecoder()
597{
598}
599
600bool JPEGImageDecoder::isSizeAvailable()
601{
602    if (!ImageDecoder::isSizeAvailable())
603         decode(true);
604
605    return ImageDecoder::isSizeAvailable();
606}
607
608bool JPEGImageDecoder::setSize(unsigned width, unsigned height)
609{
610    if (!ImageDecoder::setSize(width, height))
611        return false;
612
613    prepareScaleDataIfNecessary();
614    return true;
615}
616
617ImageFrame* JPEGImageDecoder::frameBufferAtIndex(size_t index)
618{
619    if (index)
620        return 0;
621
622    if (m_frameBufferCache.isEmpty()) {
623        m_frameBufferCache.resize(1);
624        m_frameBufferCache[0].setPremultiplyAlpha(m_premultiplyAlpha);
625    }
626
627    ImageFrame& frame = m_frameBufferCache[0];
628    if (frame.status() != ImageFrame::FrameComplete)
629        decode(false);
630    return &frame;
631}
632
633bool JPEGImageDecoder::setFailed()
634{
635    m_reader.clear();
636    return ImageDecoder::setFailed();
637}
638
639template <J_COLOR_SPACE colorSpace>
640void setPixel(ImageFrame& buffer, ImageFrame::PixelData* currentAddress, JSAMPARRAY samples, int column)
641{
642    JSAMPLE* jsample = *samples + column * (colorSpace == JCS_RGB ? 3 : 4);
643
644    switch (colorSpace) {
645    case JCS_RGB:
646        buffer.setRGBA(currentAddress, jsample[0], jsample[1], jsample[2], 0xFF);
647        break;
648    case JCS_CMYK:
649        // Source is 'Inverted CMYK', output is RGB.
650        // See: http://www.easyrgb.com/math.php?MATH=M12#text12
651        // Or: http://www.ilkeratalay.com/colorspacesfaq.php#rgb
652        // From CMYK to CMY:
653        // X =   X    * (1 -   K   ) +   K  [for X = C, M, or Y]
654        // Thus, from Inverted CMYK to CMY is:
655        // X = (1-iX) * (1 - (1-iK)) + (1-iK) => 1 - iX*iK
656        // From CMY (0..1) to RGB (0..1):
657        // R = 1 - C => 1 - (1 - iC*iK) => iC*iK  [G and B similar]
658        unsigned k = jsample[3];
659        buffer.setRGBA(currentAddress, jsample[0] * k / 255, jsample[1] * k / 255, jsample[2] * k / 255, 0xFF);
660        break;
661    }
662}
663
664template <J_COLOR_SPACE colorSpace, bool isScaled>
665bool JPEGImageDecoder::outputScanlines(ImageFrame& buffer)
666{
667    JSAMPARRAY samples = m_reader->samples();
668    jpeg_decompress_struct* info = m_reader->info();
669    int width = isScaled ? m_scaledColumns.size() : info->output_width;
670
671    while (info->output_scanline < info->output_height) {
672        // jpeg_read_scanlines will increase the scanline counter, so we
673        // save the scanline before calling it.
674        int sourceY = info->output_scanline;
675        /* Request one scanline.  Returns 0 or 1 scanlines. */
676        if (jpeg_read_scanlines(info, samples, 1) != 1)
677            return false;
678
679        int destY = scaledY(sourceY);
680        if (destY < 0)
681            continue;
682
683#if USE(QCMSLIB)
684        if (m_reader->colorTransform() && colorSpace == JCS_RGB)
685            qcms_transform_data(m_reader->colorTransform(), *samples, *samples, info->output_width);
686#endif
687
688        ImageFrame::PixelData* currentAddress = buffer.getAddr(0, destY);
689        for (int x = 0; x < width; ++x) {
690            setPixel<colorSpace>(buffer, currentAddress, samples, isScaled ? m_scaledColumns[x] : x);
691            ++currentAddress;
692        }
693    }
694    return true;
695}
696
697template <J_COLOR_SPACE colorSpace>
698bool JPEGImageDecoder::outputScanlines(ImageFrame& buffer)
699{
700    return m_scaled ? outputScanlines<colorSpace, true>(buffer) : outputScanlines<colorSpace, false>(buffer);
701}
702
703bool JPEGImageDecoder::outputScanlines()
704{
705    if (m_frameBufferCache.isEmpty())
706        return false;
707
708    // Initialize the framebuffer if needed.
709    ImageFrame& buffer = m_frameBufferCache[0];
710    if (buffer.status() == ImageFrame::FrameEmpty) {
711        if (!buffer.setSize(scaledSize().width(), scaledSize().height()))
712            return setFailed();
713        buffer.setStatus(ImageFrame::FramePartial);
714        // The buffer is transparent outside the decoded area while the image is
715        // loading. The completed image will be marked fully opaque in jpegComplete().
716        buffer.setHasAlpha(true);
717        buffer.setColorProfile(m_colorProfile);
718
719        // For JPEGs, the frame always fills the entire image.
720        buffer.setOriginalFrameRect(IntRect(IntPoint(), size()));
721    }
722
723    jpeg_decompress_struct* info = m_reader->info();
724
725#if defined(TURBO_JPEG_RGB_SWIZZLE)
726    if (!m_scaled && turboSwizzled(info->out_color_space)) {
727        while (info->output_scanline < info->output_height) {
728            unsigned char* row = reinterpret_cast<unsigned char*>(buffer.getAddr(0, info->output_scanline));
729            if (jpeg_read_scanlines(info, &row, 1) != 1)
730                return false;
731#if USE(QCMSLIB)
732            if (qcms_transform* transform = m_reader->colorTransform())
733                qcms_transform_data_type(transform, row, row, info->output_width, rgbOutputColorSpace() == JCS_EXT_BGRA ? QCMS_OUTPUT_BGRX : QCMS_OUTPUT_RGBX);
734#endif
735         }
736         return true;
737     }
738#endif
739
740    switch (info->out_color_space) {
741    // The code inside outputScanlines<int, bool> will be executed
742    // for each pixel, so we want to avoid any extra comparisons there.
743    // That is why we use template and template specializations here so
744    // the proper code will be generated at compile time.
745    case JCS_RGB:
746        return outputScanlines<JCS_RGB>(buffer);
747    case JCS_CMYK:
748        return outputScanlines<JCS_CMYK>(buffer);
749    default:
750        ASSERT_NOT_REACHED();
751    }
752
753    return setFailed();
754}
755
756void JPEGImageDecoder::jpegComplete()
757{
758    if (m_frameBufferCache.isEmpty())
759        return;
760
761    // Hand back an appropriately sized buffer, even if the image ended up being
762    // empty.
763    ImageFrame& buffer = m_frameBufferCache[0];
764    buffer.setHasAlpha(false);
765    buffer.setStatus(ImageFrame::FrameComplete);
766}
767
768void JPEGImageDecoder::decode(bool onlySize)
769{
770    if (failed())
771        return;
772
773    if (!m_reader)
774        m_reader = adoptPtr(new JPEGImageReader(this));
775
776    // If we couldn't decode the image but we've received all the data, decoding
777    // has failed.
778    if (!m_reader->decode(*m_data, onlySize) && isAllDataReceived())
779        setFailed();
780    // If we're done decoding the image, we don't need the JPEGImageReader
781    // anymore.  (If we failed, |m_reader| has already been cleared.)
782    else if (!m_frameBufferCache.isEmpty() && (m_frameBufferCache[0].status() == ImageFrame::FrameComplete))
783        m_reader.clear();
784}
785
786}
787