Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / platform / image-decoders / jpeg / JPEGImageDecoder.cpp
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 "platform/image-decoders/jpeg/JPEGImageDecoder.h"
42
43 #include "platform/PlatformInstrumentation.h"
44 #include "wtf/PassOwnPtr.h"
45 #include "wtf/dtoa/utils.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 #error Blink assumes a little-endian target.
61 #endif
62
63 #if defined(JCS_ALPHA_EXTENSIONS)
64 #define TURBO_JPEG_RGB_SWIZZLE
65 #if SK_B32_SHIFT // Output little-endian RGBA pixels (Android).
66 inline J_COLOR_SPACE rgbOutputColorSpace() { return JCS_EXT_RGBA; }
67 #else // Output little-endian BGRA pixels.
68 inline J_COLOR_SPACE rgbOutputColorSpace() { return JCS_EXT_BGRA; }
69 #endif
70 inline bool turboSwizzled(J_COLOR_SPACE colorSpace) { return colorSpace == JCS_EXT_RGBA || colorSpace == JCS_EXT_BGRA; }
71 inline bool colorSpaceHasAlpha(J_COLOR_SPACE colorSpace) { return turboSwizzled(colorSpace); }
72 #else
73 inline J_COLOR_SPACE rgbOutputColorSpace() { return JCS_RGB; }
74 inline bool colorSpaceHasAlpha(J_COLOR_SPACE) { return false; }
75 #endif
76
77 #if USE(LOW_QUALITY_IMAGE_NO_JPEG_DITHERING)
78 inline J_DCT_METHOD dctMethod() { return JDCT_IFAST; }
79 inline J_DITHER_MODE ditherMode() { return JDITHER_NONE; }
80 #else
81 inline J_DCT_METHOD dctMethod() { return JDCT_ISLOW; }
82 inline J_DITHER_MODE ditherMode() { return JDITHER_FS; }
83 #endif
84
85 #if USE(LOW_QUALITY_IMAGE_NO_JPEG_FANCY_UPSAMPLING)
86 inline bool doFancyUpsampling() { return false; }
87 #else
88 inline bool doFancyUpsampling() { return true; }
89 #endif
90
91 namespace {
92
93 const int exifMarker = JPEG_APP0 + 1;
94
95 // JPEG only supports a denominator of 8.
96 const unsigned scaleDenominator = 8;
97
98 } // namespace
99
100 namespace blink {
101
102 struct decoder_error_mgr {
103     struct jpeg_error_mgr pub; // "public" fields for IJG library
104     jmp_buf setjmp_buffer;     // For handling catastropic errors
105 };
106
107 enum jstate {
108     JPEG_HEADER,                 // Reading JFIF headers
109     JPEG_START_DECOMPRESS,
110     JPEG_DECOMPRESS_PROGRESSIVE, // Output progressive pixels
111     JPEG_DECOMPRESS_SEQUENTIAL,  // Output sequential pixels
112     JPEG_DONE,
113     JPEG_ERROR
114 };
115
116 enum yuv_subsampling {
117     YUV_UNKNOWN,
118     YUV_410,
119     YUV_411,
120     YUV_420,
121     YUV_422,
122     YUV_440,
123     YUV_444
124 };
125
126 void init_source(j_decompress_ptr jd);
127 boolean fill_input_buffer(j_decompress_ptr jd);
128 void skip_input_data(j_decompress_ptr jd, long num_bytes);
129 void term_source(j_decompress_ptr jd);
130 void error_exit(j_common_ptr cinfo);
131
132 // Implementation of a JPEG src object that understands our state machine
133 struct decoder_source_mgr {
134     // public fields; must be first in this struct!
135     struct jpeg_source_mgr pub;
136
137     JPEGImageReader* decoder;
138 };
139
140 static unsigned readUint16(JOCTET* data, bool isBigEndian)
141 {
142     if (isBigEndian)
143         return (GETJOCTET(data[0]) << 8) | GETJOCTET(data[1]);
144     return (GETJOCTET(data[1]) << 8) | GETJOCTET(data[0]);
145 }
146
147 static unsigned readUint32(JOCTET* data, bool isBigEndian)
148 {
149     if (isBigEndian)
150         return (GETJOCTET(data[0]) << 24) | (GETJOCTET(data[1]) << 16) | (GETJOCTET(data[2]) << 8) | GETJOCTET(data[3]);
151     return (GETJOCTET(data[3]) << 24) | (GETJOCTET(data[2]) << 16) | (GETJOCTET(data[1]) << 8) | GETJOCTET(data[0]);
152 }
153
154 static bool checkExifHeader(jpeg_saved_marker_ptr marker, bool& isBigEndian, unsigned& ifdOffset)
155 {
156     // For exif data, the APP1 block is followed by 'E', 'x', 'i', 'f', '\0',
157     // then a fill byte, and then a tiff file that contains the metadata.
158     // A tiff file starts with 'I', 'I' (intel / little endian byte order) or
159     // 'M', 'M' (motorola / big endian byte order), followed by (uint16_t)42,
160     // followed by an uint32_t with the offset to the tag block, relative to the
161     // tiff file start.
162     const unsigned exifHeaderSize = 14;
163     if (!(marker->marker == exifMarker
164         && marker->data_length >= exifHeaderSize
165         && marker->data[0] == 'E'
166         && marker->data[1] == 'x'
167         && marker->data[2] == 'i'
168         && marker->data[3] == 'f'
169         && marker->data[4] == '\0'
170         // data[5] is a fill byte
171         && ((marker->data[6] == 'I' && marker->data[7] == 'I')
172             || (marker->data[6] == 'M' && marker->data[7] == 'M'))))
173         return false;
174
175     isBigEndian = marker->data[6] == 'M';
176     if (readUint16(marker->data + 8, isBigEndian) != 42)
177         return false;
178
179     ifdOffset = readUint32(marker->data + 10, isBigEndian);
180     return true;
181 }
182
183 static ImageOrientation readImageOrientation(jpeg_decompress_struct* info)
184 {
185     // The JPEG decoder looks at EXIF metadata.
186     // FIXME: Possibly implement XMP and IPTC support.
187     const unsigned orientationTag = 0x112;
188     const unsigned shortType = 3;
189     for (jpeg_saved_marker_ptr marker = info->marker_list; marker; marker = marker->next) {
190         bool isBigEndian;
191         unsigned ifdOffset;
192         if (!checkExifHeader(marker, isBigEndian, ifdOffset))
193             continue;
194         const unsigned offsetToTiffData = 6; // Account for 'Exif\0<fill byte>' header.
195         if (marker->data_length < offsetToTiffData || ifdOffset >= marker->data_length - offsetToTiffData)
196             continue;
197         ifdOffset += offsetToTiffData;
198
199         // The jpeg exif container format contains a tiff block for metadata.
200         // A tiff image file directory (ifd) consists of a uint16_t describing
201         // the number of ifd entries, followed by that many entries.
202         // When touching this code, it's useful to look at the tiff spec:
203         // http://partners.adobe.com/public/developer/en/tiff/TIFF6.pdf
204         JOCTET* ifd = marker->data + ifdOffset;
205         JOCTET* end = marker->data + marker->data_length;
206         if (end - ifd < 2)
207             continue;
208         unsigned tagCount = readUint16(ifd, isBigEndian);
209         ifd += 2; // Skip over the uint16 that was just read.
210
211         // Every ifd entry is 2 bytes of tag, 2 bytes of contents datatype,
212         // 4 bytes of number-of-elements, and 4 bytes of either offset to the
213         // tag data, or if the data is small enough, the inlined data itself.
214         const int ifdEntrySize = 12;
215         for (unsigned i = 0; i < tagCount && end - ifd >= ifdEntrySize; ++i, ifd += ifdEntrySize) {
216             unsigned tag = readUint16(ifd, isBigEndian);
217             unsigned type = readUint16(ifd + 2, isBigEndian);
218             unsigned count = readUint32(ifd + 4, isBigEndian);
219             if (tag == orientationTag && type == shortType && count == 1)
220                 return ImageOrientation::fromEXIFValue(readUint16(ifd + 8, isBigEndian));
221         }
222     }
223
224     return ImageOrientation();
225 }
226
227 #if USE(QCMSLIB)
228 static void readColorProfile(jpeg_decompress_struct* info, ColorProfile& colorProfile)
229 {
230 #if USE(ICCJPEG)
231     JOCTET* profile;
232     unsigned profileLength;
233
234     if (!read_icc_profile(info, &profile, &profileLength))
235         return;
236
237     // Only accept RGB color profiles from input class devices.
238     bool ignoreProfile = false;
239     char* profileData = reinterpret_cast<char*>(profile);
240     if (profileLength < ImageDecoder::iccColorProfileHeaderLength)
241         ignoreProfile = true;
242     else if (!ImageDecoder::rgbColorProfile(profileData, profileLength))
243         ignoreProfile = true;
244     else if (!ImageDecoder::inputDeviceColorProfile(profileData, profileLength))
245         ignoreProfile = true;
246
247     ASSERT(colorProfile.isEmpty());
248     if (!ignoreProfile)
249         colorProfile.append(profileData, profileLength);
250     free(profile);
251 #endif
252 }
253 #endif
254
255 static IntSize computeUVSize(const jpeg_decompress_struct* info)
256 {
257     int h = info->cur_comp_info[0]->h_samp_factor;
258     int v = info->cur_comp_info[0]->v_samp_factor;
259     return IntSize((info->output_width + h - 1) / h, (info->output_height + v - 1) / v);
260 }
261
262 static yuv_subsampling getYUVSubsampling(const jpeg_decompress_struct& info)
263 {
264     if ((DCTSIZE == 8)
265         && (info.num_components == 3)
266         && (info.scale_denom <= 8)
267         && (info.cur_comp_info[1]->h_samp_factor == 1)
268         && (info.cur_comp_info[1]->v_samp_factor == 1)
269         && (info.cur_comp_info[2]->h_samp_factor == 1)
270         && (info.cur_comp_info[2]->v_samp_factor == 1)) {
271         int h = info.cur_comp_info[0]->h_samp_factor;
272         int v = info.cur_comp_info[0]->v_samp_factor;
273         // 4:4:4 : (h == 1) && (v == 1)
274         // 4:4:0 : (h == 1) && (v == 2)
275         // 4:2:2 : (h == 2) && (v == 1)
276         // 4:2:0 : (h == 2) && (v == 2)
277         // 4:1:1 : (h == 4) && (v == 1)
278         // 4:1:0 : (h == 4) && (v == 2)
279         if (v == 1) {
280             switch (h) {
281             case 1:
282                 return YUV_444;
283             case 2:
284                 return YUV_422;
285             case 4:
286                 return YUV_411;
287             default:
288                 break;
289             }
290         } else if (v == 2) {
291             switch (h) {
292             case 1:
293                 return YUV_440;
294             case 2:
295                 return YUV_420;
296             case 4:
297                 return YUV_410;
298             default:
299                 break;
300             }
301         }
302     }
303
304     return YUV_UNKNOWN;
305 }
306
307 class JPEGImageReader {
308     WTF_MAKE_FAST_ALLOCATED;
309 public:
310     JPEGImageReader(JPEGImageDecoder* decoder)
311         : m_decoder(decoder)
312         , m_bufferLength(0)
313         , m_bytesToSkip(0)
314         , m_state(JPEG_HEADER)
315         , m_samples(0)
316 #if USE(QCMSLIB)
317         , m_transform(0)
318 #endif
319     {
320         memset(&m_info, 0, sizeof(jpeg_decompress_struct));
321
322         // We set up the normal JPEG error routines, then override error_exit.
323         m_info.err = jpeg_std_error(&m_err.pub);
324         m_err.pub.error_exit = error_exit;
325
326         // Allocate and initialize JPEG decompression object.
327         jpeg_create_decompress(&m_info);
328
329         decoder_source_mgr* src = 0;
330         if (!m_info.src) {
331             src = (decoder_source_mgr*)fastZeroedMalloc(sizeof(decoder_source_mgr));
332             if (!src) {
333                 m_state = JPEG_ERROR;
334                 return;
335             }
336         }
337
338         m_info.src = (jpeg_source_mgr*)src;
339
340         // Set up callback functions.
341         src->pub.init_source = init_source;
342         src->pub.fill_input_buffer = fill_input_buffer;
343         src->pub.skip_input_data = skip_input_data;
344         src->pub.resync_to_restart = jpeg_resync_to_restart;
345         src->pub.term_source = term_source;
346         src->decoder = this;
347
348 #if USE(ICCJPEG)
349         // Retain ICC color profile markers for color management.
350         setup_read_icc_profile(&m_info);
351 #endif
352
353         // Keep APP1 blocks, for obtaining exif data.
354         jpeg_save_markers(&m_info, exifMarker, 0xFFFF);
355     }
356
357     ~JPEGImageReader()
358     {
359         close();
360     }
361
362     void close()
363     {
364         decoder_source_mgr* src = (decoder_source_mgr*)m_info.src;
365         if (src)
366             fastFree(src);
367         m_info.src = 0;
368
369 #if USE(QCMSLIB)
370         if (m_transform)
371             qcms_transform_release(m_transform);
372         m_transform = 0;
373 #endif
374         jpeg_destroy_decompress(&m_info);
375     }
376
377     void skipBytes(long numBytes)
378     {
379         decoder_source_mgr* src = (decoder_source_mgr*)m_info.src;
380         long bytesToSkip = std::min(numBytes, (long)src->pub.bytes_in_buffer);
381         src->pub.bytes_in_buffer -= (size_t)bytesToSkip;
382         src->pub.next_input_byte += bytesToSkip;
383
384         m_bytesToSkip = std::max(numBytes - bytesToSkip, static_cast<long>(0));
385     }
386
387     bool decode(const SharedBuffer& data, bool onlySize)
388     {
389         unsigned newByteCount = data.size() - m_bufferLength;
390         unsigned readOffset = m_bufferLength - m_info.src->bytes_in_buffer;
391
392         m_info.src->bytes_in_buffer += newByteCount;
393         m_info.src->next_input_byte = (JOCTET*)(data.data()) + readOffset;
394
395         // If we still have bytes to skip, try to skip those now.
396         if (m_bytesToSkip)
397             skipBytes(m_bytesToSkip);
398
399         m_bufferLength = data.size();
400
401         // We need to do the setjmp here. Otherwise bad things will happen
402         if (setjmp(m_err.setjmp_buffer))
403             return m_decoder->setFailed();
404
405         switch (m_state) {
406         case JPEG_HEADER:
407             // Read file parameters with jpeg_read_header().
408             if (jpeg_read_header(&m_info, true) == JPEG_SUSPENDED)
409                 return false; // I/O suspension.
410
411             switch (m_info.jpeg_color_space) {
412             case JCS_YCbCr:
413                 // libjpeg can convert YCbCr image pixels to RGB.
414                 m_info.out_color_space = rgbOutputColorSpace();
415                 if (m_decoder->YUVDecoding() && (getYUVSubsampling(m_info) != YUV_UNKNOWN)) {
416                     m_info.out_color_space = JCS_YCbCr;
417                     m_info.raw_data_out = TRUE;
418                 }
419                 break;
420             case JCS_GRAYSCALE:
421             case JCS_RGB:
422                 // libjpeg can convert GRAYSCALE image pixels to RGB.
423                 m_info.out_color_space = rgbOutputColorSpace();
424 #if defined(TURBO_JPEG_RGB_SWIZZLE)
425                 if (m_info.saw_JFIF_marker)
426                     break;
427                 // FIXME: Swizzle decoding does not support Adobe transform=0
428                 // images (yet), so revert to using JSC_RGB in that case.
429                 if (m_info.saw_Adobe_marker && !m_info.Adobe_transform)
430                     m_info.out_color_space = JCS_RGB;
431 #endif
432                 break;
433             case JCS_CMYK:
434             case JCS_YCCK:
435                 // libjpeg can convert YCCK to CMYK, but neither to RGB, so we
436                 // manually convert CMKY to RGB.
437                 m_info.out_color_space = JCS_CMYK;
438                 break;
439             default:
440                 return m_decoder->setFailed();
441             }
442
443             m_state = JPEG_START_DECOMPRESS;
444
445             // We can fill in the size now that the header is available.
446             if (!m_decoder->setSize(m_info.image_width, m_info.image_height))
447                 return false;
448
449             // Calculate and set decoded size.
450             m_info.scale_num = m_decoder->desiredScaleNumerator();
451             m_info.scale_denom = scaleDenominator;
452             jpeg_calc_output_dimensions(&m_info);
453             m_decoder->setDecodedSize(m_info.output_width, m_info.output_height);
454
455             m_decoder->setOrientation(readImageOrientation(info()));
456
457 #if USE(QCMSLIB)
458             // Allow color management of the decoded RGBA pixels if possible.
459             if (!m_decoder->ignoresGammaAndColorProfile()) {
460                 ColorProfile colorProfile;
461                 readColorProfile(info(), colorProfile);
462                 createColorTransform(colorProfile, colorSpaceHasAlpha(m_info.out_color_space));
463                 if (m_transform && m_info.out_color_space == JCS_YCbCr) {
464                     m_info.out_color_space = rgbOutputColorSpace();
465                     m_info.raw_data_out = FALSE;
466                 }
467 #if defined(TURBO_JPEG_RGB_SWIZZLE)
468                 // Input RGBA data to qcms. Note: restored to BGRA on output.
469                 if (m_transform && m_info.out_color_space == JCS_EXT_BGRA)
470                     m_info.out_color_space = JCS_EXT_RGBA;
471 #endif
472                 m_decoder->setHasColorProfile(!!m_transform);
473             }
474 #endif
475             // Don't allocate a giant and superfluous memory buffer when the
476             // image is a sequential JPEG.
477             m_info.buffered_image = jpeg_has_multiple_scans(&m_info);
478
479             if (onlySize) {
480                 // We can stop here. Reduce our buffer length and available data.
481                 m_bufferLength -= m_info.src->bytes_in_buffer;
482                 m_info.src->bytes_in_buffer = 0;
483                 return true;
484             }
485         // FALL THROUGH
486
487         case JPEG_START_DECOMPRESS:
488             // Set parameters for decompression.
489             // FIXME -- Should reset dct_method and dither mode for final pass
490             // of progressive JPEG.
491             m_info.dct_method = dctMethod();
492             m_info.dither_mode = ditherMode();
493             m_info.do_fancy_upsampling = doFancyUpsampling();
494             m_info.enable_2pass_quant = false;
495             m_info.do_block_smoothing = true;
496
497             // Make a one-row-high sample array that will go away when done with
498             // image. Always make it big enough to hold an RGB row. Since this
499             // uses the IJG memory manager, it must be allocated before the call
500             // to jpeg_start_compress().
501             // FIXME: note that some output color spaces do not need the samples
502             // buffer. Remove this allocation for those color spaces.
503             m_samples = (*m_info.mem->alloc_sarray)(reinterpret_cast<j_common_ptr>(&m_info), JPOOL_IMAGE, m_info.output_width * 4, m_info.out_color_space == JCS_YCbCr ? 2 : 1);
504
505             // Start decompressor.
506             if (!jpeg_start_decompress(&m_info))
507                 return false; // I/O suspension.
508
509             // If this is a progressive JPEG ...
510             m_state = (m_info.buffered_image) ? JPEG_DECOMPRESS_PROGRESSIVE : JPEG_DECOMPRESS_SEQUENTIAL;
511         // FALL THROUGH
512
513         case JPEG_DECOMPRESS_SEQUENTIAL:
514             if (m_state == JPEG_DECOMPRESS_SEQUENTIAL) {
515
516                 if (!m_decoder->outputScanlines())
517                     return false; // I/O suspension.
518
519                 // If we've completed image output...
520                 ASSERT(m_info.output_scanline == m_info.output_height);
521                 m_state = JPEG_DONE;
522             }
523         // FALL THROUGH
524
525         case JPEG_DECOMPRESS_PROGRESSIVE:
526             if (m_state == JPEG_DECOMPRESS_PROGRESSIVE) {
527                 int status;
528                 do {
529                     status = jpeg_consume_input(&m_info);
530                 } while ((status != JPEG_SUSPENDED) && (status != JPEG_REACHED_EOI));
531
532                 for (;;) {
533                     if (!m_info.output_scanline) {
534                         int scan = m_info.input_scan_number;
535
536                         // If we haven't displayed anything yet
537                         // (output_scan_number == 0) and we have enough data for
538                         // a complete scan, force output of the last full scan.
539                         if (!m_info.output_scan_number && (scan > 1) && (status != JPEG_REACHED_EOI))
540                             --scan;
541
542                         if (!jpeg_start_output(&m_info, scan))
543                             return false; // I/O suspension.
544                     }
545
546                     if (m_info.output_scanline == 0xffffff)
547                         m_info.output_scanline = 0;
548
549                     // If outputScanlines() fails, it deletes |this|. Therefore,
550                     // copy the decoder pointer and use it to check for failure
551                     // to avoid member access in the failure case.
552                     JPEGImageDecoder* decoder = m_decoder;
553                     if (!decoder->outputScanlines()) {
554                         if (decoder->failed()) // Careful; |this| is deleted.
555                             return false;
556                         if (!m_info.output_scanline)
557                             // Didn't manage to read any lines - flag so we
558                             // don't call jpeg_start_output() multiple times for
559                             // the same scan.
560                             m_info.output_scanline = 0xffffff;
561                         return false; // I/O suspension.
562                     }
563
564                     if (m_info.output_scanline == m_info.output_height) {
565                         if (!jpeg_finish_output(&m_info))
566                             return false; // I/O suspension.
567
568                         if (jpeg_input_complete(&m_info) && (m_info.input_scan_number == m_info.output_scan_number))
569                             break;
570
571                         m_info.output_scanline = 0;
572                     }
573                 }
574
575                 m_state = JPEG_DONE;
576             }
577         // FALL THROUGH
578
579         case JPEG_DONE:
580             // Finish decompression.
581             return jpeg_finish_decompress(&m_info);
582
583         case JPEG_ERROR:
584             // We can get here if the constructor failed.
585             return m_decoder->setFailed();
586         }
587
588         return true;
589     }
590
591     jpeg_decompress_struct* info() { return &m_info; }
592     JSAMPARRAY samples() const { return m_samples; }
593     JPEGImageDecoder* decoder() { return m_decoder; }
594 #if USE(QCMSLIB)
595     qcms_transform* colorTransform() const { return m_transform; }
596
597     void createColorTransform(const ColorProfile& colorProfile, bool hasAlpha)
598     {
599         if (m_transform)
600             qcms_transform_release(m_transform);
601         m_transform = 0;
602
603         if (colorProfile.isEmpty())
604             return;
605         qcms_profile* deviceProfile = ImageDecoder::qcmsOutputDeviceProfile();
606         if (!deviceProfile)
607             return;
608         qcms_profile* inputProfile = qcms_profile_from_memory(colorProfile.data(), colorProfile.size());
609         if (!inputProfile)
610             return;
611         // We currently only support color profiles for RGB profiled images.
612         ASSERT(icSigRgbData == qcms_profile_get_color_space(inputProfile));
613         qcms_data_type dataFormat = hasAlpha ? QCMS_DATA_RGBA_8 : QCMS_DATA_RGB_8;
614         // FIXME: Don't force perceptual intent if the image profile contains an intent.
615         m_transform = qcms_transform_create(inputProfile, dataFormat, deviceProfile, dataFormat, QCMS_INTENT_PERCEPTUAL);
616         qcms_profile_release(inputProfile);
617     }
618 #endif
619
620 private:
621     JPEGImageDecoder* m_decoder;
622     unsigned m_bufferLength;
623     int m_bytesToSkip;
624
625     jpeg_decompress_struct m_info;
626     decoder_error_mgr m_err;
627     jstate m_state;
628
629     JSAMPARRAY m_samples;
630
631 #if USE(QCMSLIB)
632     qcms_transform* m_transform;
633 #endif
634 };
635
636 // Override the standard error method in the IJG JPEG decoder code.
637 void error_exit(j_common_ptr cinfo)
638 {
639     // Return control to the setjmp point.
640     decoder_error_mgr *err = reinterpret_cast_ptr<decoder_error_mgr *>(cinfo->err);
641     longjmp(err->setjmp_buffer, -1);
642 }
643
644 void init_source(j_decompress_ptr)
645 {
646 }
647
648 void skip_input_data(j_decompress_ptr jd, long num_bytes)
649 {
650     decoder_source_mgr *src = (decoder_source_mgr *)jd->src;
651     src->decoder->skipBytes(num_bytes);
652 }
653
654 boolean fill_input_buffer(j_decompress_ptr)
655 {
656     // Our decode step always sets things up properly, so if this method is ever
657     // called, then we have hit the end of the buffer.  A return value of false
658     // indicates that we have no data to supply yet.
659     return false;
660 }
661
662 void term_source(j_decompress_ptr jd)
663 {
664     decoder_source_mgr *src = (decoder_source_mgr *)jd->src;
665     src->decoder->decoder()->jpegComplete();
666 }
667
668 JPEGImageDecoder::JPEGImageDecoder(ImageSource::AlphaOption alphaOption,
669     ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption,
670     size_t maxDecodedBytes)
671     : ImageDecoder(alphaOption, gammaAndColorProfileOption, maxDecodedBytes)
672     , m_hasColorProfile(false)
673 {
674 }
675
676 JPEGImageDecoder::~JPEGImageDecoder()
677 {
678 }
679
680 bool JPEGImageDecoder::isSizeAvailable()
681 {
682     if (!ImageDecoder::isSizeAvailable())
683          decode(true);
684
685     return ImageDecoder::isSizeAvailable();
686 }
687
688 bool JPEGImageDecoder::setSize(unsigned width, unsigned height)
689 {
690     if (!ImageDecoder::setSize(width, height))
691         return false;
692
693     if (!desiredScaleNumerator())
694         return setFailed();
695
696     setDecodedSize(width, height);
697     return true;
698 }
699
700 void JPEGImageDecoder::setDecodedSize(unsigned width, unsigned height)
701 {
702     m_decodedSize = IntSize(width, height);
703 }
704
705 IntSize JPEGImageDecoder::decodedYUVSize(int component) const
706 {
707     if (((component == 1) || (component == 2)) && m_reader.get()) { // Asking for U or V
708         const jpeg_decompress_struct* info = m_reader->info();
709         if (info && (info->out_color_space == JCS_YCbCr)) {
710             return computeUVSize(info);
711         }
712     }
713
714     return m_decodedSize;
715 }
716
717 unsigned JPEGImageDecoder::desiredScaleNumerator() const
718 {
719     size_t originalBytes = size().width() * size().height() * 4;
720     if (originalBytes <= m_maxDecodedBytes) {
721         return scaleDenominator;
722     }
723
724     // Downsample according to the maximum decoded size.
725     unsigned scaleNumerator = static_cast<unsigned>(floor(sqrt(
726         // MSVC needs explicit parameter type for sqrt().
727         static_cast<float>(m_maxDecodedBytes * scaleDenominator * scaleDenominator / originalBytes))));
728
729     return scaleNumerator;
730 }
731
732 bool JPEGImageDecoder::decodeToYUV()
733 {
734     PlatformInstrumentation::willDecodeImage("JPEG");
735     decode(false);
736     PlatformInstrumentation::didDecodeImage();
737     return !failed();
738 }
739
740 ImageFrame* JPEGImageDecoder::frameBufferAtIndex(size_t index)
741 {
742     if (index)
743         return 0;
744
745     if (m_frameBufferCache.isEmpty()) {
746         m_frameBufferCache.resize(1);
747         m_frameBufferCache[0].setPremultiplyAlpha(m_premultiplyAlpha);
748     }
749
750     ImageFrame& frame = m_frameBufferCache[0];
751     if (frame.status() != ImageFrame::FrameComplete) {
752         PlatformInstrumentation::willDecodeImage("JPEG");
753         decode(false);
754         PlatformInstrumentation::didDecodeImage();
755     }
756
757     frame.notifyBitmapIfPixelsChanged();
758     return &frame;
759 }
760
761 bool JPEGImageDecoder::setFailed()
762 {
763     m_reader.clear();
764     return ImageDecoder::setFailed();
765 }
766
767 void JPEGImageDecoder::setImagePlanes(OwnPtr<ImagePlanes>& imagePlanes)
768 {
769     m_imagePlanes = imagePlanes.release();
770 }
771
772 template <J_COLOR_SPACE colorSpace> void setPixel(ImageFrame& buffer, ImageFrame::PixelData* pixel, JSAMPARRAY samples, int column)
773 {
774     ASSERT_NOT_REACHED();
775 }
776
777 template <> void setPixel<JCS_RGB>(ImageFrame& buffer, ImageFrame::PixelData* pixel, JSAMPARRAY samples, int column)
778 {
779     JSAMPLE* jsample = *samples + column * 3;
780     buffer.setRGBARaw(pixel, jsample[0], jsample[1], jsample[2], 255);
781 }
782
783 template <> void setPixel<JCS_CMYK>(ImageFrame& buffer, ImageFrame::PixelData* pixel, JSAMPARRAY samples, int column)
784 {
785     JSAMPLE* jsample = *samples + column * 4;
786
787     // Source is 'Inverted CMYK', output is RGB.
788     // See: http://www.easyrgb.com/math.php?MATH=M12#text12
789     // Or: http://www.ilkeratalay.com/colorspacesfaq.php#rgb
790     // From CMYK to CMY:
791     // X =   X    * (1 -   K   ) +   K  [for X = C, M, or Y]
792     // Thus, from Inverted CMYK to CMY is:
793     // X = (1-iX) * (1 - (1-iK)) + (1-iK) => 1 - iX*iK
794     // From CMY (0..1) to RGB (0..1):
795     // R = 1 - C => 1 - (1 - iC*iK) => iC*iK  [G and B similar]
796     unsigned k = jsample[3];
797     buffer.setRGBARaw(pixel, jsample[0] * k / 255, jsample[1] * k / 255, jsample[2] * k / 255, 255);
798 }
799
800 template <J_COLOR_SPACE colorSpace> bool outputRows(JPEGImageReader* reader, ImageFrame& buffer)
801 {
802     JSAMPARRAY samples = reader->samples();
803     jpeg_decompress_struct* info = reader->info();
804     int width = info->output_width;
805
806     while (info->output_scanline < info->output_height) {
807         // jpeg_read_scanlines will increase the scanline counter, so we
808         // save the scanline before calling it.
809         int y = info->output_scanline;
810         // Request one scanline: returns 0 or 1 scanlines.
811         if (jpeg_read_scanlines(info, samples, 1) != 1)
812             return false;
813 #if USE(QCMSLIB)
814         if (reader->colorTransform() && colorSpace == JCS_RGB)
815             qcms_transform_data(reader->colorTransform(), *samples, *samples, width);
816 #endif
817         ImageFrame::PixelData* pixel = buffer.getAddr(0, y);
818         for (int x = 0; x < width; ++pixel, ++x)
819             setPixel<colorSpace>(buffer, pixel, samples, x);
820     }
821
822     buffer.setPixelsChanged(true);
823     return true;
824 }
825
826 static bool outputRawData(JPEGImageReader* reader, ImagePlanes* imagePlanes)
827 {
828     JSAMPARRAY samples = reader->samples();
829     jpeg_decompress_struct* info = reader->info();
830     JSAMPARRAY bufferraw[3];
831     JSAMPROW bufferraw2[32];
832     bufferraw[0] = &bufferraw2[0]; // Y channel rows (8 or 16)
833     bufferraw[1] = &bufferraw2[16]; // U channel rows (8)
834     bufferraw[2] = &bufferraw2[24]; // V channel rows (8)
835     int yWidth = info->output_width;
836     int yHeight = info->output_height;
837     int yMaxH = yHeight - 1;
838     int v = info->cur_comp_info[0]->v_samp_factor;
839     IntSize uvSize = computeUVSize(info);
840     int uvMaxH = uvSize.height() - 1;
841     JSAMPROW outputY = static_cast<JSAMPROW>(imagePlanes->plane(0));
842     JSAMPROW outputU = static_cast<JSAMPROW>(imagePlanes->plane(1));
843     JSAMPROW outputV = static_cast<JSAMPROW>(imagePlanes->plane(2));
844     size_t rowBytesY = imagePlanes->rowBytes(0);
845     size_t rowBytesU = imagePlanes->rowBytes(1);
846     size_t rowBytesV = imagePlanes->rowBytes(2);
847
848     int yScanlinesToRead = DCTSIZE * v;
849     JSAMPROW yLastRow = *samples;
850     JSAMPROW uLastRow = yLastRow + 2 * yWidth;
851     JSAMPROW vLastRow = uLastRow + 2 * yWidth;
852     JSAMPROW dummyRow = vLastRow + 2 * yWidth;
853
854     while (info->output_scanline < info->output_height) {
855         // Request 8 or 16 scanlines: returns 0 or more scanlines.
856         bool hasYLastRow(false), hasUVLastRow(false);
857         // Assign 8 or 16 rows of memory to read the Y channel.
858         for (int i = 0; i < yScanlinesToRead; ++i) {
859             int scanline = (info->output_scanline + i);
860             if (scanline < yMaxH) {
861                 bufferraw2[i] = &outputY[scanline * rowBytesY];
862             } else if (scanline == yMaxH) {
863                 bufferraw2[i] = yLastRow;
864                 hasYLastRow = true;
865             } else {
866                 bufferraw2[i] = dummyRow;
867             }
868         }
869         int scaledScanline = info->output_scanline / v;
870         // Assign 8 rows of memory to read the U and V channels.
871         for (int i = 0; i < 8; ++i) {
872             int scanline = (scaledScanline + i);
873             if (scanline < uvMaxH) {
874                 bufferraw2[16 + i] = &outputU[scanline * rowBytesU];
875                 bufferraw2[24 + i] = &outputV[scanline * rowBytesV];
876             } else if (scanline == uvMaxH) {
877                 bufferraw2[16 + i] = uLastRow;
878                 bufferraw2[24 + i] = vLastRow;
879                 hasUVLastRow = true;
880             } else {
881                 bufferraw2[16 + i] = dummyRow;
882                 bufferraw2[24 + i] = dummyRow;
883             }
884         }
885         JDIMENSION scanlinesRead = jpeg_read_raw_data(info, bufferraw, yScanlinesToRead);
886
887         if (scanlinesRead == 0)
888             return false;
889
890         if (hasYLastRow) {
891             memcpy(&outputY[yMaxH * rowBytesY], yLastRow, yWidth);
892         }
893         if (hasUVLastRow) {
894             memcpy(&outputU[uvMaxH * rowBytesU], uLastRow, uvSize.width());
895             memcpy(&outputV[uvMaxH * rowBytesV], vLastRow, uvSize.width());
896         }
897     }
898
899     info->output_scanline = std::min(info->output_scanline, info->output_height);
900
901     return true;
902 }
903
904 bool JPEGImageDecoder::outputScanlines()
905 {
906     if (m_frameBufferCache.isEmpty())
907         return false;
908
909     jpeg_decompress_struct* info = m_reader->info();
910
911     if (m_imagePlanes.get()) {
912         return outputRawData(m_reader.get(), m_imagePlanes.get());
913     }
914
915     // Initialize the framebuffer if needed.
916     ImageFrame& buffer = m_frameBufferCache[0];
917     if (buffer.status() == ImageFrame::FrameEmpty) {
918         ASSERT(info->output_width == static_cast<JDIMENSION>(m_decodedSize.width()));
919         ASSERT(info->output_height == static_cast<JDIMENSION>(m_decodedSize.height()));
920
921         if (!buffer.setSize(info->output_width, info->output_height))
922             return setFailed();
923         buffer.setStatus(ImageFrame::FramePartial);
924         // The buffer is transparent outside the decoded area while the image is
925         // loading. The completed image will be marked fully opaque in jpegComplete().
926         buffer.setHasAlpha(true);
927
928         // For JPEGs, the frame always fills the entire image.
929         buffer.setOriginalFrameRect(IntRect(IntPoint(), size()));
930     }
931
932 #if defined(TURBO_JPEG_RGB_SWIZZLE)
933     if (turboSwizzled(info->out_color_space)) {
934         while (info->output_scanline < info->output_height) {
935             unsigned char* row = reinterpret_cast<unsigned char*>(buffer.getAddr(0, info->output_scanline));
936             if (jpeg_read_scanlines(info, &row, 1) != 1)
937                 return false;
938 #if USE(QCMSLIB)
939             if (qcms_transform* transform = m_reader->colorTransform())
940                 qcms_transform_data_type(transform, row, row, info->output_width, rgbOutputColorSpace() == JCS_EXT_BGRA ? QCMS_OUTPUT_BGRX : QCMS_OUTPUT_RGBX);
941 #endif
942         }
943         buffer.setPixelsChanged(true);
944         return true;
945     }
946 #endif
947
948     switch (info->out_color_space) {
949     case JCS_RGB:
950         return outputRows<JCS_RGB>(m_reader.get(), buffer);
951     case JCS_CMYK:
952         return outputRows<JCS_CMYK>(m_reader.get(), buffer);
953     default:
954         ASSERT_NOT_REACHED();
955     }
956
957     return setFailed();
958 }
959
960 void JPEGImageDecoder::jpegComplete()
961 {
962     if (m_frameBufferCache.isEmpty())
963         return;
964
965     // Hand back an appropriately sized buffer, even if the image ended up being
966     // empty.
967     ImageFrame& buffer = m_frameBufferCache[0];
968     buffer.setHasAlpha(false);
969     buffer.setStatus(ImageFrame::FrameComplete);
970 }
971
972 void JPEGImageDecoder::decode(bool onlySize)
973 {
974     if (failed())
975         return;
976
977     if (!m_reader) {
978         m_reader = adoptPtr(new JPEGImageReader(this));
979     }
980
981     // If we couldn't decode the image but we've received all the data, decoding
982     // has failed.
983     if (!m_reader->decode(*m_data, onlySize) && isAllDataReceived())
984         setFailed();
985     // If we're done decoding the image, we don't need the JPEGImageReader
986     // anymore.  (If we failed, |m_reader| has already been cleared.)
987     else if (!m_frameBufferCache.isEmpty() && (m_frameBufferCache[0].status() == ImageFrame::FrameComplete))
988         m_reader.clear();
989 }
990
991 }