2 * Copyright (C) 2006 Apple Computer, Inc.
4 * Portions are Copyright (C) 2001-6 mozilla.org
7 * Stuart Parmenter <stuart@mozilla.com>
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 * Alternatively, the contents of this file may be used under the terms
24 * of either the Mozilla Public License Version 1.1, found at
25 * http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
26 * License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
27 * (the "GPL"), in which case the provisions of the MPL or the GPL are
28 * applicable instead of those above. If you wish to allow use of your
29 * version of this file only under the terms of one of those two
30 * licenses (the MPL or the GPL) and not to allow others to use your
31 * version of this file under the LGPL, indicate your decision by
32 * deletingthe provisions above and replace them with the notice and
33 * other provisions required by the MPL or the GPL, as the case may be.
34 * If you do not delete the provisions above, a recipient may use your
35 * version of this file under any of the LGPL, the MPL or the GPL.
39 #include "JPEGImageDecoder.h"
43 #if PLATFORM(CAIRO) || PLATFORM(QT) || PLATFORM(WX)
46 // Remove warnings from warning level 4.
47 #pragma warning(disable : 4611) // warning C4611: interaction between '_setjmp' and C++ object destruction is non-portable
49 // if ADDRESS_TAG_BIT is dfined, INT32 has been declared as a typedef in the PlatformSDK (BaseTsd.h),
50 // so we need to stop jpeglib.h from trying to #define it
51 // see here for more info: http://www.cygwin.com/ml/cygwin/2004-07/msg01051.html
52 # if defined(ADDRESS_TAG_BIT) && !defined(XMD_H)
54 # define VTK_JPEG_XMD_H
56 #endif // COMPILER(MSVC)
63 # if defined(VTK_JPEG_XMD_H)
64 # undef VTK_JPEG_XMD_H
67 #endif // COMPILER(MSVC)
73 struct decoder_error_mgr {
74 struct jpeg_error_mgr pub; /* "public" fields for IJG library*/
75 jmp_buf setjmp_buffer; /* For handling catastropic errors */
79 JPEG_HEADER, /* Reading JFIF headers */
80 JPEG_START_DECOMPRESS,
81 JPEG_DECOMPRESS_PROGRESSIVE, /* Output progressive pixels */
82 JPEG_DECOMPRESS_SEQUENTIAL, /* Output sequential pixels */
84 JPEG_SINK_NON_JPEG_TRAILER, /* Some image files have a */
85 /* non-JPEG trailer */
89 void init_source(j_decompress_ptr jd);
90 boolean fill_input_buffer(j_decompress_ptr jd);
91 void skip_input_data(j_decompress_ptr jd, long num_bytes);
92 void term_source(j_decompress_ptr jd);
93 void error_exit(j_common_ptr cinfo);
96 * Implementation of a JPEG src object that understands our state machine
98 struct decoder_source_mgr {
99 /* public fields; must be first in this struct! */
100 struct jpeg_source_mgr pub;
102 JPEGImageReader *decoder;
105 class JPEGImageReader
108 JPEGImageReader(JPEGImageDecoder* decoder)
112 , m_state(JPEG_HEADER)
115 memset(&m_info, 0, sizeof(jpeg_decompress_struct));
117 /* We set up the normal JPEG error routines, then override error_exit. */
118 m_info.err = jpeg_std_error(&m_err.pub);
119 m_err.pub.error_exit = error_exit;
121 /* Allocate and initialize JPEG decompression object */
122 jpeg_create_decompress(&m_info);
124 decoder_source_mgr* src = 0;
126 src = (decoder_source_mgr*)fastCalloc(sizeof(decoder_source_mgr), 1);
128 m_state = JPEG_ERROR;
133 m_info.src = (jpeg_source_mgr*)src;
135 /* Set up callback functions. */
136 src->pub.init_source = init_source;
137 src->pub.fill_input_buffer = fill_input_buffer;
138 src->pub.skip_input_data = skip_input_data;
139 src->pub.resync_to_restart = jpeg_resync_to_restart;
140 src->pub.term_source = term_source;
150 decoder_source_mgr* src = (decoder_source_mgr*)m_info.src;
155 jpeg_destroy_decompress(&m_info);
158 void skipBytes(long num_bytes) {
159 decoder_source_mgr* src = (decoder_source_mgr*)m_info.src;
160 long bytesToSkip = std::min(num_bytes, (long)src->pub.bytes_in_buffer);
161 src->pub.bytes_in_buffer -= (size_t)bytesToSkip;
162 src->pub.next_input_byte += bytesToSkip;
164 if (num_bytes > bytesToSkip)
165 m_bytesToSkip = (size_t)(num_bytes - bytesToSkip);
170 bool decode(const Vector<char>& data, bool sizeOnly) {
171 m_decodingSizeOnly = sizeOnly;
173 unsigned newByteCount = data.size() - m_bufferLength;
174 unsigned readOffset = m_bufferLength - m_info.src->bytes_in_buffer;
176 m_info.src->bytes_in_buffer += newByteCount;
177 m_info.src->next_input_byte = (JOCTET*)(data.data()) + readOffset;
179 // If we still have bytes to skip, try to skip those now.
181 skipBytes(m_bytesToSkip);
183 m_bufferLength = data.size();
185 // We need to do the setjmp here. Otherwise bad things will happen
186 if (setjmp(m_err.setjmp_buffer)) {
187 m_state = JPEG_SINK_NON_JPEG_TRAILER;
195 /* Read file parameters with jpeg_read_header() */
196 if (jpeg_read_header(&m_info, true) == JPEG_SUSPENDED)
197 return true; /* I/O suspension */
199 /* let libjpeg take care of gray->RGB and YCbCr->RGB conversions */
200 switch (m_info.jpeg_color_space) {
204 m_info.out_color_space = JCS_RGB;
209 m_state = JPEG_ERROR;
214 * Don't allocate a giant and superfluous memory buffer
215 * when the image is a sequential JPEG.
217 m_info.buffered_image = jpeg_has_multiple_scans(&m_info);
219 /* Used to set up image size so arrays can be allocated */
220 jpeg_calc_output_dimensions(&m_info);
223 * Make a one-row-high sample array that will go away
224 * when done with image. Always make it big enough to
225 * hold an RGB row. Since this uses the IJG memory
226 * manager, it must be allocated before the call to
227 * jpeg_start_compress().
229 int row_stride = m_info.output_width * 4; // RGBA buffer
232 m_samples = (*m_info.mem->alloc_sarray)((j_common_ptr) &m_info,
236 m_state = JPEG_START_DECOMPRESS;
238 // We can fill in the size now that the header is available.
239 m_decoder->setSize(m_info.image_width, m_info.image_height);
241 if (m_decodingSizeOnly) {
243 // Reduce our buffer length and available data.
244 m_bufferLength -= m_info.src->bytes_in_buffer;
245 m_info.src->bytes_in_buffer = 0;
250 case JPEG_START_DECOMPRESS:
252 /* Set parameters for decompression */
253 /* FIXME -- Should reset dct_method and dither mode
254 * for final pass of progressive JPEG
256 m_info.dct_method = JDCT_ISLOW;
257 m_info.dither_mode = JDITHER_FS;
258 m_info.do_fancy_upsampling = true;
259 m_info.enable_2pass_quant = false;
260 m_info.do_block_smoothing = true;
262 /* Start decompressor */
263 if (!jpeg_start_decompress(&m_info))
264 return true; /* I/O suspension */
266 /* If this is a progressive JPEG ... */
267 m_state = (m_info.buffered_image) ? JPEG_DECOMPRESS_PROGRESSIVE : JPEG_DECOMPRESS_SEQUENTIAL;
270 case JPEG_DECOMPRESS_SEQUENTIAL:
272 if (m_state == JPEG_DECOMPRESS_SEQUENTIAL) {
274 if (!m_decoder->outputScanlines())
275 return true; /* I/O suspension */
277 /* If we've completed image output ... */
278 assert(m_info.output_scanline == m_info.output_height);
283 case JPEG_DECOMPRESS_PROGRESSIVE:
285 if (m_state == JPEG_DECOMPRESS_PROGRESSIVE) {
288 status = jpeg_consume_input(&m_info);
289 } while ((status != JPEG_SUSPENDED) &&
290 (status != JPEG_REACHED_EOI));
293 if (m_info.output_scanline == 0) {
294 int scan = m_info.input_scan_number;
296 /* if we haven't displayed anything yet (output_scan_number==0)
297 and we have enough data for a complete scan, force output
298 of the last full scan */
299 if ((m_info.output_scan_number == 0) &&
301 (status != JPEG_REACHED_EOI))
304 if (!jpeg_start_output(&m_info, scan))
305 return true; /* I/O suspension */
308 if (m_info.output_scanline == 0xffffff)
309 m_info.output_scanline = 0;
311 if (!m_decoder->outputScanlines()) {
312 if (m_info.output_scanline == 0)
313 /* didn't manage to read any lines - flag so we don't call
314 jpeg_start_output() multiple times for the same scan */
315 m_info.output_scanline = 0xffffff;
316 return true; /* I/O suspension */
319 if (m_info.output_scanline == m_info.output_height) {
320 if (!jpeg_finish_output(&m_info))
321 return true; /* I/O suspension */
323 if (jpeg_input_complete(&m_info) &&
324 (m_info.input_scan_number == m_info.output_scan_number))
327 m_info.output_scanline = 0;
337 /* Finish decompression */
338 if (!jpeg_finish_decompress(&m_info))
339 return true; /* I/O suspension */
341 m_state = JPEG_SINK_NON_JPEG_TRAILER;
347 case JPEG_SINK_NON_JPEG_TRAILER:
357 jpeg_decompress_struct* info() { return &m_info; }
358 JSAMPARRAY samples() const { return m_samples; }
359 JPEGImageDecoder* decoder() { return m_decoder; }
362 JPEGImageDecoder* m_decoder;
363 unsigned m_bufferLength;
365 bool m_decodingSizeOnly;
368 jpeg_decompress_struct m_info;
369 decoder_error_mgr m_err;
372 JSAMPARRAY m_samples;
375 /* Override the standard error method in the IJG JPEG decoder code. */
376 void error_exit(j_common_ptr cinfo)
378 /* Return control to the setjmp point. */
379 decoder_error_mgr *err = (decoder_error_mgr *) cinfo->err;
380 longjmp(err->setjmp_buffer, -1);
383 void init_source(j_decompress_ptr jd)
387 void skip_input_data(j_decompress_ptr jd, long num_bytes)
389 decoder_source_mgr *src = (decoder_source_mgr *)jd->src;
390 src->decoder->skipBytes(num_bytes);
393 boolean fill_input_buffer(j_decompress_ptr jd)
395 // Our decode step always sets things up properly, so if this method is ever
396 // called, then we have hit the end of the buffer. A return value of FALSE indicates
397 // that we have no data to supply yet.
401 void term_source (j_decompress_ptr jd)
403 decoder_source_mgr *src = (decoder_source_mgr *)jd->src;
404 src->decoder->decoder()->jpegComplete();
407 JPEGImageDecoder::JPEGImageDecoder()
411 JPEGImageDecoder::~JPEGImageDecoder()
416 // Take the data and store it.
417 void JPEGImageDecoder::setData(SharedBuffer* data, bool allDataReceived)
422 // Cache our new data.
423 ImageDecoder::setData(data, allDataReceived);
425 // Create the JPEG reader.
426 if (!m_reader && !m_failed)
427 m_reader = new JPEGImageReader(this);
430 // Whether or not the size information has been decoded yet.
431 bool JPEGImageDecoder::isSizeAvailable() const
433 // If we have pending data to decode, send it to the JPEG reader now.
434 if (!m_sizeAvailable && m_reader) {
438 // The decoder will go ahead and aggressively consume everything up until the
439 // size is encountered.
443 return m_sizeAvailable;
446 RGBA32Buffer* JPEGImageDecoder::frameBufferAtIndex(size_t index)
451 if (m_frameBufferCache.isEmpty())
452 m_frameBufferCache.resize(1);
454 RGBA32Buffer& frame = m_frameBufferCache[0];
455 if (frame.status() != RGBA32Buffer::FrameComplete && m_reader)
456 // Decode this frame.
461 // Feed data to the JPEG reader.
462 void JPEGImageDecoder::decode(bool sizeOnly) const
467 m_failed = !m_reader->decode(m_data->buffer(), sizeOnly);
469 if (m_failed || (!m_frameBufferCache.isEmpty() && m_frameBufferCache[0].status() == RGBA32Buffer::FrameComplete)) {
475 bool JPEGImageDecoder::outputScanlines()
477 if (m_frameBufferCache.isEmpty())
480 // Resize to the width and height of the image.
481 RGBA32Buffer& buffer = m_frameBufferCache[0];
482 if (buffer.status() == RGBA32Buffer::FrameEmpty) {
483 // Let's resize our buffer now to the correct width/height.
484 RGBA32Array& bytes = buffer.bytes();
485 bytes.resize(m_size.width() * m_size.height());
487 // Update our status to be partially complete.
488 buffer.setStatus(RGBA32Buffer::FramePartial);
490 // For JPEGs, the frame always fills the entire image.
491 buffer.setRect(IntRect(0, 0, m_size.width(), m_size.height()));
493 // We don't have alpha (this is the default when the buffer is constructed).
496 jpeg_decompress_struct* info = m_reader->info();
497 JSAMPARRAY samples = m_reader->samples();
499 unsigned* dst = buffer.bytes().data() + info->output_scanline * m_size.width();
501 while (info->output_scanline < info->output_height) {
502 /* Request one scanline. Returns 0 or 1 scanlines. */
503 if (jpeg_read_scanlines(info, samples, 1) != 1)
505 JSAMPLE *j1 = samples[0];
506 for (unsigned i = 0; i < info->output_width; ++i) {
510 RGBA32Buffer::setRGBA(*dst++, r, g, b, 0xFF);
513 buffer.ensureHeight(info->output_scanline);
519 void JPEGImageDecoder::jpegComplete()
521 if (m_frameBufferCache.isEmpty())
524 // Hand back an appropriately sized buffer, even if the image ended up being empty.
525 RGBA32Buffer& buffer = m_frameBufferCache[0];
526 buffer.setStatus(RGBA32Buffer::FrameComplete);
531 #endif // PLATFORM(CAIRO)