blob: d1cbed037719f2fee2cbe4b7f4bca739e0667c9f [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
29/*
30 * Assumes IsIco was called and returned true
31 * Creates an Ico decoder
32 * Reads enough of the stream to determine the image format
33 */
34SkCodec* SkIcoCodec::NewFromStream(SkStream* stream) {
msarettd0be5bb2015-03-25 06:29:18 -070035 // Ensure that we do not leak the input stream
Ben Wagner145dbcd2016-11-03 14:40:50 -040036 std::unique_ptr<SkStream> inputStream(stream);
msarettd0be5bb2015-03-25 06:29:18 -070037
msarett9bde9182015-03-25 05:27:48 -070038 // Header size constants
39 static const uint32_t kIcoDirectoryBytes = 6;
40 static const uint32_t kIcoDirEntryBytes = 16;
41
42 // Read the directory header
Ben Wagner7ecc5962016-11-02 17:07:33 -040043 std::unique_ptr<uint8_t[]> dirBuffer(new uint8_t[kIcoDirectoryBytes]);
msarettd0be5bb2015-03-25 06:29:18 -070044 if (inputStream.get()->read(dirBuffer.get(), kIcoDirectoryBytes) !=
msarett9bde9182015-03-25 05:27:48 -070045 kIcoDirectoryBytes) {
scroggo230d4ac2015-03-26 07:15:55 -070046 SkCodecPrintf("Error: unable to read ico directory header.\n");
halcanary96fcdcc2015-08-27 07:41:13 -070047 return nullptr;
msarett9bde9182015-03-25 05:27:48 -070048 }
49
50 // Process the directory header
51 const uint16_t numImages = get_short(dirBuffer.get(), 4);
52 if (0 == numImages) {
scroggo230d4ac2015-03-26 07:15:55 -070053 SkCodecPrintf("Error: No images embedded in ico.\n");
halcanary96fcdcc2015-08-27 07:41:13 -070054 return nullptr;
msarett9bde9182015-03-25 05:27:48 -070055 }
56
msarett9bde9182015-03-25 05:27:48 -070057 // This structure is used to represent the vital information about entries
58 // in the directory header. We will obtain this information for each
59 // directory entry.
60 struct Entry {
61 uint32_t offset;
62 uint32_t size;
63 };
Leon Scroggins III005a9702017-06-29 15:41:32 -040064 SkAutoFree dirEntryBuffer(sk_malloc_flags(sizeof(Entry) * numImages,
65 SK_MALLOC_TEMP));
66 if (!dirEntryBuffer) {
67 SkCodecPrintf("Error: OOM allocating ICO directory for %i images.\n",
68 numImages);
69 return nullptr;
70 }
71 auto* directoryEntries = reinterpret_cast<Entry*>(dirEntryBuffer.get());
msarett9bde9182015-03-25 05:27:48 -070072
73 // Iterate over directory entries
74 for (uint32_t i = 0; i < numImages; i++) {
Leon Scroggins III005a9702017-06-29 15:41:32 -040075 uint8_t entryBuffer[kIcoDirEntryBytes];
76 if (inputStream->read(entryBuffer, kIcoDirEntryBytes) !=
77 kIcoDirEntryBytes) {
78 SkCodecPrintf("Error: Dir entries truncated in ico.\n");
79 return nullptr;
80 }
81
msarett9bde9182015-03-25 05:27:48 -070082 // The directory entry contains information such as width, height,
83 // bits per pixel, and number of colors in the color palette. We will
84 // ignore these fields since they are repeated in the header of the
85 // embedded image. In the event of an inconsistency, we would always
86 // defer to the value in the embedded header anyway.
87
88 // Specifies the size of the embedded image, including the header
Leon Scroggins III005a9702017-06-29 15:41:32 -040089 uint32_t size = get_int(entryBuffer, 8);
msarett9bde9182015-03-25 05:27:48 -070090
91 // Specifies the offset of the embedded image from the start of file.
92 // It does not indicate the start of the pixel data, but rather the
93 // start of the embedded image header.
Leon Scroggins III005a9702017-06-29 15:41:32 -040094 uint32_t offset = get_int(entryBuffer, 12);
msarett9bde9182015-03-25 05:27:48 -070095
96 // Save the vital fields
Leon Scroggins III005a9702017-06-29 15:41:32 -040097 directoryEntries[i].offset = offset;
98 directoryEntries[i].size = size;
msarett9bde9182015-03-25 05:27:48 -070099 }
100
101 // It is "customary" that the embedded images will be stored in order of
102 // increasing offset. However, the specification does not indicate that
103 // they must be stored in this order, so we will not trust that this is the
104 // case. Here we sort the embedded images by increasing offset.
105 struct EntryLessThan {
106 bool operator() (Entry a, Entry b) const {
107 return a.offset < b.offset;
108 }
109 };
110 EntryLessThan lessThan;
Leon Scroggins III005a9702017-06-29 15:41:32 -0400111 SkTQSort(directoryEntries, &directoryEntries[numImages - 1], lessThan);
msarett9bde9182015-03-25 05:27:48 -0700112
113 // Now will construct a candidate codec for each of the embedded images
114 uint32_t bytesRead = kIcoDirectoryBytes + numImages * kIcoDirEntryBytes;
Ben Wagner145dbcd2016-11-03 14:40:50 -0400115 std::unique_ptr<SkTArray<std::unique_ptr<SkCodec>, true>> codecs(
116 new (SkTArray<std::unique_ptr<SkCodec>, true>)(numImages));
msarett9bde9182015-03-25 05:27:48 -0700117 for (uint32_t i = 0; i < numImages; i++) {
Leon Scroggins III005a9702017-06-29 15:41:32 -0400118 uint32_t offset = directoryEntries[i].offset;
119 uint32_t size = directoryEntries[i].size;
msarette6dd0042015-10-09 11:07:34 -0700120
msarett9bde9182015-03-25 05:27:48 -0700121 // Ensure that the offset is valid
122 if (offset < bytesRead) {
scroggo230d4ac2015-03-26 07:15:55 -0700123 SkCodecPrintf("Warning: invalid ico offset.\n");
msarett9bde9182015-03-25 05:27:48 -0700124 continue;
125 }
126
127 // If we cannot skip, assume we have reached the end of the stream and
128 // stop trying to make codecs
msarettd0be5bb2015-03-25 06:29:18 -0700129 if (inputStream.get()->skip(offset - bytesRead) != offset - bytesRead) {
scroggo230d4ac2015-03-26 07:15:55 -0700130 SkCodecPrintf("Warning: could not skip to ico offset.\n");
msarett9bde9182015-03-25 05:27:48 -0700131 break;
132 }
133 bytesRead = offset;
134
135 // Create a new stream for the embedded codec
Leon Scroggins III12a4dc92017-06-05 14:06:57 -0400136 SkAutoFree buffer(sk_malloc_flags(size, 0));
137 if (!buffer) {
138 SkCodecPrintf("Warning: OOM trying to create embedded stream.\n");
139 break;
140 }
141
142 if (inputStream->read(buffer.get(), size) != size) {
scroggo230d4ac2015-03-26 07:15:55 -0700143 SkCodecPrintf("Warning: could not create embedded stream.\n");
msarett9bde9182015-03-25 05:27:48 -0700144 break;
145 }
Leon Scroggins III12a4dc92017-06-05 14:06:57 -0400146
147 sk_sp<SkData> data(SkData::MakeFromMalloc(buffer.release(), size));
Ben Wagner145dbcd2016-11-03 14:40:50 -0400148 std::unique_ptr<SkMemoryStream> embeddedStream(new SkMemoryStream(data));
msarett9bde9182015-03-25 05:27:48 -0700149 bytesRead += size;
150
151 // Check if the embedded codec is bmp or png and create the codec
halcanary96fcdcc2015-08-27 07:41:13 -0700152 SkCodec* codec = nullptr;
scroggodb30be22015-12-08 18:54:13 -0800153 if (SkPngCodec::IsPng((const char*) data->bytes(), data->size())) {
mtklein18300a32016-03-16 13:53:35 -0700154 codec = SkPngCodec::NewFromStream(embeddedStream.release());
msarett9bde9182015-03-25 05:27:48 -0700155 } else {
mtklein18300a32016-03-16 13:53:35 -0700156 codec = SkBmpCodec::NewFromIco(embeddedStream.release());
msarett9bde9182015-03-25 05:27:48 -0700157 }
158
159 // Save a valid codec
halcanary96fcdcc2015-08-27 07:41:13 -0700160 if (nullptr != codec) {
msarett9bde9182015-03-25 05:27:48 -0700161 codecs->push_back().reset(codec);
162 }
163 }
164
165 // Recognize if there are no valid codecs
166 if (0 == codecs->count()) {
scroggo230d4ac2015-03-26 07:15:55 -0700167 SkCodecPrintf("Error: could not find any valid embedded ico codecs.\n");
halcanary96fcdcc2015-08-27 07:41:13 -0700168 return nullptr;
msarett9bde9182015-03-25 05:27:48 -0700169 }
170
171 // Use the largest codec as a "suggestion" for image info
Matt Sarett29121eb2016-10-17 14:32:46 -0400172 size_t maxSize = 0;
173 int maxIndex = 0;
174 for (int i = 0; i < codecs->count(); i++) {
msarett9bde9182015-03-25 05:27:48 -0700175 SkImageInfo info = codecs->operator[](i)->getInfo();
Matt Sarett29121eb2016-10-17 14:32:46 -0400176 size_t size = info.getSafeSize(info.minRowBytes());
177
msarett9bde9182015-03-25 05:27:48 -0700178 if (size > maxSize) {
179 maxSize = size;
180 maxIndex = i;
181 }
182 }
msarettc30c4182016-04-20 11:53:35 -0700183 int width = codecs->operator[](maxIndex)->getInfo().width();
184 int height = codecs->operator[](maxIndex)->getInfo().height();
185 SkEncodedInfo info = codecs->operator[](maxIndex)->getEncodedInfo();
Matt Sarett7f650bd2016-10-30 21:25:34 -0400186 SkColorSpace* colorSpace = codecs->operator[](maxIndex)->getInfo().colorSpace();
msarett9bde9182015-03-25 05:27:48 -0700187
188 // Note that stream is owned by the embedded codec, the ico does not need
189 // direct access to the stream.
Matt Sarett7f650bd2016-10-30 21:25:34 -0400190 return new SkIcoCodec(width, height, info, codecs.release(), sk_ref_sp(colorSpace));
msarett9bde9182015-03-25 05:27:48 -0700191}
192
193/*
194 * Creates an instance of the decoder
195 * Called only by NewFromStream
196 */
msarettc30c4182016-04-20 11:53:35 -0700197SkIcoCodec::SkIcoCodec(int width, int height, const SkEncodedInfo& info,
Ben Wagner145dbcd2016-11-03 14:40:50 -0400198 SkTArray<std::unique_ptr<SkCodec>, true>* codecs,
Matt Sarett7f650bd2016-10-30 21:25:34 -0400199 sk_sp<SkColorSpace> colorSpace)
Leon Scroggins IIIc6e6a5f2017-06-05 15:53:38 -0400200 // The source SkColorSpaceXform::ColorFormat will not be used. The embedded
201 // codec's will be used instead.
202 : INHERITED(width, height, info, SkColorSpaceXform::ColorFormat(), nullptr,
203 std::move(colorSpace))
msarett9bde9182015-03-25 05:27:48 -0700204 , fEmbeddedCodecs(codecs)
msarettbe8216a2015-12-04 08:00:50 -0800205 , fCurrScanlineCodec(nullptr)
scroggo8e6c7ad2016-09-16 08:20:38 -0700206 , fCurrIncrementalCodec(nullptr)
msarett9bde9182015-03-25 05:27:48 -0700207{}
208
209/*
210 * Chooses the best dimensions given the desired scale
211 */
Chris Blume66f23322017-04-19 12:40:46 -0700212SkISize SkIcoCodec::onGetScaledDimensions(float desiredScale) const {
msarett9bde9182015-03-25 05:27:48 -0700213 // We set the dimensions to the largest candidate image by default.
214 // Regardless of the scale request, this is the largest image that we
215 // will decode.
msarett9bde9182015-03-25 05:27:48 -0700216 int origWidth = this->getInfo().width();
217 int origHeight = this->getInfo().height();
218 float desiredSize = desiredScale * origWidth * origHeight;
219 // At least one image will have smaller error than this initial value
220 float minError = ((float) (origWidth * origHeight)) - desiredSize + 1.0f;
221 int32_t minIndex = -1;
222 for (int32_t i = 0; i < fEmbeddedCodecs->count(); i++) {
223 int width = fEmbeddedCodecs->operator[](i)->getInfo().width();
224 int height = fEmbeddedCodecs->operator[](i)->getInfo().height();
225 float error = SkTAbs(((float) (width * height)) - desiredSize);
226 if (error < minError) {
227 minError = error;
228 minIndex = i;
229 }
230 }
231 SkASSERT(minIndex >= 0);
232
233 return fEmbeddedCodecs->operator[](minIndex)->getInfo().dimensions();
234}
235
msarettbe8216a2015-12-04 08:00:50 -0800236int SkIcoCodec::chooseCodec(const SkISize& requestedSize, int startIndex) {
237 SkASSERT(startIndex >= 0);
238
scroggoe7fc14b2015-10-02 13:14:46 -0700239 // FIXME: Cache the index from onGetScaledDimensions?
msarettbe8216a2015-12-04 08:00:50 -0800240 for (int i = startIndex; i < fEmbeddedCodecs->count(); i++) {
241 if (fEmbeddedCodecs->operator[](i)->getInfo().dimensions() == requestedSize) {
242 return i;
scroggoe7fc14b2015-10-02 13:14:46 -0700243 }
244 }
245
msarettbe8216a2015-12-04 08:00:50 -0800246 return -1;
247}
248
249bool SkIcoCodec::onDimensionsSupported(const SkISize& dim) {
250 return this->chooseCodec(dim, 0) >= 0;
scroggoe7fc14b2015-10-02 13:14:46 -0700251}
252
msarett9bde9182015-03-25 05:27:48 -0700253/*
254 * Initiates the Ico decode
255 */
256SkCodec::Result SkIcoCodec::onGetPixels(const SkImageInfo& dstInfo,
257 void* dst, size_t dstRowBytes,
Leon Scroggins571b30f2017-07-11 17:35:31 +0000258 const Options& opts,
259 int* rowsDecoded) {
scroggob636b452015-07-22 07:16:20 -0700260 if (opts.fSubset) {
261 // Subsets are not supported.
262 return kUnimplemented;
263 }
scroggocc2feb12015-08-14 08:32:46 -0700264
msarettbe8216a2015-12-04 08:00:50 -0800265 int index = 0;
266 SkCodec::Result result = kInvalidScale;
267 while (true) {
268 index = this->chooseCodec(dstInfo.dimensions(), index);
269 if (index < 0) {
270 break;
msarett1603e932015-12-04 05:43:09 -0800271 }
msarettbe8216a2015-12-04 08:00:50 -0800272
Ben Wagner145dbcd2016-11-03 14:40:50 -0400273 SkCodec* embeddedCodec = fEmbeddedCodecs->operator[](index).get();
Leon Scroggins571b30f2017-07-11 17:35:31 +0000274 result = embeddedCodec->getPixels(dstInfo, dst, dstRowBytes, &opts);
msarettbe8216a2015-12-04 08:00:50 -0800275 switch (result) {
276 case kSuccess:
277 case kIncompleteInput:
278 // The embedded codec will handle filling incomplete images, so we will indicate
279 // that all of the rows are initialized.
msarettf4004f92016-02-11 10:49:31 -0800280 *rowsDecoded = dstInfo.height();
msarettbe8216a2015-12-04 08:00:50 -0800281 return result;
282 default:
283 // Continue trying to find a valid embedded codec on a failed decode.
284 break;
285 }
286
287 index++;
msarett1603e932015-12-04 05:43:09 -0800288 }
289
290 SkCodecPrintf("Error: No matching candidate image in ico.\n");
291 return result;
292}
msarettbe8216a2015-12-04 08:00:50 -0800293
294SkCodec::Result SkIcoCodec::onStartScanlineDecode(const SkImageInfo& dstInfo,
Leon Scroggins571b30f2017-07-11 17:35:31 +0000295 const SkCodec::Options& options) {
msarettbe8216a2015-12-04 08:00:50 -0800296 int index = 0;
297 SkCodec::Result result = kInvalidScale;
298 while (true) {
299 index = this->chooseCodec(dstInfo.dimensions(), index);
300 if (index < 0) {
301 break;
302 }
303
Ben Wagner145dbcd2016-11-03 14:40:50 -0400304 SkCodec* embeddedCodec = fEmbeddedCodecs->operator[](index).get();
Leon Scroggins571b30f2017-07-11 17:35:31 +0000305 result = embeddedCodec->startScanlineDecode(dstInfo, &options);
msarettbe8216a2015-12-04 08:00:50 -0800306 if (kSuccess == result) {
307 fCurrScanlineCodec = embeddedCodec;
scroggo8e6c7ad2016-09-16 08:20:38 -0700308 fCurrIncrementalCodec = nullptr;
msarettbe8216a2015-12-04 08:00:50 -0800309 return result;
310 }
311
312 index++;
313 }
314
315 SkCodecPrintf("Error: No matching candidate image in ico.\n");
316 return result;
317}
318
319int SkIcoCodec::onGetScanlines(void* dst, int count, size_t rowBytes) {
320 SkASSERT(fCurrScanlineCodec);
321 return fCurrScanlineCodec->getScanlines(dst, count, rowBytes);
322}
323
324bool SkIcoCodec::onSkipScanlines(int count) {
325 SkASSERT(fCurrScanlineCodec);
326 return fCurrScanlineCodec->skipScanlines(count);
327}
328
scroggo8e6c7ad2016-09-16 08:20:38 -0700329SkCodec::Result SkIcoCodec::onStartIncrementalDecode(const SkImageInfo& dstInfo,
Leon Scroggins571b30f2017-07-11 17:35:31 +0000330 void* pixels, size_t rowBytes, const SkCodec::Options& options) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700331 int index = 0;
332 while (true) {
333 index = this->chooseCodec(dstInfo.dimensions(), index);
334 if (index < 0) {
335 break;
336 }
337
Ben Wagner145dbcd2016-11-03 14:40:50 -0400338 SkCodec* embeddedCodec = fEmbeddedCodecs->operator[](index).get();
scroggo8e6c7ad2016-09-16 08:20:38 -0700339 switch (embeddedCodec->startIncrementalDecode(dstInfo,
Leon Scroggins571b30f2017-07-11 17:35:31 +0000340 pixels, rowBytes, &options)) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700341 case kSuccess:
342 fCurrIncrementalCodec = embeddedCodec;
343 fCurrScanlineCodec = nullptr;
344 return kSuccess;
345 case kUnimplemented:
346 // FIXME: embeddedCodec is a BMP. If scanline decoding would work,
347 // return kUnimplemented so that SkSampledCodec will fall through
348 // to use the scanline decoder.
349 // Note that calling startScanlineDecode will require an extra
350 // rewind. The embedded codec has an SkMemoryStream, which is
351 // cheap to rewind, though it will do extra work re-reading the
352 // header.
353 // Also note that we pass nullptr for Options. This is because
354 // Options that are valid for incremental decoding may not be
355 // valid for scanline decoding.
356 // Once BMP supports incremental decoding this workaround can go
357 // away.
Leon Scroggins571b30f2017-07-11 17:35:31 +0000358 if (embeddedCodec->startScanlineDecode(dstInfo) == kSuccess) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700359 return kUnimplemented;
360 }
361 // Move on to the next embedded codec.
362 break;
363 default:
364 break;
365 }
366
367 index++;
368 }
369
370 SkCodecPrintf("Error: No matching candidate image in ico.\n");
371 return kInvalidScale;
372}
373
374SkCodec::Result SkIcoCodec::onIncrementalDecode(int* rowsDecoded) {
375 SkASSERT(fCurrIncrementalCodec);
376 return fCurrIncrementalCodec->incrementalDecode(rowsDecoded);
377}
378
msarettbe8216a2015-12-04 08:00:50 -0800379SkCodec::SkScanlineOrder SkIcoCodec::onGetScanlineOrder() const {
380 // FIXME: This function will possibly return the wrong value if it is called
scroggo8e6c7ad2016-09-16 08:20:38 -0700381 // before startScanlineDecode()/startIncrementalDecode().
382 if (fCurrScanlineCodec) {
383 SkASSERT(!fCurrIncrementalCodec);
384 return fCurrScanlineCodec->getScanlineOrder();
385 }
386
387 if (fCurrIncrementalCodec) {
388 return fCurrIncrementalCodec->getScanlineOrder();
389 }
390
391 return INHERITED::onGetScanlineOrder();
msarettbe8216a2015-12-04 08:00:50 -0800392}
393
394SkSampler* SkIcoCodec::getSampler(bool createIfNecessary) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700395 if (fCurrScanlineCodec) {
396 SkASSERT(!fCurrIncrementalCodec);
397 return fCurrScanlineCodec->getSampler(createIfNecessary);
398 }
399
400 if (fCurrIncrementalCodec) {
401 return fCurrIncrementalCodec->getSampler(createIfNecessary);
402 }
403
404 return nullptr;
msarettbe8216a2015-12-04 08:00:50 -0800405}