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