Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(110)

Side by Side Diff: Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.cpp

Issue 99103006: Moving GraphicsContext and dependencies from core to platform. (Closed) Base URL: svn://svn.chromium.org/blink/trunk
Patch Set: Final patch - fixes Android Created 7 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
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 US A
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 "core/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_E XT_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) | (GETJOC TET(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, uns igned& 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 = mark er->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, isBig Endian));
211 }
212 }
213
214 return ImageOrientation();
215 }
216
217 #if USE(QCMSLIB)
218 static void readColorProfile(jpeg_decompress_struct* info, ColorProfile& colorPr ofile)
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 #else
242 UNUSED_PARAM(info);
243 UNUSED_PARAM(colorProfile);
244 #endif
245 }
246 #endif
247
248 class JPEGImageReader {
249 WTF_MAKE_FAST_ALLOCATED;
250 public:
251 JPEGImageReader(JPEGImageDecoder* decoder)
252 : m_decoder(decoder)
253 , m_bufferLength(0)
254 , m_bytesToSkip(0)
255 , m_state(JPEG_HEADER)
256 , m_samples(0)
257 #if USE(QCMSLIB)
258 , m_transform(0)
259 #endif
260 {
261 memset(&m_info, 0, sizeof(jpeg_decompress_struct));
262
263 // We set up the normal JPEG error routines, then override error_exit.
264 m_info.err = jpeg_std_error(&m_err.pub);
265 m_err.pub.error_exit = error_exit;
266
267 // Allocate and initialize JPEG decompression object.
268 jpeg_create_decompress(&m_info);
269
270 decoder_source_mgr* src = 0;
271 if (!m_info.src) {
272 src = (decoder_source_mgr*)fastCalloc(sizeof(decoder_source_mgr), 1) ;
273 if (!src) {
274 m_state = JPEG_ERROR;
275 return;
276 }
277 }
278
279 m_info.src = (jpeg_source_mgr*)src;
280
281 // Set up callback functions.
282 src->pub.init_source = init_source;
283 src->pub.fill_input_buffer = fill_input_buffer;
284 src->pub.skip_input_data = skip_input_data;
285 src->pub.resync_to_restart = jpeg_resync_to_restart;
286 src->pub.term_source = term_source;
287 src->decoder = this;
288
289 #if USE(ICCJPEG)
290 // Retain ICC color profile markers for color management.
291 setup_read_icc_profile(&m_info);
292 #endif
293
294 // Keep APP1 blocks, for obtaining exif data.
295 jpeg_save_markers(&m_info, exifMarker, 0xFFFF);
296 }
297
298 ~JPEGImageReader()
299 {
300 close();
301 }
302
303 void close()
304 {
305 decoder_source_mgr* src = (decoder_source_mgr*)m_info.src;
306 if (src)
307 fastFree(src);
308 m_info.src = 0;
309
310 #if USE(QCMSLIB)
311 if (m_transform)
312 qcms_transform_release(m_transform);
313 m_transform = 0;
314 #endif
315 jpeg_destroy_decompress(&m_info);
316 }
317
318 void skipBytes(long numBytes)
319 {
320 decoder_source_mgr* src = (decoder_source_mgr*)m_info.src;
321 long bytesToSkip = std::min(numBytes, (long)src->pub.bytes_in_buffer);
322 src->pub.bytes_in_buffer -= (size_t)bytesToSkip;
323 src->pub.next_input_byte += bytesToSkip;
324
325 m_bytesToSkip = std::max(numBytes - bytesToSkip, static_cast<long>(0));
326 }
327
328 bool decode(const SharedBuffer& data, bool onlySize)
329 {
330 unsigned newByteCount = data.size() - m_bufferLength;
331 unsigned readOffset = m_bufferLength - m_info.src->bytes_in_buffer;
332
333 m_info.src->bytes_in_buffer += newByteCount;
334 m_info.src->next_input_byte = (JOCTET*)(data.data()) + readOffset;
335
336 // If we still have bytes to skip, try to skip those now.
337 if (m_bytesToSkip)
338 skipBytes(m_bytesToSkip);
339
340 m_bufferLength = data.size();
341
342 // We need to do the setjmp here. Otherwise bad things will happen
343 if (setjmp(m_err.setjmp_buffer))
344 return m_decoder->setFailed();
345
346 switch (m_state) {
347 case JPEG_HEADER:
348 // Read file parameters with jpeg_read_header().
349 if (jpeg_read_header(&m_info, true) == JPEG_SUSPENDED)
350 return false; // I/O suspension.
351
352 switch (m_info.jpeg_color_space) {
353 case JCS_GRAYSCALE:
354 case JCS_RGB:
355 case JCS_YCbCr:
356 // libjpeg can convert GRAYSCALE and YCbCr image pixels to RGB.
357 m_info.out_color_space = rgbOutputColorSpace();
358 #if defined(TURBO_JPEG_RGB_SWIZZLE)
359 if (m_info.saw_JFIF_marker)
360 break;
361 // FIXME: Swizzle decoding does not support Adobe transform=0
362 // images (yet), so revert to using JSC_RGB in that case.
363 if (m_info.saw_Adobe_marker && !m_info.Adobe_transform)
364 m_info.out_color_space = JCS_RGB;
365 #endif
366 break;
367 case JCS_CMYK:
368 case JCS_YCCK:
369 // libjpeg can convert YCCK to CMYK, but neither to RGB, so we
370 // manually convert CMKY to RGB.
371 m_info.out_color_space = JCS_CMYK;
372 break;
373 default:
374 return m_decoder->setFailed();
375 }
376
377 m_state = JPEG_START_DECOMPRESS;
378
379 // We can fill in the size now that the header is available.
380 if (!m_decoder->setSize(m_info.image_width, m_info.image_height))
381 return false;
382
383 m_decoder->setOrientation(readImageOrientation(info()));
384
385 #if USE(QCMSLIB)
386 // Allow color management of the decoded RGBA pixels if possible.
387 if (!m_decoder->ignoresGammaAndColorProfile()) {
388 ColorProfile colorProfile;
389 readColorProfile(info(), colorProfile);
390 createColorTransform(colorProfile, colorSpaceHasAlpha(m_info.out _color_space));
391 #if defined(TURBO_JPEG_RGB_SWIZZLE)
392 // Input RGBA data to qcms. Note: restored to BGRA on output.
393 if (m_transform && m_info.out_color_space == JCS_EXT_BGRA)
394 m_info.out_color_space = JCS_EXT_RGBA;
395 #endif
396 }
397 #endif
398 // Don't allocate a giant and superfluous memory buffer when the
399 // image is a sequential JPEG.
400 m_info.buffered_image = jpeg_has_multiple_scans(&m_info);
401
402 if (onlySize) {
403 // We can stop here. Reduce our buffer length and available data .
404 m_bufferLength -= m_info.src->bytes_in_buffer;
405 m_info.src->bytes_in_buffer = 0;
406 return true;
407 }
408 // FALL THROUGH
409
410 case JPEG_START_DECOMPRESS:
411 // Set parameters for decompression.
412 // FIXME -- Should reset dct_method and dither mode for final pass
413 // of progressive JPEG.
414 m_info.dct_method = dctMethod();
415 m_info.dither_mode = ditherMode();
416 m_info.do_fancy_upsampling = doFancyUpsampling();
417 m_info.enable_2pass_quant = false;
418 m_info.do_block_smoothing = true;
419
420 if (m_decoder->size() != m_decoder->decodedSize()) {
421 m_info.scale_denom = scaleDenominator;
422 m_info.scale_num = m_decoder->decodedSize().width() * scaleDenom inator / m_info.image_width;
423 }
424
425 // Used to set up image size so arrays can be allocated.
426 jpeg_calc_output_dimensions(&m_info);
427
428 // Make a one-row-high sample array that will go away when done with
429 // image. Always make it big enough to hold an RGB row. Since this
430 // uses the IJG memory manager, it must be allocated before the call
431 // to jpeg_start_compress().
432 // FIXME: note that some output color spaces do not need the samples
433 // buffer. Remove this allocation for those color spaces.
434 m_samples = (*m_info.mem->alloc_sarray)(reinterpret_cast<j_common_pt r>(&m_info), JPOOL_IMAGE, m_info.output_width * 4, 1);
435
436 // Start decompressor.
437 if (!jpeg_start_decompress(&m_info))
438 return false; // I/O suspension.
439
440 // If this is a progressive JPEG ...
441 m_state = (m_info.buffered_image) ? JPEG_DECOMPRESS_PROGRESSIVE : JP EG_DECOMPRESS_SEQUENTIAL;
442 // FALL THROUGH
443
444 case JPEG_DECOMPRESS_SEQUENTIAL:
445 if (m_state == JPEG_DECOMPRESS_SEQUENTIAL) {
446
447 if (!m_decoder->outputScanlines())
448 return false; // I/O suspension.
449
450 // If we've completed image output...
451 ASSERT(m_info.output_scanline == m_info.output_height);
452 m_state = JPEG_DONE;
453 }
454 // FALL THROUGH
455
456 case JPEG_DECOMPRESS_PROGRESSIVE:
457 if (m_state == JPEG_DECOMPRESS_PROGRESSIVE) {
458 int status;
459 do {
460 status = jpeg_consume_input(&m_info);
461 } while ((status != JPEG_SUSPENDED) && (status != JPEG_REACHED_E OI));
462
463 for (;;) {
464 if (!m_info.output_scanline) {
465 int scan = m_info.input_scan_number;
466
467 // If we haven't displayed anything yet
468 // (output_scan_number == 0) and we have enough data for
469 // a complete scan, force output of the last full scan.
470 if (!m_info.output_scan_number && (scan > 1) && (status != JPEG_REACHED_EOI))
471 --scan;
472
473 if (!jpeg_start_output(&m_info, scan))
474 return false; // I/O suspension.
475 }
476
477 if (m_info.output_scanline == 0xffffff)
478 m_info.output_scanline = 0;
479
480 // If outputScanlines() fails, it deletes |this|. Therefore,
481 // copy the decoder pointer and use it to check for failure
482 // to avoid member access in the failure case.
483 JPEGImageDecoder* decoder = m_decoder;
484 if (!decoder->outputScanlines()) {
485 if (decoder->failed()) // Careful; |this| is deleted.
486 return false;
487 if (!m_info.output_scanline)
488 // Didn't manage to read any lines - flag so we
489 // don't call jpeg_start_output() multiple times for
490 // the same scan.
491 m_info.output_scanline = 0xffffff;
492 return false; // I/O suspension.
493 }
494
495 if (m_info.output_scanline == m_info.output_height) {
496 if (!jpeg_finish_output(&m_info))
497 return false; // I/O suspension.
498
499 if (jpeg_input_complete(&m_info) && (m_info.input_scan_n umber == m_info.output_scan_number))
500 break;
501
502 m_info.output_scanline = 0;
503 }
504 }
505
506 m_state = JPEG_DONE;
507 }
508 // FALL THROUGH
509
510 case JPEG_DONE:
511 // Finish decompression.
512 return jpeg_finish_decompress(&m_info);
513
514 case JPEG_ERROR:
515 // We can get here if the constructor failed.
516 return m_decoder->setFailed();
517 }
518
519 return true;
520 }
521
522 jpeg_decompress_struct* info() { return &m_info; }
523 JSAMPARRAY samples() const { return m_samples; }
524 JPEGImageDecoder* decoder() { return m_decoder; }
525 #if USE(QCMSLIB)
526 qcms_transform* colorTransform() const { return m_transform; }
527
528 void createColorTransform(const ColorProfile& colorProfile, bool hasAlpha)
529 {
530 if (m_transform)
531 qcms_transform_release(m_transform);
532 m_transform = 0;
533
534 if (colorProfile.isEmpty())
535 return;
536 qcms_profile* deviceProfile = ImageDecoder::qcmsOutputDeviceProfile();
537 if (!deviceProfile)
538 return;
539 qcms_profile* inputProfile = qcms_profile_from_memory(colorProfile.data( ), colorProfile.size());
540 if (!inputProfile)
541 return;
542 // We currently only support color profiles for RGB profiled images.
543 ASSERT(icSigRgbData == qcms_profile_get_color_space(inputProfile));
544 qcms_data_type dataFormat = hasAlpha ? QCMS_DATA_RGBA_8 : QCMS_DATA_RGB_ 8;
545 // FIXME: Don't force perceptual intent if the image profile contains an intent.
546 m_transform = qcms_transform_create(inputProfile, dataFormat, deviceProf ile, dataFormat, QCMS_INTENT_PERCEPTUAL);
547 qcms_profile_release(inputProfile);
548 }
549 #endif
550
551 private:
552 JPEGImageDecoder* m_decoder;
553 unsigned m_bufferLength;
554 int m_bytesToSkip;
555
556 jpeg_decompress_struct m_info;
557 decoder_error_mgr m_err;
558 jstate m_state;
559
560 JSAMPARRAY m_samples;
561
562 #if USE(QCMSLIB)
563 qcms_transform* m_transform;
564 #endif
565 };
566
567 // Override the standard error method in the IJG JPEG decoder code.
568 void error_exit(j_common_ptr cinfo)
569 {
570 // Return control to the setjmp point.
571 decoder_error_mgr *err = reinterpret_cast_ptr<decoder_error_mgr *>(cinfo->er r);
572 longjmp(err->setjmp_buffer, -1);
573 }
574
575 void init_source(j_decompress_ptr)
576 {
577 }
578
579 void skip_input_data(j_decompress_ptr jd, long num_bytes)
580 {
581 decoder_source_mgr *src = (decoder_source_mgr *)jd->src;
582 src->decoder->skipBytes(num_bytes);
583 }
584
585 boolean fill_input_buffer(j_decompress_ptr)
586 {
587 // Our decode step always sets things up properly, so if this method is ever
588 // called, then we have hit the end of the buffer. A return value of false
589 // indicates that we have no data to supply yet.
590 return false;
591 }
592
593 void term_source(j_decompress_ptr jd)
594 {
595 decoder_source_mgr *src = (decoder_source_mgr *)jd->src;
596 src->decoder->decoder()->jpegComplete();
597 }
598
599 JPEGImageDecoder::JPEGImageDecoder(ImageSource::AlphaOption alphaOption,
600 ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption,
601 size_t maxDecodedBytes)
602 : ImageDecoder(alphaOption, gammaAndColorProfileOption, maxDecodedBytes)
603 {
604 }
605
606 JPEGImageDecoder::~JPEGImageDecoder()
607 {
608 }
609
610 bool JPEGImageDecoder::isSizeAvailable()
611 {
612 if (!ImageDecoder::isSizeAvailable())
613 decode(true);
614
615 return ImageDecoder::isSizeAvailable();
616 }
617
618 bool JPEGImageDecoder::setSize(unsigned width, unsigned height)
619 {
620 if (!ImageDecoder::setSize(width, height))
621 return false;
622
623 size_t originalBytes = width * height * 4;
624 if (originalBytes <= m_maxDecodedBytes) {
625 m_decodedSize = IntSize(width, height);
626 return true;
627 }
628
629 // Downsample according to the maximum decoded size.
630 unsigned scaleNumerator = static_cast<unsigned>(floor(sqrt(
631 // MSVC needs explicit parameter type for sqrt().
632 static_cast<float>(m_maxDecodedBytes * scaleDenominator * scaleDenominat or / originalBytes))));
633 m_decodedSize = IntSize((scaleNumerator * width + scaleDenominator - 1) / sc aleDenominator,
634 (scaleNumerator * height + scaleDenominator - 1) / scaleDenominator);
635
636 // The image is too big to be downsampled by libjpeg.
637 // FIXME: Post-process to downsample the image.
638 if (m_decodedSize.isEmpty())
639 return setFailed();
640
641 return true;
642 }
643
644 ImageFrame* JPEGImageDecoder::frameBufferAtIndex(size_t index)
645 {
646 if (index)
647 return 0;
648
649 if (m_frameBufferCache.isEmpty()) {
650 m_frameBufferCache.resize(1);
651 m_frameBufferCache[0].setPremultiplyAlpha(m_premultiplyAlpha);
652 }
653
654 ImageFrame& frame = m_frameBufferCache[0];
655 if (frame.status() != ImageFrame::FrameComplete) {
656 PlatformInstrumentation::willDecodeImage("JPEG");
657 decode(false);
658 PlatformInstrumentation::didDecodeImage();
659 }
660
661 frame.notifyBitmapIfPixelsChanged();
662 return &frame;
663 }
664
665 bool JPEGImageDecoder::setFailed()
666 {
667 m_reader.clear();
668 return ImageDecoder::setFailed();
669 }
670
671 template <J_COLOR_SPACE colorSpace> void setPixel(ImageFrame& buffer, ImageFrame ::PixelData* pixel, JSAMPARRAY samples, int column)
672 {
673 JSAMPLE* jsample = *samples + column * (colorSpace == JCS_RGB ? 3 : 4);
674
675 switch (colorSpace) {
676 case JCS_RGB:
677 buffer.setRGBARaw(pixel, jsample[0], jsample[1], jsample[2], 255);
678 break;
679 case JCS_CMYK:
680 // Source is 'Inverted CMYK', output is RGB.
681 // See: http://www.easyrgb.com/math.php?MATH=M12#text12
682 // Or: http://www.ilkeratalay.com/colorspacesfaq.php#rgb
683 // From CMYK to CMY:
684 // X = X * (1 - K ) + K [for X = C, M, or Y]
685 // Thus, from Inverted CMYK to CMY is:
686 // X = (1-iX) * (1 - (1-iK)) + (1-iK) => 1 - iX*iK
687 // From CMY (0..1) to RGB (0..1):
688 // R = 1 - C => 1 - (1 - iC*iK) => iC*iK [G and B similar]
689 unsigned k = jsample[3];
690 buffer.setRGBARaw(pixel, jsample[0] * k / 255, jsample[1] * k / 255, jsa mple[2] * k / 255, 255);
691 break;
692 }
693 }
694
695 template <J_COLOR_SPACE colorSpace> bool outputRows(JPEGImageReader* reader, Ima geFrame& buffer)
696 {
697 JSAMPARRAY samples = reader->samples();
698 jpeg_decompress_struct* info = reader->info();
699 int width = info->output_width;
700
701 while (info->output_scanline < info->output_height) {
702 // jpeg_read_scanlines will increase the scanline counter, so we
703 // save the scanline before calling it.
704 int y = info->output_scanline;
705 // Request one scanline: returns 0 or 1 scanlines.
706 if (jpeg_read_scanlines(info, samples, 1) != 1)
707 return false;
708 #if USE(QCMSLIB)
709 if (reader->colorTransform() && colorSpace == JCS_RGB)
710 qcms_transform_data(reader->colorTransform(), *samples, *samples, wi dth);
711 #endif
712 ImageFrame::PixelData* pixel = buffer.getAddr(0, y);
713 for (int x = 0; x < width; ++pixel, ++x)
714 setPixel<colorSpace>(buffer, pixel, samples, x);
715 }
716
717 buffer.setPixelsChanged(true);
718 return true;
719 }
720
721 bool JPEGImageDecoder::outputScanlines()
722 {
723 if (m_frameBufferCache.isEmpty())
724 return false;
725
726 jpeg_decompress_struct* info = m_reader->info();
727
728 // Initialize the framebuffer if needed.
729 ImageFrame& buffer = m_frameBufferCache[0];
730 if (buffer.status() == ImageFrame::FrameEmpty) {
731 ASSERT(info->output_width == static_cast<JDIMENSION>(m_decodedSize.width ()));
732 ASSERT(info->output_height == static_cast<JDIMENSION>(m_decodedSize.heig ht()));
733
734 if (!buffer.setSize(info->output_width, info->output_height))
735 return setFailed();
736 buffer.setStatus(ImageFrame::FramePartial);
737 // The buffer is transparent outside the decoded area while the image is
738 // loading. The completed image will be marked fully opaque in jpegCompl ete().
739 buffer.setHasAlpha(true);
740
741 // For JPEGs, the frame always fills the entire image.
742 buffer.setOriginalFrameRect(IntRect(IntPoint(), size()));
743 }
744
745 #if defined(TURBO_JPEG_RGB_SWIZZLE)
746 if (turboSwizzled(info->out_color_space)) {
747 while (info->output_scanline < info->output_height) {
748 unsigned char* row = reinterpret_cast<unsigned char*>(buffer.getAddr (0, info->output_scanline));
749 if (jpeg_read_scanlines(info, &row, 1) != 1)
750 return false;
751 #if USE(QCMSLIB)
752 if (qcms_transform* transform = m_reader->colorTransform())
753 qcms_transform_data_type(transform, row, row, info->output_width , rgbOutputColorSpace() == JCS_EXT_BGRA ? QCMS_OUTPUT_BGRX : QCMS_OUTPUT_RGBX);
754 #endif
755 }
756 buffer.setPixelsChanged(true);
757 return true;
758 }
759 #endif
760
761 switch (info->out_color_space) {
762 case JCS_RGB:
763 return outputRows<JCS_RGB>(m_reader.get(), buffer);
764 case JCS_CMYK:
765 return outputRows<JCS_CMYK>(m_reader.get(), buffer);
766 default:
767 ASSERT_NOT_REACHED();
768 }
769
770 return setFailed();
771 }
772
773 void JPEGImageDecoder::jpegComplete()
774 {
775 if (m_frameBufferCache.isEmpty())
776 return;
777
778 // Hand back an appropriately sized buffer, even if the image ended up being
779 // empty.
780 ImageFrame& buffer = m_frameBufferCache[0];
781 buffer.setHasAlpha(false);
782 buffer.setStatus(ImageFrame::FrameComplete);
783 }
784
785 void JPEGImageDecoder::decode(bool onlySize)
786 {
787 if (failed())
788 return;
789
790 if (!m_reader) {
791 m_reader = adoptPtr(new JPEGImageReader(this));
792 }
793
794 // If we couldn't decode the image but we've received all the data, decoding
795 // has failed.
796 if (!m_reader->decode(*m_data, onlySize) && isAllDataReceived())
797 setFailed();
798 // If we're done decoding the image, we don't need the JPEGImageReader
799 // anymore. (If we failed, |m_reader| has already been cleared.)
800 else if (!m_frameBufferCache.isEmpty() && (m_frameBufferCache[0].status() == ImageFrame::FrameComplete))
801 m_reader.clear();
802 }
803
804 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698