initial import
[vuplus_webkit] / Source / WebCore / 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 "JPEGImageDecoder.h"
42 #include <stdio.h>  // Needed by jpeglib.h for FILE.
43 #include <wtf/PassOwnPtr.h>
44
45 #if OS(WINCE) || PLATFORM(BREWMP_SIMULATOR)
46 // Remove warning: 'FAR' macro redefinition
47 #undef FAR
48
49 // jmorecfg.h in libjpeg checks for XMD_H with the comment: "X11/xmd.h correctly defines INT32"
50 // fix INT32 redefinition error by pretending we are X11/xmd.h
51 #define XMD_H
52 #endif
53
54 extern "C" {
55
56 #include "jpeglib.h"
57
58 #if USE(ICCJPEG)
59 #include "iccjpeg.h"
60 #endif
61
62 }
63
64 #include <setjmp.h>
65
66 namespace WebCore {
67
68 struct decoder_error_mgr {
69     struct jpeg_error_mgr pub; // "public" fields for IJG library
70     jmp_buf setjmp_buffer;     // For handling catastropic errors
71 };
72
73 enum jstate {
74     JPEG_HEADER,                 // Reading JFIF headers
75     JPEG_START_DECOMPRESS,
76     JPEG_DECOMPRESS_PROGRESSIVE, // Output progressive pixels
77     JPEG_DECOMPRESS_SEQUENTIAL,  // Output sequential pixels
78     JPEG_DONE,
79     JPEG_ERROR    
80 };
81
82 void init_source(j_decompress_ptr jd);
83 boolean fill_input_buffer(j_decompress_ptr jd);
84 void skip_input_data(j_decompress_ptr jd, long num_bytes);
85 void term_source(j_decompress_ptr jd);
86 void error_exit(j_common_ptr cinfo);
87
88 // Implementation of a JPEG src object that understands our state machine
89 struct decoder_source_mgr {
90     // public fields; must be first in this struct!
91     struct jpeg_source_mgr pub;
92
93     JPEGImageReader* decoder;
94 };
95
96 static ColorProfile readColorProfile(jpeg_decompress_struct* info)
97 {
98 #if USE(ICCJPEG)
99     JOCTET* profile;
100     unsigned int profileLength;
101
102     if (!read_icc_profile(info, &profile, &profileLength))
103         return ColorProfile();
104
105     ColorProfile colorProfile;
106     colorProfile.append(reinterpret_cast<char*>(profile), profileLength);
107     free(profile);
108     return colorProfile;
109 #else
110     return ColorProfile();
111 #endif
112 }
113
114 class JPEGImageReader
115 {
116 public:
117     JPEGImageReader(JPEGImageDecoder* decoder)
118         : m_decoder(decoder)
119         , m_bufferLength(0)
120         , m_bytesToSkip(0)
121         , m_state(JPEG_HEADER)
122         , m_samples(0)
123     {
124         memset(&m_info, 0, sizeof(jpeg_decompress_struct));
125  
126         // We set up the normal JPEG error routines, then override error_exit.
127         m_info.err = jpeg_std_error(&m_err.pub);
128         m_err.pub.error_exit = error_exit;
129
130         // Allocate and initialize JPEG decompression object.
131         jpeg_create_decompress(&m_info);
132   
133         decoder_source_mgr* src = 0;
134         if (!m_info.src) {
135             src = (decoder_source_mgr*)fastCalloc(sizeof(decoder_source_mgr), 1);
136             if (!src) {
137                 m_state = JPEG_ERROR;
138                 return;
139             }
140         }
141
142         m_info.src = (jpeg_source_mgr*)src;
143
144         // Set up callback functions.
145         src->pub.init_source = init_source;
146         src->pub.fill_input_buffer = fill_input_buffer;
147         src->pub.skip_input_data = skip_input_data;
148         src->pub.resync_to_restart = jpeg_resync_to_restart;
149         src->pub.term_source = term_source;
150         src->decoder = this;
151
152         // Enable these markers for the ICC color profile.
153         // Apparently there are 16 of these markers.  I don't see anywhere in the header with this constant.
154         for (unsigned i = 0; i < 0xF; ++i)
155             jpeg_save_markers(&m_info, JPEG_APP0 + i, 0xFFFF);
156     }
157
158     ~JPEGImageReader()
159     {
160         close();
161     }
162
163     void close()
164     {
165         decoder_source_mgr* src = (decoder_source_mgr*)m_info.src;
166         if (src)
167             fastFree(src);
168         m_info.src = 0;
169
170         jpeg_destroy_decompress(&m_info);
171     }
172
173     void skipBytes(long numBytes)
174     {
175         decoder_source_mgr* src = (decoder_source_mgr*)m_info.src;
176         long bytesToSkip = std::min(numBytes, (long)src->pub.bytes_in_buffer);
177         src->pub.bytes_in_buffer -= (size_t)bytesToSkip;
178         src->pub.next_input_byte += bytesToSkip;
179
180         m_bytesToSkip = std::max(numBytes - bytesToSkip, static_cast<long>(0));
181     }
182
183     bool decode(const SharedBuffer& data, bool onlySize)
184     {
185         m_decodingSizeOnly = onlySize;
186
187         unsigned newByteCount = data.size() - m_bufferLength;
188         unsigned readOffset = m_bufferLength - m_info.src->bytes_in_buffer;
189
190         m_info.src->bytes_in_buffer += newByteCount;
191         m_info.src->next_input_byte = (JOCTET*)(data.data()) + readOffset;
192
193         // If we still have bytes to skip, try to skip those now.
194         if (m_bytesToSkip)
195             skipBytes(m_bytesToSkip);
196
197         m_bufferLength = data.size();
198         
199         // We need to do the setjmp here. Otherwise bad things will happen
200         if (setjmp(m_err.setjmp_buffer))
201             return m_decoder->setFailed();
202
203         switch (m_state) {
204         case JPEG_HEADER:
205             // Read file parameters with jpeg_read_header().
206             if (jpeg_read_header(&m_info, true) == JPEG_SUSPENDED)
207                 return false; // I/O suspension.
208
209             // Let libjpeg take care of gray->RGB and YCbCr->RGB conversions.
210             switch (m_info.jpeg_color_space) {
211             case JCS_GRAYSCALE:
212             case JCS_YCbCr:
213                 // Grayscale images get "upsampled" by libjpeg.  If we use
214                 // their color profile, CoreGraphics will "upsample" them
215                 // again, resulting in horizontal distortions.
216                 m_decoder->setIgnoreGammaAndColorProfile(true);
217                 // Note fall-through!
218             case JCS_RGB:
219                 m_info.out_color_space = JCS_RGB;
220                 break;
221             case JCS_CMYK:
222             case JCS_YCCK:
223                 // jpeglib cannot convert these to rgb, but it can convert ycck
224                 // to cmyk.
225                 m_info.out_color_space = JCS_CMYK;
226
227                 // Same as with grayscale images, we convert CMYK images to RGBA
228                 // ones. When we keep the color profiles of these CMYK images,
229                 // CoreGraphics will convert their colors again. So, we discard
230                 // their color profiles to prevent color corruption.
231                 m_decoder->setIgnoreGammaAndColorProfile(true);
232                 break;
233             default:
234                 return m_decoder->setFailed();
235             }
236
237             // Don't allocate a giant and superfluous memory buffer when the
238             // image is a sequential JPEG.
239             m_info.buffered_image = jpeg_has_multiple_scans(&m_info);
240
241             // Used to set up image size so arrays can be allocated.
242             jpeg_calc_output_dimensions(&m_info);
243
244             // Make a one-row-high sample array that will go away when done with
245             // image. Always make it big enough to hold an RGB row.  Since this
246             // uses the IJG memory manager, it must be allocated before the call
247             // to jpeg_start_compress().
248             m_samples = (*m_info.mem->alloc_sarray)((j_common_ptr) &m_info, JPOOL_IMAGE, m_info.output_width * 4, 1);
249
250             m_state = JPEG_START_DECOMPRESS;
251
252             // We can fill in the size now that the header is available.
253             if (!m_decoder->setSize(m_info.image_width, m_info.image_height))
254                 return false;
255
256             if (!m_decoder->ignoresGammaAndColorProfile())
257                 m_decoder->setColorProfile(readColorProfile(info()));
258
259             if (m_decodingSizeOnly) {
260                 // We can stop here.  Reduce our buffer length and available
261                 // data.
262                 m_bufferLength -= m_info.src->bytes_in_buffer;
263                 m_info.src->bytes_in_buffer = 0;
264                 return true;
265             }
266         // FALL THROUGH
267
268         case JPEG_START_DECOMPRESS:
269             // Set parameters for decompression.
270             // FIXME -- Should reset dct_method and dither mode for final pass
271             // of progressive JPEG.
272             m_info.dct_method =  JDCT_ISLOW;
273             m_info.dither_mode = JDITHER_FS;
274             m_info.do_fancy_upsampling = true;
275             m_info.enable_2pass_quant = false;
276             m_info.do_block_smoothing = true;
277
278             // Start decompressor.
279             if (!jpeg_start_decompress(&m_info))
280                 return false; // I/O suspension.
281
282             // If this is a progressive JPEG ...
283             m_state = (m_info.buffered_image) ? JPEG_DECOMPRESS_PROGRESSIVE : JPEG_DECOMPRESS_SEQUENTIAL;
284         // FALL THROUGH
285
286         case JPEG_DECOMPRESS_SEQUENTIAL:
287             if (m_state == JPEG_DECOMPRESS_SEQUENTIAL) {
288   
289                 if (!m_decoder->outputScanlines())
290                     return false; // I/O suspension.
291   
292                 // If we've completed image output...
293                 ASSERT(m_info.output_scanline == m_info.output_height);
294                 m_state = JPEG_DONE;
295             }
296         // FALL THROUGH
297
298         case JPEG_DECOMPRESS_PROGRESSIVE:
299             if (m_state == JPEG_DECOMPRESS_PROGRESSIVE) {
300                 int status;
301                 do {
302                     status = jpeg_consume_input(&m_info);
303                 } while ((status != JPEG_SUSPENDED) && (status != JPEG_REACHED_EOI));
304
305                 for (;;) {
306                     if (!m_info.output_scanline) {
307                         int scan = m_info.input_scan_number;
308
309                         // If we haven't displayed anything yet
310                         // (output_scan_number == 0) and we have enough data for
311                         // a complete scan, force output of the last full scan.
312                         if (!m_info.output_scan_number && (scan > 1) && (status != JPEG_REACHED_EOI))
313                             --scan;
314
315                         if (!jpeg_start_output(&m_info, scan))
316                             return false; // I/O suspension.
317                     }
318
319                     if (m_info.output_scanline == 0xffffff)
320                         m_info.output_scanline = 0;
321
322                     if (!m_decoder->outputScanlines()) {
323                         if (!m_info.output_scanline)
324                             // Didn't manage to read any lines - flag so we
325                             // don't call jpeg_start_output() multiple times for
326                             // the same scan.
327                             m_info.output_scanline = 0xffffff;
328                         return false; // I/O suspension.
329                     }
330
331                     if (m_info.output_scanline == m_info.output_height) {
332                         if (!jpeg_finish_output(&m_info))
333                             return false; // I/O suspension.
334
335                         if (jpeg_input_complete(&m_info) && (m_info.input_scan_number == m_info.output_scan_number))
336                             break;
337
338                         m_info.output_scanline = 0;
339                     }
340                 }
341
342                 m_state = JPEG_DONE;
343             }
344         // FALL THROUGH
345
346         case JPEG_DONE:
347             // Finish decompression.
348             return jpeg_finish_decompress(&m_info);
349
350         case JPEG_ERROR:
351             // We can get here if the constructor failed.
352             return m_decoder->setFailed();
353         }
354
355         return true;
356     }
357
358     jpeg_decompress_struct* info() { return &m_info; }
359     JSAMPARRAY samples() const { return m_samples; }
360     JPEGImageDecoder* decoder() { return m_decoder; }
361
362 private:
363     JPEGImageDecoder* m_decoder;
364     unsigned m_bufferLength;
365     int m_bytesToSkip;
366     bool m_decodingSizeOnly;
367     bool m_initialized;
368
369     jpeg_decompress_struct m_info;
370     decoder_error_mgr m_err;
371     jstate m_state;
372
373     JSAMPARRAY m_samples;
374 };
375
376 // Override the standard error method in the IJG JPEG decoder code.
377 void error_exit(j_common_ptr cinfo)
378 {
379     // Return control to the setjmp point.
380     decoder_error_mgr *err = (decoder_error_mgr *) cinfo->err;
381     longjmp(err->setjmp_buffer, -1);
382 }
383
384 void init_source(j_decompress_ptr jd)
385 {
386 }
387
388 void skip_input_data(j_decompress_ptr jd, long num_bytes)
389 {
390     decoder_source_mgr *src = (decoder_source_mgr *)jd->src;
391     src->decoder->skipBytes(num_bytes);
392 }
393
394 boolean fill_input_buffer(j_decompress_ptr jd)
395 {
396     // Our decode step always sets things up properly, so if this method is ever
397     // called, then we have hit the end of the buffer.  A return value of false
398     // indicates that we have no data to supply yet.
399     return false;
400 }
401
402 void term_source(j_decompress_ptr jd)
403 {
404     decoder_source_mgr *src = (decoder_source_mgr *)jd->src;
405     src->decoder->decoder()->jpegComplete();
406 }
407
408 JPEGImageDecoder::JPEGImageDecoder(ImageSource::AlphaOption alphaOption,
409                                    ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption)
410     : ImageDecoder(alphaOption, gammaAndColorProfileOption)
411 {
412 }
413
414 JPEGImageDecoder::~JPEGImageDecoder()
415 {
416 }
417
418 bool JPEGImageDecoder::isSizeAvailable()
419 {
420     if (!ImageDecoder::isSizeAvailable())
421          decode(true);
422
423     return ImageDecoder::isSizeAvailable();
424 }
425
426 bool JPEGImageDecoder::setSize(unsigned width, unsigned height)
427 {
428     if (!ImageDecoder::setSize(width, height))
429         return false;
430
431     prepareScaleDataIfNecessary();
432     return true;
433 }
434
435 ImageFrame* JPEGImageDecoder::frameBufferAtIndex(size_t index)
436 {
437     if (index)
438         return 0;
439
440     if (m_frameBufferCache.isEmpty()) {
441         m_frameBufferCache.resize(1);
442         m_frameBufferCache[0].setPremultiplyAlpha(m_premultiplyAlpha);
443     }
444
445     ImageFrame& frame = m_frameBufferCache[0];
446     if (frame.status() != ImageFrame::FrameComplete)
447         decode(false);
448     return &frame;
449 }
450
451 bool JPEGImageDecoder::setFailed()
452 {
453     m_reader.clear();
454     return ImageDecoder::setFailed();
455 }
456
457 bool JPEGImageDecoder::outputScanlines()
458 {
459     if (m_frameBufferCache.isEmpty())
460         return false;
461
462     // Initialize the framebuffer if needed.
463     ImageFrame& buffer = m_frameBufferCache[0];
464     if (buffer.status() == ImageFrame::FrameEmpty) {
465         if (!buffer.setSize(scaledSize().width(), scaledSize().height()))
466             return setFailed();
467         buffer.setStatus(ImageFrame::FramePartial);
468         buffer.setHasAlpha(false);
469         buffer.setColorProfile(m_colorProfile);
470
471         // For JPEGs, the frame always fills the entire image.
472         buffer.setOriginalFrameRect(IntRect(IntPoint(), size()));
473     }
474
475     jpeg_decompress_struct* info = m_reader->info();
476     JSAMPARRAY samples = m_reader->samples();
477
478     while (info->output_scanline < info->output_height) {
479         // jpeg_read_scanlines will increase the scanline counter, so we
480         // save the scanline before calling it.
481         int sourceY = info->output_scanline;
482         /* Request one scanline.  Returns 0 or 1 scanlines. */
483         if (jpeg_read_scanlines(info, samples, 1) != 1)
484             return false;
485
486         int destY = scaledY(sourceY);
487         if (destY < 0)
488             continue;
489         int width = m_scaled ? m_scaledColumns.size() : info->output_width;
490         for (int x = 0; x < width; ++x) {
491             JSAMPLE* jsample = *samples + (m_scaled ? m_scaledColumns[x] : x) * ((info->out_color_space == JCS_RGB) ? 3 : 4);
492             if (info->out_color_space == JCS_RGB)
493                 buffer.setRGBA(x, destY, jsample[0], jsample[1], jsample[2], 0xFF);
494             else if (info->out_color_space == JCS_CMYK) {
495                 // Source is 'Inverted CMYK', output is RGB.
496                 // See: http://www.easyrgb.com/math.php?MATH=M12#text12
497                 // Or:  http://www.ilkeratalay.com/colorspacesfaq.php#rgb
498                 // From CMYK to CMY:
499                 // X =   X    * (1 -   K   ) +   K  [for X = C, M, or Y]
500                 // Thus, from Inverted CMYK to CMY is:
501                 // X = (1-iX) * (1 - (1-iK)) + (1-iK) => 1 - iX*iK
502                 // From CMY (0..1) to RGB (0..1):
503                 // R = 1 - C => 1 - (1 - iC*iK) => iC*iK  [G and B similar]
504                 unsigned k = jsample[3];
505                 buffer.setRGBA(x, destY, jsample[0] * k / 255, jsample[1] * k / 255, jsample[2] * k / 255, 0xFF);
506             } else {
507                 ASSERT_NOT_REACHED();
508                 return setFailed();
509             }
510         }
511     }
512
513     return true;
514 }
515
516 void JPEGImageDecoder::jpegComplete()
517 {
518     if (m_frameBufferCache.isEmpty())
519         return;
520
521     // Hand back an appropriately sized buffer, even if the image ended up being
522     // empty.
523     m_frameBufferCache[0].setStatus(ImageFrame::FrameComplete);
524 }
525
526 void JPEGImageDecoder::decode(bool onlySize)
527 {
528     if (failed())
529         return;
530
531     if (!m_reader)
532         m_reader = adoptPtr(new JPEGImageReader(this));
533
534     // If we couldn't decode the image but we've received all the data, decoding
535     // has failed.
536     if (!m_reader->decode(*m_data, onlySize) && isAllDataReceived())
537         setFailed();
538     // If we're done decoding the image, we don't need the JPEGImageReader
539     // anymore.  (If we failed, |m_reader| has already been cleared.)
540     else if (!m_frameBufferCache.isEmpty() && (m_frameBufferCache[0].status() == ImageFrame::FrameComplete))
541         m_reader.clear();
542 }
543
544 }