blob: e9551cbb6ff098338da2ec16383488b6332702a3 [file] [log] [blame]
msarett74114382015-03-16 11:55:18 -07001/*
2 * Copyright 2015 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "SkCodec_libbmp.h"
9#include "SkCodecPriv.h"
10#include "SkColorPriv.h"
11#include "SkStream.h"
12
13/*
14 *
15 * Checks if the conversion between the input image and the requested output
16 * image has been implemented
17 *
18 */
19static bool conversion_possible(const SkImageInfo& dst,
20 const SkImageInfo& src) {
msaretteed039b2015-03-18 11:11:19 -070021 // Ensure that the profile type is unchanged
22 if (dst.profileType() != src.profileType()) {
msarett74114382015-03-16 11:55:18 -070023 return false;
24 }
msaretteed039b2015-03-18 11:11:19 -070025
26 // Check for supported color and alpha types
27 switch (dst.colorType()) {
28 case kN32_SkColorType:
29 return src.alphaType() == dst.alphaType() ||
30 (kPremul_SkAlphaType == dst.alphaType() &&
31 kUnpremul_SkAlphaType == src.alphaType());
tomhudson7aa846c2015-03-24 13:47:41 -070032 case kRGB_565_SkColorType:
33 return src.alphaType() == dst.alphaType() &&
34 kOpaque_SkAlphaType == dst.alphaType();
msaretteed039b2015-03-18 11:11:19 -070035 default:
36 return false;
msarett74114382015-03-16 11:55:18 -070037 }
msarett74114382015-03-16 11:55:18 -070038}
39
40/*
41 *
42 * Defines the version and type of the second bitmap header
43 *
44 */
45enum BitmapHeaderType {
46 kInfoV1_BitmapHeaderType,
47 kInfoV2_BitmapHeaderType,
48 kInfoV3_BitmapHeaderType,
49 kInfoV4_BitmapHeaderType,
50 kInfoV5_BitmapHeaderType,
51 kOS2V1_BitmapHeaderType,
52 kOS2VX_BitmapHeaderType,
53 kUnknown_BitmapHeaderType
54};
55
56/*
57 *
58 * Possible bitmap compression types
59 *
60 */
61enum BitmapCompressionMethod {
62 kNone_BitmapCompressionMethod = 0,
63 k8BitRLE_BitmapCompressionMethod = 1,
64 k4BitRLE_BitmapCompressionMethod = 2,
65 kBitMasks_BitmapCompressionMethod = 3,
66 kJpeg_BitmapCompressionMethod = 4,
67 kPng_BitmapCompressionMethod = 5,
68 kAlphaBitMasks_BitmapCompressionMethod = 6,
69 kCMYK_BitmapCompressionMethod = 11,
70 kCMYK8BitRLE_BitmapCompressionMethod = 12,
71 kCMYK4BitRLE_BitmapCompressionMethod = 13
72};
73
74/*
75 *
76 * Checks the start of the stream to see if the image is a bitmap
77 *
78 */
79bool SkBmpCodec::IsBmp(SkStream* stream) {
80 // TODO: Support "IC", "PT", "CI", "CP", "BA"
81 // TODO: ICO files may contain a BMP and need to use this decoder
82 const char bmpSig[] = { 'B', 'M' };
83 char buffer[sizeof(bmpSig)];
84 return stream->read(buffer, sizeof(bmpSig)) == sizeof(bmpSig) &&
85 !memcmp(buffer, bmpSig, sizeof(bmpSig));
86}
87
88/*
89 *
90 * Assumes IsBmp was called and returned true
tomhudson7aa846c2015-03-24 13:47:41 -070091 * Creates a bitmap decoder
msarett74114382015-03-16 11:55:18 -070092 * Reads enough of the stream to determine the image format
93 *
94 */
95SkCodec* SkBmpCodec::NewFromStream(SkStream* stream) {
96 // Header size constants
97 static const uint32_t kBmpHeaderBytes = 14;
98 static const uint32_t kBmpHeaderBytesPlusFour = kBmpHeaderBytes + 4;
99 static const uint32_t kBmpOS2V1Bytes = 12;
100 static const uint32_t kBmpOS2V2Bytes = 64;
101 static const uint32_t kBmpInfoBaseBytes = 16;
102 static const uint32_t kBmpInfoV1Bytes = 40;
103 static const uint32_t kBmpInfoV2Bytes = 52;
104 static const uint32_t kBmpInfoV3Bytes = 56;
105 static const uint32_t kBmpInfoV4Bytes = 108;
106 static const uint32_t kBmpInfoV5Bytes = 124;
107 static const uint32_t kBmpMaskBytes = 12;
108
tomhudson7aa846c2015-03-24 13:47:41 -0700109 // Read the first header and the size of the second header
110 SkAutoTDeleteArray<uint8_t> hBuffer(
111 SkNEW_ARRAY(uint8_t, kBmpHeaderBytesPlusFour));
112 if (stream->read(hBuffer.get(), kBmpHeaderBytesPlusFour) !=
113 kBmpHeaderBytesPlusFour) {
114 SkDebugf("Error: unable to read first bitmap header.\n");
115 return NULL;
msarett74114382015-03-16 11:55:18 -0700116 }
117
tomhudson7aa846c2015-03-24 13:47:41 -0700118 // The total bytes in the bmp file
119 // We only need to use this value for RLE decoding, so we will only check
120 // that it is valid in the RLE case.
121 const uint32_t totalBytes = get_int(hBuffer.get(), 2);
122
123 // The offset from the start of the file where the pixel data begins
124 const uint32_t offset = get_int(hBuffer.get(), 10);
125 if (offset < kBmpHeaderBytes + kBmpOS2V1Bytes) {
126 SkDebugf("Error: invalid starting location for pixel data\n");
127 return NULL;
128 }
129
130 // The size of the second (info) header in bytes
131 // The size is the first field of the second header, so we have already
132 // read the first four infoBytes.
133 const uint32_t infoBytes = get_int(hBuffer.get(), 14);
134 if (infoBytes < kBmpOS2V1Bytes) {
135 SkDebugf("Error: invalid second header size.\n");
136 return NULL;
137 }
msarett74114382015-03-16 11:55:18 -0700138 const uint32_t infoBytesRemaining = infoBytes - 4;
tomhudson7aa846c2015-03-24 13:47:41 -0700139 hBuffer.free();
msarett74114382015-03-16 11:55:18 -0700140
141 // Read the second header
142 SkAutoTDeleteArray<uint8_t> iBuffer(
143 SkNEW_ARRAY(uint8_t, infoBytesRemaining));
144 if (stream->read(iBuffer.get(), infoBytesRemaining) != infoBytesRemaining) {
145 SkDebugf("Error: unable to read second bitmap header.\n");
146 return NULL;
147 }
148
149 // The number of bits used per pixel in the pixel data
150 uint16_t bitsPerPixel;
151
152 // The compression method for the pixel data
153 uint32_t compression = kNone_BitmapCompressionMethod;
154
155 // Number of colors in the color table, defaults to 0 or max (see below)
156 uint32_t numColors = 0;
157
158 // Bytes per color in the color table, early versions use 3, most use 4
159 uint32_t bytesPerColor;
160
161 // The image width and height
162 int width, height;
163
164 // Determine image information depending on second header format
165 BitmapHeaderType headerType;
166 if (infoBytes >= kBmpInfoBaseBytes) {
167 // Check the version of the header
168 switch (infoBytes) {
169 case kBmpInfoV1Bytes:
170 headerType = kInfoV1_BitmapHeaderType;
171 break;
172 case kBmpInfoV2Bytes:
173 headerType = kInfoV2_BitmapHeaderType;
174 break;
175 case kBmpInfoV3Bytes:
176 headerType = kInfoV3_BitmapHeaderType;
177 break;
178 case kBmpInfoV4Bytes:
179 headerType = kInfoV4_BitmapHeaderType;
180 break;
181 case kBmpInfoV5Bytes:
182 headerType = kInfoV5_BitmapHeaderType;
183 break;
184 case 16:
185 case 20:
186 case 24:
187 case 28:
188 case 32:
189 case 36:
190 case 42:
191 case 46:
192 case 48:
193 case 60:
194 case kBmpOS2V2Bytes:
195 headerType = kOS2VX_BitmapHeaderType;
196 break;
197 default:
198 // We do not signal an error here because there is the
199 // possibility of new or undocumented bmp header types. Most
200 // of the newer versions of bmp headers are similar to and
201 // build off of the older versions, so we may still be able to
202 // decode the bmp.
203 SkDebugf("Warning: unknown bmp header format.\n");
204 headerType = kUnknown_BitmapHeaderType;
205 break;
206 }
207 // We check the size of the header before entering the if statement.
208 // We should not reach this point unless the size is large enough for
209 // these required fields.
210 SkASSERT(infoBytesRemaining >= 12);
211 width = get_int(iBuffer.get(), 0);
212 height = get_int(iBuffer.get(), 4);
213 bitsPerPixel = get_short(iBuffer.get(), 10);
214
215 // Some versions do not have these fields, so we check before
216 // overwriting the default value.
217 if (infoBytesRemaining >= 16) {
218 compression = get_int(iBuffer.get(), 12);
219 if (infoBytesRemaining >= 32) {
220 numColors = get_int(iBuffer.get(), 28);
221 }
222 }
223
224 // All of the headers that reach this point, store color table entries
225 // using 4 bytes per pixel.
226 bytesPerColor = 4;
227 } else if (infoBytes >= kBmpOS2V1Bytes) {
228 // The OS2V1 is treated separately because it has a unique format
229 headerType = kOS2V1_BitmapHeaderType;
230 width = (int) get_short(iBuffer.get(), 0);
231 height = (int) get_short(iBuffer.get(), 2);
232 bitsPerPixel = get_short(iBuffer.get(), 6);
233 bytesPerColor = 3;
234 } else {
235 // There are no valid bmp headers
236 SkDebugf("Error: second bitmap header size is invalid.\n");
237 return NULL;
238 }
239
240 // Check for valid dimensions from header
241 RowOrder rowOrder = kBottomUp_RowOrder;
242 if (height < 0) {
243 height = -height;
244 rowOrder = kTopDown_RowOrder;
245 }
246 static const int kBmpMaxDim = 1 << 16;
247 if (width < 0 || width >= kBmpMaxDim || height >= kBmpMaxDim) {
248 // TODO: Decide if we want to support really large bmps.
249 SkDebugf("Error: invalid bitmap dimensions.\n");
250 return NULL;
251 }
252
253 // Create mask struct
254 SkMasks::InputMasks inputMasks;
msaretteed039b2015-03-18 11:11:19 -0700255 memset(&inputMasks, 0, sizeof(SkMasks::InputMasks));
msarett74114382015-03-16 11:55:18 -0700256
257 // Determine the input compression format and set bit masks if necessary
258 uint32_t maskBytes = 0;
259 BitmapInputFormat inputFormat = kUnknown_BitmapInputFormat;
260 switch (compression) {
261 case kNone_BitmapCompressionMethod:
262 inputFormat = kStandard_BitmapInputFormat;
263 break;
264 case k8BitRLE_BitmapCompressionMethod:
265 if (bitsPerPixel != 8) {
266 SkDebugf("Warning: correcting invalid bitmap format.\n");
267 bitsPerPixel = 8;
268 }
269 inputFormat = kRLE_BitmapInputFormat;
270 break;
271 case k4BitRLE_BitmapCompressionMethod:
272 if (bitsPerPixel != 4) {
273 SkDebugf("Warning: correcting invalid bitmap format.\n");
274 bitsPerPixel = 4;
275 }
276 inputFormat = kRLE_BitmapInputFormat;
277 break;
278 case kAlphaBitMasks_BitmapCompressionMethod:
279 case kBitMasks_BitmapCompressionMethod:
280 // Load the masks
281 inputFormat = kBitMask_BitmapInputFormat;
282 switch (headerType) {
283 case kInfoV1_BitmapHeaderType: {
284 // The V1 header stores the bit masks after the header
285 SkAutoTDeleteArray<uint8_t> mBuffer(
286 SkNEW_ARRAY(uint8_t, kBmpMaskBytes));
287 if (stream->read(mBuffer.get(), kBmpMaskBytes) !=
288 kBmpMaskBytes) {
289 SkDebugf("Error: unable to read bit inputMasks.\n");
290 return NULL;
291 }
292 maskBytes = kBmpMaskBytes;
293 inputMasks.red = get_int(mBuffer.get(), 0);
294 inputMasks.green = get_int(mBuffer.get(), 4);
295 inputMasks.blue = get_int(mBuffer.get(), 8);
296 break;
297 }
298 case kInfoV2_BitmapHeaderType:
299 case kInfoV3_BitmapHeaderType:
300 case kInfoV4_BitmapHeaderType:
301 case kInfoV5_BitmapHeaderType:
302 // Header types are matched based on size. If the header
303 // is V2+, we are guaranteed to be able to read at least
304 // this size.
305 SkASSERT(infoBytesRemaining >= 48);
306 inputMasks.red = get_int(iBuffer.get(), 36);
307 inputMasks.green = get_int(iBuffer.get(), 40);
308 inputMasks.blue = get_int(iBuffer.get(), 44);
309 break;
310 case kOS2VX_BitmapHeaderType:
311 // TODO: Decide if we intend to support this.
312 // It is unsupported in the previous version and
313 // in chromium. I have not come across a test case
314 // that uses this format.
315 SkDebugf("Error: huffman format unsupported.\n");
316 return NULL;
317 default:
318 SkDebugf("Error: invalid bmp bit masks header.\n");
319 return NULL;
320 }
321 break;
322 case kJpeg_BitmapCompressionMethod:
323 if (24 == bitsPerPixel) {
324 inputFormat = kRLE_BitmapInputFormat;
325 break;
326 }
327 // Fall through
328 case kPng_BitmapCompressionMethod:
329 // TODO: Decide if we intend to support this.
330 // It is unsupported in the previous version and
331 // in chromium. I think it is used mostly for printers.
332 SkDebugf("Error: compression format not supported.\n");
333 return NULL;
334 case kCMYK_BitmapCompressionMethod:
335 case kCMYK8BitRLE_BitmapCompressionMethod:
336 case kCMYK4BitRLE_BitmapCompressionMethod:
337 // TODO: Same as above.
338 SkDebugf("Error: CMYK not supported for bitmap decoding.\n");
339 return NULL;
340 default:
341 SkDebugf("Error: invalid format for bitmap decoding.\n");
342 return NULL;
343 }
344
345 // Most versions of bmps should be rendered as opaque. Either they do
346 // not have an alpha channel, or they expect the alpha channel to be
tomhudson7aa846c2015-03-24 13:47:41 -0700347 // ignored. V4+ bmp files introduce an alpha mask and allow the creator
msarett74114382015-03-16 11:55:18 -0700348 // of the image to use the alpha channels. However, many of these images
tomhudson7aa846c2015-03-24 13:47:41 -0700349 // leave the alpha channel blank and expect to be rendered as opaque. For
350 // this reason, we set the alpha type to kUnknown for V4+ bmps and figure
351 // out the alpha type during the decode.
msarett74114382015-03-16 11:55:18 -0700352 SkAlphaType alphaType = kOpaque_SkAlphaType;
tomhudson7aa846c2015-03-24 13:47:41 -0700353 if (kInfoV4_BitmapHeaderType == headerType ||
msarett74114382015-03-16 11:55:18 -0700354 kInfoV5_BitmapHeaderType == headerType) {
355 // Header types are matched based on size. If the header is
tomhudson7aa846c2015-03-24 13:47:41 -0700356 // V4+, we are guaranteed to be able to read at least this size.
msarett74114382015-03-16 11:55:18 -0700357 SkASSERT(infoBytesRemaining > 52);
358 inputMasks.alpha = get_int(iBuffer.get(), 48);
359 if (inputMasks.alpha != 0) {
360 alphaType = kUnpremul_SkAlphaType;
361 }
362 }
363 iBuffer.free();
364
365 // Check for valid bits per pixel input
366 switch (bitsPerPixel) {
367 // In addition to more standard pixel compression formats, bmp supports
368 // the use of bit masks to determine pixel components. The standard
369 // format for representing 16-bit colors is 555 (XRRRRRGGGGGBBBBB),
370 // which does not map well to any Skia color formats. For this reason,
371 // we will always enable mask mode with 16 bits per pixel.
372 case 16:
373 if (kBitMask_BitmapInputFormat != inputFormat) {
374 inputMasks.red = 0x7C00;
375 inputMasks.green = 0x03E0;
376 inputMasks.blue = 0x001F;
377 inputFormat = kBitMask_BitmapInputFormat;
378 }
379 break;
380 case 1:
381 case 2:
382 case 4:
383 case 8:
384 case 24:
385 case 32:
386 break;
387 default:
388 SkDebugf("Error: invalid input value for bits per pixel.\n");
389 return NULL;
390 }
391
392 // Check that input bit masks are valid and create the masks object
393 SkAutoTDelete<SkMasks>
394 masks(SkMasks::CreateMasks(inputMasks, bitsPerPixel));
395 if (NULL == masks) {
396 SkDebugf("Error: invalid input masks.\n");
397 return NULL;
398 }
399
msaretteed039b2015-03-18 11:11:19 -0700400 // Check for a valid number of total bytes when in RLE mode
401 if (totalBytes <= offset && kRLE_BitmapInputFormat == inputFormat) {
msarett74114382015-03-16 11:55:18 -0700402 SkDebugf("Error: RLE requires valid input size.\n");
403 return NULL;
404 }
msaretteed039b2015-03-18 11:11:19 -0700405 const size_t RLEBytes = totalBytes - offset;
406
407 // Calculate the number of bytes read so far
408 const uint32_t bytesRead = kBmpHeaderBytes + infoBytes + maskBytes;
tomhudson7aa846c2015-03-24 13:47:41 -0700409 if (offset < bytesRead) {
msaretteed039b2015-03-18 11:11:19 -0700410 SkDebugf("Error: pixel data offset less than header size.\n");
411 return NULL;
412 }
msarett74114382015-03-16 11:55:18 -0700413
414 // Return the codec
415 // We will use ImageInfo to store width, height, and alpha type. We will
msaretteed039b2015-03-18 11:11:19 -0700416 // set color type to kN32_SkColorType because that should be the default
417 // output.
msarett74114382015-03-16 11:55:18 -0700418 const SkImageInfo& imageInfo = SkImageInfo::Make(width, height,
419 kN32_SkColorType, alphaType);
420 return SkNEW_ARGS(SkBmpCodec, (imageInfo, stream, bitsPerPixel,
msaretteed039b2015-03-18 11:11:19 -0700421 inputFormat, masks.detach(), numColors,
422 bytesPerColor, offset - bytesRead,
tomhudson7aa846c2015-03-24 13:47:41 -0700423 rowOrder, RLEBytes));
msarett74114382015-03-16 11:55:18 -0700424}
425
426/*
427 *
428 * Creates an instance of the decoder
429 * Called only by NewFromStream
430 *
431 */
432SkBmpCodec::SkBmpCodec(const SkImageInfo& info, SkStream* stream,
433 uint16_t bitsPerPixel, BitmapInputFormat inputFormat,
msaretteed039b2015-03-18 11:11:19 -0700434 SkMasks* masks, uint32_t numColors,
435 uint32_t bytesPerColor, uint32_t offset,
tomhudson7aa846c2015-03-24 13:47:41 -0700436 RowOrder rowOrder, size_t RLEBytes)
msarett74114382015-03-16 11:55:18 -0700437 : INHERITED(info, stream)
438 , fBitsPerPixel(bitsPerPixel)
439 , fInputFormat(inputFormat)
440 , fMasks(masks)
msaretteed039b2015-03-18 11:11:19 -0700441 , fColorTable(NULL)
442 , fNumColors(numColors)
443 , fBytesPerColor(bytesPerColor)
444 , fOffset(offset)
msarett74114382015-03-16 11:55:18 -0700445 , fRowOrder(rowOrder)
msaretteed039b2015-03-18 11:11:19 -0700446 , fRLEBytes(RLEBytes)
msarett74114382015-03-16 11:55:18 -0700447{}
448
449/*
450 *
451 * Initiates the bitmap decode
452 *
453 */
454SkCodec::Result SkBmpCodec::onGetPixels(const SkImageInfo& dstInfo,
455 void* dst, size_t dstRowBytes,
scroggo95526622015-03-17 05:02:17 -0700456 const Options&,
msarett74114382015-03-16 11:55:18 -0700457 SkPMColor*, int*) {
msaretteed039b2015-03-18 11:11:19 -0700458 // Check for proper input and output formats
msarett74114382015-03-16 11:55:18 -0700459 if (!this->rewindIfNeeded()) {
460 return kCouldNotRewind;
461 }
tomhudson7aa846c2015-03-24 13:47:41 -0700462 if (dstInfo.dimensions() != this->getOriginalInfo().dimensions()) {
msarett74114382015-03-16 11:55:18 -0700463 SkDebugf("Error: scaling not supported.\n");
464 return kInvalidScale;
465 }
tomhudson7aa846c2015-03-24 13:47:41 -0700466 if (!conversion_possible(dstInfo, this->getOriginalInfo())) {
msarett74114382015-03-16 11:55:18 -0700467 SkDebugf("Error: cannot convert input type to output type.\n");
468 return kInvalidConversion;
469 }
470
msaretteed039b2015-03-18 11:11:19 -0700471 // Create the color table if necessary and prepare the stream for decode
472 if (!createColorTable(dstInfo.alphaType())) {
473 SkDebugf("Error: could not create color table.\n");
474 return kInvalidInput;
475 }
476
477 // Perform the decode
msarett74114382015-03-16 11:55:18 -0700478 switch (fInputFormat) {
479 case kBitMask_BitmapInputFormat:
480 return decodeMask(dstInfo, dst, dstRowBytes);
481 case kRLE_BitmapInputFormat:
482 return decodeRLE(dstInfo, dst, dstRowBytes);
483 case kStandard_BitmapInputFormat:
484 return decode(dstInfo, dst, dstRowBytes);
485 default:
486 SkASSERT(false);
487 return kInvalidInput;
488 }
489}
490
491/*
492 *
msaretteed039b2015-03-18 11:11:19 -0700493 * Process the color table for the bmp input
494 *
495 */
496 bool SkBmpCodec::createColorTable(SkAlphaType alphaType) {
497 // Allocate memory for color table
498 uint32_t colorBytes = 0;
499 uint32_t maxColors = 0;
500 SkPMColor colorTable[256];
501 if (fBitsPerPixel <= 8) {
502 // Zero is a default for maxColors
503 // Also set fNumColors to maxColors when it is too large
504 maxColors = 1 << fBitsPerPixel;
505 if (fNumColors == 0 || fNumColors >= maxColors) {
506 fNumColors = maxColors;
507 }
508
509 // Read the color table from the stream
510 colorBytes = fNumColors * fBytesPerColor;
511 SkAutoTDeleteArray<uint8_t> cBuffer(SkNEW_ARRAY(uint8_t, colorBytes));
512 if (stream()->read(cBuffer.get(), colorBytes) != colorBytes) {
513 SkDebugf("Error: unable to read color table.\n");
514 return false;
515 }
516
517 // Choose the proper packing function
518 SkPMColor (*packARGB) (uint32_t, uint32_t, uint32_t, uint32_t);
519 switch (alphaType) {
520 case kOpaque_SkAlphaType:
521 case kUnpremul_SkAlphaType:
522 packARGB = &SkPackARGB32NoCheck;
523 break;
524 case kPremul_SkAlphaType:
525 packARGB = &SkPreMultiplyARGB;
526 break;
527 default:
528 // This should not be reached because conversion possible
529 // should fail if the alpha type is not one of the above
530 // values.
531 SkASSERT(false);
532 packARGB = NULL;
533 break;
534 }
535
536 // Fill in the color table
537 uint32_t i = 0;
538 for (; i < fNumColors; i++) {
539 uint8_t blue = get_byte(cBuffer.get(), i*fBytesPerColor);
540 uint8_t green = get_byte(cBuffer.get(), i*fBytesPerColor + 1);
541 uint8_t red = get_byte(cBuffer.get(), i*fBytesPerColor + 2);
542 uint8_t alpha = kOpaque_SkAlphaType == alphaType ? 0xFF :
543 (fMasks->getAlphaMask() >> 24) &
544 get_byte(cBuffer.get(), i*fBytesPerColor + 3);
545 colorTable[i] = packARGB(alpha, red, green, blue);
546 }
547
548 // To avoid segmentation faults on bad pixel data, fill the end of the
549 // color table with black. This is the same the behavior as the
550 // chromium decoder.
551 for (; i < maxColors; i++) {
552 colorTable[i] = SkPackARGB32NoCheck(0xFF, 0, 0, 0);
553 }
554 }
555
tomhudson7aa846c2015-03-24 13:47:41 -0700556 // Check that we have not read past the pixel array offset
557 if(fOffset < colorBytes) {
558 // This may occur on OS 2.1 and other old versions where the color
559 // table defaults to max size, and the bmp tries to use a smaller color
560 // table. This is invalid, and our decision is to indicate an error,
561 // rather than try to guess the intended size of the color table.
562 SkDebugf("Error: pixel data offset less than color table size.\n");
563 return false;
564 }
msaretteed039b2015-03-18 11:11:19 -0700565
tomhudson7aa846c2015-03-24 13:47:41 -0700566 // After reading the color table, skip to the start of the pixel array
567 if (stream()->skip(fOffset - colorBytes) != fOffset - colorBytes) {
568 SkDebugf("Error: unable to skip to image data.\n");
569 return false;
msaretteed039b2015-03-18 11:11:19 -0700570 }
571
572 // Set the color table and return true on success
tomhudson7aa846c2015-03-24 13:47:41 -0700573 if (maxColors > 0) {
574 fColorTable.reset(SkNEW_ARGS(SkColorTable, (colorTable, maxColors)));
575 }
msaretteed039b2015-03-18 11:11:19 -0700576 return true;
577}
578
579/*
580 *
msarett74114382015-03-16 11:55:18 -0700581 * Performs the bitmap decoding for bit masks input format
582 *
583 */
584SkCodec::Result SkBmpCodec::decodeMask(const SkImageInfo& dstInfo,
585 void* dst, size_t dstRowBytes) {
586 // Set constant values
587 const int width = dstInfo.width();
588 const int height = dstInfo.height();
589 const size_t rowBytes = SkAlign4(compute_row_bytes(width, fBitsPerPixel));
590
msaretteed039b2015-03-18 11:11:19 -0700591 // Allocate a buffer large enough to hold the full image
592 SkAutoTDeleteArray<uint8_t>
593 srcBuffer(SkNEW_ARRAY(uint8_t, height*rowBytes));
594 uint8_t* srcRow = srcBuffer.get();
msarett74114382015-03-16 11:55:18 -0700595
596 // Create the swizzler
msaretteed039b2015-03-18 11:11:19 -0700597 SkAutoTDelete<SkMaskSwizzler> maskSwizzler(
598 SkMaskSwizzler::CreateMaskSwizzler(dstInfo, dst, dstRowBytes,
599 fMasks, fBitsPerPixel));
msarett74114382015-03-16 11:55:18 -0700600
601 // Iterate over rows of the image
602 bool transparent = true;
603 for (int y = 0; y < height; y++) {
604 // Read a row of the input
msaretteed039b2015-03-18 11:11:19 -0700605 if (stream()->read(srcRow, rowBytes) != rowBytes) {
msarett74114382015-03-16 11:55:18 -0700606 SkDebugf("Warning: incomplete input stream.\n");
607 return kIncompleteInput;
608 }
609
610 // Decode the row in destination format
msaretteed039b2015-03-18 11:11:19 -0700611 int row = kBottomUp_RowOrder == fRowOrder ? height - 1 - y : y;
612 SkSwizzler::ResultAlpha r = maskSwizzler->next(srcRow, row);
msarett74114382015-03-16 11:55:18 -0700613 transparent &= SkSwizzler::IsTransparent(r);
614
615 // Move to the next row
msaretteed039b2015-03-18 11:11:19 -0700616 srcRow = SkTAddOffset<uint8_t>(srcRow, rowBytes);
msarett74114382015-03-16 11:55:18 -0700617 }
618
619 // Some fully transparent bmp images are intended to be opaque. Here, we
620 // correct for this possibility.
msarett74114382015-03-16 11:55:18 -0700621 if (transparent) {
msaretteed039b2015-03-18 11:11:19 -0700622 const SkImageInfo& opaqueInfo =
623 dstInfo.makeAlphaType(kOpaque_SkAlphaType);
624 SkAutoTDelete<SkMaskSwizzler> opaqueSwizzler(
625 SkMaskSwizzler::CreateMaskSwizzler(opaqueInfo, dst, dstRowBytes,
626 fMasks, fBitsPerPixel));
627 srcRow = srcBuffer.get();
msarett74114382015-03-16 11:55:18 -0700628 for (int y = 0; y < height; y++) {
msaretteed039b2015-03-18 11:11:19 -0700629 // Decode the row in opaque format
630 int row = kBottomUp_RowOrder == fRowOrder ? height - 1 - y : y;
631 opaqueSwizzler->next(srcRow, row);
632
633 // Move to the next row
634 srcRow = SkTAddOffset<uint8_t>(srcRow, rowBytes);
msarett74114382015-03-16 11:55:18 -0700635 }
636 }
637
638 // Finished decoding the entire image
639 return kSuccess;
640}
641
642/*
643 *
644 * Set an RLE pixel using the color table
645 *
646 */
msaretteed039b2015-03-18 11:11:19 -0700647void SkBmpCodec::setRLEPixel(SkPMColor* dst, size_t dstRowBytes,
648 const SkImageInfo& dstInfo, uint32_t x, uint32_t y,
649 uint8_t index) {
650 // Set the row
651 int height = dstInfo.height();
652 int row;
msarett74114382015-03-16 11:55:18 -0700653 if (kBottomUp_RowOrder == fRowOrder) {
msaretteed039b2015-03-18 11:11:19 -0700654 row = height - y - 1;
655 } else {
656 row = y;
msarett74114382015-03-16 11:55:18 -0700657 }
msaretteed039b2015-03-18 11:11:19 -0700658
659 // Set the pixel based on destination color type
660 switch (dstInfo.colorType()) {
661 case kN32_SkColorType: {
662 SkPMColor* dstRow = SkTAddOffset<SkPMColor>(dst,
663 row * (int) dstRowBytes);
664 dstRow[x] = fColorTable->operator[](index);
665 break;
666 }
667 case kRGB_565_SkColorType: {
668 uint16_t* dstRow = SkTAddOffset<uint16_t>(dst,
669 row * (int) dstRowBytes);
670 dstRow[x] = SkPixel32ToPixel16(fColorTable->operator[](index));
671 break;
672 }
673 default:
674 // This case should not be reached. We should catch an invalid
675 // color type when we check that the conversion is possible.
676 SkASSERT(false);
677 break;
678 }
679}
680
681/*
682 *
683 * Set an RLE pixel from R, G, B values
684 *
685 */
686void SkBmpCodec::setRLE24Pixel(SkPMColor* dst, size_t dstRowBytes,
687 const SkImageInfo& dstInfo, uint32_t x,
688 uint32_t y, uint8_t red, uint8_t green,
689 uint8_t blue) {
690 // Set the row
691 int height = dstInfo.height();
692 int row;
693 if (kBottomUp_RowOrder == fRowOrder) {
694 row = height - y - 1;
695 } else {
696 row = y;
697 }
698
699 // Set the pixel based on destination color type
700 switch (dstInfo.colorType()) {
701 case kN32_SkColorType: {
702 SkPMColor* dstRow = SkTAddOffset<SkPMColor>(dst,
703 row * (int) dstRowBytes);
704 dstRow[x] = SkPackARGB32NoCheck(0xFF, red, green, blue);
705 break;
706 }
707 case kRGB_565_SkColorType: {
708 uint16_t* dstRow = SkTAddOffset<uint16_t>(dst,
709 row * (int) dstRowBytes);
710 dstRow[x] = SkPack888ToRGB16(red, green, blue);
711 break;
712 }
713 default:
714 // This case should not be reached. We should catch an invalid
715 // color type when we check that the conversion is possible.
716 SkASSERT(false);
717 break;
718 }
msarett74114382015-03-16 11:55:18 -0700719}
720
721/*
722 *
723 * Performs the bitmap decoding for RLE input format
724 * RLE decoding is performed all at once, rather than a one row at a time
725 *
726 */
727SkCodec::Result SkBmpCodec::decodeRLE(const SkImageInfo& dstInfo,
728 void* dst, size_t dstRowBytes) {
729 // Set RLE flags
730 static const uint8_t RLE_ESCAPE = 0;
731 static const uint8_t RLE_EOL = 0;
732 static const uint8_t RLE_EOF = 1;
733 static const uint8_t RLE_DELTA = 2;
734
735 // Set constant values
736 const int width = dstInfo.width();
737 const int height = dstInfo.height();
738
739 // Input buffer parameters
740 uint32_t currByte = 0;
msaretteed039b2015-03-18 11:11:19 -0700741 SkAutoTDeleteArray<uint8_t> buffer(SkNEW_ARRAY(uint8_t, fRLEBytes));
742 size_t totalBytes = stream()->read(buffer.get(), fRLEBytes);
743 if (totalBytes < fRLEBytes) {
msarett74114382015-03-16 11:55:18 -0700744 SkDebugf("Warning: incomplete RLE file.\n");
745 } else if (totalBytes <= 0) {
746 SkDebugf("Error: could not read RLE image data.\n");
747 return kInvalidInput;
748 }
749
750 // Destination parameters
751 int x = 0;
752 int y = 0;
753 // If the code skips pixels, remaining pixels are transparent or black
754 // TODO: Skip this if memory was already zeroed.
755 memset(dst, 0, dstRowBytes * height);
756 SkPMColor* dstPtr = (SkPMColor*) dst;
757
758 while (true) {
759 // Every entry takes at least two bytes
760 if ((int) totalBytes - currByte < 2) {
761 SkDebugf("Warning: incomplete RLE input.\n");
762 return kIncompleteInput;
763 }
764
765 // Read the next two bytes. These bytes have different meanings
766 // depending on their values. In the first interpretation, the first
767 // byte is an escape flag and the second byte indicates what special
768 // task to perform.
769 const uint8_t flag = buffer.get()[currByte++];
770 const uint8_t task = buffer.get()[currByte++];
771
772 // If we have reached a row that is beyond the image size, and the RLE
773 // code does not indicate end of file, abort and signal a warning.
774 if (y >= height && (flag != RLE_ESCAPE || (task != RLE_EOF))) {
775 SkDebugf("Warning: invalid RLE input.\n");
776 return kIncompleteInput;
777 }
778
779 // Perform decoding
780 if (RLE_ESCAPE == flag) {
781 switch (task) {
782 case RLE_EOL:
783 x = 0;
784 y++;
785 break;
786 case RLE_EOF:
787 return kSuccess;
788 case RLE_DELTA: {
789 // Two bytes are needed to specify delta
790 if ((int) totalBytes - currByte < 2) {
791 SkDebugf("Warning: incomplete RLE input\n");
792 return kIncompleteInput;
793 }
794 // Modify x and y
795 const uint8_t dx = buffer.get()[currByte++];
796 const uint8_t dy = buffer.get()[currByte++];
797 x += dx;
798 y += dy;
799 if (x > width || y > height) {
800 SkDebugf("Warning: invalid RLE input.\n");
801 return kIncompleteInput;
802 }
803 break;
804 }
805 default: {
806 // If task does not match any of the above signals, it
807 // indicates that we have a sequence of non-RLE pixels.
808 // Furthermore, the value of task is equal to the number
809 // of pixels to interpret.
810 uint8_t numPixels = task;
811 const size_t rowBytes = compute_row_bytes(numPixels,
812 fBitsPerPixel);
813 // Abort if setting numPixels moves us off the edge of the
814 // image. Also abort if there are not enough bytes
815 // remaining in the stream to set numPixels.
816 if (x + numPixels > width ||
817 (int) totalBytes - currByte < SkAlign2(rowBytes)) {
818 SkDebugf("Warning: invalid RLE input.\n");
819 return kIncompleteInput;
820 }
821 // Set numPixels number of pixels
msarett74114382015-03-16 11:55:18 -0700822 while (numPixels > 0) {
823 switch(fBitsPerPixel) {
824 case 4: {
825 SkASSERT(currByte < totalBytes);
826 uint8_t val = buffer.get()[currByte++];
msaretteed039b2015-03-18 11:11:19 -0700827 setRLEPixel(dstPtr, dstRowBytes, dstInfo, x++,
828 y, val >> 4);
msarett74114382015-03-16 11:55:18 -0700829 numPixels--;
830 if (numPixels != 0) {
msaretteed039b2015-03-18 11:11:19 -0700831 setRLEPixel(dstPtr, dstRowBytes, dstInfo,
msarett74114382015-03-16 11:55:18 -0700832 x++, y, val & 0xF);
833 numPixels--;
834 }
835 break;
836 }
837 case 8:
838 SkASSERT(currByte < totalBytes);
msaretteed039b2015-03-18 11:11:19 -0700839 setRLEPixel(dstPtr, dstRowBytes, dstInfo, x++,
840 y, buffer.get()[currByte++]);
msarett74114382015-03-16 11:55:18 -0700841 numPixels--;
842 break;
843 case 24: {
844 SkASSERT(currByte + 2 < totalBytes);
845 uint8_t blue = buffer.get()[currByte++];
846 uint8_t green = buffer.get()[currByte++];
847 uint8_t red = buffer.get()[currByte++];
msaretteed039b2015-03-18 11:11:19 -0700848 setRLE24Pixel(dstPtr, dstRowBytes, dstInfo,
849 x++, y, red, green, blue);
msarett74114382015-03-16 11:55:18 -0700850 numPixels--;
851 }
852 default:
853 SkASSERT(false);
854 return kInvalidInput;
855 }
856 }
857 // Skip a byte if necessary to maintain alignment
858 if (!SkIsAlign2(rowBytes)) {
859 currByte++;
860 }
861 break;
862 }
863 }
864 } else {
865 // If the first byte read is not a flag, it indicates the number of
866 // pixels to set in RLE mode.
867 const uint8_t numPixels = flag;
868 const int endX = SkTMin<int>(x + numPixels, width);
869
870 if (24 == fBitsPerPixel) {
871 // In RLE24, the second byte read is part of the pixel color.
872 // There are two more required bytes to finish encoding the
873 // color.
874 if ((int) totalBytes - currByte < 2) {
875 SkDebugf("Warning: incomplete RLE input\n");
876 return kIncompleteInput;
877 }
878
879 // Fill the pixels up to endX with the specified color
880 uint8_t blue = task;
881 uint8_t green = buffer.get()[currByte++];
882 uint8_t red = buffer.get()[currByte++];
msarett74114382015-03-16 11:55:18 -0700883 while (x < endX) {
msaretteed039b2015-03-18 11:11:19 -0700884 setRLE24Pixel(dstPtr, dstRowBytes, dstInfo, x++, y, red,
885 green, blue);
msarett74114382015-03-16 11:55:18 -0700886 }
887 } else {
888 // In RLE8 or RLE4, the second byte read gives the index in the
889 // color table to look up the pixel color.
890 // RLE8 has one color index that gets repeated
891 // RLE4 has two color indexes in the upper and lower 4 bits of
892 // the bytes, which are alternated
893 uint8_t indices[2] = { task, task };
894 if (4 == fBitsPerPixel) {
895 indices[0] >>= 4;
896 indices[1] &= 0xf;
897 }
898
899 // Set the indicated number of pixels
900 for (int which = 0; x < endX; x++) {
msaretteed039b2015-03-18 11:11:19 -0700901 setRLEPixel(dstPtr, dstRowBytes, dstInfo, x, y,
msarett74114382015-03-16 11:55:18 -0700902 indices[which]);
903 which = !which;
904 }
905 }
906 }
907 }
908}
909
910/*
911 *
912 * Performs the bitmap decoding for standard input format
913 *
914 */
915SkCodec::Result SkBmpCodec::decode(const SkImageInfo& dstInfo,
916 void* dst, size_t dstRowBytes) {
917 // Set constant values
918 const int width = dstInfo.width();
919 const int height = dstInfo.height();
920 const size_t rowBytes = SkAlign4(compute_row_bytes(width, fBitsPerPixel));
msarett74114382015-03-16 11:55:18 -0700921
922 // Get swizzler configuration
923 SkSwizzler::SrcConfig config;
924 switch (fBitsPerPixel) {
925 case 1:
926 config = SkSwizzler::kIndex1;
927 break;
928 case 2:
929 config = SkSwizzler::kIndex2;
930 break;
931 case 4:
932 config = SkSwizzler::kIndex4;
933 break;
934 case 8:
935 config = SkSwizzler::kIndex;
936 break;
937 case 24:
938 config = SkSwizzler::kBGR;
939 break;
940 case 32:
msaretteed039b2015-03-18 11:11:19 -0700941 if (kOpaque_SkAlphaType == dstInfo.alphaType()) {
msarett74114382015-03-16 11:55:18 -0700942 config = SkSwizzler::kBGRX;
943 } else {
944 config = SkSwizzler::kBGRA;
945 }
946 break;
947 default:
948 SkASSERT(false);
949 return kInvalidInput;
950 }
951
952 // Create swizzler
msaretteed039b2015-03-18 11:11:19 -0700953 SkAutoTDelete<SkSwizzler> swizzler(SkSwizzler::CreateSwizzler(config,
954 fColorTable->readColors(), dstInfo, dst, dstRowBytes,
955 SkImageGenerator::kNo_ZeroInitialized));
msarett74114382015-03-16 11:55:18 -0700956
957 // Allocate space for a row buffer and a source for the swizzler
958 SkAutoTDeleteArray<uint8_t> srcBuffer(SkNEW_ARRAY(uint8_t, rowBytes));
959
960 // Iterate over rows of the image
961 // FIXME: bool transparent = true;
962 for (int y = 0; y < height; y++) {
963 // Read a row of the input
964 if (stream()->read(srcBuffer.get(), rowBytes) != rowBytes) {
965 SkDebugf("Warning: incomplete input stream.\n");
966 return kIncompleteInput;
967 }
968
969 // Decode the row in destination format
970 uint32_t row;
971 if (kTopDown_RowOrder == fRowOrder) {
972 row = y;
973 } else {
974 row = height - 1 - y;
975 }
976
977 swizzler->next(srcBuffer.get(), row);
978 // FIXME: SkSwizzler::ResultAlpha r =
979 // swizzler->next(srcBuffer.get(), row);
980 // FIXME: transparent &= SkSwizzler::IsTransparent(r);
981 }
982
983 // FIXME: This code exists to match the behavior in the chromium decoder
984 // and to follow the bmp specification as it relates to alpha masks. It is
985 // commented out because we have yet to discover a test image that provides
986 // an alpha mask and uses this decode mode.
987
988 // Now we adjust the output image with some additional behavior that
989 // SkSwizzler does not support. Firstly, all bmp images that contain
990 // alpha are masked by the alpha mask. Secondly, many fully transparent
991 // bmp images are intended to be opaque. Here, we make those corrections.
tomhudson7aa846c2015-03-24 13:47:41 -0700992 // Modifying alpha is safe because colors are stored unpremultiplied.
msarett74114382015-03-16 11:55:18 -0700993 /*
994 SkPMColor* dstRow = (SkPMColor*) dst;
995 if (SkSwizzler::kBGRA == config) {
996 for (int y = 0; y < height; y++) {
997 for (int x = 0; x < width; x++) {
998 if (transparent) {
999 dstRow[x] |= 0xFF000000;
1000 } else {
1001 dstRow[x] &= alphaMask;
1002 }
1003 dstRow = SkTAddOffset<SkPMColor>(dstRow, dstRowBytes);
1004 }
1005 }
1006 }
1007 */
1008
msarett74114382015-03-16 11:55:18 -07001009 // Finished decoding the entire image
1010 return kSuccess;
1011}