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