2 * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
14 * * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include "platform/image-decoders/ico/ICOImageDecoder.h"
36 #include "platform/PlatformInstrumentation.h"
37 #include "platform/image-decoders/png/PNGImageDecoder.h"
38 #include "wtf/PassOwnPtr.h"
42 // Number of bits in .ICO/.CUR used to store the directory and its entries,
43 // respectively (doesn't match sizeof values for member structs since we omit
45 static const size_t sizeOfDirectory = 6;
46 static const size_t sizeOfDirEntry = 16;
48 ICOImageDecoder::ICOImageDecoder(ImageSource::AlphaOption alphaOption,
49 ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption,
50 size_t maxDecodedBytes)
51 : ImageDecoder(alphaOption, gammaAndColorProfileOption, maxDecodedBytes)
56 ICOImageDecoder::~ICOImageDecoder()
60 void ICOImageDecoder::setData(SharedBuffer* data, bool allDataReceived)
65 ImageDecoder::setData(data, allDataReceived);
67 for (BMPReaders::iterator i(m_bmpReaders.begin()); i != m_bmpReaders.end(); ++i) {
71 for (size_t i = 0; i < m_pngDecoders.size(); ++i)
72 setDataForPNGDecoderAtIndex(i);
75 bool ICOImageDecoder::isSizeAvailable()
77 if (!ImageDecoder::isSizeAvailable())
80 return ImageDecoder::isSizeAvailable();
83 IntSize ICOImageDecoder::size() const
85 return m_frameSize.isEmpty() ? ImageDecoder::size() : m_frameSize;
88 IntSize ICOImageDecoder::frameSizeAtIndex(size_t index) const
90 return (index && (index < m_dirEntries.size())) ? m_dirEntries[index].m_size : size();
93 bool ICOImageDecoder::setSize(unsigned width, unsigned height)
95 // The size calculated inside the BMPImageReader had better match the one in
96 // the icon directory.
97 return m_frameSize.isEmpty() ? ImageDecoder::setSize(width, height) : ((IntSize(width, height) == m_frameSize) || setFailed());
100 size_t ICOImageDecoder::frameCount()
103 if (m_frameBufferCache.isEmpty()) {
104 m_frameBufferCache.resize(m_dirEntries.size());
105 for (size_t i = 0; i < m_dirEntries.size(); ++i) {
106 m_frameBufferCache[i].setPremultiplyAlpha(m_premultiplyAlpha);
107 m_frameBufferCache[i].setRequiredPreviousFrameIndex(kNotFound);
110 // CAUTION: We must not resize m_frameBufferCache again after this, as
111 // decodeAtIndex() may give a BMPImageReader a pointer to one of the
113 return m_frameBufferCache.size();
116 ImageFrame* ICOImageDecoder::frameBufferAtIndex(size_t index)
118 // Ensure |index| is valid.
119 if (index >= frameCount())
122 ImageFrame* buffer = &m_frameBufferCache[index];
123 if (buffer->status() != ImageFrame::FrameComplete) {
124 PlatformInstrumentation::willDecodeImage("ICO");
125 decode(index, false);
126 PlatformInstrumentation::didDecodeImage();
131 bool ICOImageDecoder::setFailed()
133 m_bmpReaders.clear();
134 m_pngDecoders.clear();
135 return ImageDecoder::setFailed();
138 bool ICOImageDecoder::hotSpot(IntPoint& hotSpot) const
140 // When unspecified, the default frame is always frame 0. This is consistent with
141 // BitmapImage where currentFrame() starts at 0 and only increases when animation is
143 return hotSpotAtIndex(0, hotSpot);
146 bool ICOImageDecoder::hotSpotAtIndex(size_t index, IntPoint& hotSpot) const
148 if (index >= m_dirEntries.size() || m_fileType != CURSOR)
151 hotSpot = m_dirEntries[index].m_hotSpot;
157 bool ICOImageDecoder::compareEntries(const IconDirectoryEntry& a, const IconDirectoryEntry& b)
159 // Larger icons are better. After that, higher bit-depth icons are better.
160 const int aEntryArea = a.m_size.width() * a.m_size.height();
161 const int bEntryArea = b.m_size.width() * b.m_size.height();
162 return (aEntryArea == bEntryArea) ? (a.m_bitCount > b.m_bitCount) : (aEntryArea > bEntryArea);
165 void ICOImageDecoder::setDataForPNGDecoderAtIndex(size_t index)
167 if (!m_pngDecoders[index])
170 const IconDirectoryEntry& dirEntry = m_dirEntries[index];
171 // Copy out PNG data to a separate vector and send to the PNG decoder.
172 // FIXME: Save this copy by making the PNG decoder able to take an
174 RefPtr<SharedBuffer> pngData(SharedBuffer::create(&m_data->data()[dirEntry.m_imageOffset], m_data->size() - dirEntry.m_imageOffset));
175 m_pngDecoders[index]->setData(pngData.get(), isAllDataReceived());
178 void ICOImageDecoder::decode(size_t index, bool onlySize)
183 // If we couldn't decode the image but we've received all the data, decoding
185 if ((!decodeDirectory() || (!onlySize && !decodeAtIndex(index))) && isAllDataReceived())
187 // If we're done decoding this frame, we don't need the BMPImageReader or
188 // PNGImageDecoder anymore. (If we failed, these have already been
190 else if ((m_frameBufferCache.size() > index) && (m_frameBufferCache[index].status() == ImageFrame::FrameComplete)) {
191 m_bmpReaders[index].clear();
192 m_pngDecoders[index].clear();
196 bool ICOImageDecoder::decodeDirectory()
198 // Read and process directory.
199 if ((m_decodedOffset < sizeOfDirectory) && !processDirectory())
202 // Read and process directory entries.
203 return (m_decodedOffset >= (sizeOfDirectory + (m_dirEntries.size() * sizeOfDirEntry))) || processDirectoryEntries();
206 bool ICOImageDecoder::decodeAtIndex(size_t index)
208 ASSERT_WITH_SECURITY_IMPLICATION(index < m_dirEntries.size());
209 const IconDirectoryEntry& dirEntry = m_dirEntries[index];
210 const ImageType imageType = imageTypeAtIndex(index);
211 if (imageType == Unknown)
212 return false; // Not enough data to determine image type yet.
214 if (imageType == BMP) {
215 if (!m_bmpReaders[index]) {
216 // We need to have already sized m_frameBufferCache before this, and
217 // we must not resize it again later (see caution in frameCount()).
218 ASSERT(m_frameBufferCache.size() == m_dirEntries.size());
219 m_bmpReaders[index] = adoptPtr(new BMPImageReader(this, dirEntry.m_imageOffset, 0, true));
220 m_bmpReaders[index]->setData(m_data.get());
221 m_bmpReaders[index]->setBuffer(&m_frameBufferCache[index]);
223 m_frameSize = dirEntry.m_size;
224 bool result = m_bmpReaders[index]->decodeBMP(false);
225 m_frameSize = IntSize();
229 if (!m_pngDecoders[index]) {
230 m_pngDecoders[index] = adoptPtr(
231 new PNGImageDecoder(m_premultiplyAlpha ? ImageSource::AlphaPremultiplied : ImageSource::AlphaNotPremultiplied,
232 m_ignoreGammaAndColorProfile ? ImageSource::GammaAndColorProfileIgnored : ImageSource::GammaAndColorProfileApplied, m_maxDecodedBytes));
233 setDataForPNGDecoderAtIndex(index);
235 // Fail if the size the PNGImageDecoder calculated does not match the size
237 if (m_pngDecoders[index]->isSizeAvailable() && (m_pngDecoders[index]->size() != dirEntry.m_size))
239 m_frameBufferCache[index] = *m_pngDecoders[index]->frameBufferAtIndex(0);
240 m_frameBufferCache[index].setPremultiplyAlpha(m_premultiplyAlpha);
241 m_frameBufferCache[index].setRequiredPreviousFrameIndex(kNotFound);
242 return !m_pngDecoders[index]->failed() || setFailed();
245 bool ICOImageDecoder::processDirectory()
248 ASSERT(!m_decodedOffset);
249 if (m_data->size() < sizeOfDirectory)
251 const uint16_t fileType = readUint16(2);
252 const uint16_t idCount = readUint16(4);
253 m_decodedOffset = sizeOfDirectory;
255 // See if this is an icon filetype we understand, and make sure we have at
256 // least one entry in the directory.
257 if (((fileType != ICON) && (fileType != CURSOR)) || (!idCount))
260 m_fileType = static_cast<FileType>(fileType);
262 // Enlarge member vectors to hold all the entries.
263 m_dirEntries.resize(idCount);
264 m_bmpReaders.resize(idCount);
265 m_pngDecoders.resize(idCount);
269 bool ICOImageDecoder::processDirectoryEntries()
271 // Read directory entries.
272 ASSERT(m_decodedOffset == sizeOfDirectory);
273 if ((m_decodedOffset > m_data->size()) || ((m_data->size() - m_decodedOffset) < (m_dirEntries.size() * sizeOfDirEntry)))
275 for (IconDirectoryEntries::iterator i(m_dirEntries.begin()); i != m_dirEntries.end(); ++i)
276 *i = readDirectoryEntry(); // Updates m_decodedOffset.
278 // Make sure the specified image offsets are past the end of the directory
280 for (IconDirectoryEntries::iterator i(m_dirEntries.begin()); i != m_dirEntries.end(); ++i) {
281 if (i->m_imageOffset < m_decodedOffset)
285 // Arrange frames in decreasing quality order.
286 std::sort(m_dirEntries.begin(), m_dirEntries.end(), compareEntries);
288 // The image size is the size of the largest entry.
289 const IconDirectoryEntry& dirEntry = m_dirEntries.first();
290 // Technically, this next call shouldn't be able to fail, since the width
291 // and height here are each <= 256, and |m_frameSize| is empty.
292 return setSize(dirEntry.m_size.width(), dirEntry.m_size.height());
295 ICOImageDecoder::IconDirectoryEntry ICOImageDecoder::readDirectoryEntry()
298 // The casts to uint8_t in the next few lines are because that's the on-disk
299 // type of the width and height values. Storing them in ints (instead of
300 // matching uint8_ts) is so we can record dimensions of size 256 (which is
301 // what a zero byte really means).
302 int width = static_cast<uint8_t>(m_data->data()[m_decodedOffset]);
305 int height = static_cast<uint8_t>(m_data->data()[m_decodedOffset + 1]);
308 IconDirectoryEntry entry;
309 entry.m_size = IntSize(width, height);
310 if (m_fileType == CURSOR) {
311 entry.m_bitCount = 0;
312 entry.m_hotSpot = IntPoint(readUint16(4), readUint16(6));
314 entry.m_bitCount = readUint16(6);
315 entry.m_hotSpot = IntPoint();
317 entry.m_imageOffset = readUint32(12);
319 // Some icons don't have a bit depth, only a color count. Convert the
320 // color count to the minimum necessary bit depth. It doesn't matter if
321 // this isn't quite what the bitmap info header says later, as we only use
322 // this value to determine which icon entry is best.
323 if (!entry.m_bitCount) {
324 int colorCount = static_cast<uint8_t>(m_data->data()[m_decodedOffset + 2]);
326 colorCount = 256; // Vague in the spec, needed by real-world icons.
327 for (--colorCount; colorCount; colorCount >>= 1)
331 m_decodedOffset += sizeOfDirEntry;
335 ICOImageDecoder::ImageType ICOImageDecoder::imageTypeAtIndex(size_t index)
337 // Check if this entry is a BMP or a PNG; we need 4 bytes to check the magic
339 ASSERT_WITH_SECURITY_IMPLICATION(index < m_dirEntries.size());
340 const uint32_t imageOffset = m_dirEntries[index].m_imageOffset;
341 if ((imageOffset > m_data->size()) || ((m_data->size() - imageOffset) < 4))
343 return strncmp(&m_data->data()[imageOffset], "\x89PNG", 4) ? BMP : PNG;