blob: e8e6531a06c7c29db550643443653a7c47330589 [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
18/*
19 * Checks the start of the stream to see if the image is an Ico or Cur
20 */
21bool SkIcoCodec::IsIco(SkStream* stream) {
22 const char icoSig[] = { '\x00', '\x00', '\x01', '\x00' };
23 const char curSig[] = { '\x00', '\x00', '\x02', '\x00' };
24 char buffer[sizeof(icoSig)];
25 return stream->read(buffer, sizeof(icoSig)) == sizeof(icoSig) &&
26 (!memcmp(buffer, icoSig, sizeof(icoSig)) ||
27 !memcmp(buffer, curSig, sizeof(curSig)));
28}
29
30/*
31 * Assumes IsIco was called and returned true
32 * Creates an Ico decoder
33 * Reads enough of the stream to determine the image format
34 */
35SkCodec* SkIcoCodec::NewFromStream(SkStream* stream) {
msarettd0be5bb2015-03-25 06:29:18 -070036 // Ensure that we do not leak the input stream
37 SkAutoTDelete<SkStream> inputStream(stream);
38
msarett9bde9182015-03-25 05:27:48 -070039 // Header size constants
40 static const uint32_t kIcoDirectoryBytes = 6;
41 static const uint32_t kIcoDirEntryBytes = 16;
42
43 // Read the directory header
halcanary385fe4d2015-08-26 13:07:48 -070044 SkAutoTDeleteArray<uint8_t> dirBuffer(new uint8_t[kIcoDirectoryBytes]);
msarettd0be5bb2015-03-25 06:29:18 -070045 if (inputStream.get()->read(dirBuffer.get(), kIcoDirectoryBytes) !=
msarett9bde9182015-03-25 05:27:48 -070046 kIcoDirectoryBytes) {
scroggo230d4ac2015-03-26 07:15:55 -070047 SkCodecPrintf("Error: unable to read ico directory header.\n");
msarett9bde9182015-03-25 05:27:48 -070048 return NULL;
49 }
50
51 // Process the directory header
52 const uint16_t numImages = get_short(dirBuffer.get(), 4);
53 if (0 == numImages) {
scroggo230d4ac2015-03-26 07:15:55 -070054 SkCodecPrintf("Error: No images embedded in ico.\n");
msarett9bde9182015-03-25 05:27:48 -070055 return NULL;
56 }
57
58 // Ensure that we can read all of indicated directory entries
halcanary385fe4d2015-08-26 13:07:48 -070059 SkAutoTDeleteArray<uint8_t> entryBuffer(new uint8_t[numImages * kIcoDirEntryBytes]);
msarettd0be5bb2015-03-25 06:29:18 -070060 if (inputStream.get()->read(entryBuffer.get(), numImages*kIcoDirEntryBytes) !=
msarett9bde9182015-03-25 05:27:48 -070061 numImages*kIcoDirEntryBytes) {
scroggo230d4ac2015-03-26 07:15:55 -070062 SkCodecPrintf("Error: unable to read ico directory entries.\n");
msarett9bde9182015-03-25 05:27:48 -070063 return NULL;
64 }
65
66 // This structure is used to represent the vital information about entries
67 // in the directory header. We will obtain this information for each
68 // directory entry.
69 struct Entry {
70 uint32_t offset;
71 uint32_t size;
72 };
halcanary385fe4d2015-08-26 13:07:48 -070073 SkAutoTDeleteArray<Entry> directoryEntries(new Entry[numImages]);
msarett9bde9182015-03-25 05:27:48 -070074
75 // Iterate over directory entries
76 for (uint32_t i = 0; i < numImages; i++) {
77 // The directory entry contains information such as width, height,
78 // bits per pixel, and number of colors in the color palette. We will
79 // ignore these fields since they are repeated in the header of the
80 // embedded image. In the event of an inconsistency, we would always
81 // defer to the value in the embedded header anyway.
82
83 // Specifies the size of the embedded image, including the header
84 uint32_t size = get_int(entryBuffer.get(), 8 + i*kIcoDirEntryBytes);
85
86 // Specifies the offset of the embedded image from the start of file.
87 // It does not indicate the start of the pixel data, but rather the
88 // start of the embedded image header.
89 uint32_t offset = get_int(entryBuffer.get(), 12 + i*kIcoDirEntryBytes);
90
91 // Save the vital fields
92 directoryEntries.get()[i].offset = offset;
93 directoryEntries.get()[i].size = size;
94 }
95
96 // It is "customary" that the embedded images will be stored in order of
97 // increasing offset. However, the specification does not indicate that
98 // they must be stored in this order, so we will not trust that this is the
99 // case. Here we sort the embedded images by increasing offset.
100 struct EntryLessThan {
101 bool operator() (Entry a, Entry b) const {
102 return a.offset < b.offset;
103 }
104 };
105 EntryLessThan lessThan;
106 SkTQSort(directoryEntries.get(), directoryEntries.get() + numImages - 1,
107 lessThan);
108
109 // Now will construct a candidate codec for each of the embedded images
110 uint32_t bytesRead = kIcoDirectoryBytes + numImages * kIcoDirEntryBytes;
111 SkAutoTDelete<SkTArray<SkAutoTDelete<SkCodec>, true>> codecs(
halcanary385fe4d2015-08-26 13:07:48 -0700112 new (SkTArray<SkAutoTDelete<SkCodec>, true>)(numImages));
msarett9bde9182015-03-25 05:27:48 -0700113 for (uint32_t i = 0; i < numImages; i++) {
114 uint32_t offset = directoryEntries.get()[i].offset;
115 uint32_t size = directoryEntries.get()[i].size;
116
117 // Ensure that the offset is valid
118 if (offset < bytesRead) {
scroggo230d4ac2015-03-26 07:15:55 -0700119 SkCodecPrintf("Warning: invalid ico offset.\n");
msarett9bde9182015-03-25 05:27:48 -0700120 continue;
121 }
122
123 // If we cannot skip, assume we have reached the end of the stream and
124 // stop trying to make codecs
msarettd0be5bb2015-03-25 06:29:18 -0700125 if (inputStream.get()->skip(offset - bytesRead) != offset - bytesRead) {
scroggo230d4ac2015-03-26 07:15:55 -0700126 SkCodecPrintf("Warning: could not skip to ico offset.\n");
msarett9bde9182015-03-25 05:27:48 -0700127 break;
128 }
129 bytesRead = offset;
130
131 // Create a new stream for the embedded codec
msarettd0be5bb2015-03-25 06:29:18 -0700132 SkAutoTUnref<SkData> data(
133 SkData::NewFromStream(inputStream.get(), size));
msarett9bde9182015-03-25 05:27:48 -0700134 if (NULL == data.get()) {
scroggo230d4ac2015-03-26 07:15:55 -0700135 SkCodecPrintf("Warning: could not create embedded stream.\n");
msarett9bde9182015-03-25 05:27:48 -0700136 break;
137 }
halcanary385fe4d2015-08-26 13:07:48 -0700138 SkAutoTDelete<SkMemoryStream> embeddedStream(new SkMemoryStream(data.get()));
msarett9bde9182015-03-25 05:27:48 -0700139 bytesRead += size;
140
141 // Check if the embedded codec is bmp or png and create the codec
142 const bool isPng = SkPngCodec::IsPng(embeddedStream);
143 SkAssertResult(embeddedStream->rewind());
144 SkCodec* codec = NULL;
145 if (isPng) {
146 codec = SkPngCodec::NewFromStream(embeddedStream.detach());
147 } else {
148 codec = SkBmpCodec::NewFromIco(embeddedStream.detach());
149 }
150
151 // Save a valid codec
152 if (NULL != codec) {
153 codecs->push_back().reset(codec);
154 }
155 }
156
157 // Recognize if there are no valid codecs
158 if (0 == codecs->count()) {
scroggo230d4ac2015-03-26 07:15:55 -0700159 SkCodecPrintf("Error: could not find any valid embedded ico codecs.\n");
msarett9bde9182015-03-25 05:27:48 -0700160 return NULL;
161 }
162
163 // Use the largest codec as a "suggestion" for image info
164 uint32_t maxSize = 0;
165 uint32_t maxIndex = 0;
166 for (int32_t i = 0; i < codecs->count(); i++) {
167 SkImageInfo info = codecs->operator[](i)->getInfo();
168 uint32_t size = info.width() * info.height();
169 if (size > maxSize) {
170 maxSize = size;
171 maxIndex = i;
172 }
173 }
174 SkImageInfo info = codecs->operator[](maxIndex)->getInfo();
175
scroggocc2feb12015-08-14 08:32:46 -0700176 // ICOs contain an alpha mask after the image which means we cannot
177 // guarantee that an image is opaque, even if the sub-codec thinks it
178 // is.
179 // FIXME (msarett): The BMP decoder depends on the alpha type in order
180 // to decode correctly, otherwise it could report kUnpremul and we would
181 // not have to correct it here. Is there a better way?
182 // FIXME (msarett): This is only true for BMP in ICO - could a PNG in ICO
183 // be opaque? Is it okay that we missed out on the opportunity to mark
184 // such an image as opaque?
185 info = info.makeAlphaType(kUnpremul_SkAlphaType);
186
msarett9bde9182015-03-25 05:27:48 -0700187 // Note that stream is owned by the embedded codec, the ico does not need
188 // direct access to the stream.
halcanary385fe4d2015-08-26 13:07:48 -0700189 return new SkIcoCodec(info, codecs.detach());
msarett9bde9182015-03-25 05:27:48 -0700190}
191
192/*
193 * Creates an instance of the decoder
194 * Called only by NewFromStream
195 */
196SkIcoCodec::SkIcoCodec(const SkImageInfo& info,
197 SkTArray<SkAutoTDelete<SkCodec>, true>* codecs)
198 : INHERITED(info, NULL)
199 , fEmbeddedCodecs(codecs)
200{}
201
202/*
203 * Chooses the best dimensions given the desired scale
204 */
205SkISize SkIcoCodec::onGetScaledDimensions(float desiredScale) const {
206 // We set the dimensions to the largest candidate image by default.
207 // Regardless of the scale request, this is the largest image that we
208 // will decode.
209 if (desiredScale >= 1.0) {
210 return this->getInfo().dimensions();
211 }
212
213 int origWidth = this->getInfo().width();
214 int origHeight = this->getInfo().height();
215 float desiredSize = desiredScale * origWidth * origHeight;
216 // At least one image will have smaller error than this initial value
217 float minError = ((float) (origWidth * origHeight)) - desiredSize + 1.0f;
218 int32_t minIndex = -1;
219 for (int32_t i = 0; i < fEmbeddedCodecs->count(); i++) {
220 int width = fEmbeddedCodecs->operator[](i)->getInfo().width();
221 int height = fEmbeddedCodecs->operator[](i)->getInfo().height();
222 float error = SkTAbs(((float) (width * height)) - desiredSize);
223 if (error < minError) {
224 minError = error;
225 minIndex = i;
226 }
227 }
228 SkASSERT(minIndex >= 0);
229
230 return fEmbeddedCodecs->operator[](minIndex)->getInfo().dimensions();
231}
232
233/*
234 * Initiates the Ico decode
235 */
236SkCodec::Result SkIcoCodec::onGetPixels(const SkImageInfo& dstInfo,
237 void* dst, size_t dstRowBytes,
238 const Options& opts, SkPMColor* ct,
239 int* ptr) {
scroggob636b452015-07-22 07:16:20 -0700240 if (opts.fSubset) {
241 // Subsets are not supported.
242 return kUnimplemented;
243 }
scroggocc2feb12015-08-14 08:32:46 -0700244
245 if (!valid_alpha(dstInfo.alphaType(), this->getInfo().alphaType())) {
246 return kInvalidConversion;
247 }
248
msarett9bde9182015-03-25 05:27:48 -0700249 // We return invalid scale if there is no candidate image with matching
250 // dimensions.
251 Result result = kInvalidScale;
252 for (int32_t i = 0; i < fEmbeddedCodecs->count(); i++) {
scroggocc2feb12015-08-14 08:32:46 -0700253 SkCodec* embeddedCodec = fEmbeddedCodecs->operator[](i);
msarett9bde9182015-03-25 05:27:48 -0700254 // If the dimensions match, try to decode
scroggocc2feb12015-08-14 08:32:46 -0700255 if (dstInfo.dimensions() == embeddedCodec->getInfo().dimensions()) {
msarett9bde9182015-03-25 05:27:48 -0700256
257 // Perform the decode
scroggocc2feb12015-08-14 08:32:46 -0700258 // FIXME: (msarett): ICO is considered non-opaque, even if the embedded BMP
259 // incorrectly claims it has no alpha.
260 SkImageInfo info = dstInfo.makeAlphaType(embeddedCodec->getInfo().alphaType());
261 result = embeddedCodec->getPixels(info, dst, dstRowBytes, &opts, ct, ptr);
msarett9bde9182015-03-25 05:27:48 -0700262
263 // On a fatal error, keep trying to find an image to decode
264 if (kInvalidConversion == result || kInvalidInput == result ||
265 kInvalidScale == result) {
scroggo230d4ac2015-03-26 07:15:55 -0700266 SkCodecPrintf("Warning: Attempt to decode candidate ico failed.\n");
msarett9bde9182015-03-25 05:27:48 -0700267 continue;
268 }
269
270 // On success or partial success, return the result
271 return result;
272 }
273 }
274
scroggo230d4ac2015-03-26 07:15:55 -0700275 SkCodecPrintf("Error: No matching candidate image in ico.\n");
msarett9bde9182015-03-25 05:27:48 -0700276 return result;
277}