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