blob: 660576a26a0fb098df81745c3b7cc3d30f978118 [file] [log] [blame]
msarett9bde9182015-03-25 05:27:48 -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
msarettb46e5e22015-07-30 11:36:40 -07008#include "SkBmpCodec.h"
msarett9bde9182015-03-25 05:27:48 -07009#include "SkCodec_libico.h"
10#include "SkCodec_libpng.h"
11#include "SkCodecPriv.h"
12#include "SkColorPriv.h"
13#include "SkData.h"
14#include "SkStream.h"
15#include "SkTDArray.h"
16#include "SkTSort.h"
17
msarettbe8216a2015-12-04 08:00:50 -080018static bool ico_conversion_possible(const SkImageInfo& dstInfo) {
19 // We only support kN32_SkColorType.
20 // This makes sense for BMP-in-ICO. The presence of an AND
21 // mask (which changes colors and adds transparency) means that
22 // we cannot use k565 or kIndex8.
23 // FIXME: For PNG-in-ICO, we could technically support whichever
24 // color types that the png supports.
25 if (kN32_SkColorType != dstInfo.colorType()) {
26 return false;
27 }
28
29 // We only support transparent alpha types. This is necessary for
30 // BMP-in-ICOs since there will be an AND mask.
31 // FIXME: For opaque PNG-in-ICOs, we should be able to support kOpaque.
32 return kPremul_SkAlphaType == dstInfo.alphaType() ||
33 kUnpremul_SkAlphaType == dstInfo.alphaType();
34}
35
36static SkImageInfo fix_embedded_alpha(const SkImageInfo& dstInfo, SkAlphaType embeddedAlpha) {
37 // FIXME (msarett): ICO is considered non-opaque, even if the embedded BMP
38 // incorrectly claims it has no alpha.
39 switch (embeddedAlpha) {
40 case kPremul_SkAlphaType:
41 case kUnpremul_SkAlphaType:
42 // Use the requested alpha type if the embedded codec supports alpha.
43 embeddedAlpha = dstInfo.alphaType();
44 break;
45 case kOpaque_SkAlphaType:
46 // If the embedded codec claims it is opaque, decode as if it is opaque.
47 break;
48 default:
49 SkASSERT(false);
50 break;
51 }
52 return dstInfo.makeAlphaType(embeddedAlpha);
53}
54
msarett9bde9182015-03-25 05:27:48 -070055/*
56 * Checks the start of the stream to see if the image is an Ico or Cur
57 */
scroggodb30be22015-12-08 18:54:13 -080058bool SkIcoCodec::IsIco(const void* buffer, size_t bytesRead) {
msarett9bde9182015-03-25 05:27:48 -070059 const char icoSig[] = { '\x00', '\x00', '\x01', '\x00' };
60 const char curSig[] = { '\x00', '\x00', '\x02', '\x00' };
scroggodb30be22015-12-08 18:54:13 -080061 return bytesRead >= sizeof(icoSig) &&
msarett9bde9182015-03-25 05:27:48 -070062 (!memcmp(buffer, icoSig, sizeof(icoSig)) ||
63 !memcmp(buffer, curSig, sizeof(curSig)));
64}
65
66/*
67 * Assumes IsIco was called and returned true
68 * Creates an Ico decoder
69 * Reads enough of the stream to determine the image format
70 */
71SkCodec* SkIcoCodec::NewFromStream(SkStream* stream) {
msarettd0be5bb2015-03-25 06:29:18 -070072 // Ensure that we do not leak the input stream
73 SkAutoTDelete<SkStream> inputStream(stream);
74
msarett9bde9182015-03-25 05:27:48 -070075 // Header size constants
76 static const uint32_t kIcoDirectoryBytes = 6;
77 static const uint32_t kIcoDirEntryBytes = 16;
78
79 // Read the directory header
halcanary385fe4d2015-08-26 13:07:48 -070080 SkAutoTDeleteArray<uint8_t> dirBuffer(new uint8_t[kIcoDirectoryBytes]);
msarettd0be5bb2015-03-25 06:29:18 -070081 if (inputStream.get()->read(dirBuffer.get(), kIcoDirectoryBytes) !=
msarett9bde9182015-03-25 05:27:48 -070082 kIcoDirectoryBytes) {
scroggo230d4ac2015-03-26 07:15:55 -070083 SkCodecPrintf("Error: unable to read ico directory header.\n");
halcanary96fcdcc2015-08-27 07:41:13 -070084 return nullptr;
msarett9bde9182015-03-25 05:27:48 -070085 }
86
87 // Process the directory header
88 const uint16_t numImages = get_short(dirBuffer.get(), 4);
89 if (0 == numImages) {
scroggo230d4ac2015-03-26 07:15:55 -070090 SkCodecPrintf("Error: No images embedded in ico.\n");
halcanary96fcdcc2015-08-27 07:41:13 -070091 return nullptr;
msarett9bde9182015-03-25 05:27:48 -070092 }
93
94 // Ensure that we can read all of indicated directory entries
halcanary385fe4d2015-08-26 13:07:48 -070095 SkAutoTDeleteArray<uint8_t> entryBuffer(new uint8_t[numImages * kIcoDirEntryBytes]);
msarettd0be5bb2015-03-25 06:29:18 -070096 if (inputStream.get()->read(entryBuffer.get(), numImages*kIcoDirEntryBytes) !=
msarett9bde9182015-03-25 05:27:48 -070097 numImages*kIcoDirEntryBytes) {
scroggo230d4ac2015-03-26 07:15:55 -070098 SkCodecPrintf("Error: unable to read ico directory entries.\n");
halcanary96fcdcc2015-08-27 07:41:13 -070099 return nullptr;
msarett9bde9182015-03-25 05:27:48 -0700100 }
101
102 // This structure is used to represent the vital information about entries
103 // in the directory header. We will obtain this information for each
104 // directory entry.
105 struct Entry {
106 uint32_t offset;
107 uint32_t size;
108 };
halcanary385fe4d2015-08-26 13:07:48 -0700109 SkAutoTDeleteArray<Entry> directoryEntries(new Entry[numImages]);
msarett9bde9182015-03-25 05:27:48 -0700110
111 // Iterate over directory entries
112 for (uint32_t i = 0; i < numImages; i++) {
113 // The directory entry contains information such as width, height,
114 // bits per pixel, and number of colors in the color palette. We will
115 // ignore these fields since they are repeated in the header of the
116 // embedded image. In the event of an inconsistency, we would always
117 // defer to the value in the embedded header anyway.
118
119 // Specifies the size of the embedded image, including the header
120 uint32_t size = get_int(entryBuffer.get(), 8 + i*kIcoDirEntryBytes);
121
122 // Specifies the offset of the embedded image from the start of file.
123 // It does not indicate the start of the pixel data, but rather the
124 // start of the embedded image header.
125 uint32_t offset = get_int(entryBuffer.get(), 12 + i*kIcoDirEntryBytes);
126
127 // Save the vital fields
128 directoryEntries.get()[i].offset = offset;
129 directoryEntries.get()[i].size = size;
130 }
131
132 // It is "customary" that the embedded images will be stored in order of
133 // increasing offset. However, the specification does not indicate that
134 // they must be stored in this order, so we will not trust that this is the
135 // case. Here we sort the embedded images by increasing offset.
136 struct EntryLessThan {
137 bool operator() (Entry a, Entry b) const {
138 return a.offset < b.offset;
139 }
140 };
141 EntryLessThan lessThan;
142 SkTQSort(directoryEntries.get(), directoryEntries.get() + numImages - 1,
143 lessThan);
144
145 // Now will construct a candidate codec for each of the embedded images
146 uint32_t bytesRead = kIcoDirectoryBytes + numImages * kIcoDirEntryBytes;
147 SkAutoTDelete<SkTArray<SkAutoTDelete<SkCodec>, true>> codecs(
halcanary385fe4d2015-08-26 13:07:48 -0700148 new (SkTArray<SkAutoTDelete<SkCodec>, true>)(numImages));
msarett9bde9182015-03-25 05:27:48 -0700149 for (uint32_t i = 0; i < numImages; i++) {
150 uint32_t offset = directoryEntries.get()[i].offset;
151 uint32_t size = directoryEntries.get()[i].size;
msarette6dd0042015-10-09 11:07:34 -0700152
msarett9bde9182015-03-25 05:27:48 -0700153 // Ensure that the offset is valid
154 if (offset < bytesRead) {
scroggo230d4ac2015-03-26 07:15:55 -0700155 SkCodecPrintf("Warning: invalid ico offset.\n");
msarett9bde9182015-03-25 05:27:48 -0700156 continue;
157 }
158
159 // If we cannot skip, assume we have reached the end of the stream and
160 // stop trying to make codecs
msarettd0be5bb2015-03-25 06:29:18 -0700161 if (inputStream.get()->skip(offset - bytesRead) != offset - bytesRead) {
scroggo230d4ac2015-03-26 07:15:55 -0700162 SkCodecPrintf("Warning: could not skip to ico offset.\n");
msarett9bde9182015-03-25 05:27:48 -0700163 break;
164 }
165 bytesRead = offset;
166
167 // Create a new stream for the embedded codec
msarettd0be5bb2015-03-25 06:29:18 -0700168 SkAutoTUnref<SkData> data(
169 SkData::NewFromStream(inputStream.get(), size));
halcanary96fcdcc2015-08-27 07:41:13 -0700170 if (nullptr == data.get()) {
scroggo230d4ac2015-03-26 07:15:55 -0700171 SkCodecPrintf("Warning: could not create embedded stream.\n");
msarett9bde9182015-03-25 05:27:48 -0700172 break;
173 }
halcanary385fe4d2015-08-26 13:07:48 -0700174 SkAutoTDelete<SkMemoryStream> embeddedStream(new SkMemoryStream(data.get()));
msarett9bde9182015-03-25 05:27:48 -0700175 bytesRead += size;
176
177 // Check if the embedded codec is bmp or png and create the codec
halcanary96fcdcc2015-08-27 07:41:13 -0700178 SkCodec* codec = nullptr;
scroggodb30be22015-12-08 18:54:13 -0800179 if (SkPngCodec::IsPng((const char*) data->bytes(), data->size())) {
msarett9bde9182015-03-25 05:27:48 -0700180 codec = SkPngCodec::NewFromStream(embeddedStream.detach());
181 } else {
182 codec = SkBmpCodec::NewFromIco(embeddedStream.detach());
183 }
184
185 // Save a valid codec
halcanary96fcdcc2015-08-27 07:41:13 -0700186 if (nullptr != codec) {
msarett9bde9182015-03-25 05:27:48 -0700187 codecs->push_back().reset(codec);
188 }
189 }
190
191 // Recognize if there are no valid codecs
192 if (0 == codecs->count()) {
scroggo230d4ac2015-03-26 07:15:55 -0700193 SkCodecPrintf("Error: could not find any valid embedded ico codecs.\n");
halcanary96fcdcc2015-08-27 07:41:13 -0700194 return nullptr;
msarett9bde9182015-03-25 05:27:48 -0700195 }
196
197 // Use the largest codec as a "suggestion" for image info
198 uint32_t maxSize = 0;
199 uint32_t maxIndex = 0;
200 for (int32_t i = 0; i < codecs->count(); i++) {
201 SkImageInfo info = codecs->operator[](i)->getInfo();
202 uint32_t size = info.width() * info.height();
203 if (size > maxSize) {
204 maxSize = size;
205 maxIndex = i;
206 }
207 }
208 SkImageInfo info = codecs->operator[](maxIndex)->getInfo();
209
scroggocc2feb12015-08-14 08:32:46 -0700210 // ICOs contain an alpha mask after the image which means we cannot
211 // guarantee that an image is opaque, even if the sub-codec thinks it
212 // is.
213 // FIXME (msarett): The BMP decoder depends on the alpha type in order
214 // to decode correctly, otherwise it could report kUnpremul and we would
215 // not have to correct it here. Is there a better way?
216 // FIXME (msarett): This is only true for BMP in ICO - could a PNG in ICO
217 // be opaque? Is it okay that we missed out on the opportunity to mark
218 // such an image as opaque?
219 info = info.makeAlphaType(kUnpremul_SkAlphaType);
220
msarett9bde9182015-03-25 05:27:48 -0700221 // Note that stream is owned by the embedded codec, the ico does not need
222 // direct access to the stream.
halcanary385fe4d2015-08-26 13:07:48 -0700223 return new SkIcoCodec(info, codecs.detach());
msarett9bde9182015-03-25 05:27:48 -0700224}
225
226/*
227 * Creates an instance of the decoder
228 * Called only by NewFromStream
229 */
230SkIcoCodec::SkIcoCodec(const SkImageInfo& info,
231 SkTArray<SkAutoTDelete<SkCodec>, true>* codecs)
halcanary96fcdcc2015-08-27 07:41:13 -0700232 : INHERITED(info, nullptr)
msarett9bde9182015-03-25 05:27:48 -0700233 , fEmbeddedCodecs(codecs)
msarettbe8216a2015-12-04 08:00:50 -0800234 , fCurrScanlineCodec(nullptr)
msarett9bde9182015-03-25 05:27:48 -0700235{}
236
237/*
238 * Chooses the best dimensions given the desired scale
239 */
240SkISize SkIcoCodec::onGetScaledDimensions(float desiredScale) const {
241 // We set the dimensions to the largest candidate image by default.
242 // Regardless of the scale request, this is the largest image that we
243 // will decode.
msarett9bde9182015-03-25 05:27:48 -0700244 int origWidth = this->getInfo().width();
245 int origHeight = this->getInfo().height();
246 float desiredSize = desiredScale * origWidth * origHeight;
247 // At least one image will have smaller error than this initial value
248 float minError = ((float) (origWidth * origHeight)) - desiredSize + 1.0f;
249 int32_t minIndex = -1;
250 for (int32_t i = 0; i < fEmbeddedCodecs->count(); i++) {
251 int width = fEmbeddedCodecs->operator[](i)->getInfo().width();
252 int height = fEmbeddedCodecs->operator[](i)->getInfo().height();
253 float error = SkTAbs(((float) (width * height)) - desiredSize);
254 if (error < minError) {
255 minError = error;
256 minIndex = i;
257 }
258 }
259 SkASSERT(minIndex >= 0);
260
261 return fEmbeddedCodecs->operator[](minIndex)->getInfo().dimensions();
262}
263
msarettbe8216a2015-12-04 08:00:50 -0800264int SkIcoCodec::chooseCodec(const SkISize& requestedSize, int startIndex) {
265 SkASSERT(startIndex >= 0);
266
scroggoe7fc14b2015-10-02 13:14:46 -0700267 // FIXME: Cache the index from onGetScaledDimensions?
msarettbe8216a2015-12-04 08:00:50 -0800268 for (int i = startIndex; i < fEmbeddedCodecs->count(); i++) {
269 if (fEmbeddedCodecs->operator[](i)->getInfo().dimensions() == requestedSize) {
270 return i;
scroggoe7fc14b2015-10-02 13:14:46 -0700271 }
272 }
273
msarettbe8216a2015-12-04 08:00:50 -0800274 return -1;
275}
276
277bool SkIcoCodec::onDimensionsSupported(const SkISize& dim) {
278 return this->chooseCodec(dim, 0) >= 0;
scroggoe7fc14b2015-10-02 13:14:46 -0700279}
280
msarett9bde9182015-03-25 05:27:48 -0700281/*
282 * Initiates the Ico decode
283 */
284SkCodec::Result SkIcoCodec::onGetPixels(const SkImageInfo& dstInfo,
285 void* dst, size_t dstRowBytes,
msarette6dd0042015-10-09 11:07:34 -0700286 const Options& opts, SkPMColor* colorTable,
287 int* colorCount, int* rowsDecoded) {
scroggob636b452015-07-22 07:16:20 -0700288 if (opts.fSubset) {
289 // Subsets are not supported.
290 return kUnimplemented;
291 }
scroggocc2feb12015-08-14 08:32:46 -0700292
msarettbe8216a2015-12-04 08:00:50 -0800293 if (!ico_conversion_possible(dstInfo)) {
scroggocc2feb12015-08-14 08:32:46 -0700294 return kInvalidConversion;
295 }
296
msarettbe8216a2015-12-04 08:00:50 -0800297 int index = 0;
298 SkCodec::Result result = kInvalidScale;
299 while (true) {
300 index = this->chooseCodec(dstInfo.dimensions(), index);
301 if (index < 0) {
302 break;
msarett1603e932015-12-04 05:43:09 -0800303 }
msarettbe8216a2015-12-04 08:00:50 -0800304
305 SkCodec* embeddedCodec = fEmbeddedCodecs->operator[](index);
306 SkImageInfo decodeInfo = fix_embedded_alpha(dstInfo, embeddedCodec->getInfo().alphaType());
307 SkASSERT(decodeInfo.colorType() == kN32_SkColorType);
308 result = embeddedCodec->getPixels(decodeInfo, dst, dstRowBytes, &opts, colorTable,
309 colorCount);
310
311 switch (result) {
312 case kSuccess:
313 case kIncompleteInput:
314 // The embedded codec will handle filling incomplete images, so we will indicate
315 // that all of the rows are initialized.
316 *rowsDecoded = decodeInfo.height();
317 return result;
318 default:
319 // Continue trying to find a valid embedded codec on a failed decode.
320 break;
321 }
322
323 index++;
msarett1603e932015-12-04 05:43:09 -0800324 }
325
326 SkCodecPrintf("Error: No matching candidate image in ico.\n");
327 return result;
328}
msarettbe8216a2015-12-04 08:00:50 -0800329
330SkCodec::Result SkIcoCodec::onStartScanlineDecode(const SkImageInfo& dstInfo,
331 const SkCodec::Options& options, SkPMColor colorTable[], int* colorCount) {
332 if (!ico_conversion_possible(dstInfo)) {
333 return kInvalidConversion;
334 }
335
336 int index = 0;
337 SkCodec::Result result = kInvalidScale;
338 while (true) {
339 index = this->chooseCodec(dstInfo.dimensions(), index);
340 if (index < 0) {
341 break;
342 }
343
344 SkCodec* embeddedCodec = fEmbeddedCodecs->operator[](index);
345 SkImageInfo decodeInfo = fix_embedded_alpha(dstInfo, embeddedCodec->getInfo().alphaType());
346 result = embeddedCodec->startScanlineDecode(decodeInfo, &options, colorTable, colorCount);
347 if (kSuccess == result) {
348 fCurrScanlineCodec = embeddedCodec;
349 return result;
350 }
351
352 index++;
353 }
354
355 SkCodecPrintf("Error: No matching candidate image in ico.\n");
356 return result;
357}
358
359int SkIcoCodec::onGetScanlines(void* dst, int count, size_t rowBytes) {
360 SkASSERT(fCurrScanlineCodec);
361 return fCurrScanlineCodec->getScanlines(dst, count, rowBytes);
362}
363
364bool SkIcoCodec::onSkipScanlines(int count) {
365 SkASSERT(fCurrScanlineCodec);
366 return fCurrScanlineCodec->skipScanlines(count);
367}
368
369SkCodec::SkScanlineOrder SkIcoCodec::onGetScanlineOrder() const {
370 // FIXME: This function will possibly return the wrong value if it is called
371 // before startScanlineDecode().
372 return fCurrScanlineCodec ? fCurrScanlineCodec->getScanlineOrder() :
373 INHERITED::onGetScanlineOrder();
374}
375
376SkSampler* SkIcoCodec::getSampler(bool createIfNecessary) {
377 return fCurrScanlineCodec ? fCurrScanlineCodec->getSampler(createIfNecessary) : nullptr;
378}