1 /*
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 "SkBmpStandardCodec.h"
9 #include "SkCodecPriv.h"
10 #include "SkColorPriv.h"
11 #include "SkStream.h"
12
13 /*
14 * Creates an instance of the decoder
15 * Called only by NewFromStream
16 */
SkBmpStandardCodec(int width,int height,const SkEncodedInfo & info,SkStream * stream,uint16_t bitsPerPixel,uint32_t numColors,uint32_t bytesPerColor,uint32_t offset,SkCodec::SkScanlineOrder rowOrder,bool isOpaque,bool inIco)17 SkBmpStandardCodec::SkBmpStandardCodec(int width, int height, const SkEncodedInfo& info,
18 SkStream* stream, uint16_t bitsPerPixel, uint32_t numColors,
19 uint32_t bytesPerColor, uint32_t offset,
20 SkCodec::SkScanlineOrder rowOrder,
21 bool isOpaque, bool inIco)
22 : INHERITED(width, height, info, stream, bitsPerPixel, rowOrder)
23 , fColorTable(nullptr)
24 , fNumColors(numColors)
25 , fBytesPerColor(bytesPerColor)
26 , fOffset(offset)
27 , fSwizzler(nullptr)
28 , fSrcBuffer(new uint8_t[this->srcRowBytes()])
29 , fIsOpaque(isOpaque)
30 , fInIco(inIco)
31 , fAndMaskRowBytes(fInIco ? SkAlign4(compute_row_bytes(this->getInfo().width(), 1)) : 0)
32 , fXformOnDecode(false)
33 {}
34
35 /*
36 * Initiates the bitmap decode
37 */
onGetPixels(const SkImageInfo & dstInfo,void * dst,size_t dstRowBytes,const Options & opts,SkPMColor * inputColorPtr,int * inputColorCount,int * rowsDecoded)38 SkCodec::Result SkBmpStandardCodec::onGetPixels(const SkImageInfo& dstInfo,
39 void* dst, size_t dstRowBytes,
40 const Options& opts,
41 SkPMColor* inputColorPtr,
42 int* inputColorCount,
43 int* rowsDecoded) {
44 if (opts.fSubset) {
45 // Subsets are not supported.
46 return kUnimplemented;
47 }
48 if (dstInfo.dimensions() != this->getInfo().dimensions()) {
49 SkCodecPrintf("Error: scaling not supported.\n");
50 return kInvalidScale;
51 }
52
53 Result result = this->prepareToDecode(dstInfo, opts, inputColorPtr, inputColorCount);
54 if (kSuccess != result) {
55 return result;
56 }
57 int rows = this->decodeRows(dstInfo, dst, dstRowBytes, opts);
58 if (rows != dstInfo.height()) {
59 *rowsDecoded = rows;
60 return kIncompleteInput;
61 }
62 return kSuccess;
63 }
64
65 /*
66 * Process the color table for the bmp input
67 */
createColorTable(SkColorType dstColorType,SkAlphaType dstAlphaType,int * numColors)68 bool SkBmpStandardCodec::createColorTable(SkColorType dstColorType, SkAlphaType dstAlphaType,
69 int* numColors) {
70 // Allocate memory for color table
71 uint32_t colorBytes = 0;
72 SkPMColor colorTable[256];
73 if (this->bitsPerPixel() <= 8) {
74 // Inform the caller of the number of colors
75 uint32_t maxColors = 1 << this->bitsPerPixel();
76 if (nullptr != numColors) {
77 // We set the number of colors to maxColors in order to ensure
78 // safe memory accesses. Otherwise, an invalid pixel could
79 // access memory outside of our color table array.
80 *numColors = maxColors;
81 }
82 // Don't bother reading more than maxColors.
83 const uint32_t numColorsToRead =
84 fNumColors == 0 ? maxColors : SkTMin(fNumColors, maxColors);
85
86 // Read the color table from the stream
87 colorBytes = numColorsToRead * fBytesPerColor;
88 std::unique_ptr<uint8_t[]> cBuffer(new uint8_t[colorBytes]);
89 if (stream()->read(cBuffer.get(), colorBytes) != colorBytes) {
90 SkCodecPrintf("Error: unable to read color table.\n");
91 return false;
92 }
93
94 SkColorType packColorType = dstColorType;
95 SkAlphaType packAlphaType = dstAlphaType;
96 if (this->colorXform()) {
97 packColorType = kBGRA_8888_SkColorType;
98 packAlphaType = kUnpremul_SkAlphaType;
99 }
100
101 // Choose the proper packing function
102 bool isPremul = (kPremul_SkAlphaType == packAlphaType) && !fIsOpaque;
103 PackColorProc packARGB = choose_pack_color_proc(isPremul, packColorType);
104
105 // Fill in the color table
106 uint32_t i = 0;
107 for (; i < numColorsToRead; i++) {
108 uint8_t blue = get_byte(cBuffer.get(), i*fBytesPerColor);
109 uint8_t green = get_byte(cBuffer.get(), i*fBytesPerColor + 1);
110 uint8_t red = get_byte(cBuffer.get(), i*fBytesPerColor + 2);
111 uint8_t alpha;
112 if (fIsOpaque) {
113 alpha = 0xFF;
114 } else {
115 alpha = get_byte(cBuffer.get(), i*fBytesPerColor + 3);
116 }
117 colorTable[i] = packARGB(alpha, red, green, blue);
118 }
119
120 // To avoid segmentation faults on bad pixel data, fill the end of the
121 // color table with black. This is the same the behavior as the
122 // chromium decoder.
123 for (; i < maxColors; i++) {
124 colorTable[i] = SkPackARGB32NoCheck(0xFF, 0, 0, 0);
125 }
126
127 if (this->colorXform() && !fXformOnDecode) {
128 SkColorSpaceXform::ColorFormat dstFormat = select_xform_format_ct(dstColorType);
129 SkColorSpaceXform::ColorFormat srcFormat = SkColorSpaceXform::kBGRA_8888_ColorFormat;
130 SkAlphaType xformAlphaType = select_xform_alpha(dstAlphaType,
131 this->getInfo().alphaType());
132 SkAssertResult(this->colorXform()->apply(dstFormat, colorTable, srcFormat, colorTable,
133 maxColors, xformAlphaType));
134 }
135
136 // Set the color table
137 fColorTable.reset(new SkColorTable(colorTable, maxColors));
138 }
139
140 // Bmp-in-Ico files do not use an offset to indicate where the pixel data
141 // begins. Pixel data always begins immediately after the color table.
142 if (!fInIco) {
143 // Check that we have not read past the pixel array offset
144 if(fOffset < colorBytes) {
145 // This may occur on OS 2.1 and other old versions where the color
146 // table defaults to max size, and the bmp tries to use a smaller
147 // color table. This is invalid, and our decision is to indicate
148 // an error, rather than try to guess the intended size of the
149 // color table.
150 SkCodecPrintf("Error: pixel data offset less than color table size.\n");
151 return false;
152 }
153
154 // After reading the color table, skip to the start of the pixel array
155 if (stream()->skip(fOffset - colorBytes) != fOffset - colorBytes) {
156 SkCodecPrintf("Error: unable to skip to image data.\n");
157 return false;
158 }
159 }
160
161 // Return true on success
162 return true;
163 }
164
initializeSwizzler(const SkImageInfo & dstInfo,const Options & opts)165 void SkBmpStandardCodec::initializeSwizzler(const SkImageInfo& dstInfo, const Options& opts) {
166 // In the case of bmp-in-icos, we will report BGRA to the client,
167 // since we may be required to apply an alpha mask after the decode.
168 // However, the swizzler needs to know the actual format of the bmp.
169 SkEncodedInfo encodedInfo = this->getEncodedInfo();
170 if (fInIco) {
171 if (this->bitsPerPixel() <= 8) {
172 encodedInfo = SkEncodedInfo::Make(SkEncodedInfo::kPalette_Color,
173 encodedInfo.alpha(), this->bitsPerPixel());
174 } else if (this->bitsPerPixel() == 24) {
175 encodedInfo = SkEncodedInfo::Make(SkEncodedInfo::kBGR_Color,
176 SkEncodedInfo::kOpaque_Alpha, 8);
177 }
178 }
179
180 // Get a pointer to the color table if it exists
181 const SkPMColor* colorPtr = get_color_ptr(fColorTable.get());
182
183 SkImageInfo swizzlerInfo = dstInfo;
184 SkCodec::Options swizzlerOptions = opts;
185 if (this->colorXform()) {
186 swizzlerInfo = swizzlerInfo.makeColorType(kXformSrcColorType);
187 if (kPremul_SkAlphaType == dstInfo.alphaType()) {
188 swizzlerInfo = swizzlerInfo.makeAlphaType(kUnpremul_SkAlphaType);
189 }
190
191 swizzlerOptions.fZeroInitialized = kNo_ZeroInitialized;
192 }
193
194
195 fSwizzler.reset(SkSwizzler::CreateSwizzler(encodedInfo, colorPtr, swizzlerInfo,
196 swizzlerOptions));
197 SkASSERT(fSwizzler);
198 }
199
onPrepareToDecode(const SkImageInfo & dstInfo,const SkCodec::Options & options,SkPMColor inputColorPtr[],int * inputColorCount)200 SkCodec::Result SkBmpStandardCodec::onPrepareToDecode(const SkImageInfo& dstInfo,
201 const SkCodec::Options& options, SkPMColor inputColorPtr[], int* inputColorCount) {
202 fXformOnDecode = false;
203 if (this->colorXform()) {
204 fXformOnDecode = apply_xform_on_decode(dstInfo.colorType(), this->getEncodedInfo().color());
205 if (fXformOnDecode) {
206 this->resetXformBuffer(dstInfo.width());
207 }
208 }
209
210 // Create the color table if necessary and prepare the stream for decode
211 // Note that if it is non-NULL, inputColorCount will be modified
212 if (!this->createColorTable(dstInfo.colorType(), dstInfo.alphaType(), inputColorCount)) {
213 SkCodecPrintf("Error: could not create color table.\n");
214 return SkCodec::kInvalidInput;
215 }
216
217 // Copy the color table to the client if necessary
218 copy_color_table(dstInfo, fColorTable.get(), inputColorPtr, inputColorCount);
219
220 // Initialize a swizzler
221 this->initializeSwizzler(dstInfo, options);
222 return SkCodec::kSuccess;
223 }
224
225 /*
226 * Performs the bitmap decoding for standard input format
227 */
decodeRows(const SkImageInfo & dstInfo,void * dst,size_t dstRowBytes,const Options & opts)228 int SkBmpStandardCodec::decodeRows(const SkImageInfo& dstInfo, void* dst, size_t dstRowBytes,
229 const Options& opts) {
230 // Iterate over rows of the image
231 const int height = dstInfo.height();
232 for (int y = 0; y < height; y++) {
233 // Read a row of the input
234 if (this->stream()->read(fSrcBuffer.get(), this->srcRowBytes()) != this->srcRowBytes()) {
235 SkCodecPrintf("Warning: incomplete input stream.\n");
236 return y;
237 }
238
239 // Decode the row in destination format
240 uint32_t row = this->getDstRow(y, dstInfo.height());
241
242 void* dstRow = SkTAddOffset<void>(dst, row * dstRowBytes);
243
244 if (fXformOnDecode) {
245 SkASSERT(this->colorXform());
246 SkImageInfo xformInfo = dstInfo.makeWH(fSwizzler->swizzleWidth(), dstInfo.height());
247 fSwizzler->swizzle(this->xformBuffer(), fSrcBuffer.get());
248 this->applyColorXform(xformInfo, dstRow, this->xformBuffer());
249 } else {
250 fSwizzler->swizzle(dstRow, fSrcBuffer.get());
251 }
252 }
253
254 if (fInIco && fIsOpaque) {
255 const int startScanline = this->currScanline();
256 if (startScanline < 0) {
257 // We are not performing a scanline decode.
258 // Just decode the entire ICO mask and return.
259 decodeIcoMask(this->stream(), dstInfo, dst, dstRowBytes);
260 return height;
261 }
262
263 // In order to perform a scanline ICO decode, we must be able
264 // to skip ahead in the stream in order to apply the AND mask
265 // to the requested scanlines.
266 // We will do this by taking advantage of the fact that
267 // SkIcoCodec always uses a SkMemoryStream as its underlying
268 // representation of the stream.
269 const void* memoryBase = this->stream()->getMemoryBase();
270 SkASSERT(nullptr != memoryBase);
271 SkASSERT(this->stream()->hasLength());
272 SkASSERT(this->stream()->hasPosition());
273
274 const size_t length = this->stream()->getLength();
275 const size_t currPosition = this->stream()->getPosition();
276
277 // Calculate how many bytes we must skip to reach the AND mask.
278 const int remainingScanlines = this->getInfo().height() - startScanline - height;
279 const size_t bytesToSkip = remainingScanlines * this->srcRowBytes() +
280 startScanline * fAndMaskRowBytes;
281 const size_t subStreamStartPosition = currPosition + bytesToSkip;
282 if (subStreamStartPosition >= length) {
283 // FIXME: How can we indicate that this decode was actually incomplete?
284 return height;
285 }
286
287 // Create a subStream to pass to decodeIcoMask(). It is useful to encapsulate
288 // the memory base into a stream in order to safely handle incomplete images
289 // without reading out of bounds memory.
290 const void* subStreamMemoryBase = SkTAddOffset<const void>(memoryBase,
291 subStreamStartPosition);
292 const size_t subStreamLength = length - subStreamStartPosition;
293 // This call does not transfer ownership of the subStreamMemoryBase.
294 SkMemoryStream subStream(subStreamMemoryBase, subStreamLength, false);
295
296 // FIXME: If decodeIcoMask does not succeed, is there a way that we can
297 // indicate the decode was incomplete?
298 decodeIcoMask(&subStream, dstInfo, dst, dstRowBytes);
299 }
300
301 return height;
302 }
303
decodeIcoMask(SkStream * stream,const SkImageInfo & dstInfo,void * dst,size_t dstRowBytes)304 void SkBmpStandardCodec::decodeIcoMask(SkStream* stream, const SkImageInfo& dstInfo,
305 void* dst, size_t dstRowBytes) {
306 // BMP in ICO have transparency, so this cannot be 565, and this mask
307 // prevents us from using kIndex8. The below code depends on the output
308 // being an SkPMColor.
309 SkASSERT(kRGBA_8888_SkColorType == dstInfo.colorType() ||
310 kBGRA_8888_SkColorType == dstInfo.colorType() ||
311 kRGBA_F16_SkColorType == dstInfo.colorType());
312
313 // If we are sampling, make sure that we only mask the sampled pixels.
314 // We do not need to worry about sampling in the y-dimension because that
315 // should be handled by SkSampledCodec.
316 const int sampleX = fSwizzler->sampleX();
317 const int sampledWidth = get_scaled_dimension(this->getInfo().width(), sampleX);
318 const int srcStartX = get_start_coord(sampleX);
319
320
321 SkPMColor* dstPtr = (SkPMColor*) dst;
322 for (int y = 0; y < dstInfo.height(); y++) {
323 // The srcBuffer will at least be large enough
324 if (stream->read(fSrcBuffer.get(), fAndMaskRowBytes) != fAndMaskRowBytes) {
325 SkCodecPrintf("Warning: incomplete AND mask for bmp-in-ico.\n");
326 return;
327 }
328
329 auto applyMask = [dstInfo](void* dstRow, int x, uint64_t bit) {
330 if (kRGBA_F16_SkColorType == dstInfo.colorType()) {
331 uint64_t* dst64 = (uint64_t*) dstRow;
332 dst64[x] &= bit - 1;
333 } else {
334 uint32_t* dst32 = (uint32_t*) dstRow;
335 dst32[x] &= bit - 1;
336 }
337 };
338
339 int row = this->getDstRow(y, dstInfo.height());
340
341 void* dstRow = SkTAddOffset<SkPMColor>(dstPtr, row * dstRowBytes);
342
343 int srcX = srcStartX;
344 for (int dstX = 0; dstX < sampledWidth; dstX++) {
345 int quotient;
346 int modulus;
347 SkTDivMod(srcX, 8, "ient, &modulus);
348 uint32_t shift = 7 - modulus;
349 uint64_t alphaBit = (fSrcBuffer.get()[quotient] >> shift) & 0x1;
350 applyMask(dstRow, dstX, alphaBit);
351 srcX += sampleX;
352 }
353 }
354 }
355
onGetFillValue(const SkImageInfo & dstInfo) const356 uint64_t SkBmpStandardCodec::onGetFillValue(const SkImageInfo& dstInfo) const {
357 const SkPMColor* colorPtr = get_color_ptr(fColorTable.get());
358 if (colorPtr) {
359 return get_color_table_fill_value(dstInfo.colorType(), dstInfo.alphaType(), colorPtr, 0,
360 this->colorXform(), false);
361 }
362 return INHERITED::onGetFillValue(dstInfo);
363 }
364