2 * Copyright (C) 2012 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
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 #include "platform/graphics/ImageFrameGenerator.h"
30 #include "platform/SharedBuffer.h"
31 #include "platform/TraceEvent.h"
32 #include "platform/graphics/DiscardablePixelRef.h"
33 #include "platform/graphics/ImageDecodingStore.h"
34 #include "platform/graphics/ScaledImageFragment.h"
35 #include "platform/image-decoders/ImageDecoder.h"
37 #include "skia/ext/image_operations.h"
38 #include "third_party/skia/include/core/SkMallocPixelRef.h"
42 // Creates a SkPixelRef such that the memory for pixels is given by an external body.
43 // This is used to write directly to the memory given by Skia during decoding.
44 class ImageFrameGenerator::ExternalMemoryAllocator : public SkBitmap::Allocator {
46 ExternalMemoryAllocator(const SkImageInfo& info, void* pixels, size_t rowBytes)
49 , m_rowBytes(rowBytes)
53 virtual bool allocPixelRef(SkBitmap* dst, SkColorTable* ctable) OVERRIDE
56 if (!dst->asImageInfo(&info))
59 if (info != m_info || m_rowBytes != dst->rowBytes())
62 if (!dst->installPixels(m_info, m_pixels, m_rowBytes, 0, 0))
74 ImageFrameGenerator::ImageFrameGenerator(const SkISize& fullSize, PassRefPtr<SharedBuffer> data, bool allDataReceived, bool isMultiFrame)
75 : m_fullSize(fullSize)
76 , m_isMultiFrame(isMultiFrame)
77 , m_decodeFailedAndEmpty(false)
78 , m_decodeCount(ScaledImageFragment::FirstPartialImage)
79 , m_discardableAllocator(adoptPtr(new DiscardablePixelRefAllocator()))
81 setData(data.get(), allDataReceived);
84 ImageFrameGenerator::~ImageFrameGenerator()
86 // FIXME: This check is not really thread-safe. This should be changed to:
87 // ImageDecodingStore::removeCacheFromInstance(this);
88 // Which uses a lock internally.
89 if (ImageDecodingStore::instance())
90 ImageDecodingStore::instance()->removeCacheIndexedByGenerator(this);
93 void ImageFrameGenerator::setData(PassRefPtr<SharedBuffer> data, bool allDataReceived)
95 m_data.setData(data.get(), allDataReceived);
98 void ImageFrameGenerator::copyData(RefPtr<SharedBuffer>* data, bool* allDataReceived)
100 SharedBuffer* buffer = 0;
101 m_data.data(&buffer, allDataReceived);
103 *data = buffer->copy();
106 const ScaledImageFragment* ImageFrameGenerator::decodeAndScale(const SkISize& scaledSize, size_t index)
108 // Prevents concurrent decode or scale operations on the same image data.
109 // Multiple LazyDecodingPixelRefs can call this method at the same time.
110 MutexLocker lock(m_decodeMutex);
111 if (m_decodeFailedAndEmpty)
114 const ScaledImageFragment* cachedImage = 0;
116 cachedImage = tryToLockCompleteCache(scaledSize, index);
120 TRACE_EVENT2("webkit", "ImageFrameGenerator::decodeAndScale", "generator", this, "decodeCount", static_cast<int>(m_decodeCount));
122 cachedImage = tryToResumeDecode(scaledSize, index);
128 bool ImageFrameGenerator::decodeAndScale(const SkImageInfo& info, size_t index, void* pixels, size_t rowBytes)
130 // This method is called to populate a discardable memory owned by Skia.
132 // Prevents concurrent decode or scale operations on the same image data.
133 MutexLocker lock(m_decodeMutex);
135 // This implementation does not support scaling so check the requested size.
136 SkISize scaledSize = SkISize::Make(info.fWidth, info.fHeight);
137 ASSERT(m_fullSize == scaledSize);
139 if (m_decodeFailedAndEmpty)
142 TRACE_EVENT2("webkit", "ImageFrameGenerator::decodeAndScale", "generator", this, "decodeCount", static_cast<int>(m_decodeCount));
144 // Don't use discardable memory for decoding if Skia is providing output
145 // memory. Instead use ExternalMemoryAllocator such that we can
146 // write directly to the memory given by Skia.
149 // This is not pretty because this class is used in two different code
150 // paths: discardable memory decoding on Android and discardable memory
151 // in Skia. Once the transition to caching in Skia is complete we can get
152 // rid of the logic that handles discardable memory.
153 m_discardableAllocator.clear();
154 m_externalAllocator = adoptPtr(new ExternalMemoryAllocator(info, pixels, rowBytes));
156 const ScaledImageFragment* cachedImage = tryToResumeDecode(scaledSize, index);
160 // Don't keep the allocator because it contains a pointer to memory
161 // that we do not own.
162 m_externalAllocator.clear();
164 ASSERT(cachedImage->bitmap().width() == scaledSize.width());
165 ASSERT(cachedImage->bitmap().height() == scaledSize.height());
168 // Check to see if decoder has written directly to the memory provided
169 // by Skia. If not make a copy.
170 if (cachedImage->bitmap().getPixels() != pixels)
171 result = cachedImage->bitmap().copyPixelsTo(pixels, rowBytes * info.fHeight, rowBytes);
172 ImageDecodingStore::instance()->unlockCache(this, cachedImage);
176 const ScaledImageFragment* ImageFrameGenerator::tryToLockCompleteCache(const SkISize& scaledSize, size_t index)
178 const ScaledImageFragment* cachedImage = 0;
179 if (ImageDecodingStore::instance()->lockCache(this, scaledSize, index, &cachedImage))
184 const ScaledImageFragment* ImageFrameGenerator::tryToResumeDecode(const SkISize& scaledSize, size_t index)
186 TRACE_EVENT1("webkit", "ImageFrameGenerator::tryToResumeDecodeAndScale", "index", static_cast<int>(index));
188 ImageDecoder* decoder = 0;
189 const bool resumeDecoding = ImageDecodingStore::instance()->lockDecoder(this, m_fullSize, &decoder);
190 ASSERT(!resumeDecoding || decoder);
192 OwnPtr<ScaledImageFragment> fullSizeImage = decode(index, &decoder);
197 // If we are not resuming decoding that means the decoder is freshly
198 // created and we have ownership. If we are resuming decoding then
199 // the decoder is owned by ImageDecodingStore.
200 OwnPtr<ImageDecoder> decoderContainer;
202 decoderContainer = adoptPtr(decoder);
204 if (!fullSizeImage) {
205 // If decode has failed and resulted an empty image we can save work
206 // in the future by returning early.
207 m_decodeFailedAndEmpty = !m_isMultiFrame && decoder->failed();
210 ImageDecodingStore::instance()->unlockDecoder(this, decoder);
214 const ScaledImageFragment* cachedImage = ImageDecodingStore::instance()->insertAndLockCache(this, fullSizeImage.release());
216 // If the image generated is complete then there is no need to keep
217 // the decoder. The exception is multi-frame decoder which can generate
218 // multiple complete frames.
219 const bool removeDecoder = cachedImage->isComplete() && !m_isMultiFrame;
221 if (resumeDecoding) {
223 ImageDecodingStore::instance()->removeDecoder(this, decoder);
225 ImageDecodingStore::instance()->unlockDecoder(this, decoder);
226 } else if (!removeDecoder) {
227 ImageDecodingStore::instance()->insertDecoder(this, decoderContainer.release(), DiscardablePixelRef::isDiscardable(cachedImage->bitmap().pixelRef()));
233 PassOwnPtr<ScaledImageFragment> ImageFrameGenerator::decode(size_t index, ImageDecoder** decoder)
235 TRACE_EVENT2("webkit", "ImageFrameGenerator::decode", "width", m_fullSize.width(), "height", m_fullSize.height());
238 SharedBuffer* data = 0;
239 bool allDataReceived = false;
240 bool newDecoder = false;
241 m_data.data(&data, &allDataReceived);
243 // Try to create an ImageDecoder if we are not given one.
246 if (m_imageDecoderFactory)
247 *decoder = m_imageDecoderFactory->create().leakPtr();
250 *decoder = ImageDecoder::create(*data, ImageSource::AlphaPremultiplied, ImageSource::GammaAndColorProfileApplied).leakPtr();
256 // An external memory allocator is used if this variable is true.
257 bool useExternalAllocator = false;
259 if (!m_isMultiFrame && newDecoder && allDataReceived) {
260 // We are supporting two decoding paths in this code. Use the
261 // external memory allocator in the Skia discardable path to
262 // save one memory copy.
263 if (m_externalAllocator) {
264 (*decoder)->setMemoryAllocator(m_externalAllocator.get());
265 useExternalAllocator = true;
267 (*decoder)->setMemoryAllocator(m_discardableAllocator.get());
269 (*decoder)->setData(data, allDataReceived);
270 // If this call returns a newly allocated DiscardablePixelRef, then
271 // ImageFrame::m_bitmap and the contained DiscardablePixelRef are locked.
272 // They will be unlocked when ImageDecoder is destroyed since ImageDecoder
273 // owns the ImageFrame. Partially decoded SkBitmap is thus inserted into the
274 // ImageDecodingStore while locked.
275 ImageFrame* frame = (*decoder)->frameBufferAtIndex(index);
276 (*decoder)->setData(0, false); // Unref SharedBuffer from ImageDecoder.
277 (*decoder)->clearCacheExceptFrame(index);
278 (*decoder)->setMemoryAllocator(0);
280 if (!frame || frame->status() == ImageFrame::FrameEmpty)
283 // A cache object is considered complete if we can decode a complete frame.
284 // Or we have received all data. The image might not be fully decoded in
286 const bool isCacheComplete = frame->status() == ImageFrame::FrameComplete || allDataReceived;
287 SkBitmap fullSizeBitmap = frame->getSkBitmap();
288 if (fullSizeBitmap.isNull())
292 MutexLocker lock(m_alphaMutex);
293 if (index >= m_hasAlpha.size()) {
294 const size_t oldSize = m_hasAlpha.size();
295 m_hasAlpha.resize(index + 1);
296 for (size_t i = oldSize; i < m_hasAlpha.size(); ++i)
297 m_hasAlpha[i] = true;
299 m_hasAlpha[index] = !fullSizeBitmap.isOpaque();
301 ASSERT(fullSizeBitmap.width() == m_fullSize.width() && fullSizeBitmap.height() == m_fullSize.height());
303 // We early out and do not copy the memory if decoder writes directly to
304 // the memory provided by Skia and the decode was complete.
305 if (useExternalAllocator && isCacheComplete)
306 return ScaledImageFragment::createComplete(m_fullSize, index, fullSizeBitmap);
308 // If the image is progressively decoded we need to return a copy.
309 // This is to avoid future decode operations writing to the same bitmap.
310 // FIXME: Note that discardable allocator is used. This is because the code
311 // is still used in the Android discardable memory path. When this code is
312 // used in the Skia discardable memory path |m_discardableAllocator| is empty.
313 // This is confusing and should be cleaned up when we can deprecate the use
314 // case for Android discardable memory.
316 if (!fullSizeBitmap.copyTo(©Bitmap, fullSizeBitmap.config(), m_discardableAllocator.get()))
320 return ScaledImageFragment::createComplete(m_fullSize, index, copyBitmap);
321 return ScaledImageFragment::createPartial(m_fullSize, index, nextGenerationId(), copyBitmap);
324 bool ImageFrameGenerator::hasAlpha(size_t index)
326 MutexLocker lock(m_alphaMutex);
327 if (index < m_hasAlpha.size())
328 return m_hasAlpha[index];