2 * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
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
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.
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.
32 #include "platform/image-decoders/bmp/BMPImageReader.h"
36 // See comments on m_lookupTableAddresses in the header.
37 const uint8_t nBitTo8BitlookupTable[] = {
43 0, 36, 73, 109, 146, 182, 219, 255,
45 0, 17, 34, 51, 68, 85, 102, 119, 136, 153, 170, 187, 204, 221, 238, 255,
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,
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,
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,
69 BMPImageReader::BMPImageReader(ImageDecoder* parent, size_t decodedAndHeaderOffset, size_t imgDataOffset, bool isInICO)
72 , m_decodedOffset(decodedAndHeaderOffset)
73 , m_headerOffset(decodedAndHeaderOffset)
74 , m_imgDataOffset(imgDataOffset)
78 , m_needToProcessBitmasks(false)
79 , m_needToProcessColorTable(false)
80 , m_seenNonZeroAlphaPixel(false)
81 , m_seenZeroAlphaPixel(false)
83 , m_decodingAndMask(false)
85 // Clue-in decodeBMP() that we need to detect the correct info header size.
86 memset(&m_infoHeader, 0, sizeof(m_infoHeader));
89 bool BMPImageReader::decodeBMP(bool onlySize)
91 // Calculate size of info header.
92 if (!m_infoHeader.biSize && !readInfoHeaderSize())
95 // Read and process info header.
96 if ((m_decodedOffset < (m_headerOffset + m_infoHeader.biSize)) && !processInfoHeader())
99 // processInfoHeader() set the size, so if that's all we needed, we're done.
103 // Read and process the bitmasks, if needed.
104 if (m_needToProcessBitmasks && !processBitmasks())
107 // Read and process the color table, if needed.
108 if (m_needToProcessColorTable && !processColorTable())
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);
122 // For BMPs, the frame always fills the entire image.
123 m_buffer->setOriginalFrameRect(IntRect(IntPoint(), m_parent->size()));
126 m_coord.setY(m_parent->size().height() - 1);
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())
139 // If the image has an AND mask and there was no alpha data, process the
141 if (m_isInICO && !m_decodingAndMask && !m_buffer->hasAlpha()) {
142 // Reset decoding coordinates to start of image.
144 m_coord.setY(m_isTopDown ? 0 : (m_parent->size().height() - 1));
146 // The AND mask is stored as 1-bit data.
147 m_infoHeader.biBitCount = 1;
149 m_decodingAndMask = true;
151 if (m_decodingAndMask) {
152 const ProcessingResult result = processNonRLEData(false, 0);
153 if (result != Success)
154 return (result == Failure) ? m_parent->setFailed() : false;
158 m_buffer->setStatus(ImageFrame::FrameComplete);
162 bool BMPImageReader::readInfoHeaderSize()
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))
168 m_infoHeader.biSize = readUint32(0);
169 // Don't increment m_decodedOffset here, it just makes the code in
170 // processInfoHeader() more confusing.
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
175 if (((m_headerOffset + m_infoHeader.biSize) < m_headerOffset) || (m_imgDataOffset && (m_imgDataOffset < (m_headerOffset + m_infoHeader.biSize))))
176 return m_parent->setFailed();
178 // See if this is a header size we understand:
180 if (m_infoHeader.biSize == 12)
183 else if ((m_infoHeader.biSize == 40) || isWindowsV4Plus())
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)))
189 return m_parent->setFailed();
194 bool BMPImageReader::processInfoHeader()
197 ASSERT(m_decodedOffset == m_headerOffset);
198 if ((m_decodedOffset > m_data->size()) || ((m_data->size() - m_decodedOffset) < m_infoHeader.biSize) || !readInfoHeader())
200 m_decodedOffset += m_infoHeader.biSize;
202 // Sanity-check header values.
203 if (!isInfoHeaderValid())
204 return m_parent->setFailed();
207 if (!m_parent->setSize(m_infoHeader.biWidth, m_infoHeader.biHeight))
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;
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;
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;
236 bool BMPImageReader::readInfoHeader()
238 // Pre-initialize some fields that not all headers set.
239 m_infoHeader.biCompression = RGB;
240 m_infoHeader.biClrUsed = 0;
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);
250 m_infoHeader.biWidth = readUint32(4);
251 m_infoHeader.biHeight = readUint32(8);
253 m_infoHeader.biHeight /= 2;
254 m_infoHeader.biBitCount = readUint16(14);
256 // Read compression type, if present.
257 if (m_infoHeader.biSize >= 20) {
258 uint32_t biCompression = readUint32(16);
260 // Detect OS/2 2.x-specific compression types.
261 if ((biCompression == 3) && (m_infoHeader.biBitCount == 1)) {
262 m_infoHeader.biCompression = HUFFMAN1D;
264 } else if ((biCompression == 4) && (m_infoHeader.biBitCount == 24)) {
265 m_infoHeader.biCompression = RLE24;
267 } else if (biCompression > 5)
268 return m_parent->setFailed(); // Some type we don't understand.
270 m_infoHeader.biCompression = static_cast<CompressionType>(biCompression);
273 // Read colors used, if present.
274 if (m_infoHeader.biSize >= 36)
275 m_infoHeader.biClrUsed = readUint32(32);
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().)
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);
294 // Detect top-down BMPs.
295 if (m_infoHeader.biHeight < 0) {
297 m_infoHeader.biHeight = -m_infoHeader.biHeight;
303 bool BMPImageReader::isInfoHeaderValid() const
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)
310 // Only Windows V3+ has top-down bitmaps.
311 if (m_isTopDown && (m_isOS21x || m_isOS22x))
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)))
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) {
327 if (!m_infoHeader.biBitCount)
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))
341 // See comments in RLE8.
342 if (!m_infoHeader.biBitCount || (m_infoHeader.biBitCount > 4))
347 // Only valid for Windows V3+.
348 if (m_isOS21x || m_isOS22x || ((m_infoHeader.biBitCount != 16) && (m_infoHeader.biBitCount != 32)))
354 // Only valid for Windows V3+.
355 if (m_isOS21x || m_isOS22x || m_infoHeader.biBitCount)
360 // Only valid for OS/2 2.x.
361 if (!m_isOS22x || (m_infoHeader.biBitCount != 1))
366 // Only valid for OS/2 2.x.
367 if (!m_isOS22x || (m_infoHeader.biBitCount != 24))
372 // Some type we don't understand. This should have been caught in
374 ASSERT_NOT_REACHED();
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))
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
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)))
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))
395 // * OS/2 2.x Huffman-encoded monochrome bitmaps (see
396 // http://www.fileformat.info/mirror/egff/ch09_05.htm , re: "G31D"
398 if (m_infoHeader.biCompression == HUFFMAN1D)
404 bool BMPImageReader::processBitmasks()
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.
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();
427 if ((m_data->size() - m_decodedOffset) < SIZEOF_BITMASKS)
429 m_bitMasks[0] = readUint32(0);
430 m_bitMasks[1] = readUint32(4);
431 m_bitMasks[2] = readUint32(8);
433 m_decodedOffset += SIZEOF_BITMASKS;
436 // Alpha is a poorly-documented and inconsistently-used feature.
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.
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.
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().)
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.
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
467 if (!isWindowsV4Plus())
468 m_bitMasks[3] = (m_isInICO && (m_infoHeader.biCompression != BITFIELDS) && (m_infoHeader.biBitCount == 32)) ? static_cast<uint32_t>(0xff000000) : 0;
470 // We've now decoded all the non-image data we care about. Skip anything
471 // else before the actual raster data.
473 m_decodedOffset = m_imgDataOffset;
474 m_needToProcessBitmasks = false;
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);
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];
489 m_bitShiftsRight[i] = 0;
490 m_lookupTableAddresses[i] = 0;
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();
500 // Count offset into pixel data.
501 for (m_bitShiftsRight[i] = 0; !(tempMask & 1); tempMask >>= 1)
502 ++m_bitShiftsRight[i];
504 // Count size of mask.
506 for (; tempMask & 1; tempMask >>= 1)
509 // Make sure bitmask is contiguous.
511 return m_parent->setFailed();
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.
516 m_bitShiftsRight[i] += (numBits - 8);
520 // Calculate LUT address.
521 m_lookupTableAddresses[i] = numBits ? (nBitTo8BitlookupTable + (1 << numBits) - 2) : 0;
527 bool BMPImageReader::processColorTable()
529 size_t tableSizeInBytes = m_infoHeader.biClrUsed * (m_isOS21x ? 3 : 4);
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();
536 if ((m_decodedOffset > m_data->size()) || ((m_data->size() - m_decodedOffset) < tableSizeInBytes))
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).
548 // We've now decoded all the non-image data we care about. Skip anything
549 // else before the actual raster data.
551 m_decodedOffset = m_imgDataOffset;
552 m_needToProcessColorTable = false;
557 bool BMPImageReader::processRLEData()
559 if (m_decodedOffset > m_data->size())
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
572 // (2) When Delta, EOL, or EOF are seen, what happens to the "skipped"
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.
582 // Impossible to decode row-at-a-time, so just do things as a stream of
585 // Every entry takes at least two bytes; bail if there isn't enough
587 if ((m_data->size() - m_decodedOffset) < 2)
590 // For every entry except EOF, we'd better not have reached the end of
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();
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();
606 m_decodedOffset += 2;
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);
615 case 2: { // Magic token: Delta
616 // The next two bytes specify dx and dy. Bail if there isn't
618 if ((m_data->size() - m_decodedOffset) < 4)
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];
626 m_buffer->setHasAlpha(true);
627 if (((m_coord.x() + dx) > m_parent->size().width()) || pastEndOfImage(dy))
628 return m_parent->setFailed();
630 // Skip intervening pixels.
631 m_coord.move(dx, m_isTopDown ? dy : -dy);
633 m_decodedOffset += 4;
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;
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());
660 if (m_infoHeader.biCompression == RLE24) {
661 // Bail if there isn't enough data.
662 if ((m_data->size() - m_decodedOffset) < 4)
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;
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;
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]);
683 setRGBA(0, 0, 0, 255);
687 m_decodedOffset += 2;
693 BMPImageReader::ProcessingResult BMPImageReader::processNonRLEData(bool inRLE, int numPixels)
695 if (m_decodedOffset > m_data->size())
696 return InsufficientData;
699 numPixels = m_parent->size().width();
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())
706 // Determine how many bytes of data the requested number of pixels
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;
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;
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.
740 m_buffer->setHasAlpha(true);
744 // See comments near the end of processRLEData().
745 if (colorIndex < m_infoHeader.biClrUsed)
748 setRGBA(0, 0, 0, 255);
750 pixelData <<= m_infoHeader.biBitCount;
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);
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
767 int alpha = getAlpha(pixel);
768 if (!m_seenNonZeroAlphaPixel && !alpha) {
769 m_seenZeroAlphaPixel = true;
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);
780 setRGBA(getComponent(pixel, 0), getComponent(pixel, 1),
781 getComponent(pixel, 2), alpha);
785 // Success, keep going.
786 m_decodedOffset += paddedNumBytes;
789 moveBufferToNextRow();
792 // Finished decoding whole image.
796 void BMPImageReader::moveBufferToNextRow()
798 m_coord.move(-m_coord.x(), m_isTopDown ? 1 : -1);
801 } // namespace WebCore