Home | History | Annotate | Download | only in png
      1 /*
      2  * Copyright (C) 2006 Apple Computer, Inc.
      3  * Copyright (C) 2007-2009 Torch Mobile, Inc.
      4  * Copyright (C) Research In Motion Limited 2009-2010. All rights reserved.
      5  *
      6  * Portions are Copyright (C) 2001 mozilla.org
      7  *
      8  * Other contributors:
      9  *   Stuart Parmenter <stuart (at) mozilla.com>
     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 "PNGImageDecoder.h"
     42 #include "png.h"
     43 
     44 #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))
     45 #define JMPBUF(png_ptr) png_jmpbuf(png_ptr)
     46 #else
     47 #define JMPBUF(png_ptr) png_ptr->jmpbuf
     48 #endif
     49 
     50 namespace WebCore {
     51 
     52 // Gamma constants.
     53 const double cMaxGamma = 21474.83;
     54 const double cDefaultGamma = 2.2;
     55 const double cInverseGamma = 0.45455;
     56 
     57 // Protect against large PNGs. See Mozilla's bug #251381 for more info.
     58 const unsigned long cMaxPNGSize = 1000000UL;
     59 
     60 // Called if the decoding of the image fails.
     61 static void PNGAPI decodingFailed(png_structp png, png_const_charp)
     62 {
     63     longjmp(JMPBUF(png), 1);
     64 }
     65 
     66 // Callbacks given to the read struct.  The first is for warnings (we want to
     67 // treat a particular warning as an error, which is why we have to register this
     68 // callback).
     69 static void PNGAPI decodingWarning(png_structp png, png_const_charp warningMsg)
     70 {
     71     // Mozilla did this, so we will too.
     72     // Convert a tRNS warning to be an error (see
     73     // http://bugzilla.mozilla.org/show_bug.cgi?id=251381 )
     74     if (!strncmp(warningMsg, "Missing PLTE before tRNS", 24))
     75         png_error(png, warningMsg);
     76 }
     77 
     78 // Called when we have obtained the header information (including the size).
     79 static void PNGAPI headerAvailable(png_structp png, png_infop)
     80 {
     81     static_cast<PNGImageDecoder*>(png_get_progressive_ptr(png))->headerAvailable();
     82 }
     83 
     84 // Called when a row is ready.
     85 static void PNGAPI rowAvailable(png_structp png, png_bytep rowBuffer, png_uint_32 rowIndex, int interlacePass)
     86 {
     87     static_cast<PNGImageDecoder*>(png_get_progressive_ptr(png))->rowAvailable(rowBuffer, rowIndex, interlacePass);
     88 }
     89 
     90 // Called when we have completely finished decoding the image.
     91 static void PNGAPI pngComplete(png_structp png, png_infop)
     92 {
     93     static_cast<PNGImageDecoder*>(png_get_progressive_ptr(png))->pngComplete();
     94 }
     95 
     96 class PNGImageReader
     97 {
     98 public:
     99     PNGImageReader(PNGImageDecoder* decoder)
    100         : m_readOffset(0)
    101         , m_decodingSizeOnly(false)
    102         , m_interlaceBuffer(0)
    103         , m_hasAlpha(false)
    104         , m_currentBufferSize(0)
    105     {
    106         m_png = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, decodingFailed, decodingWarning);
    107         m_info = png_create_info_struct(m_png);
    108         png_set_progressive_read_fn(m_png, decoder, headerAvailable, rowAvailable, pngComplete);
    109     }
    110 
    111     ~PNGImageReader()
    112     {
    113         close();
    114     }
    115 
    116     void close()
    117     {
    118         if (m_png && m_info)
    119             // This will zero the pointers.
    120             png_destroy_read_struct(&m_png, &m_info, 0);
    121         delete[] m_interlaceBuffer;
    122         m_interlaceBuffer = 0;
    123         m_readOffset = 0;
    124     }
    125 
    126     unsigned currentBufferSize() const { return m_currentBufferSize; }
    127 
    128     bool decode(const SharedBuffer& data, bool sizeOnly)
    129     {
    130         m_decodingSizeOnly = sizeOnly;
    131         PNGImageDecoder* decoder = static_cast<PNGImageDecoder*>(png_get_progressive_ptr(m_png));
    132 
    133         // We need to do the setjmp here. Otherwise bad things will happen.
    134         if (setjmp(JMPBUF(m_png)))
    135             return decoder->setFailed();
    136 
    137         const char* segment;
    138         while (unsigned segmentLength = data.getSomeData(segment, m_readOffset)) {
    139             m_readOffset += segmentLength;
    140             m_currentBufferSize = m_readOffset;
    141             png_process_data(m_png, m_info, reinterpret_cast<png_bytep>(const_cast<char*>(segment)), segmentLength);
    142             // We explicitly specify the superclass isSizeAvailable() because we
    143             // merely want to check if we've managed to set the size, not
    144             // (recursively) trigger additional decoding if we haven't.
    145             if (sizeOnly ? decoder->ImageDecoder::isSizeAvailable() : decoder->isComplete())
    146                 return true;
    147         }
    148         return false;
    149     }
    150 
    151     bool decodingSizeOnly() const { return m_decodingSizeOnly; }
    152     png_structp pngPtr() const { return m_png; }
    153     png_infop infoPtr() const { return m_info; }
    154     png_bytep interlaceBuffer() const { return m_interlaceBuffer; }
    155     bool hasAlpha() const { return m_hasAlpha; }
    156 
    157     void setReadOffset(unsigned offset) { m_readOffset = offset; }
    158     void setHasAlpha(bool b) { m_hasAlpha = b; }
    159 
    160     void createInterlaceBuffer(int size) { m_interlaceBuffer = new png_byte[size]; }
    161 
    162 private:
    163     unsigned m_readOffset;
    164     bool m_decodingSizeOnly;
    165     png_structp m_png;
    166     png_infop m_info;
    167     png_bytep m_interlaceBuffer;
    168     bool m_hasAlpha;
    169     unsigned m_currentBufferSize;
    170 };
    171 
    172 PNGImageDecoder::PNGImageDecoder(ImageSource::AlphaOption alphaOption,
    173                                  ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption)
    174     : ImageDecoder(alphaOption, gammaAndColorProfileOption)
    175     , m_doNothingOnFailure(false)
    176 {
    177 }
    178 
    179 PNGImageDecoder::~PNGImageDecoder()
    180 {
    181 }
    182 
    183 bool PNGImageDecoder::isSizeAvailable()
    184 {
    185     if (!ImageDecoder::isSizeAvailable())
    186          decode(true);
    187 
    188     return ImageDecoder::isSizeAvailable();
    189 }
    190 
    191 bool PNGImageDecoder::setSize(unsigned width, unsigned height)
    192 {
    193     if (!ImageDecoder::setSize(width, height))
    194         return false;
    195 
    196     prepareScaleDataIfNecessary();
    197     return true;
    198 }
    199 
    200 ImageFrame* PNGImageDecoder::frameBufferAtIndex(size_t index)
    201 {
    202     if (index)
    203         return 0;
    204 
    205     if (m_frameBufferCache.isEmpty()) {
    206         m_frameBufferCache.resize(1);
    207         m_frameBufferCache[0].setPremultiplyAlpha(m_premultiplyAlpha);
    208     }
    209 
    210     ImageFrame& frame = m_frameBufferCache[0];
    211     if (frame.status() != ImageFrame::FrameComplete)
    212         decode(false);
    213     return &frame;
    214 }
    215 
    216 bool PNGImageDecoder::setFailed()
    217 {
    218     if (m_doNothingOnFailure)
    219         return false;
    220     m_reader.clear();
    221     return ImageDecoder::setFailed();
    222 }
    223 
    224 static ColorProfile readColorProfile(png_structp png, png_infop info)
    225 {
    226 #ifdef PNG_iCCP_SUPPORTED
    227     char* profileName;
    228     int compressionType;
    229     char* profile;
    230     png_uint_32 profileLength;
    231     if (png_get_iCCP(png, info, &profileName, &compressionType, &profile, &profileLength)) {
    232         ColorProfile colorProfile;
    233         colorProfile.append(profile, profileLength);
    234         return colorProfile;
    235     }
    236 #endif
    237     return ColorProfile();
    238 }
    239 
    240 void PNGImageDecoder::headerAvailable()
    241 {
    242     png_structp png = m_reader->pngPtr();
    243     png_infop info = m_reader->infoPtr();
    244     png_uint_32 width = png_get_image_width(png, info);
    245     png_uint_32 height = png_get_image_height(png, info);
    246 
    247     // Protect against large images.
    248     if (width > cMaxPNGSize || height > cMaxPNGSize) {
    249         longjmp(JMPBUF(png), 1);
    250         return;
    251     }
    252 
    253     // We can fill in the size now that the header is available.  Avoid memory
    254     // corruption issues by neutering setFailed() during this call; if we don't
    255     // do this, failures will cause |m_reader| to be deleted, and our jmpbuf
    256     // will cease to exist.  Note that we'll still properly set the failure flag
    257     // in this case as soon as we longjmp().
    258     m_doNothingOnFailure = true;
    259     bool result = setSize(width, height);
    260     m_doNothingOnFailure = false;
    261     if (!result) {
    262         longjmp(JMPBUF(png), 1);
    263         return;
    264     }
    265 
    266     int bitDepth, colorType, interlaceType, compressionType, filterType, channels;
    267     png_get_IHDR(png, info, &width, &height, &bitDepth, &colorType, &interlaceType, &compressionType, &filterType);
    268 
    269     if ((colorType == PNG_COLOR_TYPE_RGB || colorType == PNG_COLOR_TYPE_RGB_ALPHA) && !m_ignoreGammaAndColorProfile) {
    270         // We currently support color profiles only for RGB and RGBA PNGs.  Supporting
    271         // color profiles for gray-scale images is slightly tricky, at least using the
    272         // CoreGraphics ICC library, because we expand gray-scale images to RGB but we
    273         // don't similarly transform the color profile.  We'd either need to transform
    274         // the color profile or we'd need to decode into a gray-scale image buffer and
    275         // hand that to CoreGraphics.
    276         m_colorProfile = readColorProfile(png, info);
    277     }
    278 
    279     // The options we set here match what Mozilla does.
    280 
    281     // Expand to ensure we use 24-bit for RGB and 32-bit for RGBA.
    282     if (colorType == PNG_COLOR_TYPE_PALETTE || (colorType == PNG_COLOR_TYPE_GRAY && bitDepth < 8))
    283         png_set_expand(png);
    284 
    285     png_bytep trns = 0;
    286     int trnsCount = 0;
    287     if (png_get_valid(png, info, PNG_INFO_tRNS)) {
    288         png_get_tRNS(png, info, &trns, &trnsCount, 0);
    289         png_set_expand(png);
    290     }
    291 
    292     if (bitDepth == 16)
    293         png_set_strip_16(png);
    294 
    295     if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
    296         png_set_gray_to_rgb(png);
    297 
    298     // Deal with gamma and keep it under our control.
    299     double gamma;
    300     if (!m_ignoreGammaAndColorProfile && png_get_gAMA(png, info, &gamma)) {
    301         if ((gamma <= 0.0) || (gamma > cMaxGamma)) {
    302             gamma = cInverseGamma;
    303             png_set_gAMA(png, info, gamma);
    304         }
    305         png_set_gamma(png, cDefaultGamma, gamma);
    306     } else
    307         png_set_gamma(png, cDefaultGamma, cInverseGamma);
    308 
    309     // Tell libpng to send us rows for interlaced pngs.
    310     if (interlaceType == PNG_INTERLACE_ADAM7)
    311         png_set_interlace_handling(png);
    312 
    313     // Update our info now.
    314     png_read_update_info(png, info);
    315     channels = png_get_channels(png, info);
    316     ASSERT(channels == 3 || channels == 4);
    317 
    318     m_reader->setHasAlpha(channels == 4);
    319 
    320     if (m_reader->decodingSizeOnly()) {
    321         // If we only needed the size, halt the reader.
    322 #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))
    323         // '0' argument to png_process_data_pause means: Do not cache unprocessed data.
    324         m_reader->setReadOffset(m_reader->currentBufferSize() - png_process_data_pause(png, 0));
    325 #else
    326         m_reader->setReadOffset(m_reader->currentBufferSize() - png->buffer_size);
    327         png->buffer_size = 0;
    328 #endif
    329     }
    330 }
    331 
    332 void PNGImageDecoder::rowAvailable(unsigned char* rowBuffer, unsigned rowIndex, int interlacePass)
    333 {
    334     if (m_frameBufferCache.isEmpty())
    335         return;
    336 
    337     // Initialize the framebuffer if needed.
    338     ImageFrame& buffer = m_frameBufferCache[0];
    339     if (buffer.status() == ImageFrame::FrameEmpty) {
    340         if (!buffer.setSize(scaledSize().width(), scaledSize().height())) {
    341             longjmp(JMPBUF(m_reader->pngPtr()), 1);
    342             return;
    343         }
    344         buffer.setStatus(ImageFrame::FramePartial);
    345         buffer.setHasAlpha(false);
    346         buffer.setColorProfile(m_colorProfile);
    347 
    348         // For PNGs, the frame always fills the entire image.
    349         buffer.setOriginalFrameRect(IntRect(IntPoint(), size()));
    350 
    351         if (png_get_interlace_type(m_reader->pngPtr(), m_reader->infoPtr()) != PNG_INTERLACE_NONE)
    352             m_reader->createInterlaceBuffer((m_reader->hasAlpha() ? 4 : 3) * size().width() * size().height());
    353     }
    354 
    355     if (!rowBuffer)
    356         return;
    357 
    358     // libpng comments (pasted in here to explain what follows)
    359     /*
    360      * this function is called for every row in the image.  If the
    361      * image is interlacing, and you turned on the interlace handler,
    362      * this function will be called for every row in every pass.
    363      * Some of these rows will not be changed from the previous pass.
    364      * When the row is not changed, the new_row variable will be NULL.
    365      * The rows and passes are called in order, so you don't really
    366      * need the row_num and pass, but I'm supplying them because it
    367      * may make your life easier.
    368      *
    369      * For the non-NULL rows of interlaced images, you must call
    370      * png_progressive_combine_row() passing in the row and the
    371      * old row.  You can call this function for NULL rows (it will
    372      * just return) and for non-interlaced images (it just does the
    373      * memcpy for you) if it will make the code easier.  Thus, you
    374      * can just do this for all cases:
    375      *
    376      *    png_progressive_combine_row(png_ptr, old_row, new_row);
    377      *
    378      * where old_row is what was displayed for previous rows.  Note
    379      * that the first pass (pass == 0 really) will completely cover
    380      * the old row, so the rows do not have to be initialized.  After
    381      * the first pass (and only for interlaced images), you will have
    382      * to pass the current row, and the function will combine the
    383      * old row and the new row.
    384      */
    385 
    386     png_structp png = m_reader->pngPtr();
    387     bool hasAlpha = m_reader->hasAlpha();
    388     unsigned colorChannels = hasAlpha ? 4 : 3;
    389     png_bytep row;
    390     png_bytep interlaceBuffer = m_reader->interlaceBuffer();
    391     if (interlaceBuffer) {
    392         row = interlaceBuffer + (rowIndex * colorChannels * size().width());
    393         png_progressive_combine_row(png, row, rowBuffer);
    394     } else
    395         row = rowBuffer;
    396 
    397     // Copy the data into our buffer.
    398     int width = scaledSize().width();
    399     int destY = scaledY(rowIndex);
    400 
    401     // Check that the row is within the image bounds. LibPNG may supply an extra row.
    402     if (destY < 0 || destY >= scaledSize().height())
    403         return;
    404     bool nonTrivialAlpha = false;
    405     for (int x = 0; x < width; ++x) {
    406         png_bytep pixel = row + (m_scaled ? m_scaledColumns[x] : x) * colorChannels;
    407         unsigned alpha = hasAlpha ? pixel[3] : 255;
    408         buffer.setRGBA(x, destY, pixel[0], pixel[1], pixel[2], alpha);
    409         nonTrivialAlpha |= alpha < 255;
    410     }
    411     if (nonTrivialAlpha && !buffer.hasAlpha())
    412         buffer.setHasAlpha(nonTrivialAlpha);
    413 }
    414 
    415 void PNGImageDecoder::pngComplete()
    416 {
    417     if (!m_frameBufferCache.isEmpty())
    418         m_frameBufferCache.first().setStatus(ImageFrame::FrameComplete);
    419 }
    420 
    421 void PNGImageDecoder::decode(bool onlySize)
    422 {
    423     if (failed())
    424         return;
    425 
    426     if (!m_reader)
    427         m_reader.set(new PNGImageReader(this));
    428 
    429     // If we couldn't decode the image but we've received all the data, decoding
    430     // has failed.
    431     if (!m_reader->decode(*m_data, onlySize) && isAllDataReceived())
    432         setFailed();
    433     // If we're done decoding the image, we don't need the PNGImageReader
    434     // anymore.  (If we failed, |m_reader| has already been cleared.)
    435     else if (isComplete())
    436         m_reader.clear();
    437 }
    438 
    439 } // namespace WebCore
    440