Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(208)

Side by Side Diff: src/codec/SkCodec_libico.cpp

Issue 1567863003: Rename SkGifCodec, SkIcoCodec, SkWbmpCodec (Closed) Base URL: https://skia.googlesource.com/skia.git@master
Patch Set: Created 4 years, 11 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « src/codec/SkCodec_libico.h ('k') | src/codec/SkCodec_wbmp.h » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 /*
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
8 #include "SkBmpCodec.h"
9 #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 static 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
36 static SkImageInfo fix_embedded_alpha(const SkImageInfo& dstInfo, SkAlphaType em beddedAlpha) {
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 opa que.
47 break;
48 default:
49 SkASSERT(false);
50 break;
51 }
52 return dstInfo.makeAlphaType(embeddedAlpha);
53 }
54
55 /*
56 * Checks the start of the stream to see if the image is an Ico or Cur
57 */
58 bool SkIcoCodec::IsIco(const void* buffer, size_t bytesRead) {
59 const char icoSig[] = { '\x00', '\x00', '\x01', '\x00' };
60 const char curSig[] = { '\x00', '\x00', '\x02', '\x00' };
61 return bytesRead >= sizeof(icoSig) &&
62 (!memcmp(buffer, icoSig, sizeof(icoSig)) ||
63 !memcmp(buffer, curSig, sizeof(curSig)));
64 }
65
66 /*
67 * Assumes IsIco was called and returned true
68 * Creates an Ico decoder
69 * Reads enough of the stream to determine the image format
70 */
71 SkCodec* SkIcoCodec::NewFromStream(SkStream* stream) {
72 // Ensure that we do not leak the input stream
73 SkAutoTDelete<SkStream> inputStream(stream);
74
75 // Header size constants
76 static const uint32_t kIcoDirectoryBytes = 6;
77 static const uint32_t kIcoDirEntryBytes = 16;
78
79 // Read the directory header
80 SkAutoTDeleteArray<uint8_t> dirBuffer(new uint8_t[kIcoDirectoryBytes]);
81 if (inputStream.get()->read(dirBuffer.get(), kIcoDirectoryBytes) !=
82 kIcoDirectoryBytes) {
83 SkCodecPrintf("Error: unable to read ico directory header.\n");
84 return nullptr;
85 }
86
87 // Process the directory header
88 const uint16_t numImages = get_short(dirBuffer.get(), 4);
89 if (0 == numImages) {
90 SkCodecPrintf("Error: No images embedded in ico.\n");
91 return nullptr;
92 }
93
94 // Ensure that we can read all of indicated directory entries
95 SkAutoTDeleteArray<uint8_t> entryBuffer(new uint8_t[numImages * kIcoDirEntry Bytes]);
96 if (inputStream.get()->read(entryBuffer.get(), numImages*kIcoDirEntryBytes) !=
97 numImages*kIcoDirEntryBytes) {
98 SkCodecPrintf("Error: unable to read ico directory entries.\n");
99 return nullptr;
100 }
101
102 // This structure is used to represent the vital information about entries
103 // in the directory header. We will obtain this information for each
104 // directory entry.
105 struct Entry {
106 uint32_t offset;
107 uint32_t size;
108 };
109 SkAutoTDeleteArray<Entry> directoryEntries(new Entry[numImages]);
110
111 // Iterate over directory entries
112 for (uint32_t i = 0; i < numImages; i++) {
113 // The directory entry contains information such as width, height,
114 // bits per pixel, and number of colors in the color palette. We will
115 // ignore these fields since they are repeated in the header of the
116 // embedded image. In the event of an inconsistency, we would always
117 // defer to the value in the embedded header anyway.
118
119 // Specifies the size of the embedded image, including the header
120 uint32_t size = get_int(entryBuffer.get(), 8 + i*kIcoDirEntryBytes);
121
122 // Specifies the offset of the embedded image from the start of file.
123 // It does not indicate the start of the pixel data, but rather the
124 // start of the embedded image header.
125 uint32_t offset = get_int(entryBuffer.get(), 12 + i*kIcoDirEntryBytes);
126
127 // Save the vital fields
128 directoryEntries.get()[i].offset = offset;
129 directoryEntries.get()[i].size = size;
130 }
131
132 // It is "customary" that the embedded images will be stored in order of
133 // increasing offset. However, the specification does not indicate that
134 // they must be stored in this order, so we will not trust that this is the
135 // case. Here we sort the embedded images by increasing offset.
136 struct EntryLessThan {
137 bool operator() (Entry a, Entry b) const {
138 return a.offset < b.offset;
139 }
140 };
141 EntryLessThan lessThan;
142 SkTQSort(directoryEntries.get(), directoryEntries.get() + numImages - 1,
143 lessThan);
144
145 // Now will construct a candidate codec for each of the embedded images
146 uint32_t bytesRead = kIcoDirectoryBytes + numImages * kIcoDirEntryBytes;
147 SkAutoTDelete<SkTArray<SkAutoTDelete<SkCodec>, true>> codecs(
148 new (SkTArray<SkAutoTDelete<SkCodec>, true>)(numImages));
149 for (uint32_t i = 0; i < numImages; i++) {
150 uint32_t offset = directoryEntries.get()[i].offset;
151 uint32_t size = directoryEntries.get()[i].size;
152
153 // Ensure that the offset is valid
154 if (offset < bytesRead) {
155 SkCodecPrintf("Warning: invalid ico offset.\n");
156 continue;
157 }
158
159 // If we cannot skip, assume we have reached the end of the stream and
160 // stop trying to make codecs
161 if (inputStream.get()->skip(offset - bytesRead) != offset - bytesRead) {
162 SkCodecPrintf("Warning: could not skip to ico offset.\n");
163 break;
164 }
165 bytesRead = offset;
166
167 // Create a new stream for the embedded codec
168 SkAutoTUnref<SkData> data(
169 SkData::NewFromStream(inputStream.get(), size));
170 if (nullptr == data.get()) {
171 SkCodecPrintf("Warning: could not create embedded stream.\n");
172 break;
173 }
174 SkAutoTDelete<SkMemoryStream> embeddedStream(new SkMemoryStream(data.get ()));
175 bytesRead += size;
176
177 // Check if the embedded codec is bmp or png and create the codec
178 SkCodec* codec = nullptr;
179 if (SkPngCodec::IsPng((const char*) data->bytes(), data->size())) {
180 codec = SkPngCodec::NewFromStream(embeddedStream.detach());
181 } else {
182 codec = SkBmpCodec::NewFromIco(embeddedStream.detach());
183 }
184
185 // Save a valid codec
186 if (nullptr != codec) {
187 codecs->push_back().reset(codec);
188 }
189 }
190
191 // Recognize if there are no valid codecs
192 if (0 == codecs->count()) {
193 SkCodecPrintf("Error: could not find any valid embedded ico codecs.\n");
194 return nullptr;
195 }
196
197 // Use the largest codec as a "suggestion" for image info
198 uint32_t maxSize = 0;
199 uint32_t maxIndex = 0;
200 for (int32_t i = 0; i < codecs->count(); i++) {
201 SkImageInfo info = codecs->operator[](i)->getInfo();
202 uint32_t size = info.width() * info.height();
203 if (size > maxSize) {
204 maxSize = size;
205 maxIndex = i;
206 }
207 }
208 SkImageInfo info = codecs->operator[](maxIndex)->getInfo();
209
210 // ICOs contain an alpha mask after the image which means we cannot
211 // guarantee that an image is opaque, even if the sub-codec thinks it
212 // is.
213 // FIXME (msarett): The BMP decoder depends on the alpha type in order
214 // to decode correctly, otherwise it could report kUnpremul and we would
215 // not have to correct it here. Is there a better way?
216 // FIXME (msarett): This is only true for BMP in ICO - could a PNG in ICO
217 // be opaque? Is it okay that we missed out on the opportunity to mark
218 // such an image as opaque?
219 info = info.makeAlphaType(kUnpremul_SkAlphaType);
220
221 // Note that stream is owned by the embedded codec, the ico does not need
222 // direct access to the stream.
223 return new SkIcoCodec(info, codecs.detach());
224 }
225
226 /*
227 * Creates an instance of the decoder
228 * Called only by NewFromStream
229 */
230 SkIcoCodec::SkIcoCodec(const SkImageInfo& info,
231 SkTArray<SkAutoTDelete<SkCodec>, true>* codecs)
232 : INHERITED(info, nullptr)
233 , fEmbeddedCodecs(codecs)
234 , fCurrScanlineCodec(nullptr)
235 {}
236
237 /*
238 * Chooses the best dimensions given the desired scale
239 */
240 SkISize SkIcoCodec::onGetScaledDimensions(float desiredScale) const {
241 // We set the dimensions to the largest candidate image by default.
242 // Regardless of the scale request, this is the largest image that we
243 // will decode.
244 int origWidth = this->getInfo().width();
245 int origHeight = this->getInfo().height();
246 float desiredSize = desiredScale * origWidth * origHeight;
247 // At least one image will have smaller error than this initial value
248 float minError = ((float) (origWidth * origHeight)) - desiredSize + 1.0f;
249 int32_t minIndex = -1;
250 for (int32_t i = 0; i < fEmbeddedCodecs->count(); i++) {
251 int width = fEmbeddedCodecs->operator[](i)->getInfo().width();
252 int height = fEmbeddedCodecs->operator[](i)->getInfo().height();
253 float error = SkTAbs(((float) (width * height)) - desiredSize);
254 if (error < minError) {
255 minError = error;
256 minIndex = i;
257 }
258 }
259 SkASSERT(minIndex >= 0);
260
261 return fEmbeddedCodecs->operator[](minIndex)->getInfo().dimensions();
262 }
263
264 int SkIcoCodec::chooseCodec(const SkISize& requestedSize, int startIndex) {
265 SkASSERT(startIndex >= 0);
266
267 // FIXME: Cache the index from onGetScaledDimensions?
268 for (int i = startIndex; i < fEmbeddedCodecs->count(); i++) {
269 if (fEmbeddedCodecs->operator[](i)->getInfo().dimensions() == requestedS ize) {
270 return i;
271 }
272 }
273
274 return -1;
275 }
276
277 bool SkIcoCodec::onDimensionsSupported(const SkISize& dim) {
278 return this->chooseCodec(dim, 0) >= 0;
279 }
280
281 /*
282 * Initiates the Ico decode
283 */
284 SkCodec::Result SkIcoCodec::onGetPixels(const SkImageInfo& dstInfo,
285 void* dst, size_t dstRowBytes,
286 const Options& opts, SkPMColor* colorTab le,
287 int* colorCount, int* rowsDecoded) {
288 if (opts.fSubset) {
289 // Subsets are not supported.
290 return kUnimplemented;
291 }
292
293 if (!ico_conversion_possible(dstInfo)) {
294 return kInvalidConversion;
295 }
296
297 int index = 0;
298 SkCodec::Result result = kInvalidScale;
299 while (true) {
300 index = this->chooseCodec(dstInfo.dimensions(), index);
301 if (index < 0) {
302 break;
303 }
304
305 SkCodec* embeddedCodec = fEmbeddedCodecs->operator[](index);
306 SkImageInfo decodeInfo = fix_embedded_alpha(dstInfo, embeddedCodec->getI nfo().alphaType());
307 SkASSERT(decodeInfo.colorType() == kN32_SkColorType);
308 result = embeddedCodec->getPixels(decodeInfo, dst, dstRowBytes, &opts, c olorTable,
309 colorCount);
310
311 switch (result) {
312 case kSuccess:
313 case kIncompleteInput:
314 // The embedded codec will handle filling incomplete images, so we will indicate
315 // that all of the rows are initialized.
316 *rowsDecoded = decodeInfo.height();
317 return result;
318 default:
319 // Continue trying to find a valid embedded codec on a failed de code.
320 break;
321 }
322
323 index++;
324 }
325
326 SkCodecPrintf("Error: No matching candidate image in ico.\n");
327 return result;
328 }
329
330 SkCodec::Result SkIcoCodec::onStartScanlineDecode(const SkImageInfo& dstInfo,
331 const SkCodec::Options& options, SkPMColor colorTable[], int* colorCount ) {
332 if (!ico_conversion_possible(dstInfo)) {
333 return kInvalidConversion;
334 }
335
336 int index = 0;
337 SkCodec::Result result = kInvalidScale;
338 while (true) {
339 index = this->chooseCodec(dstInfo.dimensions(), index);
340 if (index < 0) {
341 break;
342 }
343
344 SkCodec* embeddedCodec = fEmbeddedCodecs->operator[](index);
345 SkImageInfo decodeInfo = fix_embedded_alpha(dstInfo, embeddedCodec->getI nfo().alphaType());
346 result = embeddedCodec->startScanlineDecode(decodeInfo, &options, colorT able, colorCount);
347 if (kSuccess == result) {
348 fCurrScanlineCodec = embeddedCodec;
349 return result;
350 }
351
352 index++;
353 }
354
355 SkCodecPrintf("Error: No matching candidate image in ico.\n");
356 return result;
357 }
358
359 int SkIcoCodec::onGetScanlines(void* dst, int count, size_t rowBytes) {
360 SkASSERT(fCurrScanlineCodec);
361 return fCurrScanlineCodec->getScanlines(dst, count, rowBytes);
362 }
363
364 bool SkIcoCodec::onSkipScanlines(int count) {
365 SkASSERT(fCurrScanlineCodec);
366 return fCurrScanlineCodec->skipScanlines(count);
367 }
368
369 SkCodec::SkScanlineOrder SkIcoCodec::onGetScanlineOrder() const {
370 // FIXME: This function will possibly return the wrong value if it is called
371 // before startScanlineDecode().
372 return fCurrScanlineCodec ? fCurrScanlineCodec->getScanlineOrder() :
373 INHERITED::onGetScanlineOrder();
374 }
375
376 SkSampler* SkIcoCodec::getSampler(bool createIfNecessary) {
377 return fCurrScanlineCodec ? fCurrScanlineCodec->getSampler(createIfNecessary ) : nullptr;
378 }
OLDNEW
« no previous file with comments | « src/codec/SkCodec_libico.h ('k') | src/codec/SkCodec_wbmp.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698