blob: b5e399d878810232bac7eee65d0d8d6e8a5de17b [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
57 // Ensure that we can read all of indicated directory entries
Ben Wagner7ecc5962016-11-02 17:07:33 -040058 std::unique_ptr<uint8_t[]> entryBuffer(new uint8_t[numImages * kIcoDirEntryBytes]);
msarettd0be5bb2015-03-25 06:29:18 -070059 if (inputStream.get()->read(entryBuffer.get(), numImages*kIcoDirEntryBytes) !=
msarett9bde9182015-03-25 05:27:48 -070060 numImages*kIcoDirEntryBytes) {
scroggo230d4ac2015-03-26 07:15:55 -070061 SkCodecPrintf("Error: unable to read ico directory entries.\n");
halcanary96fcdcc2015-08-27 07:41:13 -070062 return nullptr;
msarett9bde9182015-03-25 05:27:48 -070063 }
64
65 // This structure is used to represent the vital information about entries
66 // in the directory header. We will obtain this information for each
67 // directory entry.
68 struct Entry {
69 uint32_t offset;
70 uint32_t size;
71 };
Ben Wagner7ecc5962016-11-02 17:07:33 -040072 std::unique_ptr<Entry[]> directoryEntries(new Entry[numImages]);
msarett9bde9182015-03-25 05:27:48 -070073
74 // Iterate over directory entries
75 for (uint32_t i = 0; i < numImages; i++) {
76 // The directory entry contains information such as width, height,
77 // bits per pixel, and number of colors in the color palette. We will
78 // ignore these fields since they are repeated in the header of the
79 // embedded image. In the event of an inconsistency, we would always
80 // defer to the value in the embedded header anyway.
81
82 // Specifies the size of the embedded image, including the header
83 uint32_t size = get_int(entryBuffer.get(), 8 + i*kIcoDirEntryBytes);
84
85 // Specifies the offset of the embedded image from the start of file.
86 // It does not indicate the start of the pixel data, but rather the
87 // start of the embedded image header.
88 uint32_t offset = get_int(entryBuffer.get(), 12 + i*kIcoDirEntryBytes);
89
90 // Save the vital fields
91 directoryEntries.get()[i].offset = offset;
92 directoryEntries.get()[i].size = size;
93 }
94
95 // It is "customary" that the embedded images will be stored in order of
96 // increasing offset. However, the specification does not indicate that
97 // they must be stored in this order, so we will not trust that this is the
98 // case. Here we sort the embedded images by increasing offset.
99 struct EntryLessThan {
100 bool operator() (Entry a, Entry b) const {
101 return a.offset < b.offset;
102 }
103 };
104 EntryLessThan lessThan;
105 SkTQSort(directoryEntries.get(), directoryEntries.get() + numImages - 1,
106 lessThan);
107
108 // Now will construct a candidate codec for each of the embedded images
109 uint32_t bytesRead = kIcoDirectoryBytes + numImages * kIcoDirEntryBytes;
Ben Wagner145dbcd2016-11-03 14:40:50 -0400110 std::unique_ptr<SkTArray<std::unique_ptr<SkCodec>, true>> codecs(
111 new (SkTArray<std::unique_ptr<SkCodec>, true>)(numImages));
msarett9bde9182015-03-25 05:27:48 -0700112 for (uint32_t i = 0; i < numImages; i++) {
113 uint32_t offset = directoryEntries.get()[i].offset;
114 uint32_t size = directoryEntries.get()[i].size;
msarette6dd0042015-10-09 11:07:34 -0700115
msarett9bde9182015-03-25 05:27:48 -0700116 // Ensure that the offset is valid
117 if (offset < bytesRead) {
scroggo230d4ac2015-03-26 07:15:55 -0700118 SkCodecPrintf("Warning: invalid ico offset.\n");
msarett9bde9182015-03-25 05:27:48 -0700119 continue;
120 }
121
122 // If we cannot skip, assume we have reached the end of the stream and
123 // stop trying to make codecs
msarettd0be5bb2015-03-25 06:29:18 -0700124 if (inputStream.get()->skip(offset - bytesRead) != offset - bytesRead) {
scroggo230d4ac2015-03-26 07:15:55 -0700125 SkCodecPrintf("Warning: could not skip to ico offset.\n");
msarett9bde9182015-03-25 05:27:48 -0700126 break;
127 }
128 bytesRead = offset;
129
130 // Create a new stream for the embedded codec
bungeman38d909e2016-08-02 14:40:46 -0700131 sk_sp<SkData> data(SkData::MakeFromStream(inputStream.get(), size));
halcanary96fcdcc2015-08-27 07:41:13 -0700132 if (nullptr == data.get()) {
scroggo230d4ac2015-03-26 07:15:55 -0700133 SkCodecPrintf("Warning: could not create embedded stream.\n");
msarett9bde9182015-03-25 05:27:48 -0700134 break;
135 }
Ben Wagner145dbcd2016-11-03 14:40:50 -0400136 std::unique_ptr<SkMemoryStream> embeddedStream(new SkMemoryStream(data));
msarett9bde9182015-03-25 05:27:48 -0700137 bytesRead += size;
138
139 // Check if the embedded codec is bmp or png and create the codec
halcanary96fcdcc2015-08-27 07:41:13 -0700140 SkCodec* codec = nullptr;
scroggodb30be22015-12-08 18:54:13 -0800141 if (SkPngCodec::IsPng((const char*) data->bytes(), data->size())) {
mtklein18300a32016-03-16 13:53:35 -0700142 codec = SkPngCodec::NewFromStream(embeddedStream.release());
msarett9bde9182015-03-25 05:27:48 -0700143 } else {
mtklein18300a32016-03-16 13:53:35 -0700144 codec = SkBmpCodec::NewFromIco(embeddedStream.release());
msarett9bde9182015-03-25 05:27:48 -0700145 }
146
147 // Save a valid codec
halcanary96fcdcc2015-08-27 07:41:13 -0700148 if (nullptr != codec) {
msarett9bde9182015-03-25 05:27:48 -0700149 codecs->push_back().reset(codec);
150 }
151 }
152
153 // Recognize if there are no valid codecs
154 if (0 == codecs->count()) {
scroggo230d4ac2015-03-26 07:15:55 -0700155 SkCodecPrintf("Error: could not find any valid embedded ico codecs.\n");
halcanary96fcdcc2015-08-27 07:41:13 -0700156 return nullptr;
msarett9bde9182015-03-25 05:27:48 -0700157 }
158
159 // Use the largest codec as a "suggestion" for image info
Matt Sarett29121eb2016-10-17 14:32:46 -0400160 size_t maxSize = 0;
161 int maxIndex = 0;
162 for (int i = 0; i < codecs->count(); i++) {
msarett9bde9182015-03-25 05:27:48 -0700163 SkImageInfo info = codecs->operator[](i)->getInfo();
Matt Sarett29121eb2016-10-17 14:32:46 -0400164 size_t size = info.getSafeSize(info.minRowBytes());
165
msarett9bde9182015-03-25 05:27:48 -0700166 if (size > maxSize) {
167 maxSize = size;
168 maxIndex = i;
169 }
170 }
msarettc30c4182016-04-20 11:53:35 -0700171 int width = codecs->operator[](maxIndex)->getInfo().width();
172 int height = codecs->operator[](maxIndex)->getInfo().height();
173 SkEncodedInfo info = codecs->operator[](maxIndex)->getEncodedInfo();
Matt Sarett7f650bd2016-10-30 21:25:34 -0400174 SkColorSpace* colorSpace = codecs->operator[](maxIndex)->getInfo().colorSpace();
msarett9bde9182015-03-25 05:27:48 -0700175
176 // Note that stream is owned by the embedded codec, the ico does not need
177 // direct access to the stream.
Matt Sarett7f650bd2016-10-30 21:25:34 -0400178 return new SkIcoCodec(width, height, info, codecs.release(), sk_ref_sp(colorSpace));
msarett9bde9182015-03-25 05:27:48 -0700179}
180
181/*
182 * Creates an instance of the decoder
183 * Called only by NewFromStream
184 */
msarettc30c4182016-04-20 11:53:35 -0700185SkIcoCodec::SkIcoCodec(int width, int height, const SkEncodedInfo& info,
Ben Wagner145dbcd2016-11-03 14:40:50 -0400186 SkTArray<std::unique_ptr<SkCodec>, true>* codecs,
Matt Sarett7f650bd2016-10-30 21:25:34 -0400187 sk_sp<SkColorSpace> colorSpace)
188 : INHERITED(width, height, info, nullptr, std::move(colorSpace))
msarett9bde9182015-03-25 05:27:48 -0700189 , fEmbeddedCodecs(codecs)
msarettbe8216a2015-12-04 08:00:50 -0800190 , fCurrScanlineCodec(nullptr)
scroggo8e6c7ad2016-09-16 08:20:38 -0700191 , fCurrIncrementalCodec(nullptr)
msarett9bde9182015-03-25 05:27:48 -0700192{}
193
194/*
195 * Chooses the best dimensions given the desired scale
196 */
197SkISize SkIcoCodec::onGetScaledDimensions(float desiredScale) const {
198 // We set the dimensions to the largest candidate image by default.
199 // Regardless of the scale request, this is the largest image that we
200 // will decode.
msarett9bde9182015-03-25 05:27:48 -0700201 int origWidth = this->getInfo().width();
202 int origHeight = this->getInfo().height();
203 float desiredSize = desiredScale * origWidth * origHeight;
204 // At least one image will have smaller error than this initial value
205 float minError = ((float) (origWidth * origHeight)) - desiredSize + 1.0f;
206 int32_t minIndex = -1;
207 for (int32_t i = 0; i < fEmbeddedCodecs->count(); i++) {
208 int width = fEmbeddedCodecs->operator[](i)->getInfo().width();
209 int height = fEmbeddedCodecs->operator[](i)->getInfo().height();
210 float error = SkTAbs(((float) (width * height)) - desiredSize);
211 if (error < minError) {
212 minError = error;
213 minIndex = i;
214 }
215 }
216 SkASSERT(minIndex >= 0);
217
218 return fEmbeddedCodecs->operator[](minIndex)->getInfo().dimensions();
219}
220
msarettbe8216a2015-12-04 08:00:50 -0800221int SkIcoCodec::chooseCodec(const SkISize& requestedSize, int startIndex) {
222 SkASSERT(startIndex >= 0);
223
scroggoe7fc14b2015-10-02 13:14:46 -0700224 // FIXME: Cache the index from onGetScaledDimensions?
msarettbe8216a2015-12-04 08:00:50 -0800225 for (int i = startIndex; i < fEmbeddedCodecs->count(); i++) {
226 if (fEmbeddedCodecs->operator[](i)->getInfo().dimensions() == requestedSize) {
227 return i;
scroggoe7fc14b2015-10-02 13:14:46 -0700228 }
229 }
230
msarettbe8216a2015-12-04 08:00:50 -0800231 return -1;
232}
233
234bool SkIcoCodec::onDimensionsSupported(const SkISize& dim) {
235 return this->chooseCodec(dim, 0) >= 0;
scroggoe7fc14b2015-10-02 13:14:46 -0700236}
237
msarett9bde9182015-03-25 05:27:48 -0700238/*
239 * Initiates the Ico decode
240 */
241SkCodec::Result SkIcoCodec::onGetPixels(const SkImageInfo& dstInfo,
242 void* dst, size_t dstRowBytes,
msarette6dd0042015-10-09 11:07:34 -0700243 const Options& opts, SkPMColor* colorTable,
244 int* colorCount, int* rowsDecoded) {
scroggob636b452015-07-22 07:16:20 -0700245 if (opts.fSubset) {
246 // Subsets are not supported.
247 return kUnimplemented;
248 }
scroggocc2feb12015-08-14 08:32:46 -0700249
msarettbe8216a2015-12-04 08:00:50 -0800250 int index = 0;
251 SkCodec::Result result = kInvalidScale;
252 while (true) {
253 index = this->chooseCodec(dstInfo.dimensions(), index);
254 if (index < 0) {
255 break;
msarett1603e932015-12-04 05:43:09 -0800256 }
msarettbe8216a2015-12-04 08:00:50 -0800257
Ben Wagner145dbcd2016-11-03 14:40:50 -0400258 SkCodec* embeddedCodec = fEmbeddedCodecs->operator[](index).get();
259 result = embeddedCodec->getPixels(dstInfo, dst, dstRowBytes, &opts, colorTable, colorCount);
msarettbe8216a2015-12-04 08:00:50 -0800260 switch (result) {
261 case kSuccess:
262 case kIncompleteInput:
263 // The embedded codec will handle filling incomplete images, so we will indicate
264 // that all of the rows are initialized.
msarettf4004f92016-02-11 10:49:31 -0800265 *rowsDecoded = dstInfo.height();
msarettbe8216a2015-12-04 08:00:50 -0800266 return result;
267 default:
268 // Continue trying to find a valid embedded codec on a failed decode.
269 break;
270 }
271
272 index++;
msarett1603e932015-12-04 05:43:09 -0800273 }
274
275 SkCodecPrintf("Error: No matching candidate image in ico.\n");
276 return result;
277}
msarettbe8216a2015-12-04 08:00:50 -0800278
279SkCodec::Result SkIcoCodec::onStartScanlineDecode(const SkImageInfo& dstInfo,
280 const SkCodec::Options& options, SkPMColor colorTable[], int* colorCount) {
msarettbe8216a2015-12-04 08:00:50 -0800281 int index = 0;
282 SkCodec::Result result = kInvalidScale;
283 while (true) {
284 index = this->chooseCodec(dstInfo.dimensions(), index);
285 if (index < 0) {
286 break;
287 }
288
Ben Wagner145dbcd2016-11-03 14:40:50 -0400289 SkCodec* embeddedCodec = fEmbeddedCodecs->operator[](index).get();
msarettf4004f92016-02-11 10:49:31 -0800290 result = embeddedCodec->startScanlineDecode(dstInfo, &options, colorTable, colorCount);
msarettbe8216a2015-12-04 08:00:50 -0800291 if (kSuccess == result) {
292 fCurrScanlineCodec = embeddedCodec;
scroggo8e6c7ad2016-09-16 08:20:38 -0700293 fCurrIncrementalCodec = nullptr;
msarettbe8216a2015-12-04 08:00:50 -0800294 return result;
295 }
296
297 index++;
298 }
299
300 SkCodecPrintf("Error: No matching candidate image in ico.\n");
301 return result;
302}
303
304int SkIcoCodec::onGetScanlines(void* dst, int count, size_t rowBytes) {
305 SkASSERT(fCurrScanlineCodec);
306 return fCurrScanlineCodec->getScanlines(dst, count, rowBytes);
307}
308
309bool SkIcoCodec::onSkipScanlines(int count) {
310 SkASSERT(fCurrScanlineCodec);
311 return fCurrScanlineCodec->skipScanlines(count);
312}
313
scroggo8e6c7ad2016-09-16 08:20:38 -0700314SkCodec::Result SkIcoCodec::onStartIncrementalDecode(const SkImageInfo& dstInfo,
315 void* pixels, size_t rowBytes, const SkCodec::Options& options,
316 SkPMColor* colorTable, int* colorCount) {
317 int index = 0;
318 while (true) {
319 index = this->chooseCodec(dstInfo.dimensions(), index);
320 if (index < 0) {
321 break;
322 }
323
Ben Wagner145dbcd2016-11-03 14:40:50 -0400324 SkCodec* embeddedCodec = fEmbeddedCodecs->operator[](index).get();
scroggo8e6c7ad2016-09-16 08:20:38 -0700325 switch (embeddedCodec->startIncrementalDecode(dstInfo,
326 pixels, rowBytes, &options, colorTable, colorCount)) {
327 case kSuccess:
328 fCurrIncrementalCodec = embeddedCodec;
329 fCurrScanlineCodec = nullptr;
330 return kSuccess;
331 case kUnimplemented:
332 // FIXME: embeddedCodec is a BMP. If scanline decoding would work,
333 // return kUnimplemented so that SkSampledCodec will fall through
334 // to use the scanline decoder.
335 // Note that calling startScanlineDecode will require an extra
336 // rewind. The embedded codec has an SkMemoryStream, which is
337 // cheap to rewind, though it will do extra work re-reading the
338 // header.
339 // Also note that we pass nullptr for Options. This is because
340 // Options that are valid for incremental decoding may not be
341 // valid for scanline decoding.
342 // Once BMP supports incremental decoding this workaround can go
343 // away.
344 if (embeddedCodec->startScanlineDecode(dstInfo, nullptr,
345 colorTable, colorCount) == kSuccess) {
346 return kUnimplemented;
347 }
348 // Move on to the next embedded codec.
349 break;
350 default:
351 break;
352 }
353
354 index++;
355 }
356
357 SkCodecPrintf("Error: No matching candidate image in ico.\n");
358 return kInvalidScale;
359}
360
361SkCodec::Result SkIcoCodec::onIncrementalDecode(int* rowsDecoded) {
362 SkASSERT(fCurrIncrementalCodec);
363 return fCurrIncrementalCodec->incrementalDecode(rowsDecoded);
364}
365
msarettbe8216a2015-12-04 08:00:50 -0800366SkCodec::SkScanlineOrder SkIcoCodec::onGetScanlineOrder() const {
367 // FIXME: This function will possibly return the wrong value if it is called
scroggo8e6c7ad2016-09-16 08:20:38 -0700368 // before startScanlineDecode()/startIncrementalDecode().
369 if (fCurrScanlineCodec) {
370 SkASSERT(!fCurrIncrementalCodec);
371 return fCurrScanlineCodec->getScanlineOrder();
372 }
373
374 if (fCurrIncrementalCodec) {
375 return fCurrIncrementalCodec->getScanlineOrder();
376 }
377
378 return INHERITED::onGetScanlineOrder();
msarettbe8216a2015-12-04 08:00:50 -0800379}
380
381SkSampler* SkIcoCodec::getSampler(bool createIfNecessary) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700382 if (fCurrScanlineCodec) {
383 SkASSERT(!fCurrIncrementalCodec);
384 return fCurrScanlineCodec->getSampler(createIfNecessary);
385 }
386
387 if (fCurrIncrementalCodec) {
388 return fCurrIncrementalCodec->getSampler(createIfNecessary);
389 }
390
391 return nullptr;
msarettbe8216a2015-12-04 08:00:50 -0800392}