This source file includes following definitions.
- rgbOutputColorSpace
- rgbOutputColorSpace
- turboSwizzled
- colorSpaceHasAlpha
- rgbOutputColorSpace
- colorSpaceHasAlpha
- dctMethod
- ditherMode
- dctMethod
- ditherMode
- doFancyUpsampling
- doFancyUpsampling
- readUint16
- readUint32
- checkExifHeader
- readImageOrientation
- readColorProfile
- m_transform
- close
- skipBytes
- decode
- info
- samples
- decoder
- colorTransform
- createColorTransform
- error_exit
- init_source
- skip_input_data
- fill_input_buffer
- term_source
- isSizeAvailable
- setSize
- setDecodedSize
- desiredScaleNumerator
- frameBufferAtIndex
- setFailed
- setPixel
- outputRows
- outputScanlines
- jpegComplete
- decode
#include "config.h"
#include "platform/image-decoders/jpeg/JPEGImageDecoder.h"
#include "platform/PlatformInstrumentation.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/dtoa/utils.h"
extern "C" {
#include <stdio.h>
#include "jpeglib.h"
#if USE(ICCJPEG)
#include "iccjpeg.h"
#endif
#if USE(QCMSLIB)
#include "qcms.h"
#endif
#include <setjmp.h>
}
#if CPU(BIG_ENDIAN) || CPU(MIDDLE_ENDIAN)
#error Blink assumes a little-endian target.
#endif
#if defined(JCS_ALPHA_EXTENSIONS)
#define TURBO_JPEG_RGB_SWIZZLE
#if SK_B32_SHIFT
inline J_COLOR_SPACE rgbOutputColorSpace() { return JCS_EXT_RGBA; }
#else
inline J_COLOR_SPACE rgbOutputColorSpace() { return JCS_EXT_BGRA; }
#endif
inline bool turboSwizzled(J_COLOR_SPACE colorSpace) { return colorSpace == JCS_EXT_RGBA || colorSpace == JCS_EXT_BGRA; }
inline bool colorSpaceHasAlpha(J_COLOR_SPACE colorSpace) { return turboSwizzled(colorSpace); }
#else
inline J_COLOR_SPACE rgbOutputColorSpace() { return JCS_RGB; }
inline bool colorSpaceHasAlpha(J_COLOR_SPACE) { return false; }
#endif
#if USE(LOW_QUALITY_IMAGE_NO_JPEG_DITHERING)
inline J_DCT_METHOD dctMethod() { return JDCT_IFAST; }
inline J_DITHER_MODE ditherMode() { return JDITHER_NONE; }
#else
inline J_DCT_METHOD dctMethod() { return JDCT_ISLOW; }
inline J_DITHER_MODE ditherMode() { return JDITHER_FS; }
#endif
#if USE(LOW_QUALITY_IMAGE_NO_JPEG_FANCY_UPSAMPLING)
inline bool doFancyUpsampling() { return false; }
#else
inline bool doFancyUpsampling() { return true; }
#endif
namespace {
const int exifMarker = JPEG_APP0 + 1;
const unsigned scaleDenominator = 8;
}
namespace WebCore {
struct decoder_error_mgr {
struct jpeg_error_mgr pub;
jmp_buf setjmp_buffer;
};
enum jstate {
JPEG_HEADER,
JPEG_START_DECOMPRESS,
JPEG_DECOMPRESS_PROGRESSIVE,
JPEG_DECOMPRESS_SEQUENTIAL,
JPEG_DONE,
JPEG_ERROR
};
void init_source(j_decompress_ptr jd);
boolean fill_input_buffer(j_decompress_ptr jd);
void skip_input_data(j_decompress_ptr jd, long num_bytes);
void term_source(j_decompress_ptr jd);
void error_exit(j_common_ptr cinfo);
struct decoder_source_mgr {
struct jpeg_source_mgr pub;
JPEGImageReader* decoder;
};
static unsigned readUint16(JOCTET* data, bool isBigEndian)
{
if (isBigEndian)
return (GETJOCTET(data[0]) << 8) | GETJOCTET(data[1]);
return (GETJOCTET(data[1]) << 8) | GETJOCTET(data[0]);
}
static unsigned readUint32(JOCTET* data, bool isBigEndian)
{
if (isBigEndian)
return (GETJOCTET(data[0]) << 24) | (GETJOCTET(data[1]) << 16) | (GETJOCTET(data[2]) << 8) | GETJOCTET(data[3]);
return (GETJOCTET(data[3]) << 24) | (GETJOCTET(data[2]) << 16) | (GETJOCTET(data[1]) << 8) | GETJOCTET(data[0]);
}
static bool checkExifHeader(jpeg_saved_marker_ptr marker, bool& isBigEndian, unsigned& ifdOffset)
{
const unsigned exifHeaderSize = 14;
if (!(marker->marker == exifMarker
&& marker->data_length >= exifHeaderSize
&& marker->data[0] == 'E'
&& marker->data[1] == 'x'
&& marker->data[2] == 'i'
&& marker->data[3] == 'f'
&& marker->data[4] == '\0'
&& ((marker->data[6] == 'I' && marker->data[7] == 'I')
|| (marker->data[6] == 'M' && marker->data[7] == 'M'))))
return false;
isBigEndian = marker->data[6] == 'M';
if (readUint16(marker->data + 8, isBigEndian) != 42)
return false;
ifdOffset = readUint32(marker->data + 10, isBigEndian);
return true;
}
static ImageOrientation readImageOrientation(jpeg_decompress_struct* info)
{
const unsigned orientationTag = 0x112;
const unsigned shortType = 3;
for (jpeg_saved_marker_ptr marker = info->marker_list; marker; marker = marker->next) {
bool isBigEndian;
unsigned ifdOffset;
if (!checkExifHeader(marker, isBigEndian, ifdOffset))
continue;
const unsigned offsetToTiffData = 6;
if (marker->data_length < offsetToTiffData || ifdOffset >= marker->data_length - offsetToTiffData)
continue;
ifdOffset += offsetToTiffData;
JOCTET* ifd = marker->data + ifdOffset;
JOCTET* end = marker->data + marker->data_length;
if (end - ifd < 2)
continue;
unsigned tagCount = readUint16(ifd, isBigEndian);
ifd += 2;
const int ifdEntrySize = 12;
for (unsigned i = 0; i < tagCount && end - ifd >= ifdEntrySize; ++i, ifd += ifdEntrySize) {
unsigned tag = readUint16(ifd, isBigEndian);
unsigned type = readUint16(ifd + 2, isBigEndian);
unsigned count = readUint32(ifd + 4, isBigEndian);
if (tag == orientationTag && type == shortType && count == 1)
return ImageOrientation::fromEXIFValue(readUint16(ifd + 8, isBigEndian));
}
}
return ImageOrientation();
}
#if USE(QCMSLIB)
static void readColorProfile(jpeg_decompress_struct* info, ColorProfile& colorProfile)
{
#if USE(ICCJPEG)
JOCTET* profile;
unsigned profileLength;
if (!read_icc_profile(info, &profile, &profileLength))
return;
bool ignoreProfile = false;
char* profileData = reinterpret_cast<char*>(profile);
if (profileLength < ImageDecoder::iccColorProfileHeaderLength)
ignoreProfile = true;
else if (!ImageDecoder::rgbColorProfile(profileData, profileLength))
ignoreProfile = true;
else if (!ImageDecoder::inputDeviceColorProfile(profileData, profileLength))
ignoreProfile = true;
ASSERT(colorProfile.isEmpty());
if (!ignoreProfile)
colorProfile.append(profileData, profileLength);
free(profile);
#endif
}
#endif
class JPEGImageReader {
WTF_MAKE_FAST_ALLOCATED;
public:
JPEGImageReader(JPEGImageDecoder* decoder)
: m_decoder(decoder)
, m_bufferLength(0)
, m_bytesToSkip(0)
, m_state(JPEG_HEADER)
, m_samples(0)
#if USE(QCMSLIB)
, m_transform(0)
#endif
{
memset(&m_info, 0, sizeof(jpeg_decompress_struct));
m_info.err = jpeg_std_error(&m_err.pub);
m_err.pub.error_exit = error_exit;
jpeg_create_decompress(&m_info);
decoder_source_mgr* src = 0;
if (!m_info.src) {
src = (decoder_source_mgr*)fastZeroedMalloc(sizeof(decoder_source_mgr));
if (!src) {
m_state = JPEG_ERROR;
return;
}
}
m_info.src = (jpeg_source_mgr*)src;
src->pub.init_source = init_source;
src->pub.fill_input_buffer = fill_input_buffer;
src->pub.skip_input_data = skip_input_data;
src->pub.resync_to_restart = jpeg_resync_to_restart;
src->pub.term_source = term_source;
src->decoder = this;
#if USE(ICCJPEG)
setup_read_icc_profile(&m_info);
#endif
jpeg_save_markers(&m_info, exifMarker, 0xFFFF);
}
~JPEGImageReader()
{
close();
}
void close()
{
decoder_source_mgr* src = (decoder_source_mgr*)m_info.src;
if (src)
fastFree(src);
m_info.src = 0;
#if USE(QCMSLIB)
if (m_transform)
qcms_transform_release(m_transform);
m_transform = 0;
#endif
jpeg_destroy_decompress(&m_info);
}
void skipBytes(long numBytes)
{
decoder_source_mgr* src = (decoder_source_mgr*)m_info.src;
long bytesToSkip = std::min(numBytes, (long)src->pub.bytes_in_buffer);
src->pub.bytes_in_buffer -= (size_t)bytesToSkip;
src->pub.next_input_byte += bytesToSkip;
m_bytesToSkip = std::max(numBytes - bytesToSkip, static_cast<long>(0));
}
bool decode(const SharedBuffer& data, bool onlySize)
{
unsigned newByteCount = data.size() - m_bufferLength;
unsigned readOffset = m_bufferLength - m_info.src->bytes_in_buffer;
m_info.src->bytes_in_buffer += newByteCount;
m_info.src->next_input_byte = (JOCTET*)(data.data()) + readOffset;
if (m_bytesToSkip)
skipBytes(m_bytesToSkip);
m_bufferLength = data.size();
if (setjmp(m_err.setjmp_buffer))
return m_decoder->setFailed();
switch (m_state) {
case JPEG_HEADER:
if (jpeg_read_header(&m_info, true) == JPEG_SUSPENDED)
return false;
switch (m_info.jpeg_color_space) {
case JCS_GRAYSCALE:
case JCS_RGB:
case JCS_YCbCr:
m_info.out_color_space = rgbOutputColorSpace();
#if defined(TURBO_JPEG_RGB_SWIZZLE)
if (m_info.saw_JFIF_marker)
break;
if (m_info.saw_Adobe_marker && !m_info.Adobe_transform)
m_info.out_color_space = JCS_RGB;
#endif
break;
case JCS_CMYK:
case JCS_YCCK:
m_info.out_color_space = JCS_CMYK;
break;
default:
return m_decoder->setFailed();
}
m_state = JPEG_START_DECOMPRESS;
if (!m_decoder->setSize(m_info.image_width, m_info.image_height))
return false;
m_info.scale_num = m_decoder->desiredScaleNumerator();
m_info.scale_denom = scaleDenominator;
jpeg_calc_output_dimensions(&m_info);
m_decoder->setDecodedSize(m_info.output_width, m_info.output_height);
m_decoder->setOrientation(readImageOrientation(info()));
#if USE(QCMSLIB)
if (!m_decoder->ignoresGammaAndColorProfile()) {
ColorProfile colorProfile;
readColorProfile(info(), colorProfile);
createColorTransform(colorProfile, colorSpaceHasAlpha(m_info.out_color_space));
#if defined(TURBO_JPEG_RGB_SWIZZLE)
if (m_transform && m_info.out_color_space == JCS_EXT_BGRA)
m_info.out_color_space = JCS_EXT_RGBA;
#endif
}
#endif
m_info.buffered_image = jpeg_has_multiple_scans(&m_info);
if (onlySize) {
m_bufferLength -= m_info.src->bytes_in_buffer;
m_info.src->bytes_in_buffer = 0;
return true;
}
case JPEG_START_DECOMPRESS:
m_info.dct_method = dctMethod();
m_info.dither_mode = ditherMode();
m_info.do_fancy_upsampling = doFancyUpsampling();
m_info.enable_2pass_quant = false;
m_info.do_block_smoothing = true;
m_samples = (*m_info.mem->alloc_sarray)(reinterpret_cast<j_common_ptr>(&m_info), JPOOL_IMAGE, m_info.output_width * 4, 1);
if (!jpeg_start_decompress(&m_info))
return false;
m_state = (m_info.buffered_image) ? JPEG_DECOMPRESS_PROGRESSIVE : JPEG_DECOMPRESS_SEQUENTIAL;
case JPEG_DECOMPRESS_SEQUENTIAL:
if (m_state == JPEG_DECOMPRESS_SEQUENTIAL) {
if (!m_decoder->outputScanlines())
return false;
ASSERT(m_info.output_scanline == m_info.output_height);
m_state = JPEG_DONE;
}
case JPEG_DECOMPRESS_PROGRESSIVE:
if (m_state == JPEG_DECOMPRESS_PROGRESSIVE) {
int status;
do {
status = jpeg_consume_input(&m_info);
} while ((status != JPEG_SUSPENDED) && (status != JPEG_REACHED_EOI));
for (;;) {
if (!m_info.output_scanline) {
int scan = m_info.input_scan_number;
if (!m_info.output_scan_number && (scan > 1) && (status != JPEG_REACHED_EOI))
--scan;
if (!jpeg_start_output(&m_info, scan))
return false;
}
if (m_info.output_scanline == 0xffffff)
m_info.output_scanline = 0;
JPEGImageDecoder* decoder = m_decoder;
if (!decoder->outputScanlines()) {
if (decoder->failed())
return false;
if (!m_info.output_scanline)
m_info.output_scanline = 0xffffff;
return false;
}
if (m_info.output_scanline == m_info.output_height) {
if (!jpeg_finish_output(&m_info))
return false;
if (jpeg_input_complete(&m_info) && (m_info.input_scan_number == m_info.output_scan_number))
break;
m_info.output_scanline = 0;
}
}
m_state = JPEG_DONE;
}
case JPEG_DONE:
return jpeg_finish_decompress(&m_info);
case JPEG_ERROR:
return m_decoder->setFailed();
}
return true;
}
jpeg_decompress_struct* info() { return &m_info; }
JSAMPARRAY samples() const { return m_samples; }
JPEGImageDecoder* decoder() { return m_decoder; }
#if USE(QCMSLIB)
qcms_transform* colorTransform() const { return m_transform; }
void createColorTransform(const ColorProfile& colorProfile, bool hasAlpha)
{
if (m_transform)
qcms_transform_release(m_transform);
m_transform = 0;
if (colorProfile.isEmpty())
return;
qcms_profile* deviceProfile = ImageDecoder::qcmsOutputDeviceProfile();
if (!deviceProfile)
return;
qcms_profile* inputProfile = qcms_profile_from_memory(colorProfile.data(), colorProfile.size());
if (!inputProfile)
return;
ASSERT(icSigRgbData == qcms_profile_get_color_space(inputProfile));
qcms_data_type dataFormat = hasAlpha ? QCMS_DATA_RGBA_8 : QCMS_DATA_RGB_8;
m_transform = qcms_transform_create(inputProfile, dataFormat, deviceProfile, dataFormat, QCMS_INTENT_PERCEPTUAL);
qcms_profile_release(inputProfile);
}
#endif
private:
JPEGImageDecoder* m_decoder;
unsigned m_bufferLength;
int m_bytesToSkip;
jpeg_decompress_struct m_info;
decoder_error_mgr m_err;
jstate m_state;
JSAMPARRAY m_samples;
#if USE(QCMSLIB)
qcms_transform* m_transform;
#endif
};
void error_exit(j_common_ptr cinfo)
{
decoder_error_mgr *err = reinterpret_cast_ptr<decoder_error_mgr *>(cinfo->err);
longjmp(err->setjmp_buffer, -1);
}
void init_source(j_decompress_ptr)
{
}
void skip_input_data(j_decompress_ptr jd, long num_bytes)
{
decoder_source_mgr *src = (decoder_source_mgr *)jd->src;
src->decoder->skipBytes(num_bytes);
}
boolean fill_input_buffer(j_decompress_ptr)
{
return false;
}
void term_source(j_decompress_ptr jd)
{
decoder_source_mgr *src = (decoder_source_mgr *)jd->src;
src->decoder->decoder()->jpegComplete();
}
JPEGImageDecoder::JPEGImageDecoder(ImageSource::AlphaOption alphaOption,
ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption,
size_t maxDecodedBytes)
: ImageDecoder(alphaOption, gammaAndColorProfileOption, maxDecodedBytes)
{
}
JPEGImageDecoder::~JPEGImageDecoder()
{
}
bool JPEGImageDecoder::isSizeAvailable()
{
if (!ImageDecoder::isSizeAvailable())
decode(true);
return ImageDecoder::isSizeAvailable();
}
bool JPEGImageDecoder::setSize(unsigned width, unsigned height)
{
if (!ImageDecoder::setSize(width, height))
return false;
if (!desiredScaleNumerator())
return setFailed();
setDecodedSize(width, height);
return true;
}
void JPEGImageDecoder::setDecodedSize(unsigned width, unsigned height)
{
m_decodedSize = IntSize(width, height);
}
unsigned JPEGImageDecoder::desiredScaleNumerator() const
{
size_t originalBytes = size().width() * size().height() * 4;
if (originalBytes <= m_maxDecodedBytes) {
return scaleDenominator;
}
unsigned scaleNumerator = static_cast<unsigned>(floor(sqrt(
static_cast<float>(m_maxDecodedBytes * scaleDenominator * scaleDenominator / originalBytes))));
return scaleNumerator;
}
ImageFrame* JPEGImageDecoder::frameBufferAtIndex(size_t index)
{
if (index)
return 0;
if (m_frameBufferCache.isEmpty()) {
m_frameBufferCache.resize(1);
m_frameBufferCache[0].setPremultiplyAlpha(m_premultiplyAlpha);
}
ImageFrame& frame = m_frameBufferCache[0];
if (frame.status() != ImageFrame::FrameComplete) {
PlatformInstrumentation::willDecodeImage("JPEG");
decode(false);
PlatformInstrumentation::didDecodeImage();
}
frame.notifyBitmapIfPixelsChanged();
return &frame;
}
bool JPEGImageDecoder::setFailed()
{
m_reader.clear();
return ImageDecoder::setFailed();
}
template <J_COLOR_SPACE colorSpace> void setPixel(ImageFrame& buffer, ImageFrame::PixelData* pixel, JSAMPARRAY samples, int column)
{
JSAMPLE* jsample = *samples + column * (colorSpace == JCS_RGB ? 3 : 4);
switch (colorSpace) {
case JCS_RGB:
buffer.setRGBARaw(pixel, jsample[0], jsample[1], jsample[2], 255);
break;
case JCS_CMYK:
unsigned k = jsample[3];
buffer.setRGBARaw(pixel, jsample[0] * k / 255, jsample[1] * k / 255, jsample[2] * k / 255, 255);
break;
}
}
template <J_COLOR_SPACE colorSpace> bool outputRows(JPEGImageReader* reader, ImageFrame& buffer)
{
JSAMPARRAY samples = reader->samples();
jpeg_decompress_struct* info = reader->info();
int width = info->output_width;
while (info->output_scanline < info->output_height) {
int y = info->output_scanline;
if (jpeg_read_scanlines(info, samples, 1) != 1)
return false;
#if USE(QCMSLIB)
if (reader->colorTransform() && colorSpace == JCS_RGB)
qcms_transform_data(reader->colorTransform(), *samples, *samples, width);
#endif
ImageFrame::PixelData* pixel = buffer.getAddr(0, y);
for (int x = 0; x < width; ++pixel, ++x)
setPixel<colorSpace>(buffer, pixel, samples, x);
}
buffer.setPixelsChanged(true);
return true;
}
bool JPEGImageDecoder::outputScanlines()
{
if (m_frameBufferCache.isEmpty())
return false;
jpeg_decompress_struct* info = m_reader->info();
ImageFrame& buffer = m_frameBufferCache[0];
if (buffer.status() == ImageFrame::FrameEmpty) {
ASSERT(info->output_width == static_cast<JDIMENSION>(m_decodedSize.width()));
ASSERT(info->output_height == static_cast<JDIMENSION>(m_decodedSize.height()));
if (!buffer.setSize(info->output_width, info->output_height))
return setFailed();
buffer.setStatus(ImageFrame::FramePartial);
buffer.setHasAlpha(true);
buffer.setOriginalFrameRect(IntRect(IntPoint(), size()));
}
#if defined(TURBO_JPEG_RGB_SWIZZLE)
if (turboSwizzled(info->out_color_space)) {
while (info->output_scanline < info->output_height) {
unsigned char* row = reinterpret_cast<unsigned char*>(buffer.getAddr(0, info->output_scanline));
if (jpeg_read_scanlines(info, &row, 1) != 1)
return false;
#if USE(QCMSLIB)
if (qcms_transform* transform = m_reader->colorTransform())
qcms_transform_data_type(transform, row, row, info->output_width, rgbOutputColorSpace() == JCS_EXT_BGRA ? QCMS_OUTPUT_BGRX : QCMS_OUTPUT_RGBX);
#endif
}
buffer.setPixelsChanged(true);
return true;
}
#endif
switch (info->out_color_space) {
case JCS_RGB:
return outputRows<JCS_RGB>(m_reader.get(), buffer);
case JCS_CMYK:
return outputRows<JCS_CMYK>(m_reader.get(), buffer);
default:
ASSERT_NOT_REACHED();
}
return setFailed();
}
void JPEGImageDecoder::jpegComplete()
{
if (m_frameBufferCache.isEmpty())
return;
ImageFrame& buffer = m_frameBufferCache[0];
buffer.setHasAlpha(false);
buffer.setStatus(ImageFrame::FrameComplete);
}
void JPEGImageDecoder::decode(bool onlySize)
{
if (failed())
return;
if (!m_reader) {
m_reader = adoptPtr(new JPEGImageReader(this));
}
if (!m_reader->decode(*m_data, onlySize) && isAllDataReceived())
setFailed();
else if (!m_frameBufferCache.isEmpty() && (m_frameBufferCache[0].status() == ImageFrame::FrameComplete))
m_reader.clear();
}
}