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