2 * Copyright (C) 2006 Apple Computer, Inc.
4 * Portions are Copyright (C) 2001-6 mozilla.org
7 * Stuart Parmenter <stuart@mozilla.com>
9 * Copyright (C) 2007-2009 Torch Mobile, Inc.
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.
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.
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
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.
41 #include "JPEGImageDecoder.h"
42 #include <stdio.h> // Needed by jpeglib.h for FILE.
43 #include <wtf/PassOwnPtr.h>
45 #if OS(WINCE) || PLATFORM(BREWMP_SIMULATOR)
46 // Remove warning: 'FAR' macro redefinition
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
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
74 JPEG_HEADER, // Reading JFIF headers
75 JPEG_START_DECOMPRESS,
76 JPEG_DECOMPRESS_PROGRESSIVE, // Output progressive pixels
77 JPEG_DECOMPRESS_SEQUENTIAL, // Output sequential pixels
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);
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;
93 JPEGImageReader* decoder;
96 static ColorProfile readColorProfile(jpeg_decompress_struct* info)
100 unsigned int profileLength;
102 if (!read_icc_profile(info, &profile, &profileLength))
103 return ColorProfile();
105 ColorProfile colorProfile;
106 colorProfile.append(reinterpret_cast<char*>(profile), profileLength);
110 return ColorProfile();
114 class JPEGImageReader
117 JPEGImageReader(JPEGImageDecoder* decoder)
121 , m_state(JPEG_HEADER)
124 memset(&m_info, 0, sizeof(jpeg_decompress_struct));
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;
130 // Allocate and initialize JPEG decompression object.
131 jpeg_create_decompress(&m_info);
133 decoder_source_mgr* src = 0;
135 src = (decoder_source_mgr*)fastCalloc(sizeof(decoder_source_mgr), 1);
137 m_state = JPEG_ERROR;
142 m_info.src = (jpeg_source_mgr*)src;
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;
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);
165 decoder_source_mgr* src = (decoder_source_mgr*)m_info.src;
170 jpeg_destroy_decompress(&m_info);
173 void skipBytes(long numBytes)
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;
180 m_bytesToSkip = std::max(numBytes - bytesToSkip, static_cast<long>(0));
183 bool decode(const SharedBuffer& data, bool onlySize)
185 m_decodingSizeOnly = onlySize;
187 unsigned newByteCount = data.size() - m_bufferLength;
188 unsigned readOffset = m_bufferLength - m_info.src->bytes_in_buffer;
190 m_info.src->bytes_in_buffer += newByteCount;
191 m_info.src->next_input_byte = (JOCTET*)(data.data()) + readOffset;
193 // If we still have bytes to skip, try to skip those now.
195 skipBytes(m_bytesToSkip);
197 m_bufferLength = data.size();
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();
205 // Read file parameters with jpeg_read_header().
206 if (jpeg_read_header(&m_info, true) == JPEG_SUSPENDED)
207 return false; // I/O suspension.
209 // Let libjpeg take care of gray->RGB and YCbCr->RGB conversions.
210 switch (m_info.jpeg_color_space) {
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!
219 m_info.out_color_space = JCS_RGB;
223 // jpeglib cannot convert these to rgb, but it can convert ycck
225 m_info.out_color_space = JCS_CMYK;
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);
234 return m_decoder->setFailed();
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);
241 // Used to set up image size so arrays can be allocated.
242 jpeg_calc_output_dimensions(&m_info);
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);
250 m_state = JPEG_START_DECOMPRESS;
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))
256 if (!m_decoder->ignoresGammaAndColorProfile())
257 m_decoder->setColorProfile(readColorProfile(info()));
259 if (m_decodingSizeOnly) {
260 // We can stop here. Reduce our buffer length and available
262 m_bufferLength -= m_info.src->bytes_in_buffer;
263 m_info.src->bytes_in_buffer = 0;
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;
278 // Start decompressor.
279 if (!jpeg_start_decompress(&m_info))
280 return false; // I/O suspension.
282 // If this is a progressive JPEG ...
283 m_state = (m_info.buffered_image) ? JPEG_DECOMPRESS_PROGRESSIVE : JPEG_DECOMPRESS_SEQUENTIAL;
286 case JPEG_DECOMPRESS_SEQUENTIAL:
287 if (m_state == JPEG_DECOMPRESS_SEQUENTIAL) {
289 if (!m_decoder->outputScanlines())
290 return false; // I/O suspension.
292 // If we've completed image output...
293 ASSERT(m_info.output_scanline == m_info.output_height);
298 case JPEG_DECOMPRESS_PROGRESSIVE:
299 if (m_state == JPEG_DECOMPRESS_PROGRESSIVE) {
302 status = jpeg_consume_input(&m_info);
303 } while ((status != JPEG_SUSPENDED) && (status != JPEG_REACHED_EOI));
306 if (!m_info.output_scanline) {
307 int scan = m_info.input_scan_number;
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))
315 if (!jpeg_start_output(&m_info, scan))
316 return false; // I/O suspension.
319 if (m_info.output_scanline == 0xffffff)
320 m_info.output_scanline = 0;
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
327 m_info.output_scanline = 0xffffff;
328 return false; // I/O suspension.
331 if (m_info.output_scanline == m_info.output_height) {
332 if (!jpeg_finish_output(&m_info))
333 return false; // I/O suspension.
335 if (jpeg_input_complete(&m_info) && (m_info.input_scan_number == m_info.output_scan_number))
338 m_info.output_scanline = 0;
347 // Finish decompression.
348 return jpeg_finish_decompress(&m_info);
351 // We can get here if the constructor failed.
352 return m_decoder->setFailed();
358 jpeg_decompress_struct* info() { return &m_info; }
359 JSAMPARRAY samples() const { return m_samples; }
360 JPEGImageDecoder* decoder() { return m_decoder; }
363 JPEGImageDecoder* m_decoder;
364 unsigned m_bufferLength;
366 bool m_decodingSizeOnly;
369 jpeg_decompress_struct m_info;
370 decoder_error_mgr m_err;
373 JSAMPARRAY m_samples;
376 // Override the standard error method in the IJG JPEG decoder code.
377 void error_exit(j_common_ptr cinfo)
379 // Return control to the setjmp point.
380 decoder_error_mgr *err = (decoder_error_mgr *) cinfo->err;
381 longjmp(err->setjmp_buffer, -1);
384 void init_source(j_decompress_ptr jd)
388 void skip_input_data(j_decompress_ptr jd, long num_bytes)
390 decoder_source_mgr *src = (decoder_source_mgr *)jd->src;
391 src->decoder->skipBytes(num_bytes);
394 boolean fill_input_buffer(j_decompress_ptr jd)
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.
402 void term_source(j_decompress_ptr jd)
404 decoder_source_mgr *src = (decoder_source_mgr *)jd->src;
405 src->decoder->decoder()->jpegComplete();
408 JPEGImageDecoder::JPEGImageDecoder(ImageSource::AlphaOption alphaOption,
409 ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption)
410 : ImageDecoder(alphaOption, gammaAndColorProfileOption)
414 JPEGImageDecoder::~JPEGImageDecoder()
418 bool JPEGImageDecoder::isSizeAvailable()
420 if (!ImageDecoder::isSizeAvailable())
423 return ImageDecoder::isSizeAvailable();
426 bool JPEGImageDecoder::setSize(unsigned width, unsigned height)
428 if (!ImageDecoder::setSize(width, height))
431 prepareScaleDataIfNecessary();
435 ImageFrame* JPEGImageDecoder::frameBufferAtIndex(size_t index)
440 if (m_frameBufferCache.isEmpty()) {
441 m_frameBufferCache.resize(1);
442 m_frameBufferCache[0].setPremultiplyAlpha(m_premultiplyAlpha);
445 ImageFrame& frame = m_frameBufferCache[0];
446 if (frame.status() != ImageFrame::FrameComplete)
451 bool JPEGImageDecoder::setFailed()
454 return ImageDecoder::setFailed();
457 bool JPEGImageDecoder::outputScanlines()
459 if (m_frameBufferCache.isEmpty())
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()))
467 buffer.setStatus(ImageFrame::FramePartial);
468 buffer.setHasAlpha(false);
469 buffer.setColorProfile(m_colorProfile);
471 // For JPEGs, the frame always fills the entire image.
472 buffer.setOriginalFrameRect(IntRect(IntPoint(), size()));
475 jpeg_decompress_struct* info = m_reader->info();
476 JSAMPARRAY samples = m_reader->samples();
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)
486 int destY = scaledY(sourceY);
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
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);
507 ASSERT_NOT_REACHED();
516 void JPEGImageDecoder::jpegComplete()
518 if (m_frameBufferCache.isEmpty())
521 // Hand back an appropriately sized buffer, even if the image ended up being
523 m_frameBufferCache[0].setStatus(ImageFrame::FrameComplete);
526 void JPEGImageDecoder::decode(bool onlySize)
532 m_reader = adoptPtr(new JPEGImageReader(this));
534 // If we couldn't decode the image but we've received all the data, decoding
536 if (!m_reader->decode(*m_data, onlySize) && isAllDataReceived())
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))