blob: 2e61bfe45d93b47aab811906e46407014d35396c [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 "SkCodecPriv.h"
10#include "SkColorPriv.h"
11#include "SkData.h"
msarett1a464672016-01-07 13:17:19 -080012#include "SkIcoCodec.h"
msarettbe1d5552016-01-21 09:05:23 -080013#include "SkPngCodec.h"
msarett9bde9182015-03-25 05:27:48 -070014#include "SkStream.h"
15#include "SkTDArray.h"
16#include "SkTSort.h"
17
18/*
19 * Checks the start of the stream to see if the image is an Ico or Cur
20 */
scroggodb30be22015-12-08 18:54:13 -080021bool SkIcoCodec::IsIco(const void* buffer, size_t bytesRead) {
msarett9bde9182015-03-25 05:27:48 -070022 const char icoSig[] = { '\x00', '\x00', '\x01', '\x00' };
23 const char curSig[] = { '\x00', '\x00', '\x02', '\x00' };
scroggodb30be22015-12-08 18:54:13 -080024 return bytesRead >= sizeof(icoSig) &&
msarett9bde9182015-03-25 05:27:48 -070025 (!memcmp(buffer, icoSig, sizeof(icoSig)) ||
26 !memcmp(buffer, curSig, sizeof(curSig)));
27}
28
Leon Scroggins III588fb042017-07-14 16:32:31 -040029SkCodec* SkIcoCodec::NewFromStream(SkStream* stream, Result* result) {
msarettd0be5bb2015-03-25 06:29:18 -070030 // Ensure that we do not leak the input stream
Ben Wagner145dbcd2016-11-03 14:40:50 -040031 std::unique_ptr<SkStream> inputStream(stream);
msarettd0be5bb2015-03-25 06:29:18 -070032
msarett9bde9182015-03-25 05:27:48 -070033 // Header size constants
34 static const uint32_t kIcoDirectoryBytes = 6;
35 static const uint32_t kIcoDirEntryBytes = 16;
36
37 // Read the directory header
Ben Wagner7ecc5962016-11-02 17:07:33 -040038 std::unique_ptr<uint8_t[]> dirBuffer(new uint8_t[kIcoDirectoryBytes]);
msarettd0be5bb2015-03-25 06:29:18 -070039 if (inputStream.get()->read(dirBuffer.get(), kIcoDirectoryBytes) !=
msarett9bde9182015-03-25 05:27:48 -070040 kIcoDirectoryBytes) {
scroggo230d4ac2015-03-26 07:15:55 -070041 SkCodecPrintf("Error: unable to read ico directory header.\n");
Leon Scroggins III588fb042017-07-14 16:32:31 -040042 *result = kIncompleteInput;
halcanary96fcdcc2015-08-27 07:41:13 -070043 return nullptr;
msarett9bde9182015-03-25 05:27:48 -070044 }
45
46 // Process the directory header
47 const uint16_t numImages = get_short(dirBuffer.get(), 4);
48 if (0 == numImages) {
scroggo230d4ac2015-03-26 07:15:55 -070049 SkCodecPrintf("Error: No images embedded in ico.\n");
Leon Scroggins III588fb042017-07-14 16:32:31 -040050 *result = kInvalidInput;
halcanary96fcdcc2015-08-27 07:41:13 -070051 return nullptr;
msarett9bde9182015-03-25 05:27:48 -070052 }
53
msarett9bde9182015-03-25 05:27:48 -070054 // This structure is used to represent the vital information about entries
55 // in the directory header. We will obtain this information for each
56 // directory entry.
57 struct Entry {
58 uint32_t offset;
59 uint32_t size;
60 };
Leon Scroggins III005a9702017-06-29 15:41:32 -040061 SkAutoFree dirEntryBuffer(sk_malloc_flags(sizeof(Entry) * numImages,
62 SK_MALLOC_TEMP));
63 if (!dirEntryBuffer) {
64 SkCodecPrintf("Error: OOM allocating ICO directory for %i images.\n",
65 numImages);
Leon Scroggins III588fb042017-07-14 16:32:31 -040066 *result = kInternalError;
Leon Scroggins III005a9702017-06-29 15:41:32 -040067 return nullptr;
68 }
69 auto* directoryEntries = reinterpret_cast<Entry*>(dirEntryBuffer.get());
msarett9bde9182015-03-25 05:27:48 -070070
71 // Iterate over directory entries
72 for (uint32_t i = 0; i < numImages; i++) {
Leon Scroggins III005a9702017-06-29 15:41:32 -040073 uint8_t entryBuffer[kIcoDirEntryBytes];
74 if (inputStream->read(entryBuffer, kIcoDirEntryBytes) !=
75 kIcoDirEntryBytes) {
76 SkCodecPrintf("Error: Dir entries truncated in ico.\n");
Leon Scroggins III588fb042017-07-14 16:32:31 -040077 *result = kIncompleteInput;
Leon Scroggins III005a9702017-06-29 15:41:32 -040078 return nullptr;
79 }
80
msarett9bde9182015-03-25 05:27:48 -070081 // The directory entry contains information such as width, height,
82 // bits per pixel, and number of colors in the color palette. We will
83 // ignore these fields since they are repeated in the header of the
84 // embedded image. In the event of an inconsistency, we would always
85 // defer to the value in the embedded header anyway.
86
87 // Specifies the size of the embedded image, including the header
Leon Scroggins III005a9702017-06-29 15:41:32 -040088 uint32_t size = get_int(entryBuffer, 8);
msarett9bde9182015-03-25 05:27:48 -070089
90 // Specifies the offset of the embedded image from the start of file.
91 // It does not indicate the start of the pixel data, but rather the
92 // start of the embedded image header.
Leon Scroggins III005a9702017-06-29 15:41:32 -040093 uint32_t offset = get_int(entryBuffer, 12);
msarett9bde9182015-03-25 05:27:48 -070094
95 // Save the vital fields
Leon Scroggins III005a9702017-06-29 15:41:32 -040096 directoryEntries[i].offset = offset;
97 directoryEntries[i].size = size;
msarett9bde9182015-03-25 05:27:48 -070098 }
99
Leon Scroggins III588fb042017-07-14 16:32:31 -0400100 // Default Result, if no valid embedded codecs are found.
101 *result = kInvalidInput;
102
msarett9bde9182015-03-25 05:27:48 -0700103 // It is "customary" that the embedded images will be stored in order of
104 // increasing offset. However, the specification does not indicate that
105 // they must be stored in this order, so we will not trust that this is the
106 // case. Here we sort the embedded images by increasing offset.
107 struct EntryLessThan {
108 bool operator() (Entry a, Entry b) const {
109 return a.offset < b.offset;
110 }
111 };
112 EntryLessThan lessThan;
Leon Scroggins III005a9702017-06-29 15:41:32 -0400113 SkTQSort(directoryEntries, &directoryEntries[numImages - 1], lessThan);
msarett9bde9182015-03-25 05:27:48 -0700114
115 // Now will construct a candidate codec for each of the embedded images
116 uint32_t bytesRead = kIcoDirectoryBytes + numImages * kIcoDirEntryBytes;
Ben Wagner145dbcd2016-11-03 14:40:50 -0400117 std::unique_ptr<SkTArray<std::unique_ptr<SkCodec>, true>> codecs(
118 new (SkTArray<std::unique_ptr<SkCodec>, true>)(numImages));
msarett9bde9182015-03-25 05:27:48 -0700119 for (uint32_t i = 0; i < numImages; i++) {
Leon Scroggins III005a9702017-06-29 15:41:32 -0400120 uint32_t offset = directoryEntries[i].offset;
121 uint32_t size = directoryEntries[i].size;
msarette6dd0042015-10-09 11:07:34 -0700122
msarett9bde9182015-03-25 05:27:48 -0700123 // Ensure that the offset is valid
124 if (offset < bytesRead) {
scroggo230d4ac2015-03-26 07:15:55 -0700125 SkCodecPrintf("Warning: invalid ico offset.\n");
msarett9bde9182015-03-25 05:27:48 -0700126 continue;
127 }
128
129 // If we cannot skip, assume we have reached the end of the stream and
130 // stop trying to make codecs
msarettd0be5bb2015-03-25 06:29:18 -0700131 if (inputStream.get()->skip(offset - bytesRead) != offset - bytesRead) {
scroggo230d4ac2015-03-26 07:15:55 -0700132 SkCodecPrintf("Warning: could not skip to ico offset.\n");
msarett9bde9182015-03-25 05:27:48 -0700133 break;
134 }
135 bytesRead = offset;
136
137 // Create a new stream for the embedded codec
Leon Scroggins III12a4dc92017-06-05 14:06:57 -0400138 SkAutoFree buffer(sk_malloc_flags(size, 0));
139 if (!buffer) {
140 SkCodecPrintf("Warning: OOM trying to create embedded stream.\n");
141 break;
142 }
143
144 if (inputStream->read(buffer.get(), size) != size) {
scroggo230d4ac2015-03-26 07:15:55 -0700145 SkCodecPrintf("Warning: could not create embedded stream.\n");
Leon Scroggins III588fb042017-07-14 16:32:31 -0400146 *result = kIncompleteInput;
msarett9bde9182015-03-25 05:27:48 -0700147 break;
148 }
Leon Scroggins III12a4dc92017-06-05 14:06:57 -0400149
150 sk_sp<SkData> data(SkData::MakeFromMalloc(buffer.release(), size));
Ben Wagner145dbcd2016-11-03 14:40:50 -0400151 std::unique_ptr<SkMemoryStream> embeddedStream(new SkMemoryStream(data));
msarett9bde9182015-03-25 05:27:48 -0700152 bytesRead += size;
153
154 // Check if the embedded codec is bmp or png and create the codec
halcanary96fcdcc2015-08-27 07:41:13 -0700155 SkCodec* codec = nullptr;
Leon Scroggins III588fb042017-07-14 16:32:31 -0400156 Result dummyResult;
scroggodb30be22015-12-08 18:54:13 -0800157 if (SkPngCodec::IsPng((const char*) data->bytes(), data->size())) {
Leon Scroggins III588fb042017-07-14 16:32:31 -0400158 codec = SkPngCodec::NewFromStream(embeddedStream.release(), &dummyResult);
msarett9bde9182015-03-25 05:27:48 -0700159 } else {
Leon Scroggins III588fb042017-07-14 16:32:31 -0400160 codec = SkBmpCodec::NewFromIco(embeddedStream.release(), &dummyResult);
msarett9bde9182015-03-25 05:27:48 -0700161 }
162
163 // Save a valid codec
halcanary96fcdcc2015-08-27 07:41:13 -0700164 if (nullptr != codec) {
msarett9bde9182015-03-25 05:27:48 -0700165 codecs->push_back().reset(codec);
166 }
167 }
168
169 // Recognize if there are no valid codecs
170 if (0 == codecs->count()) {
scroggo230d4ac2015-03-26 07:15:55 -0700171 SkCodecPrintf("Error: could not find any valid embedded ico codecs.\n");
halcanary96fcdcc2015-08-27 07:41:13 -0700172 return nullptr;
msarett9bde9182015-03-25 05:27:48 -0700173 }
174
175 // Use the largest codec as a "suggestion" for image info
Matt Sarett29121eb2016-10-17 14:32:46 -0400176 size_t maxSize = 0;
177 int maxIndex = 0;
178 for (int i = 0; i < codecs->count(); i++) {
msarett9bde9182015-03-25 05:27:48 -0700179 SkImageInfo info = codecs->operator[](i)->getInfo();
Matt Sarett29121eb2016-10-17 14:32:46 -0400180 size_t size = info.getSafeSize(info.minRowBytes());
181
msarett9bde9182015-03-25 05:27:48 -0700182 if (size > maxSize) {
183 maxSize = size;
184 maxIndex = i;
185 }
186 }
msarettc30c4182016-04-20 11:53:35 -0700187 int width = codecs->operator[](maxIndex)->getInfo().width();
188 int height = codecs->operator[](maxIndex)->getInfo().height();
189 SkEncodedInfo info = codecs->operator[](maxIndex)->getEncodedInfo();
Matt Sarett7f650bd2016-10-30 21:25:34 -0400190 SkColorSpace* colorSpace = codecs->operator[](maxIndex)->getInfo().colorSpace();
msarett9bde9182015-03-25 05:27:48 -0700191
Leon Scroggins III588fb042017-07-14 16:32:31 -0400192 *result = kSuccess;
193 // The original stream is no longer needed, because the embedded codecs own their
194 // own streams.
Matt Sarett7f650bd2016-10-30 21:25:34 -0400195 return new SkIcoCodec(width, height, info, codecs.release(), sk_ref_sp(colorSpace));
msarett9bde9182015-03-25 05:27:48 -0700196}
197
198/*
199 * Creates an instance of the decoder
200 * Called only by NewFromStream
201 */
msarettc30c4182016-04-20 11:53:35 -0700202SkIcoCodec::SkIcoCodec(int width, int height, const SkEncodedInfo& info,
Ben Wagner145dbcd2016-11-03 14:40:50 -0400203 SkTArray<std::unique_ptr<SkCodec>, true>* codecs,
Matt Sarett7f650bd2016-10-30 21:25:34 -0400204 sk_sp<SkColorSpace> colorSpace)
Leon Scroggins IIIc6e6a5f2017-06-05 15:53:38 -0400205 // The source SkColorSpaceXform::ColorFormat will not be used. The embedded
206 // codec's will be used instead.
207 : INHERITED(width, height, info, SkColorSpaceXform::ColorFormat(), nullptr,
208 std::move(colorSpace))
msarett9bde9182015-03-25 05:27:48 -0700209 , fEmbeddedCodecs(codecs)
msarettbe8216a2015-12-04 08:00:50 -0800210 , fCurrScanlineCodec(nullptr)
scroggo8e6c7ad2016-09-16 08:20:38 -0700211 , fCurrIncrementalCodec(nullptr)
msarett9bde9182015-03-25 05:27:48 -0700212{}
213
214/*
215 * Chooses the best dimensions given the desired scale
216 */
Chris Blume66f23322017-04-19 12:40:46 -0700217SkISize SkIcoCodec::onGetScaledDimensions(float desiredScale) const {
msarett9bde9182015-03-25 05:27:48 -0700218 // We set the dimensions to the largest candidate image by default.
219 // Regardless of the scale request, this is the largest image that we
220 // will decode.
msarett9bde9182015-03-25 05:27:48 -0700221 int origWidth = this->getInfo().width();
222 int origHeight = this->getInfo().height();
223 float desiredSize = desiredScale * origWidth * origHeight;
224 // At least one image will have smaller error than this initial value
225 float minError = ((float) (origWidth * origHeight)) - desiredSize + 1.0f;
226 int32_t minIndex = -1;
227 for (int32_t i = 0; i < fEmbeddedCodecs->count(); i++) {
228 int width = fEmbeddedCodecs->operator[](i)->getInfo().width();
229 int height = fEmbeddedCodecs->operator[](i)->getInfo().height();
230 float error = SkTAbs(((float) (width * height)) - desiredSize);
231 if (error < minError) {
232 minError = error;
233 minIndex = i;
234 }
235 }
236 SkASSERT(minIndex >= 0);
237
238 return fEmbeddedCodecs->operator[](minIndex)->getInfo().dimensions();
239}
240
msarettbe8216a2015-12-04 08:00:50 -0800241int SkIcoCodec::chooseCodec(const SkISize& requestedSize, int startIndex) {
242 SkASSERT(startIndex >= 0);
243
scroggoe7fc14b2015-10-02 13:14:46 -0700244 // FIXME: Cache the index from onGetScaledDimensions?
msarettbe8216a2015-12-04 08:00:50 -0800245 for (int i = startIndex; i < fEmbeddedCodecs->count(); i++) {
246 if (fEmbeddedCodecs->operator[](i)->getInfo().dimensions() == requestedSize) {
247 return i;
scroggoe7fc14b2015-10-02 13:14:46 -0700248 }
249 }
250
msarettbe8216a2015-12-04 08:00:50 -0800251 return -1;
252}
253
254bool SkIcoCodec::onDimensionsSupported(const SkISize& dim) {
255 return this->chooseCodec(dim, 0) >= 0;
scroggoe7fc14b2015-10-02 13:14:46 -0700256}
257
msarett9bde9182015-03-25 05:27:48 -0700258/*
259 * Initiates the Ico decode
260 */
261SkCodec::Result SkIcoCodec::onGetPixels(const SkImageInfo& dstInfo,
262 void* dst, size_t dstRowBytes,
Leon Scroggins571b30f2017-07-11 17:35:31 +0000263 const Options& opts,
264 int* rowsDecoded) {
scroggob636b452015-07-22 07:16:20 -0700265 if (opts.fSubset) {
266 // Subsets are not supported.
267 return kUnimplemented;
268 }
scroggocc2feb12015-08-14 08:32:46 -0700269
msarettbe8216a2015-12-04 08:00:50 -0800270 int index = 0;
271 SkCodec::Result result = kInvalidScale;
272 while (true) {
273 index = this->chooseCodec(dstInfo.dimensions(), index);
274 if (index < 0) {
275 break;
msarett1603e932015-12-04 05:43:09 -0800276 }
msarettbe8216a2015-12-04 08:00:50 -0800277
Ben Wagner145dbcd2016-11-03 14:40:50 -0400278 SkCodec* embeddedCodec = fEmbeddedCodecs->operator[](index).get();
Leon Scroggins571b30f2017-07-11 17:35:31 +0000279 result = embeddedCodec->getPixels(dstInfo, dst, dstRowBytes, &opts);
msarettbe8216a2015-12-04 08:00:50 -0800280 switch (result) {
281 case kSuccess:
282 case kIncompleteInput:
283 // The embedded codec will handle filling incomplete images, so we will indicate
284 // that all of the rows are initialized.
msarettf4004f92016-02-11 10:49:31 -0800285 *rowsDecoded = dstInfo.height();
msarettbe8216a2015-12-04 08:00:50 -0800286 return result;
287 default:
288 // Continue trying to find a valid embedded codec on a failed decode.
289 break;
290 }
291
292 index++;
msarett1603e932015-12-04 05:43:09 -0800293 }
294
295 SkCodecPrintf("Error: No matching candidate image in ico.\n");
296 return result;
297}
msarettbe8216a2015-12-04 08:00:50 -0800298
299SkCodec::Result SkIcoCodec::onStartScanlineDecode(const SkImageInfo& dstInfo,
Leon Scroggins571b30f2017-07-11 17:35:31 +0000300 const SkCodec::Options& options) {
msarettbe8216a2015-12-04 08:00:50 -0800301 int index = 0;
302 SkCodec::Result result = kInvalidScale;
303 while (true) {
304 index = this->chooseCodec(dstInfo.dimensions(), index);
305 if (index < 0) {
306 break;
307 }
308
Ben Wagner145dbcd2016-11-03 14:40:50 -0400309 SkCodec* embeddedCodec = fEmbeddedCodecs->operator[](index).get();
Leon Scroggins571b30f2017-07-11 17:35:31 +0000310 result = embeddedCodec->startScanlineDecode(dstInfo, &options);
msarettbe8216a2015-12-04 08:00:50 -0800311 if (kSuccess == result) {
312 fCurrScanlineCodec = embeddedCodec;
scroggo8e6c7ad2016-09-16 08:20:38 -0700313 fCurrIncrementalCodec = nullptr;
msarettbe8216a2015-12-04 08:00:50 -0800314 return result;
315 }
316
317 index++;
318 }
319
320 SkCodecPrintf("Error: No matching candidate image in ico.\n");
321 return result;
322}
323
324int SkIcoCodec::onGetScanlines(void* dst, int count, size_t rowBytes) {
325 SkASSERT(fCurrScanlineCodec);
326 return fCurrScanlineCodec->getScanlines(dst, count, rowBytes);
327}
328
329bool SkIcoCodec::onSkipScanlines(int count) {
330 SkASSERT(fCurrScanlineCodec);
331 return fCurrScanlineCodec->skipScanlines(count);
332}
333
scroggo8e6c7ad2016-09-16 08:20:38 -0700334SkCodec::Result SkIcoCodec::onStartIncrementalDecode(const SkImageInfo& dstInfo,
Leon Scroggins571b30f2017-07-11 17:35:31 +0000335 void* pixels, size_t rowBytes, const SkCodec::Options& options) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700336 int index = 0;
337 while (true) {
338 index = this->chooseCodec(dstInfo.dimensions(), index);
339 if (index < 0) {
340 break;
341 }
342
Ben Wagner145dbcd2016-11-03 14:40:50 -0400343 SkCodec* embeddedCodec = fEmbeddedCodecs->operator[](index).get();
scroggo8e6c7ad2016-09-16 08:20:38 -0700344 switch (embeddedCodec->startIncrementalDecode(dstInfo,
Leon Scroggins571b30f2017-07-11 17:35:31 +0000345 pixels, rowBytes, &options)) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700346 case kSuccess:
347 fCurrIncrementalCodec = embeddedCodec;
348 fCurrScanlineCodec = nullptr;
349 return kSuccess;
350 case kUnimplemented:
351 // FIXME: embeddedCodec is a BMP. If scanline decoding would work,
352 // return kUnimplemented so that SkSampledCodec will fall through
353 // to use the scanline decoder.
354 // Note that calling startScanlineDecode will require an extra
355 // rewind. The embedded codec has an SkMemoryStream, which is
356 // cheap to rewind, though it will do extra work re-reading the
357 // header.
358 // Also note that we pass nullptr for Options. This is because
359 // Options that are valid for incremental decoding may not be
360 // valid for scanline decoding.
361 // Once BMP supports incremental decoding this workaround can go
362 // away.
Leon Scroggins571b30f2017-07-11 17:35:31 +0000363 if (embeddedCodec->startScanlineDecode(dstInfo) == kSuccess) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700364 return kUnimplemented;
365 }
366 // Move on to the next embedded codec.
367 break;
368 default:
369 break;
370 }
371
372 index++;
373 }
374
375 SkCodecPrintf("Error: No matching candidate image in ico.\n");
376 return kInvalidScale;
377}
378
379SkCodec::Result SkIcoCodec::onIncrementalDecode(int* rowsDecoded) {
380 SkASSERT(fCurrIncrementalCodec);
381 return fCurrIncrementalCodec->incrementalDecode(rowsDecoded);
382}
383
msarettbe8216a2015-12-04 08:00:50 -0800384SkCodec::SkScanlineOrder SkIcoCodec::onGetScanlineOrder() const {
385 // FIXME: This function will possibly return the wrong value if it is called
scroggo8e6c7ad2016-09-16 08:20:38 -0700386 // before startScanlineDecode()/startIncrementalDecode().
387 if (fCurrScanlineCodec) {
388 SkASSERT(!fCurrIncrementalCodec);
389 return fCurrScanlineCodec->getScanlineOrder();
390 }
391
392 if (fCurrIncrementalCodec) {
393 return fCurrIncrementalCodec->getScanlineOrder();
394 }
395
396 return INHERITED::onGetScanlineOrder();
msarettbe8216a2015-12-04 08:00:50 -0800397}
398
399SkSampler* SkIcoCodec::getSampler(bool createIfNecessary) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700400 if (fCurrScanlineCodec) {
401 SkASSERT(!fCurrIncrementalCodec);
402 return fCurrScanlineCodec->getSampler(createIfNecessary);
403 }
404
405 if (fCurrIncrementalCodec) {
406 return fCurrIncrementalCodec->getSampler(createIfNecessary);
407 }
408
409 return nullptr;
msarettbe8216a2015-12-04 08:00:50 -0800410}