blob: e1314d712158daaa64daa608ede9ad78fe0358ab [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 */
58bool SkIcoCodec::IsIco(SkStream* stream) {
59 const char icoSig[] = { '\x00', '\x00', '\x01', '\x00' };
60 const char curSig[] = { '\x00', '\x00', '\x02', '\x00' };
61 char buffer[sizeof(icoSig)];
62 return stream->read(buffer, sizeof(icoSig)) == sizeof(icoSig) &&
63 (!memcmp(buffer, icoSig, sizeof(icoSig)) ||
64 !memcmp(buffer, curSig, sizeof(curSig)));
65}
66
67/*
68 * Assumes IsIco was called and returned true
69 * Creates an Ico decoder
70 * Reads enough of the stream to determine the image format
71 */
72SkCodec* SkIcoCodec::NewFromStream(SkStream* stream) {
msarettd0be5bb2015-03-25 06:29:18 -070073 // Ensure that we do not leak the input stream
74 SkAutoTDelete<SkStream> inputStream(stream);
75
msarett9bde9182015-03-25 05:27:48 -070076 // Header size constants
77 static const uint32_t kIcoDirectoryBytes = 6;
78 static const uint32_t kIcoDirEntryBytes = 16;
79
80 // Read the directory header
halcanary385fe4d2015-08-26 13:07:48 -070081 SkAutoTDeleteArray<uint8_t> dirBuffer(new uint8_t[kIcoDirectoryBytes]);
msarettd0be5bb2015-03-25 06:29:18 -070082 if (inputStream.get()->read(dirBuffer.get(), kIcoDirectoryBytes) !=
msarett9bde9182015-03-25 05:27:48 -070083 kIcoDirectoryBytes) {
scroggo230d4ac2015-03-26 07:15:55 -070084 SkCodecPrintf("Error: unable to read ico directory header.\n");
halcanary96fcdcc2015-08-27 07:41:13 -070085 return nullptr;
msarett9bde9182015-03-25 05:27:48 -070086 }
87
88 // Process the directory header
89 const uint16_t numImages = get_short(dirBuffer.get(), 4);
90 if (0 == numImages) {
scroggo230d4ac2015-03-26 07:15:55 -070091 SkCodecPrintf("Error: No images embedded in ico.\n");
halcanary96fcdcc2015-08-27 07:41:13 -070092 return nullptr;
msarett9bde9182015-03-25 05:27:48 -070093 }
94
95 // Ensure that we can read all of indicated directory entries
halcanary385fe4d2015-08-26 13:07:48 -070096 SkAutoTDeleteArray<uint8_t> entryBuffer(new uint8_t[numImages * kIcoDirEntryBytes]);
msarettd0be5bb2015-03-25 06:29:18 -070097 if (inputStream.get()->read(entryBuffer.get(), numImages*kIcoDirEntryBytes) !=
msarett9bde9182015-03-25 05:27:48 -070098 numImages*kIcoDirEntryBytes) {
scroggo230d4ac2015-03-26 07:15:55 -070099 SkCodecPrintf("Error: unable to read ico directory entries.\n");
halcanary96fcdcc2015-08-27 07:41:13 -0700100 return nullptr;
msarett9bde9182015-03-25 05:27:48 -0700101 }
102
103 // This structure is used to represent the vital information about entries
104 // in the directory header. We will obtain this information for each
105 // directory entry.
106 struct Entry {
107 uint32_t offset;
108 uint32_t size;
109 };
halcanary385fe4d2015-08-26 13:07:48 -0700110 SkAutoTDeleteArray<Entry> directoryEntries(new Entry[numImages]);
msarett9bde9182015-03-25 05:27:48 -0700111
112 // Iterate over directory entries
113 for (uint32_t i = 0; i < numImages; i++) {
114 // The directory entry contains information such as width, height,
115 // bits per pixel, and number of colors in the color palette. We will
116 // ignore these fields since they are repeated in the header of the
117 // embedded image. In the event of an inconsistency, we would always
118 // defer to the value in the embedded header anyway.
119
120 // Specifies the size of the embedded image, including the header
121 uint32_t size = get_int(entryBuffer.get(), 8 + i*kIcoDirEntryBytes);
122
123 // Specifies the offset of the embedded image from the start of file.
124 // It does not indicate the start of the pixel data, but rather the
125 // start of the embedded image header.
126 uint32_t offset = get_int(entryBuffer.get(), 12 + i*kIcoDirEntryBytes);
127
128 // Save the vital fields
129 directoryEntries.get()[i].offset = offset;
130 directoryEntries.get()[i].size = size;
131 }
132
133 // It is "customary" that the embedded images will be stored in order of
134 // increasing offset. However, the specification does not indicate that
135 // they must be stored in this order, so we will not trust that this is the
136 // case. Here we sort the embedded images by increasing offset.
137 struct EntryLessThan {
138 bool operator() (Entry a, Entry b) const {
139 return a.offset < b.offset;
140 }
141 };
142 EntryLessThan lessThan;
143 SkTQSort(directoryEntries.get(), directoryEntries.get() + numImages - 1,
144 lessThan);
145
146 // Now will construct a candidate codec for each of the embedded images
147 uint32_t bytesRead = kIcoDirectoryBytes + numImages * kIcoDirEntryBytes;
148 SkAutoTDelete<SkTArray<SkAutoTDelete<SkCodec>, true>> codecs(
halcanary385fe4d2015-08-26 13:07:48 -0700149 new (SkTArray<SkAutoTDelete<SkCodec>, true>)(numImages));
msarett9bde9182015-03-25 05:27:48 -0700150 for (uint32_t i = 0; i < numImages; i++) {
151 uint32_t offset = directoryEntries.get()[i].offset;
152 uint32_t size = directoryEntries.get()[i].size;
msarette6dd0042015-10-09 11:07:34 -0700153
msarett9bde9182015-03-25 05:27:48 -0700154 // Ensure that the offset is valid
155 if (offset < bytesRead) {
scroggo230d4ac2015-03-26 07:15:55 -0700156 SkCodecPrintf("Warning: invalid ico offset.\n");
msarett9bde9182015-03-25 05:27:48 -0700157 continue;
158 }
159
160 // If we cannot skip, assume we have reached the end of the stream and
161 // stop trying to make codecs
msarettd0be5bb2015-03-25 06:29:18 -0700162 if (inputStream.get()->skip(offset - bytesRead) != offset - bytesRead) {
scroggo230d4ac2015-03-26 07:15:55 -0700163 SkCodecPrintf("Warning: could not skip to ico offset.\n");
msarett9bde9182015-03-25 05:27:48 -0700164 break;
165 }
166 bytesRead = offset;
167
168 // Create a new stream for the embedded codec
msarettd0be5bb2015-03-25 06:29:18 -0700169 SkAutoTUnref<SkData> data(
170 SkData::NewFromStream(inputStream.get(), size));
halcanary96fcdcc2015-08-27 07:41:13 -0700171 if (nullptr == data.get()) {
scroggo230d4ac2015-03-26 07:15:55 -0700172 SkCodecPrintf("Warning: could not create embedded stream.\n");
msarett9bde9182015-03-25 05:27:48 -0700173 break;
174 }
halcanary385fe4d2015-08-26 13:07:48 -0700175 SkAutoTDelete<SkMemoryStream> embeddedStream(new SkMemoryStream(data.get()));
msarett9bde9182015-03-25 05:27:48 -0700176 bytesRead += size;
177
178 // Check if the embedded codec is bmp or png and create the codec
179 const bool isPng = SkPngCodec::IsPng(embeddedStream);
180 SkAssertResult(embeddedStream->rewind());
halcanary96fcdcc2015-08-27 07:41:13 -0700181 SkCodec* codec = nullptr;
msarett9bde9182015-03-25 05:27:48 -0700182 if (isPng) {
183 codec = SkPngCodec::NewFromStream(embeddedStream.detach());
184 } else {
185 codec = SkBmpCodec::NewFromIco(embeddedStream.detach());
186 }
187
188 // Save a valid codec
halcanary96fcdcc2015-08-27 07:41:13 -0700189 if (nullptr != codec) {
msarett9bde9182015-03-25 05:27:48 -0700190 codecs->push_back().reset(codec);
191 }
192 }
193
194 // Recognize if there are no valid codecs
195 if (0 == codecs->count()) {
scroggo230d4ac2015-03-26 07:15:55 -0700196 SkCodecPrintf("Error: could not find any valid embedded ico codecs.\n");
halcanary96fcdcc2015-08-27 07:41:13 -0700197 return nullptr;
msarett9bde9182015-03-25 05:27:48 -0700198 }
199
200 // Use the largest codec as a "suggestion" for image info
201 uint32_t maxSize = 0;
202 uint32_t maxIndex = 0;
203 for (int32_t i = 0; i < codecs->count(); i++) {
204 SkImageInfo info = codecs->operator[](i)->getInfo();
205 uint32_t size = info.width() * info.height();
206 if (size > maxSize) {
207 maxSize = size;
208 maxIndex = i;
209 }
210 }
211 SkImageInfo info = codecs->operator[](maxIndex)->getInfo();
212
scroggocc2feb12015-08-14 08:32:46 -0700213 // ICOs contain an alpha mask after the image which means we cannot
214 // guarantee that an image is opaque, even if the sub-codec thinks it
215 // is.
216 // FIXME (msarett): The BMP decoder depends on the alpha type in order
217 // to decode correctly, otherwise it could report kUnpremul and we would
218 // not have to correct it here. Is there a better way?
219 // FIXME (msarett): This is only true for BMP in ICO - could a PNG in ICO
220 // be opaque? Is it okay that we missed out on the opportunity to mark
221 // such an image as opaque?
222 info = info.makeAlphaType(kUnpremul_SkAlphaType);
223
msarett9bde9182015-03-25 05:27:48 -0700224 // Note that stream is owned by the embedded codec, the ico does not need
225 // direct access to the stream.
halcanary385fe4d2015-08-26 13:07:48 -0700226 return new SkIcoCodec(info, codecs.detach());
msarett9bde9182015-03-25 05:27:48 -0700227}
228
229/*
230 * Creates an instance of the decoder
231 * Called only by NewFromStream
232 */
233SkIcoCodec::SkIcoCodec(const SkImageInfo& info,
234 SkTArray<SkAutoTDelete<SkCodec>, true>* codecs)
halcanary96fcdcc2015-08-27 07:41:13 -0700235 : INHERITED(info, nullptr)
msarett9bde9182015-03-25 05:27:48 -0700236 , fEmbeddedCodecs(codecs)
msarettbe8216a2015-12-04 08:00:50 -0800237 , fCurrScanlineCodec(nullptr)
msarett9bde9182015-03-25 05:27:48 -0700238{}
239
240/*
241 * Chooses the best dimensions given the desired scale
242 */
243SkISize SkIcoCodec::onGetScaledDimensions(float desiredScale) const {
244 // We set the dimensions to the largest candidate image by default.
245 // Regardless of the scale request, this is the largest image that we
246 // will decode.
msarett9bde9182015-03-25 05:27:48 -0700247 int origWidth = this->getInfo().width();
248 int origHeight = this->getInfo().height();
249 float desiredSize = desiredScale * origWidth * origHeight;
250 // At least one image will have smaller error than this initial value
251 float minError = ((float) (origWidth * origHeight)) - desiredSize + 1.0f;
252 int32_t minIndex = -1;
253 for (int32_t i = 0; i < fEmbeddedCodecs->count(); i++) {
254 int width = fEmbeddedCodecs->operator[](i)->getInfo().width();
255 int height = fEmbeddedCodecs->operator[](i)->getInfo().height();
256 float error = SkTAbs(((float) (width * height)) - desiredSize);
257 if (error < minError) {
258 minError = error;
259 minIndex = i;
260 }
261 }
262 SkASSERT(minIndex >= 0);
263
264 return fEmbeddedCodecs->operator[](minIndex)->getInfo().dimensions();
265}
266
msarettbe8216a2015-12-04 08:00:50 -0800267int SkIcoCodec::chooseCodec(const SkISize& requestedSize, int startIndex) {
268 SkASSERT(startIndex >= 0);
269
scroggoe7fc14b2015-10-02 13:14:46 -0700270 // FIXME: Cache the index from onGetScaledDimensions?
msarettbe8216a2015-12-04 08:00:50 -0800271 for (int i = startIndex; i < fEmbeddedCodecs->count(); i++) {
272 if (fEmbeddedCodecs->operator[](i)->getInfo().dimensions() == requestedSize) {
273 return i;
scroggoe7fc14b2015-10-02 13:14:46 -0700274 }
275 }
276
msarettbe8216a2015-12-04 08:00:50 -0800277 return -1;
278}
279
280bool SkIcoCodec::onDimensionsSupported(const SkISize& dim) {
281 return this->chooseCodec(dim, 0) >= 0;
scroggoe7fc14b2015-10-02 13:14:46 -0700282}
283
msarett9bde9182015-03-25 05:27:48 -0700284/*
285 * Initiates the Ico decode
286 */
287SkCodec::Result SkIcoCodec::onGetPixels(const SkImageInfo& dstInfo,
288 void* dst, size_t dstRowBytes,
msarette6dd0042015-10-09 11:07:34 -0700289 const Options& opts, SkPMColor* colorTable,
290 int* colorCount, int* rowsDecoded) {
scroggob636b452015-07-22 07:16:20 -0700291 if (opts.fSubset) {
292 // Subsets are not supported.
293 return kUnimplemented;
294 }
scroggocc2feb12015-08-14 08:32:46 -0700295
msarettbe8216a2015-12-04 08:00:50 -0800296 if (!ico_conversion_possible(dstInfo)) {
scroggocc2feb12015-08-14 08:32:46 -0700297 return kInvalidConversion;
298 }
299
msarettbe8216a2015-12-04 08:00:50 -0800300 int index = 0;
301 SkCodec::Result result = kInvalidScale;
302 while (true) {
303 index = this->chooseCodec(dstInfo.dimensions(), index);
304 if (index < 0) {
305 break;
msarett1603e932015-12-04 05:43:09 -0800306 }
msarettbe8216a2015-12-04 08:00:50 -0800307
308 SkCodec* embeddedCodec = fEmbeddedCodecs->operator[](index);
309 SkImageInfo decodeInfo = fix_embedded_alpha(dstInfo, embeddedCodec->getInfo().alphaType());
310 SkASSERT(decodeInfo.colorType() == kN32_SkColorType);
311 result = embeddedCodec->getPixels(decodeInfo, dst, dstRowBytes, &opts, colorTable,
312 colorCount);
313
314 switch (result) {
315 case kSuccess:
316 case kIncompleteInput:
317 // The embedded codec will handle filling incomplete images, so we will indicate
318 // that all of the rows are initialized.
319 *rowsDecoded = decodeInfo.height();
320 return result;
321 default:
322 // Continue trying to find a valid embedded codec on a failed decode.
323 break;
324 }
325
326 index++;
msarett1603e932015-12-04 05:43:09 -0800327 }
328
329 SkCodecPrintf("Error: No matching candidate image in ico.\n");
330 return result;
331}
msarettbe8216a2015-12-04 08:00:50 -0800332
333SkCodec::Result SkIcoCodec::onStartScanlineDecode(const SkImageInfo& dstInfo,
334 const SkCodec::Options& options, SkPMColor colorTable[], int* colorCount) {
335 if (!ico_conversion_possible(dstInfo)) {
336 return kInvalidConversion;
337 }
338
339 int index = 0;
340 SkCodec::Result result = kInvalidScale;
341 while (true) {
342 index = this->chooseCodec(dstInfo.dimensions(), index);
343 if (index < 0) {
344 break;
345 }
346
347 SkCodec* embeddedCodec = fEmbeddedCodecs->operator[](index);
348 SkImageInfo decodeInfo = fix_embedded_alpha(dstInfo, embeddedCodec->getInfo().alphaType());
349 result = embeddedCodec->startScanlineDecode(decodeInfo, &options, colorTable, colorCount);
350 if (kSuccess == result) {
351 fCurrScanlineCodec = embeddedCodec;
352 return result;
353 }
354
355 index++;
356 }
357
358 SkCodecPrintf("Error: No matching candidate image in ico.\n");
359 return result;
360}
361
362int SkIcoCodec::onGetScanlines(void* dst, int count, size_t rowBytes) {
363 SkASSERT(fCurrScanlineCodec);
364 return fCurrScanlineCodec->getScanlines(dst, count, rowBytes);
365}
366
367bool SkIcoCodec::onSkipScanlines(int count) {
368 SkASSERT(fCurrScanlineCodec);
369 return fCurrScanlineCodec->skipScanlines(count);
370}
371
372SkCodec::SkScanlineOrder SkIcoCodec::onGetScanlineOrder() const {
373 // FIXME: This function will possibly return the wrong value if it is called
374 // before startScanlineDecode().
375 return fCurrScanlineCodec ? fCurrScanlineCodec->getScanlineOrder() :
376 INHERITED::onGetScanlineOrder();
377}
378
379SkSampler* SkIcoCodec::getSampler(bool createIfNecessary) {
380 return fCurrScanlineCodec ? fCurrScanlineCodec->getSampler(createIfNecessary) : nullptr;
381}