Home | History | Annotate | Download | only in bmp
      1 /*
      2  * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
      3  *
      4  * Redistribution and use in source and binary forms, with or without
      5  * modification, are permitted provided that the following conditions are
      6  * met:
      7  *
      8  *     * Redistributions of source code must retain the above copyright
      9  * notice, this list of conditions and the following disclaimer.
     10  *     * Redistributions in binary form must reproduce the above
     11  * copyright notice, this list of conditions and the following disclaimer
     12  * in the documentation and/or other materials provided with the
     13  * distribution.
     14  *     * Neither the name of Google Inc. nor the names of its
     15  * contributors may be used to endorse or promote products derived from
     16  * this software without specific prior written permission.
     17  *
     18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
     21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
     22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
     24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
     28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     29  */
     30 
     31 #include "config.h"
     32 #include "BMPImageReader.h"
     33 
     34 namespace WebCore {
     35 
     36 BMPImageReader::BMPImageReader(ImageDecoder* parent,
     37                                size_t decodedAndHeaderOffset,
     38                                size_t imgDataOffset,
     39                                bool usesAndMask)
     40     : m_parent(parent)
     41     , m_buffer(0)
     42     , m_decodedOffset(decodedAndHeaderOffset)
     43     , m_headerOffset(decodedAndHeaderOffset)
     44     , m_imgDataOffset(imgDataOffset)
     45     , m_isOS21x(false)
     46     , m_isOS22x(false)
     47     , m_isTopDown(false)
     48     , m_needToProcessBitmasks(false)
     49     , m_needToProcessColorTable(false)
     50     , m_tableSizeInBytes(0)
     51     , m_seenNonZeroAlphaPixel(false)
     52     , m_seenZeroAlphaPixel(false)
     53     , m_andMaskState(usesAndMask ? NotYetDecoded : None)
     54 {
     55     // Clue-in decodeBMP() that we need to detect the correct info header size.
     56     memset(&m_infoHeader, 0, sizeof(m_infoHeader));
     57 }
     58 
     59 bool BMPImageReader::decodeBMP(bool onlySize)
     60 {
     61     // Calculate size of info header.
     62     if (!m_infoHeader.biSize && !readInfoHeaderSize())
     63         return false;
     64 
     65     // Read and process info header.
     66     if ((m_decodedOffset < (m_headerOffset + m_infoHeader.biSize))
     67         && !processInfoHeader())
     68         return false;
     69 
     70     // processInfoHeader() set the size, so if that's all we needed, we're done.
     71     if (onlySize)
     72         return true;
     73 
     74     // Read and process the bitmasks, if needed.
     75     if (m_needToProcessBitmasks && !processBitmasks())
     76         return false;
     77 
     78     // Read and process the color table, if needed.
     79     if (m_needToProcessColorTable && !processColorTable())
     80         return false;
     81 
     82     // Initialize the framebuffer if needed.
     83     ASSERT(m_buffer);  // Parent should set this before asking us to decode!
     84     if (m_buffer->status() == RGBA32Buffer::FrameEmpty) {
     85         if (!m_buffer->setSize(m_parent->size().width(),
     86                                m_parent->size().height()))
     87             return setFailed();  // Unable to allocate.
     88         m_buffer->setStatus(RGBA32Buffer::FramePartial);
     89         // setSize() calls eraseARGB(), which resets the alpha flag, so we force
     90         // it back to false here.  We'll set it true below in all cases where
     91         // these 0s could actually show through.
     92         m_buffer->setHasAlpha(false);
     93 
     94         // For BMPs, the frame always fills the entire image.
     95         m_buffer->setRect(IntRect(IntPoint(), m_parent->size()));
     96 
     97         if (!m_isTopDown)
     98             m_coord.setY(m_parent->size().height() - 1);
     99     }
    100 
    101     // Decode the data.
    102     if ((m_andMaskState != Decoding) && !pastEndOfImage(0)) {
    103         if ((m_infoHeader.biCompression == RLE4)
    104             || (m_infoHeader.biCompression == RLE8)
    105             || (m_infoHeader.biCompression == RLE24)) {
    106             if (!processRLEData())
    107                 return false;
    108         } else if (!processNonRLEData(false, 0))
    109             return false;
    110     }
    111 
    112     // If the image has an AND mask and there was no alpha data, process the
    113     // mask.
    114     if ((m_andMaskState == NotYetDecoded) && !m_buffer->hasAlpha()) {
    115         // Reset decoding coordinates to start of image.
    116         m_coord.setX(0);
    117         m_coord.setY(m_isTopDown ? 0 : (m_parent->size().height() - 1));
    118 
    119         // The AND mask is stored as 1-bit data.
    120         m_infoHeader.biBitCount = 1;
    121 
    122         m_andMaskState = Decoding;
    123     }
    124     if ((m_andMaskState == Decoding) && !processNonRLEData(false, 0))
    125         return false;
    126 
    127     // Done!
    128     m_buffer->setStatus(RGBA32Buffer::FrameComplete);
    129     return true;
    130 }
    131 
    132 bool BMPImageReader::readInfoHeaderSize()
    133 {
    134     // Get size of info header.
    135     ASSERT(m_decodedOffset == m_headerOffset);
    136     if ((m_decodedOffset > m_data->size())
    137         || ((m_data->size() - m_decodedOffset) < 4))
    138         return false;
    139     m_infoHeader.biSize = readUint32(0);
    140     // Don't increment m_decodedOffset here, it just makes the code in
    141     // processInfoHeader() more confusing.
    142 
    143     // Don't allow the header to overflow (which would be harmless here, but
    144     // problematic or at least confusing in other places), or to overrun the
    145     // image data.
    146     if (((m_headerOffset + m_infoHeader.biSize) < m_headerOffset)
    147         || (m_imgDataOffset
    148             && (m_imgDataOffset < (m_headerOffset + m_infoHeader.biSize))))
    149         return setFailed();
    150 
    151     // See if this is a header size we understand:
    152     // OS/2 1.x: 12
    153     if (m_infoHeader.biSize == 12)
    154         m_isOS21x = true;
    155     // Windows V3: 40
    156     else if ((m_infoHeader.biSize == 40) || isWindowsV4Plus())
    157         ;
    158     // OS/2 2.x: any multiple of 4 between 16 and 64, inclusive, or 42 or 46
    159     else if ((m_infoHeader.biSize >= 16) && (m_infoHeader.biSize <= 64)
    160              && (((m_infoHeader.biSize & 3) == 0) || (m_infoHeader.biSize == 42)
    161                  || (m_infoHeader.biSize == 46)))
    162         m_isOS22x = true;
    163     else
    164         return setFailed();
    165 
    166     return true;
    167 }
    168 
    169 bool BMPImageReader::processInfoHeader()
    170 {
    171     // Read info header.
    172     ASSERT(m_decodedOffset == m_headerOffset);
    173     if ((m_decodedOffset > m_data->size())
    174         || ((m_data->size() - m_decodedOffset) < m_infoHeader.biSize)
    175         || !readInfoHeader())
    176         return false;
    177     m_decodedOffset += m_infoHeader.biSize;
    178 
    179     // Sanity-check header values.
    180     if (!isInfoHeaderValid())
    181         return setFailed();
    182 
    183     // Set our size.
    184     if (!m_parent->setSize(m_infoHeader.biWidth, m_infoHeader.biHeight))
    185         return setFailed();
    186 
    187     // For paletted images, bitmaps can set biClrUsed to 0 to mean "all
    188     // colors", so set it to the maximum number of colors for this bit depth.
    189     // Also do this for bitmaps that put too large a value here.
    190     if (m_infoHeader.biBitCount < 16) {
    191       const uint32_t maxColors =
    192           static_cast<uint32_t>(1) << m_infoHeader.biBitCount;
    193       if ((m_infoHeader.biClrUsed == 0)
    194           || (m_infoHeader.biClrUsed > maxColors))
    195         m_infoHeader.biClrUsed = maxColors;
    196     }
    197 
    198     // For any bitmaps that set their BitCount to the wrong value, reset the
    199     // counts now that we've calculated the number of necessary colors, since
    200     // other code relies on this value being correct.
    201     if (m_infoHeader.biCompression == RLE8)
    202         m_infoHeader.biBitCount = 8;
    203     else if (m_infoHeader.biCompression == RLE4)
    204         m_infoHeader.biBitCount = 4;
    205 
    206     // Tell caller what still needs to be processed.
    207     if (m_infoHeader.biBitCount >= 16)
    208         m_needToProcessBitmasks = true;
    209     else if (m_infoHeader.biBitCount > 0)
    210         m_needToProcessColorTable = true;
    211 
    212     return true;
    213 }
    214 
    215 bool BMPImageReader::readInfoHeader()
    216 {
    217     // Pre-initialize some fields that not all headers set.
    218     m_infoHeader.biCompression = RGB;
    219     m_infoHeader.biClrUsed = 0;
    220 
    221     if (m_isOS21x) {
    222         m_infoHeader.biWidth = readUint16(4);
    223         m_infoHeader.biHeight = readUint16(6);
    224         ASSERT(m_andMaskState == None);  // ICO is a Windows format, not OS/2!
    225         m_infoHeader.biBitCount = readUint16(10);
    226         return true;
    227     }
    228 
    229     m_infoHeader.biWidth = readUint32(4);
    230     m_infoHeader.biHeight = readUint32(8);
    231     if (m_andMaskState != None)
    232         m_infoHeader.biHeight /= 2;
    233     m_infoHeader.biBitCount = readUint16(14);
    234 
    235     // Read compression type, if present.
    236     if (m_infoHeader.biSize >= 20) {
    237         uint32_t biCompression = readUint32(16);
    238 
    239         // Detect OS/2 2.x-specific compression types.
    240         if ((biCompression == 3) && (m_infoHeader.biBitCount == 1)) {
    241             m_infoHeader.biCompression = HUFFMAN1D;
    242             m_isOS22x = true;
    243         } else if ((biCompression == 4) && (m_infoHeader.biBitCount == 24)) {
    244             m_infoHeader.biCompression = RLE24;
    245             m_isOS22x = true;
    246         } else if (biCompression > 5)
    247             return setFailed();  // Some type we don't understand.
    248         else
    249             m_infoHeader.biCompression =
    250                 static_cast<CompressionType>(biCompression);
    251     }
    252 
    253     // Read colors used, if present.
    254     if (m_infoHeader.biSize >= 36)
    255         m_infoHeader.biClrUsed = readUint32(32);
    256 
    257     // Windows V4+ can safely read the four bitmasks from 40-56 bytes in, so do
    258     // that here.  If the bit depth is less than 16, these values will be
    259     // ignored by the image data decoders.  If the bit depth is at least 16 but
    260     // the compression format isn't BITFIELDS, these values will be ignored and
    261     // overwritten* in processBitmasks().
    262     // NOTE: We allow alpha here.  Microsoft doesn't really document this well,
    263     // but some BMPs appear to use it.
    264     //
    265     // For non-Windows V4+, m_bitMasks[] et. al will be initialized later
    266     // during processBitmasks().
    267     //
    268     // *Except the alpha channel.  Bizarrely, some RGB bitmaps expect decoders
    269     // to pay attention to the alpha mask here, so there's a special case in
    270     // processBitmasks() that doesn't always overwrite that value.
    271     if (isWindowsV4Plus()) {
    272         m_bitMasks[0] = readUint32(40);
    273         m_bitMasks[1] = readUint32(44);
    274         m_bitMasks[2] = readUint32(48);
    275         m_bitMasks[3] = readUint32(52);
    276     }
    277 
    278     // Detect top-down BMPs.
    279     if (m_infoHeader.biHeight < 0) {
    280         m_isTopDown = true;
    281         m_infoHeader.biHeight = -m_infoHeader.biHeight;
    282     }
    283 
    284     return true;
    285 }
    286 
    287 bool BMPImageReader::isInfoHeaderValid() const
    288 {
    289     // Non-positive widths/heights are invalid.  (We've already flipped the
    290     // sign of the height for top-down bitmaps.)
    291     if ((m_infoHeader.biWidth <= 0) || (m_infoHeader.biHeight == 0))
    292         return false;
    293 
    294     // Only Windows V3+ has top-down bitmaps.
    295     if (m_isTopDown && (m_isOS21x || m_isOS22x))
    296         return false;
    297 
    298     // Only bit depths of 1, 4, 8, or 24 are universally supported.
    299     if ((m_infoHeader.biBitCount != 1) && (m_infoHeader.biBitCount != 4)
    300         && (m_infoHeader.biBitCount != 8)
    301         && (m_infoHeader.biBitCount != 24)) {
    302         // Windows V3+ additionally supports bit depths of 0 (for embedded
    303         // JPEG/PNG images), 16, and 32.
    304         if (m_isOS21x || m_isOS22x)
    305             return false;
    306         if ((m_infoHeader.biBitCount != 0)
    307             && (m_infoHeader.biBitCount != 16)
    308             && (m_infoHeader.biBitCount != 32))
    309             return false;
    310     }
    311 
    312     // Each compression type is only valid with certain bit depths (except RGB,
    313     // which can be used with any bit depth).  Also, some formats do not
    314     // some compression types.
    315     switch (m_infoHeader.biCompression) {
    316     case RGB:
    317         if (m_infoHeader.biBitCount == 0)
    318             return false;
    319         break;
    320 
    321     case RLE8:
    322         // Supposedly there are undocumented formats like "BitCount = 1,
    323         // Compression = RLE4" (which means "4 bit, but with a 2-color table"),
    324         // so also allow the paletted RLE compression types to have too low a
    325         // bit count; we'll correct this later.
    326         if (m_infoHeader.biBitCount == 0 || m_infoHeader.biBitCount > 8)
    327             return false;
    328         break;
    329 
    330     case RLE4:
    331         // See comments in RLE8.
    332         if (m_infoHeader.biBitCount == 0 || m_infoHeader.biBitCount > 4)
    333             return false;
    334         break;
    335 
    336     case BITFIELDS:
    337         // Only valid for Windows V3+.
    338         if (m_isOS21x || m_isOS22x)
    339             return false;
    340         if ((m_infoHeader.biBitCount != 16) && (m_infoHeader.biBitCount != 32))
    341             return false;
    342         break;
    343 
    344     case JPEG:
    345     case PNG:
    346         // Only valid for Windows V3+.
    347         if (m_isOS21x || m_isOS22x)
    348             return false;
    349         if (m_infoHeader.biBitCount != 0)
    350             return false;
    351         break;
    352 
    353     case HUFFMAN1D:
    354         // Only valid for OS/2 2.x.
    355         if (!m_isOS22x)
    356             return false;
    357         if (m_infoHeader.biBitCount != 1)
    358             return false;
    359         break;
    360 
    361     case RLE24:
    362         // Only valid for OS/2 2.x.
    363         if (!m_isOS22x)
    364             return false;
    365         if (m_infoHeader.biBitCount != 24)
    366             return false;
    367         break;
    368 
    369     default:
    370         // Some type we don't understand.  This should have been caught in
    371         // readInfoHeader().
    372         ASSERT_NOT_REACHED();
    373         return false;
    374     }
    375 
    376     // Top-down bitmaps cannot be compressed; they must be RGB or BITFIELDS.
    377     if (m_isTopDown && (m_infoHeader.biCompression != RGB)
    378         && (m_infoHeader.biCompression != BITFIELDS))
    379         return false;
    380 
    381     // Reject the following valid bitmap types that we don't currently bother
    382     // decoding.  Few other people decode these either, they're unlikely to be
    383     // in much use.
    384     // TODO(pkasting): Consider supporting these someday.
    385     //   * Bitmaps larger than 2^16 pixels in either dimension (Windows
    386     //     probably doesn't draw these well anyway, and the decoded data would
    387     //     take a lot of memory).
    388     if ((m_infoHeader.biWidth >= (1 << 16))
    389         || (m_infoHeader.biHeight >= (1 << 16)))
    390         return false;
    391     //   * Windows V3+ JPEG-in-BMP and PNG-in-BMP bitmaps (supposedly not found
    392     //     in the wild, only used to send data to printers?).
    393     if ((m_infoHeader.biCompression == JPEG)
    394         || (m_infoHeader.biCompression == PNG))
    395         return false;
    396     //   * OS/2 2.x Huffman-encoded monochrome bitmaps (see
    397     //      http://www.fileformat.info/mirror/egff/ch09_05.htm , re: "G31D"
    398     //      algorithm).
    399     if (m_infoHeader.biCompression == HUFFMAN1D)
    400         return false;
    401 
    402     return true;
    403 }
    404 
    405 bool BMPImageReader::processBitmasks()
    406 {
    407     // Create m_bitMasks[] values.
    408     if (m_infoHeader.biCompression != BITFIELDS) {
    409         // The format doesn't actually use bitmasks.  To simplify the decode
    410         // logic later, create bitmasks for the RGB data.  For Windows V4+,
    411         // this overwrites the masks we read from the header, which are
    412         // supposed to be ignored in non-BITFIELDS cases.
    413         // 16 bits:    MSB <-                     xRRRRRGG GGGBBBBB -> LSB
    414         // 24/32 bits: MSB <- [AAAAAAAA] RRRRRRRR GGGGGGGG BBBBBBBB -> LSB
    415         const int numBits = (m_infoHeader.biBitCount == 16) ? 5 : 8;
    416         for (int i = 0; i <= 2; ++i) {
    417             m_bitMasks[i] =
    418                 ((static_cast<uint32_t>(1) << (numBits * (3 - i))) - 1) ^
    419                 ((static_cast<uint32_t>(1) << (numBits * (2 - i))) - 1);
    420         }
    421 
    422         // For Windows V4+ 32-bit RGB, don't overwrite the alpha mask from the
    423         // header (see note in readInfoHeader()).
    424         if (m_infoHeader.biBitCount < 32)
    425             m_bitMasks[3] = 0;
    426         else if (!isWindowsV4Plus())
    427             m_bitMasks[3] = static_cast<uint32_t>(0xff000000);
    428     } else if (!isWindowsV4Plus()) {
    429         // For Windows V4+ BITFIELDS mode bitmaps, this was already done when
    430         // we read the info header.
    431 
    432         // Fail if we don't have enough file space for the bitmasks.
    433         static const size_t SIZEOF_BITMASKS = 12;
    434         if (((m_headerOffset + m_infoHeader.biSize + SIZEOF_BITMASKS) <
    435                 (m_headerOffset + m_infoHeader.biSize))
    436             || (m_imgDataOffset && (m_imgDataOffset <
    437                 (m_headerOffset + m_infoHeader.biSize + SIZEOF_BITMASKS))))
    438             return setFailed();
    439 
    440         // Read bitmasks.
    441         if ((m_data->size() - m_decodedOffset) < SIZEOF_BITMASKS)
    442             return false;
    443         m_bitMasks[0] = readUint32(0);
    444         m_bitMasks[1] = readUint32(4);
    445         m_bitMasks[2] = readUint32(8);
    446         // No alpha in anything other than Windows V4+.
    447         m_bitMasks[3] = 0;
    448 
    449         m_decodedOffset += SIZEOF_BITMASKS;
    450     }
    451 
    452     // We've now decoded all the non-image data we care about.  Skip anything
    453     // else before the actual raster data.
    454     if (m_imgDataOffset)
    455         m_decodedOffset = m_imgDataOffset;
    456     m_needToProcessBitmasks = false;
    457 
    458     // Check masks and set shift values.
    459     for (int i = 0; i < 4; ++i) {
    460         // Trim the mask to the allowed bit depth.  Some Windows V4+ BMPs
    461         // specify a bogus alpha channel in bits that don't exist in the pixel
    462         // data (for example, bits 25-31 in a 24-bit RGB format).
    463         if (m_infoHeader.biBitCount < 32)
    464             m_bitMasks[i] &=
    465                 ((static_cast<uint32_t>(1) << m_infoHeader.biBitCount) - 1);
    466 
    467         // For empty masks (common on the alpha channel, especially after the
    468         // trimming above), quickly clear the shifts and continue, to avoid an
    469         // infinite loop in the counting code below.
    470         uint32_t tempMask = m_bitMasks[i];
    471         if (!tempMask) {
    472             m_bitShiftsRight[i] = m_bitShiftsLeft[i] = 0;
    473             continue;
    474         }
    475 
    476         // Make sure bitmask does not overlap any other bitmasks.
    477         for (int j = 0; j < i; ++j) {
    478             if (tempMask & m_bitMasks[j])
    479                 return setFailed();
    480         }
    481 
    482         // Count offset into pixel data.
    483         for (m_bitShiftsRight[i] = 0; !(tempMask & 1); tempMask >>= 1)
    484             ++m_bitShiftsRight[i];
    485 
    486         // Count size of mask.
    487         for (m_bitShiftsLeft[i] = 8; tempMask & 1; tempMask >>= 1)
    488             --m_bitShiftsLeft[i];
    489 
    490         // Make sure bitmask is contiguous.
    491         if (tempMask)
    492             return setFailed();
    493 
    494         // Since RGBABuffer tops out at 8 bits per channel, adjust the shift
    495         // amounts to use the most significant 8 bits of the channel.
    496         if (m_bitShiftsLeft[i] < 0) {
    497             m_bitShiftsRight[i] -= m_bitShiftsLeft[i];
    498             m_bitShiftsLeft[i] = 0;
    499         }
    500     }
    501 
    502     return true;
    503 }
    504 
    505 bool BMPImageReader::processColorTable()
    506 {
    507     m_tableSizeInBytes = m_infoHeader.biClrUsed * (m_isOS21x ? 3 : 4);
    508 
    509     // Fail if we don't have enough file space for the color table.
    510     if (((m_headerOffset + m_infoHeader.biSize + m_tableSizeInBytes) <
    511             (m_headerOffset + m_infoHeader.biSize))
    512         || (m_imgDataOffset && (m_imgDataOffset <
    513             (m_headerOffset + m_infoHeader.biSize + m_tableSizeInBytes))))
    514         return setFailed();
    515 
    516     // Read color table.
    517     if ((m_decodedOffset > m_data->size())
    518         || ((m_data->size() - m_decodedOffset) < m_tableSizeInBytes))
    519         return false;
    520     m_colorTable.resize(m_infoHeader.biClrUsed);
    521     for (size_t i = 0; i < m_infoHeader.biClrUsed; ++i) {
    522         m_colorTable[i].rgbBlue = m_data->data()[m_decodedOffset++];
    523         m_colorTable[i].rgbGreen = m_data->data()[m_decodedOffset++];
    524         m_colorTable[i].rgbRed = m_data->data()[m_decodedOffset++];
    525         // Skip padding byte (not present on OS/2 1.x).
    526         if (!m_isOS21x)
    527             ++m_decodedOffset;
    528     }
    529 
    530     // We've now decoded all the non-image data we care about.  Skip anything
    531     // else before the actual raster data.
    532     if (m_imgDataOffset)
    533         m_decodedOffset = m_imgDataOffset;
    534     m_needToProcessColorTable = false;
    535 
    536     return true;
    537 }
    538 
    539 bool BMPImageReader::processRLEData()
    540 {
    541     if (m_decodedOffset > m_data->size())
    542         return false;
    543 
    544     // RLE decoding is poorly specified.  Two main problems:
    545     // (1) Are EOL markers necessary?  What happens when we have too many
    546     //     pixels for one row?
    547     //     http://www.fileformat.info/format/bmp/egff.htm says extra pixels
    548     //     should wrap to the next line.  Real BMPs I've encountered seem to
    549     //     instead expect extra pixels to be ignored until the EOL marker is
    550     //     seen, although this has only happened in a few cases and I suspect
    551     //     those BMPs may be invalid.  So we only change lines on EOL (or Delta
    552     //     with dy > 0), and fail in most cases when pixels extend past the end
    553     //     of the line.
    554     // (2) When Delta, EOL, or EOF are seen, what happens to the "skipped"
    555     //     pixels?
    556     //     http://www.daubnet.com/formats/BMP.html says these should be filled
    557     //     with color 0.  However, the "do nothing" and "don't care" comments
    558     //     of other references suggest leaving these alone, i.e. letting them
    559     //     be transparent to the background behind the image.  This seems to
    560     //     match how MSPAINT treats BMPs, so we do that.  Note that when we
    561     //     actually skip pixels for a case like this, we need to note on the
    562     //     framebuffer that we have alpha.
    563 
    564     // Impossible to decode row-at-a-time, so just do things as a stream of
    565     // bytes.
    566     while (true) {
    567         // Every entry takes at least two bytes; bail if there isn't enough
    568         // data.
    569         if ((m_data->size() - m_decodedOffset) < 2)
    570             return false;
    571 
    572         // For every entry except EOF, we'd better not have reached the end of
    573         // the image.
    574         const uint8_t count = m_data->data()[m_decodedOffset];
    575         const uint8_t code = m_data->data()[m_decodedOffset + 1];
    576         if (((count != 0) || (code != 1)) && pastEndOfImage(0))
    577             return setFailed();
    578 
    579         // Decode.
    580         if (count == 0) {
    581             switch (code) {
    582             case 0:  // Magic token: EOL
    583                 // Skip any remaining pixels in this row.
    584                 if (m_coord.x() < m_parent->size().width())
    585                     m_buffer->setHasAlpha(true);
    586                 moveBufferToNextRow();
    587 
    588                 m_decodedOffset += 2;
    589                 break;
    590 
    591             case 1:  // Magic token: EOF
    592                 // Skip any remaining pixels in the image.
    593                 if ((m_coord.x() < m_parent->size().width())
    594                     || (m_isTopDown
    595                         ? (m_coord.y() < (m_parent->size().height() - 1))
    596                         : (m_coord.y() > 0)))
    597                     m_buffer->setHasAlpha(true);
    598                 return true;
    599 
    600             case 2: {  // Magic token: Delta
    601                 // The next two bytes specify dx and dy.  Bail if there isn't
    602                 // enough data.
    603                 if ((m_data->size() - m_decodedOffset) < 4)
    604                     return false;
    605 
    606                 // Fail if this takes us past the end of the desired row or
    607                 // past the end of the image.
    608                 const uint8_t dx = m_data->data()[m_decodedOffset + 2];
    609                 const uint8_t dy = m_data->data()[m_decodedOffset + 3];
    610                 if ((dx != 0) || (dy != 0))
    611                     m_buffer->setHasAlpha(true);
    612                 if (((m_coord.x() + dx) > m_parent->size().width()) ||
    613                     pastEndOfImage(dy))
    614                     return setFailed();
    615 
    616                 // Skip intervening pixels.
    617                 m_coord.move(dx, m_isTopDown ? dy : -dy);
    618 
    619                 m_decodedOffset += 4;
    620                 break;
    621             }
    622 
    623             default:  // Absolute mode
    624                 // |code| pixels specified as in BI_RGB, zero-padded at the end
    625                 // to a multiple of 16 bits.
    626                 // Because processNonRLEData() expects m_decodedOffset to
    627                 // point to the beginning of the pixel data, bump it past
    628                 // the escape bytes and then reset if decoding failed.
    629                 m_decodedOffset += 2;
    630                 if (!processNonRLEData(true, code)) {
    631                     m_decodedOffset -= 2;
    632                     return false;
    633                 }
    634                 break;
    635             }
    636         } else {  // Encoded mode
    637             // The following color data is repeated for |count| total pixels.
    638             // Strangely, some BMPs seem to specify excessively large counts
    639             // here; ignore pixels past the end of the row.
    640             const int endX =
    641                 std::min(m_coord.x() + count, m_parent->size().width());
    642 
    643             if (m_infoHeader.biCompression == RLE24) {
    644                 // Bail if there isn't enough data.
    645                 if ((m_data->size() - m_decodedOffset) < 4)
    646                     return false;
    647 
    648                 // One BGR triple that we copy |count| times.
    649                 fillRGBA(endX, m_data->data()[m_decodedOffset + 3],
    650                          m_data->data()[m_decodedOffset + 2], code, 0xff);
    651                 m_decodedOffset += 4;
    652             } else {
    653                 // RLE8 has one color index that gets repeated; RLE4 has two
    654                 // color indexes in the upper and lower 4 bits of the byte,
    655                 // which are alternated.
    656                 size_t colorIndexes[2] = {code, code};
    657                 if (m_infoHeader.biCompression == RLE4) {
    658                     colorIndexes[0] = (colorIndexes[0] >> 4) & 0xf;
    659                     colorIndexes[1] &= 0xf;
    660                 }
    661                 if ((colorIndexes[0] >= m_infoHeader.biClrUsed)
    662                     || (colorIndexes[1] >= m_infoHeader.biClrUsed))
    663                     return setFailed();
    664                 for (int which = 0; m_coord.x() < endX; ) {
    665                     setI(colorIndexes[which]);
    666                     which = !which;
    667                 }
    668 
    669                 m_decodedOffset += 2;
    670             }
    671         }
    672     }
    673 }
    674 
    675 bool BMPImageReader::processNonRLEData(bool inRLE, int numPixels)
    676 {
    677     if (m_decodedOffset > m_data->size())
    678         return false;
    679 
    680     if (!inRLE)
    681         numPixels = m_parent->size().width();
    682 
    683     // Fail if we're being asked to decode more pixels than remain in the row.
    684     const int endX = m_coord.x() + numPixels;
    685     if (endX > m_parent->size().width())
    686         return setFailed();
    687 
    688     // Determine how many bytes of data the requested number of pixels
    689     // requires.
    690     const size_t pixelsPerByte = 8 / m_infoHeader.biBitCount;
    691     const size_t bytesPerPixel = m_infoHeader.biBitCount / 8;
    692     const size_t unpaddedNumBytes = (m_infoHeader.biBitCount < 16)
    693         ? ((numPixels + pixelsPerByte - 1) / pixelsPerByte)
    694         : (numPixels * bytesPerPixel);
    695     // RLE runs are zero-padded at the end to a multiple of 16 bits.  Non-RLE
    696     // data is in rows and is zero-padded to a multiple of 32 bits.
    697     const size_t alignBits = inRLE ? 1 : 3;
    698     const size_t paddedNumBytes = (unpaddedNumBytes + alignBits) & ~alignBits;
    699 
    700     // Decode as many rows as we can.  (For RLE, where we only want to decode
    701     // one row, we've already checked that this condition is true.)
    702     while (!pastEndOfImage(0)) {
    703         // Bail if we don't have enough data for the desired number of pixels.
    704         if ((m_data->size() - m_decodedOffset) < paddedNumBytes)
    705             return false;
    706 
    707         if (m_infoHeader.biBitCount < 16) {
    708             // Paletted data.  Pixels are stored little-endian within bytes.
    709             // Decode pixels one byte at a time, left to right (so, starting at
    710             // the most significant bits in the byte).
    711             const uint8_t mask = (1 << m_infoHeader.biBitCount) - 1;
    712             for (size_t byte = 0; byte < unpaddedNumBytes; ++byte) {
    713                 uint8_t pixelData = m_data->data()[m_decodedOffset + byte];
    714                 for (size_t pixel = 0;
    715                      (pixel < pixelsPerByte) && (m_coord.x() < endX); ++pixel) {
    716                     const size_t colorIndex =
    717                         (pixelData >> (8 - m_infoHeader.biBitCount)) & mask;
    718                     if (m_andMaskState == Decoding) {
    719                         // There's no way to accurately represent an AND + XOR
    720                         // operation as an RGBA image, so where the AND values
    721                         // are 1, we simply set the framebuffer pixels to fully
    722                         // transparent, on the assumption that most ICOs on the
    723                         // web will not be doing a lot of inverting.
    724                         if (colorIndex) {
    725                             setRGBA(0, 0, 0, 0);
    726                             m_buffer->setHasAlpha(true);
    727                         } else
    728                             m_coord.move(1, 0);
    729                     } else {
    730                         if (colorIndex >= m_infoHeader.biClrUsed)
    731                             return setFailed();
    732                         setI(colorIndex);
    733                     }
    734                     pixelData <<= m_infoHeader.biBitCount;
    735                 }
    736             }
    737         } else {
    738             // RGB data.  Decode pixels one at a time, left to right.
    739             while (m_coord.x() < endX) {
    740                 const uint32_t pixel = readCurrentPixel(bytesPerPixel);
    741 
    742                 // Some BMPs specify an alpha channel but don't actually use it
    743                 // (it contains all 0s).  To avoid displaying these images as
    744                 // fully-transparent, decode as if images are fully opaque
    745                 // until we actually see a non-zero alpha value; at that point,
    746                 // reset any previously-decoded pixels to fully transparent and
    747                 // continue decoding based on the real alpha channel values.
    748                 // As an optimization, avoid setting "hasAlpha" to true for
    749                 // images where all alpha values are 255; opaque images are
    750                 // faster to draw.
    751                 int alpha = getAlpha(pixel);
    752                 if (!m_seenNonZeroAlphaPixel && (alpha == 0)) {
    753                     m_seenZeroAlphaPixel = true;
    754                     alpha = 255;
    755                 } else {
    756                     m_seenNonZeroAlphaPixel = true;
    757                     if (m_seenZeroAlphaPixel) {
    758                         m_buffer->zeroFill();
    759                         m_seenZeroAlphaPixel = false;
    760                     } else if (alpha != 255)
    761                         m_buffer->setHasAlpha(true);
    762                 }
    763 
    764                 setRGBA(getComponent(pixel, 0), getComponent(pixel, 1),
    765                         getComponent(pixel, 2), alpha);
    766             }
    767         }
    768 
    769         // Success, keep going.
    770         m_decodedOffset += paddedNumBytes;
    771         if (inRLE)
    772             return true;
    773         moveBufferToNextRow();
    774     }
    775 
    776     // Finished decoding whole image.
    777     return true;
    778 }
    779 
    780 void BMPImageReader::moveBufferToNextRow()
    781 {
    782     m_coord.move(-m_coord.x(), m_isTopDown ? 1 : -1);
    783 }
    784 
    785 bool BMPImageReader::setFailed()
    786 {
    787     m_parent->setFailed();
    788     m_colorTable.clear();
    789     return false;
    790 }
    791 
    792 } // namespace WebCore
    793