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