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