PNGImageDecoder.cpp [plain text]
#include "config.h"
#include "PNGImageDecoder.h"
#include "Color.h"
#include "png.h"
#include <wtf/PassOwnPtr.h>
#include <wtf/StdLibExtras.h>
#if USE(QCMSLIB)
#include "qcms.h"
#endif
#if defined(PNG_LIBPNG_VER_MAJOR) && defined(PNG_LIBPNG_VER_MINOR) && (PNG_LIBPNG_VER_MAJOR > 1 || (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR >= 4))
#define JMPBUF(png_ptr) png_jmpbuf(png_ptr)
#else
#define JMPBUF(png_ptr) png_ptr->jmpbuf
#endif
namespace WebCore {
const double cMaxGamma = 21474.83;
const double cDefaultGamma = 2.2;
const double cInverseGamma = 0.45455;
const unsigned long cMaxPNGSize = 1000000UL;
static void PNGAPI decodingFailed(png_structp png, png_const_charp)
{
longjmp(JMPBUF(png), 1);
}
static void PNGAPI decodingWarning(png_structp png, png_const_charp warningMsg)
{
if (!strncmp(warningMsg, "Missing PLTE before tRNS", 24))
png_error(png, warningMsg);
}
static void PNGAPI headerAvailable(png_structp png, png_infop)
{
static_cast<PNGImageDecoder*>(png_get_progressive_ptr(png))->headerAvailable();
}
static void PNGAPI rowAvailable(png_structp png, png_bytep rowBuffer, png_uint_32 rowIndex, int interlacePass)
{
static_cast<PNGImageDecoder*>(png_get_progressive_ptr(png))->rowAvailable(rowBuffer, rowIndex, interlacePass);
}
static void PNGAPI pngComplete(png_structp png, png_infop)
{
static_cast<PNGImageDecoder*>(png_get_progressive_ptr(png))->pngComplete();
}
class PNGImageReader {
WTF_MAKE_FAST_ALLOCATED;
public:
PNGImageReader(PNGImageDecoder* decoder)
: m_readOffset(0)
, m_currentBufferSize(0)
, m_decodingSizeOnly(false)
, m_hasAlpha(false)
, m_interlaceBuffer(0)
#if USE(QCMSLIB)
, m_transform(0)
, m_rowBuffer()
#endif
{
m_png = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, decodingFailed, decodingWarning);
m_info = png_create_info_struct(m_png);
png_set_progressive_read_fn(m_png, decoder, headerAvailable, rowAvailable, pngComplete);
}
~PNGImageReader()
{
close();
}
void close()
{
if (m_png && m_info)
png_destroy_read_struct(&m_png, &m_info, 0);
#if USE(QCMSLIB)
if (m_transform)
qcms_transform_release(m_transform);
m_transform = 0;
#endif
delete[] m_interlaceBuffer;
m_interlaceBuffer = 0;
m_readOffset = 0;
}
bool decode(const SharedBuffer& data, bool sizeOnly)
{
m_decodingSizeOnly = sizeOnly;
PNGImageDecoder* decoder = static_cast<PNGImageDecoder*>(png_get_progressive_ptr(m_png));
if (setjmp(JMPBUF(m_png)))
return decoder->setFailed();
const char* segment;
while (unsigned segmentLength = data.getSomeData(segment, m_readOffset)) {
m_readOffset += segmentLength;
m_currentBufferSize = m_readOffset;
png_process_data(m_png, m_info, reinterpret_cast<png_bytep>(const_cast<char*>(segment)), segmentLength);
if (sizeOnly ? decoder->ImageDecoder::isSizeAvailable() : decoder->isComplete())
return true;
}
return false;
}
png_structp pngPtr() const { return m_png; }
png_infop infoPtr() const { return m_info; }
void setReadOffset(unsigned offset) { m_readOffset = offset; }
unsigned currentBufferSize() const { return m_currentBufferSize; }
bool decodingSizeOnly() const { return m_decodingSizeOnly; }
void setHasAlpha(bool hasAlpha) { m_hasAlpha = hasAlpha; }
bool hasAlpha() const { return m_hasAlpha; }
png_bytep interlaceBuffer() const { return m_interlaceBuffer; }
void createInterlaceBuffer(int size) { m_interlaceBuffer = new png_byte[size]; }
#if USE(QCMSLIB)
png_bytep rowBuffer() const { return m_rowBuffer.get(); }
void createRowBuffer(int size) { m_rowBuffer = std::make_unique<png_byte[]>(size); }
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:
png_structp m_png;
png_infop m_info;
unsigned m_readOffset;
unsigned m_currentBufferSize;
bool m_decodingSizeOnly;
bool m_hasAlpha;
png_bytep m_interlaceBuffer;
#if USE(QCMSLIB)
qcms_transform* m_transform;
std::unique_ptr<png_byte[]> m_rowBuffer;
#endif
};
PNGImageDecoder::PNGImageDecoder(ImageSource::AlphaOption alphaOption,
ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption)
: ImageDecoder(alphaOption, gammaAndColorProfileOption)
, m_doNothingOnFailure(false)
{
}
PNGImageDecoder::~PNGImageDecoder()
{
}
bool PNGImageDecoder::isSizeAvailable()
{
if (!ImageDecoder::isSizeAvailable())
decode(true);
return ImageDecoder::isSizeAvailable();
}
bool PNGImageDecoder::setSize(unsigned width, unsigned height)
{
if (!ImageDecoder::setSize(width, height))
return false;
prepareScaleDataIfNecessary();
return true;
}
ImageFrame* PNGImageDecoder::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)
decode(false);
return &frame;
}
bool PNGImageDecoder::setFailed()
{
if (m_doNothingOnFailure)
return false;
m_reader.clear();
return ImageDecoder::setFailed();
}
static void readColorProfile(png_structp png, png_infop info, ColorProfile& colorProfile)
{
ASSERT(colorProfile.isEmpty());
#ifdef PNG_iCCP_SUPPORTED
char* profileName;
int compressionType;
#if (PNG_LIBPNG_VER < 10500)
png_charp profile;
#else
png_bytep profile;
#endif
png_uint_32 profileLength;
if (!png_get_iCCP(png, info, &profileName, &compressionType, &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;
if (!ignoreProfile)
colorProfile.append(profileData, profileLength);
#endif
}
void PNGImageDecoder::headerAvailable()
{
png_structp png = m_reader->pngPtr();
png_infop info = m_reader->infoPtr();
png_uint_32 width = png_get_image_width(png, info);
png_uint_32 height = png_get_image_height(png, info);
if (width > cMaxPNGSize || height > cMaxPNGSize) {
longjmp(JMPBUF(png), 1);
return;
}
m_doNothingOnFailure = true;
bool result = setSize(width, height);
m_doNothingOnFailure = false;
if (!result) {
longjmp(JMPBUF(png), 1);
return;
}
int bitDepth, colorType, interlaceType, compressionType, filterType, channels;
png_get_IHDR(png, info, &width, &height, &bitDepth, &colorType, &interlaceType, &compressionType, &filterType);
if (colorType == PNG_COLOR_TYPE_PALETTE || (colorType == PNG_COLOR_TYPE_GRAY && bitDepth < 8))
png_set_expand(png);
png_bytep trns = 0;
int trnsCount = 0;
if (png_get_valid(png, info, PNG_INFO_tRNS)) {
png_get_tRNS(png, info, &trns, &trnsCount, 0);
png_set_expand(png);
}
if (bitDepth == 16)
png_set_strip_16(png);
if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
png_set_gray_to_rgb(png);
if ((colorType & PNG_COLOR_MASK_COLOR) && !m_ignoreGammaAndColorProfile) {
readColorProfile(png, info, m_colorProfile);
#if USE(QCMSLIB)
bool decodedImageHasAlpha = (colorType & PNG_COLOR_MASK_ALPHA) || trnsCount;
m_reader->createColorTransform(m_colorProfile, decodedImageHasAlpha);
m_colorProfile.clear();
#endif
}
double gamma;
if (!m_ignoreGammaAndColorProfile && png_get_gAMA(png, info, &gamma)) {
if ((gamma <= 0.0) || (gamma > cMaxGamma)) {
gamma = cInverseGamma;
png_set_gAMA(png, info, gamma);
}
png_set_gamma(png, cDefaultGamma, gamma);
} else
png_set_gamma(png, cDefaultGamma, cInverseGamma);
if (interlaceType == PNG_INTERLACE_ADAM7)
png_set_interlace_handling(png);
png_read_update_info(png, info);
channels = png_get_channels(png, info);
ASSERT(channels == 3 || channels == 4);
m_reader->setHasAlpha(channels == 4);
if (m_reader->decodingSizeOnly()) {
#if defined(PNG_LIBPNG_VER_MAJOR) && defined(PNG_LIBPNG_VER_MINOR) && (PNG_LIBPNG_VER_MAJOR > 1 || (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR >= 5))
m_reader->setReadOffset(m_reader->currentBufferSize() - png_process_data_pause(png, 0));
#else
m_reader->setReadOffset(m_reader->currentBufferSize() - png->buffer_size);
png->buffer_size = 0;
#endif
}
}
static inline void setPixelRGB(ImageFrame::PixelData* dest, png_bytep pixel)
{
*dest = 0xFF000000U | pixel[0] << 16 | pixel[1] << 8 | pixel[2];
}
static inline void setPixelRGBA(ImageFrame::PixelData* dest, png_bytep pixel, unsigned char& nonTrivialAlphaMask)
{
unsigned char a = pixel[3];
*dest = a << 24 | pixel[0] << 16 | pixel[1] << 8 | pixel[2];
nonTrivialAlphaMask |= (255 - a);
}
static inline void setPixelPremultipliedRGBA(ImageFrame::PixelData* dest, png_bytep pixel, unsigned char& nonTrivialAlphaMask)
{
unsigned char a = pixel[3];
unsigned char r = fastDivideBy255(pixel[0] * a);
unsigned char g = fastDivideBy255(pixel[1] * a);
unsigned char b = fastDivideBy255(pixel[2] * a);
*dest = a << 24 | r << 16 | g << 8 | b;
nonTrivialAlphaMask |= (255 - a);
}
void PNGImageDecoder::rowAvailable(unsigned char* rowBuffer, unsigned rowIndex, int)
{
if (m_frameBufferCache.isEmpty())
return;
ImageFrame& buffer = m_frameBufferCache[0];
if (buffer.status() == ImageFrame::FrameEmpty) {
png_structp png = m_reader->pngPtr();
if (!buffer.setSize(scaledSize().width(), scaledSize().height())) {
longjmp(JMPBUF(png), 1);
return;
}
unsigned colorChannels = m_reader->hasAlpha() ? 4 : 3;
if (PNG_INTERLACE_ADAM7 == png_get_interlace_type(png, m_reader->infoPtr())) {
m_reader->createInterlaceBuffer(colorChannels * size().width() * size().height());
if (!m_reader->interlaceBuffer()) {
longjmp(JMPBUF(png), 1);
return;
}
}
#if USE(QCMSLIB)
if (m_reader->colorTransform()) {
m_reader->createRowBuffer(colorChannels * size().width());
if (!m_reader->rowBuffer()) {
longjmp(JMPBUF(png), 1);
return;
}
}
#endif
buffer.setStatus(ImageFrame::FramePartial);
buffer.setHasAlpha(false);
buffer.setColorProfile(m_colorProfile);
buffer.setOriginalFrameRect(IntRect(IntPoint(), size()));
}
if (!rowBuffer)
return;
int y = !m_scaled ? rowIndex : scaledY(rowIndex);
if (y < 0 || y >= scaledSize().height())
return;
bool hasAlpha = m_reader->hasAlpha();
unsigned colorChannels = hasAlpha ? 4 : 3;
png_bytep row = rowBuffer;
if (png_bytep interlaceBuffer = m_reader->interlaceBuffer()) {
row = interlaceBuffer + (rowIndex * colorChannels * size().width());
png_progressive_combine_row(m_reader->pngPtr(), row, rowBuffer);
}
#if USE(QCMSLIB)
if (qcms_transform* transform = m_reader->colorTransform()) {
qcms_transform_data(transform, row, m_reader->rowBuffer(), size().width());
row = m_reader->rowBuffer();
}
#endif
ImageFrame::PixelData* address = buffer.getAddr(0, y);
int width = scaledSize().width();
unsigned char nonTrivialAlphaMask = 0;
#if ENABLE(IMAGE_DECODER_DOWN_SAMPLING)
if (m_scaled) {
for (int x = 0; x < width; ++x) {
png_bytep pixel = row + m_scaledColumns[x] * colorChannels;
unsigned alpha = hasAlpha ? pixel[3] : 255;
buffer.setRGBA(address++, pixel[0], pixel[1], pixel[2], alpha);
nonTrivialAlphaMask |= (255 - alpha);
}
} else
#endif
{
png_bytep pixel = row;
if (hasAlpha) {
if (buffer.premultiplyAlpha()) {
for (int x = 0; x < width; ++x, pixel += 4)
setPixelPremultipliedRGBA(address++, pixel, nonTrivialAlphaMask);
} else {
for (int x = 0; x < width; ++x, pixel += 4)
setPixelRGBA(address++, pixel, nonTrivialAlphaMask);
}
} else {
for (int x = 0; x < width; ++x, pixel += 3)
setPixelRGB(address++, pixel);
}
}
if (nonTrivialAlphaMask && !buffer.hasAlpha())
buffer.setHasAlpha(true);
}
void PNGImageDecoder::pngComplete()
{
if (!m_frameBufferCache.isEmpty())
m_frameBufferCache.first().setStatus(ImageFrame::FrameComplete);
}
void PNGImageDecoder::decode(bool onlySize)
{
if (failed())
return;
if (!m_reader)
m_reader = adoptPtr(new PNGImageReader(this));
if (!m_reader->decode(*m_data, onlySize) && isAllDataReceived())
setFailed();
else if (isComplete())
m_reader.clear();
}
}