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