blob: 62cda95733c97bc2c90bbe71e538800257b61d77 [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());
32 case kRGB_565_SkColorType:
33 return src.alphaType() == dst.alphaType() &&
34 kOpaque_SkAlphaType == dst.alphaType();
35 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
91 * Creates a bitmap decoder
92 * 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
109 // 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;
116 }
117
118 // 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 }
138 const uint32_t infoBytesRemaining = infoBytes - 4;
139 hBuffer.free();
140
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
347 // ignored. V4+ bmp files introduce an alpha mask and allow the creator
348 // of the image to use the alpha channels. However, many of these images
349 // 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.
352 SkAlphaType alphaType = kOpaque_SkAlphaType;
353 if (kInfoV4_BitmapHeaderType == headerType ||
354 kInfoV5_BitmapHeaderType == headerType) {
355 // Header types are matched based on size. If the header is
356 // V4+, we are guaranteed to be able to read at least this size.
357 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;
409 if (offset < bytesRead) {
410 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,
423 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,
436 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 }
462 if (dstInfo.dimensions() != this->getOriginalInfo().dimensions()) {
463 SkDebugf("Error: scaling not supported.\n");
464 return kInvalidScale;
465 }
466 if (!conversion_possible(dstInfo, this->getOriginalInfo())) {
467 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
556 // 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 }
565
566 // 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;
570 }
571
572 // Set the color table and return true on success
573 fColorTable.reset(SkNEW_ARGS(SkColorTable, (colorTable, maxColors)));
574 return true;
575}
576
577/*
578 *
msarett74114382015-03-16 11:55:18 -0700579 * Performs the bitmap decoding for bit masks input format
580 *
581 */
582SkCodec::Result SkBmpCodec::decodeMask(const SkImageInfo& dstInfo,
583 void* dst, size_t dstRowBytes) {
584 // Set constant values
585 const int width = dstInfo.width();
586 const int height = dstInfo.height();
587 const size_t rowBytes = SkAlign4(compute_row_bytes(width, fBitsPerPixel));
588
msaretteed039b2015-03-18 11:11:19 -0700589 // Allocate a buffer large enough to hold the full image
590 SkAutoTDeleteArray<uint8_t>
591 srcBuffer(SkNEW_ARRAY(uint8_t, height*rowBytes));
592 uint8_t* srcRow = srcBuffer.get();
msarett74114382015-03-16 11:55:18 -0700593
594 // Create the swizzler
msaretteed039b2015-03-18 11:11:19 -0700595 SkAutoTDelete<SkMaskSwizzler> maskSwizzler(
596 SkMaskSwizzler::CreateMaskSwizzler(dstInfo, dst, dstRowBytes,
597 fMasks, fBitsPerPixel));
msarett74114382015-03-16 11:55:18 -0700598
599 // Iterate over rows of the image
600 bool transparent = true;
601 for (int y = 0; y < height; y++) {
602 // Read a row of the input
msaretteed039b2015-03-18 11:11:19 -0700603 if (stream()->read(srcRow, rowBytes) != rowBytes) {
msarett74114382015-03-16 11:55:18 -0700604 SkDebugf("Warning: incomplete input stream.\n");
605 return kIncompleteInput;
606 }
607
608 // Decode the row in destination format
msaretteed039b2015-03-18 11:11:19 -0700609 int row = kBottomUp_RowOrder == fRowOrder ? height - 1 - y : y;
610 SkSwizzler::ResultAlpha r = maskSwizzler->next(srcRow, row);
msarett74114382015-03-16 11:55:18 -0700611 transparent &= SkSwizzler::IsTransparent(r);
612
613 // Move to the next row
msaretteed039b2015-03-18 11:11:19 -0700614 srcRow = SkTAddOffset<uint8_t>(srcRow, rowBytes);
msarett74114382015-03-16 11:55:18 -0700615 }
616
617 // Some fully transparent bmp images are intended to be opaque. Here, we
618 // correct for this possibility.
msarett74114382015-03-16 11:55:18 -0700619 if (transparent) {
msaretteed039b2015-03-18 11:11:19 -0700620 const SkImageInfo& opaqueInfo =
621 dstInfo.makeAlphaType(kOpaque_SkAlphaType);
622 SkAutoTDelete<SkMaskSwizzler> opaqueSwizzler(
623 SkMaskSwizzler::CreateMaskSwizzler(opaqueInfo, dst, dstRowBytes,
624 fMasks, fBitsPerPixel));
625 srcRow = srcBuffer.get();
msarett74114382015-03-16 11:55:18 -0700626 for (int y = 0; y < height; y++) {
msaretteed039b2015-03-18 11:11:19 -0700627 // Decode the row in opaque format
628 int row = kBottomUp_RowOrder == fRowOrder ? height - 1 - y : y;
629 opaqueSwizzler->next(srcRow, row);
630
631 // Move to the next row
632 srcRow = SkTAddOffset<uint8_t>(srcRow, rowBytes);
msarett74114382015-03-16 11:55:18 -0700633 }
634 }
635
636 // Finished decoding the entire image
637 return kSuccess;
638}
639
640/*
641 *
642 * Set an RLE pixel using the color table
643 *
644 */
msaretteed039b2015-03-18 11:11:19 -0700645void SkBmpCodec::setRLEPixel(SkPMColor* dst, size_t dstRowBytes,
646 const SkImageInfo& dstInfo, uint32_t x, uint32_t y,
647 uint8_t index) {
648 // Set the row
649 int height = dstInfo.height();
650 int row;
msarett74114382015-03-16 11:55:18 -0700651 if (kBottomUp_RowOrder == fRowOrder) {
msaretteed039b2015-03-18 11:11:19 -0700652 row = height - y - 1;
653 } else {
654 row = y;
msarett74114382015-03-16 11:55:18 -0700655 }
msaretteed039b2015-03-18 11:11:19 -0700656
657 // Set the pixel based on destination color type
658 switch (dstInfo.colorType()) {
659 case kN32_SkColorType: {
660 SkPMColor* dstRow = SkTAddOffset<SkPMColor>(dst,
661 row * (int) dstRowBytes);
662 dstRow[x] = fColorTable->operator[](index);
663 break;
664 }
665 case kRGB_565_SkColorType: {
666 uint16_t* dstRow = SkTAddOffset<uint16_t>(dst,
667 row * (int) dstRowBytes);
668 dstRow[x] = SkPixel32ToPixel16(fColorTable->operator[](index));
669 break;
670 }
671 default:
672 // This case should not be reached. We should catch an invalid
673 // color type when we check that the conversion is possible.
674 SkASSERT(false);
675 break;
676 }
677}
678
679/*
680 *
681 * Set an RLE pixel from R, G, B values
682 *
683 */
684void SkBmpCodec::setRLE24Pixel(SkPMColor* dst, size_t dstRowBytes,
685 const SkImageInfo& dstInfo, uint32_t x,
686 uint32_t y, uint8_t red, uint8_t green,
687 uint8_t blue) {
688 // Set the row
689 int height = dstInfo.height();
690 int row;
691 if (kBottomUp_RowOrder == fRowOrder) {
692 row = height - y - 1;
693 } else {
694 row = y;
695 }
696
697 // Set the pixel based on destination color type
698 switch (dstInfo.colorType()) {
699 case kN32_SkColorType: {
700 SkPMColor* dstRow = SkTAddOffset<SkPMColor>(dst,
701 row * (int) dstRowBytes);
702 dstRow[x] = SkPackARGB32NoCheck(0xFF, red, green, blue);
703 break;
704 }
705 case kRGB_565_SkColorType: {
706 uint16_t* dstRow = SkTAddOffset<uint16_t>(dst,
707 row * (int) dstRowBytes);
708 dstRow[x] = SkPack888ToRGB16(red, green, blue);
709 break;
710 }
711 default:
712 // This case should not be reached. We should catch an invalid
713 // color type when we check that the conversion is possible.
714 SkASSERT(false);
715 break;
716 }
msarett74114382015-03-16 11:55:18 -0700717}
718
719/*
720 *
721 * Performs the bitmap decoding for RLE input format
722 * RLE decoding is performed all at once, rather than a one row at a time
723 *
724 */
725SkCodec::Result SkBmpCodec::decodeRLE(const SkImageInfo& dstInfo,
726 void* dst, size_t dstRowBytes) {
727 // Set RLE flags
728 static const uint8_t RLE_ESCAPE = 0;
729 static const uint8_t RLE_EOL = 0;
730 static const uint8_t RLE_EOF = 1;
731 static const uint8_t RLE_DELTA = 2;
732
733 // Set constant values
734 const int width = dstInfo.width();
735 const int height = dstInfo.height();
736
737 // Input buffer parameters
738 uint32_t currByte = 0;
msaretteed039b2015-03-18 11:11:19 -0700739 SkAutoTDeleteArray<uint8_t> buffer(SkNEW_ARRAY(uint8_t, fRLEBytes));
740 size_t totalBytes = stream()->read(buffer.get(), fRLEBytes);
741 if (totalBytes < fRLEBytes) {
msarett74114382015-03-16 11:55:18 -0700742 SkDebugf("Warning: incomplete RLE file.\n");
743 } else if (totalBytes <= 0) {
744 SkDebugf("Error: could not read RLE image data.\n");
745 return kInvalidInput;
746 }
747
748 // Destination parameters
749 int x = 0;
750 int y = 0;
751 // If the code skips pixels, remaining pixels are transparent or black
752 // TODO: Skip this if memory was already zeroed.
753 memset(dst, 0, dstRowBytes * height);
754 SkPMColor* dstPtr = (SkPMColor*) dst;
755
756 while (true) {
757 // Every entry takes at least two bytes
758 if ((int) totalBytes - currByte < 2) {
759 SkDebugf("Warning: incomplete RLE input.\n");
760 return kIncompleteInput;
761 }
762
763 // Read the next two bytes. These bytes have different meanings
764 // depending on their values. In the first interpretation, the first
765 // byte is an escape flag and the second byte indicates what special
766 // task to perform.
767 const uint8_t flag = buffer.get()[currByte++];
768 const uint8_t task = buffer.get()[currByte++];
769
770 // If we have reached a row that is beyond the image size, and the RLE
771 // code does not indicate end of file, abort and signal a warning.
772 if (y >= height && (flag != RLE_ESCAPE || (task != RLE_EOF))) {
773 SkDebugf("Warning: invalid RLE input.\n");
774 return kIncompleteInput;
775 }
776
777 // Perform decoding
778 if (RLE_ESCAPE == flag) {
779 switch (task) {
780 case RLE_EOL:
781 x = 0;
782 y++;
783 break;
784 case RLE_EOF:
785 return kSuccess;
786 case RLE_DELTA: {
787 // Two bytes are needed to specify delta
788 if ((int) totalBytes - currByte < 2) {
789 SkDebugf("Warning: incomplete RLE input\n");
790 return kIncompleteInput;
791 }
792 // Modify x and y
793 const uint8_t dx = buffer.get()[currByte++];
794 const uint8_t dy = buffer.get()[currByte++];
795 x += dx;
796 y += dy;
797 if (x > width || y > height) {
798 SkDebugf("Warning: invalid RLE input.\n");
799 return kIncompleteInput;
800 }
801 break;
802 }
803 default: {
804 // If task does not match any of the above signals, it
805 // indicates that we have a sequence of non-RLE pixels.
806 // Furthermore, the value of task is equal to the number
807 // of pixels to interpret.
808 uint8_t numPixels = task;
809 const size_t rowBytes = compute_row_bytes(numPixels,
810 fBitsPerPixel);
811 // Abort if setting numPixels moves us off the edge of the
812 // image. Also abort if there are not enough bytes
813 // remaining in the stream to set numPixels.
814 if (x + numPixels > width ||
815 (int) totalBytes - currByte < SkAlign2(rowBytes)) {
816 SkDebugf("Warning: invalid RLE input.\n");
817 return kIncompleteInput;
818 }
819 // Set numPixels number of pixels
msarett74114382015-03-16 11:55:18 -0700820 while (numPixels > 0) {
821 switch(fBitsPerPixel) {
822 case 4: {
823 SkASSERT(currByte < totalBytes);
824 uint8_t val = buffer.get()[currByte++];
msaretteed039b2015-03-18 11:11:19 -0700825 setRLEPixel(dstPtr, dstRowBytes, dstInfo, x++,
826 y, val >> 4);
msarett74114382015-03-16 11:55:18 -0700827 numPixels--;
828 if (numPixels != 0) {
msaretteed039b2015-03-18 11:11:19 -0700829 setRLEPixel(dstPtr, dstRowBytes, dstInfo,
msarett74114382015-03-16 11:55:18 -0700830 x++, y, val & 0xF);
831 numPixels--;
832 }
833 break;
834 }
835 case 8:
836 SkASSERT(currByte < totalBytes);
msaretteed039b2015-03-18 11:11:19 -0700837 setRLEPixel(dstPtr, dstRowBytes, dstInfo, x++,
838 y, buffer.get()[currByte++]);
msarett74114382015-03-16 11:55:18 -0700839 numPixels--;
840 break;
841 case 24: {
842 SkASSERT(currByte + 2 < totalBytes);
843 uint8_t blue = buffer.get()[currByte++];
844 uint8_t green = buffer.get()[currByte++];
845 uint8_t red = buffer.get()[currByte++];
msaretteed039b2015-03-18 11:11:19 -0700846 setRLE24Pixel(dstPtr, dstRowBytes, dstInfo,
847 x++, y, red, green, blue);
msarett74114382015-03-16 11:55:18 -0700848 numPixels--;
849 }
850 default:
851 SkASSERT(false);
852 return kInvalidInput;
853 }
854 }
855 // Skip a byte if necessary to maintain alignment
856 if (!SkIsAlign2(rowBytes)) {
857 currByte++;
858 }
859 break;
860 }
861 }
862 } else {
863 // If the first byte read is not a flag, it indicates the number of
864 // pixels to set in RLE mode.
865 const uint8_t numPixels = flag;
866 const int endX = SkTMin<int>(x + numPixels, width);
867
868 if (24 == fBitsPerPixel) {
869 // In RLE24, the second byte read is part of the pixel color.
870 // There are two more required bytes to finish encoding the
871 // color.
872 if ((int) totalBytes - currByte < 2) {
873 SkDebugf("Warning: incomplete RLE input\n");
874 return kIncompleteInput;
875 }
876
877 // Fill the pixels up to endX with the specified color
878 uint8_t blue = task;
879 uint8_t green = buffer.get()[currByte++];
880 uint8_t red = buffer.get()[currByte++];
msarett74114382015-03-16 11:55:18 -0700881 while (x < endX) {
msaretteed039b2015-03-18 11:11:19 -0700882 setRLE24Pixel(dstPtr, dstRowBytes, dstInfo, x++, y, red,
883 green, blue);
msarett74114382015-03-16 11:55:18 -0700884 }
885 } else {
886 // In RLE8 or RLE4, the second byte read gives the index in the
887 // color table to look up the pixel color.
888 // RLE8 has one color index that gets repeated
889 // RLE4 has two color indexes in the upper and lower 4 bits of
890 // the bytes, which are alternated
891 uint8_t indices[2] = { task, task };
892 if (4 == fBitsPerPixel) {
893 indices[0] >>= 4;
894 indices[1] &= 0xf;
895 }
896
897 // Set the indicated number of pixels
898 for (int which = 0; x < endX; x++) {
msaretteed039b2015-03-18 11:11:19 -0700899 setRLEPixel(dstPtr, dstRowBytes, dstInfo, x, y,
msarett74114382015-03-16 11:55:18 -0700900 indices[which]);
901 which = !which;
902 }
903 }
904 }
905 }
906}
907
908/*
909 *
910 * Performs the bitmap decoding for standard input format
911 *
912 */
913SkCodec::Result SkBmpCodec::decode(const SkImageInfo& dstInfo,
914 void* dst, size_t dstRowBytes) {
915 // Set constant values
916 const int width = dstInfo.width();
917 const int height = dstInfo.height();
918 const size_t rowBytes = SkAlign4(compute_row_bytes(width, fBitsPerPixel));
msarett74114382015-03-16 11:55:18 -0700919
920 // Get swizzler configuration
921 SkSwizzler::SrcConfig config;
922 switch (fBitsPerPixel) {
923 case 1:
924 config = SkSwizzler::kIndex1;
925 break;
926 case 2:
927 config = SkSwizzler::kIndex2;
928 break;
929 case 4:
930 config = SkSwizzler::kIndex4;
931 break;
932 case 8:
933 config = SkSwizzler::kIndex;
934 break;
935 case 24:
936 config = SkSwizzler::kBGR;
937 break;
938 case 32:
msaretteed039b2015-03-18 11:11:19 -0700939 if (kOpaque_SkAlphaType == dstInfo.alphaType()) {
msarett74114382015-03-16 11:55:18 -0700940 config = SkSwizzler::kBGRX;
941 } else {
942 config = SkSwizzler::kBGRA;
943 }
944 break;
945 default:
946 SkASSERT(false);
947 return kInvalidInput;
948 }
949
950 // Create swizzler
msaretteed039b2015-03-18 11:11:19 -0700951 SkAutoTDelete<SkSwizzler> swizzler(SkSwizzler::CreateSwizzler(config,
952 fColorTable->readColors(), dstInfo, dst, dstRowBytes,
953 SkImageGenerator::kNo_ZeroInitialized));
msarett74114382015-03-16 11:55:18 -0700954
955 // Allocate space for a row buffer and a source for the swizzler
956 SkAutoTDeleteArray<uint8_t> srcBuffer(SkNEW_ARRAY(uint8_t, rowBytes));
957
958 // Iterate over rows of the image
959 // FIXME: bool transparent = true;
960 for (int y = 0; y < height; y++) {
961 // Read a row of the input
962 if (stream()->read(srcBuffer.get(), rowBytes) != rowBytes) {
963 SkDebugf("Warning: incomplete input stream.\n");
964 return kIncompleteInput;
965 }
966
967 // Decode the row in destination format
968 uint32_t row;
969 if (kTopDown_RowOrder == fRowOrder) {
970 row = y;
971 } else {
972 row = height - 1 - y;
973 }
974
975 swizzler->next(srcBuffer.get(), row);
976 // FIXME: SkSwizzler::ResultAlpha r =
977 // swizzler->next(srcBuffer.get(), row);
978 // FIXME: transparent &= SkSwizzler::IsTransparent(r);
979 }
980
981 // FIXME: This code exists to match the behavior in the chromium decoder
982 // and to follow the bmp specification as it relates to alpha masks. It is
983 // commented out because we have yet to discover a test image that provides
984 // an alpha mask and uses this decode mode.
985
986 // Now we adjust the output image with some additional behavior that
987 // SkSwizzler does not support. Firstly, all bmp images that contain
988 // alpha are masked by the alpha mask. Secondly, many fully transparent
989 // bmp images are intended to be opaque. Here, we make those corrections.
990 // Modifying alpha is safe because colors are stored unpremultiplied.
991 /*
992 SkPMColor* dstRow = (SkPMColor*) dst;
993 if (SkSwizzler::kBGRA == config) {
994 for (int y = 0; y < height; y++) {
995 for (int x = 0; x < width; x++) {
996 if (transparent) {
997 dstRow[x] |= 0xFF000000;
998 } else {
999 dstRow[x] &= alphaMask;
1000 }
1001 dstRow = SkTAddOffset<SkPMColor>(dstRow, dstRowBytes);
1002 }
1003 }
1004 }
1005 */
1006
1007 // Finished decoding the entire image
1008 return kSuccess;
1009}