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