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
55 const SkImageInfo& info = dst->info();
56 if (kUnknown_SkColorType == info.colorType())
59 if (info != m_info || m_rowBytes != dst->rowBytes())
62 if (!dst->installPixels(m_info, m_pixels, m_rowBytes))
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 ImageDecodingStore::instance()->removeCacheIndexedByGenerator(this);
89 void ImageFrameGenerator::setData(PassRefPtr<SharedBuffer> data, bool allDataReceived)
91 m_data.setData(data.get(), allDataReceived);
94 void ImageFrameGenerator::copyData(RefPtr<SharedBuffer>* data, bool* allDataReceived)
96 SharedBuffer* buffer = 0;
97 m_data.data(&buffer, allDataReceived);
99 *data = buffer->copy();
102 const ScaledImageFragment* ImageFrameGenerator::decodeAndScale(const SkISize& scaledSize, size_t index)
104 // Prevents concurrent decode or scale operations on the same image data.
105 // Multiple LazyDecodingPixelRefs can call this method at the same time.
106 MutexLocker lock(m_decodeMutex);
107 if (m_decodeFailedAndEmpty)
110 const ScaledImageFragment* cachedImage = 0;
112 cachedImage = tryToLockCompleteCache(scaledSize, index);
116 TRACE_EVENT2("blink", "ImageFrameGenerator::decodeAndScale", "generator", this, "decodeCount", static_cast<int>(m_decodeCount));
118 cachedImage = tryToResumeDecode(scaledSize, index);
124 bool ImageFrameGenerator::decodeAndScale(const SkImageInfo& info, size_t index, void* pixels, size_t rowBytes)
126 // This method is called to populate a discardable memory owned by Skia.
128 // Prevents concurrent decode or scale operations on the same image data.
129 MutexLocker lock(m_decodeMutex);
131 // This implementation does not support scaling so check the requested size.
132 SkISize scaledSize = SkISize::Make(info.fWidth, info.fHeight);
133 ASSERT(m_fullSize == scaledSize);
135 if (m_decodeFailedAndEmpty)
138 TRACE_EVENT2("blink", "ImageFrameGenerator::decodeAndScale", "generator", this, "decodeCount", static_cast<int>(m_decodeCount));
140 // Don't use discardable memory for decoding if Skia is providing output
141 // memory. Instead use ExternalMemoryAllocator such that we can
142 // write directly to the memory given by Skia.
145 // This is not pretty because this class is used in two different code
146 // paths: discardable memory decoding on Android and discardable memory
147 // in Skia. Once the transition to caching in Skia is complete we can get
148 // rid of the logic that handles discardable memory.
149 m_discardableAllocator.clear();
150 m_externalAllocator = adoptPtr(new ExternalMemoryAllocator(info, pixels, rowBytes));
152 const ScaledImageFragment* cachedImage = tryToResumeDecode(scaledSize, index);
156 // Don't keep the allocator because it contains a pointer to memory
157 // that we do not own.
158 m_externalAllocator.clear();
160 ASSERT(cachedImage->bitmap().width() == scaledSize.width());
161 ASSERT(cachedImage->bitmap().height() == scaledSize.height());
164 // Check to see if decoder has written directly to the memory provided
165 // by Skia. If not make a copy.
166 if (cachedImage->bitmap().getPixels() != pixels)
167 result = cachedImage->bitmap().copyPixelsTo(pixels, rowBytes * info.fHeight, rowBytes);
168 ImageDecodingStore::instance()->unlockCache(this, cachedImage);
172 const ScaledImageFragment* ImageFrameGenerator::tryToLockCompleteCache(const SkISize& scaledSize, size_t index)
174 const ScaledImageFragment* cachedImage = 0;
175 if (ImageDecodingStore::instance()->lockCache(this, scaledSize, index, &cachedImage))
180 const ScaledImageFragment* ImageFrameGenerator::tryToResumeDecode(const SkISize& scaledSize, size_t index)
182 TRACE_EVENT1("blink", "ImageFrameGenerator::tryToResumeDecodeAndScale", "index", static_cast<int>(index));
184 ImageDecoder* decoder = 0;
185 const bool resumeDecoding = ImageDecodingStore::instance()->lockDecoder(this, m_fullSize, &decoder);
186 ASSERT(!resumeDecoding || decoder);
188 OwnPtr<ScaledImageFragment> fullSizeImage = decode(index, &decoder);
193 // If we are not resuming decoding that means the decoder is freshly
194 // created and we have ownership. If we are resuming decoding then
195 // the decoder is owned by ImageDecodingStore.
196 OwnPtr<ImageDecoder> decoderContainer;
198 decoderContainer = adoptPtr(decoder);
200 if (!fullSizeImage) {
201 // If decode has failed and resulted an empty image we can save work
202 // in the future by returning early.
203 m_decodeFailedAndEmpty = !m_isMultiFrame && decoder->failed();
206 ImageDecodingStore::instance()->unlockDecoder(this, decoder);
210 const ScaledImageFragment* cachedImage = ImageDecodingStore::instance()->insertAndLockCache(this, fullSizeImage.release());
212 // If the image generated is complete then there is no need to keep
213 // the decoder. The exception is multi-frame decoder which can generate
214 // multiple complete frames.
215 const bool removeDecoder = cachedImage->isComplete() && !m_isMultiFrame;
217 if (resumeDecoding) {
219 ImageDecodingStore::instance()->removeDecoder(this, decoder);
221 ImageDecodingStore::instance()->unlockDecoder(this, decoder);
222 } else if (!removeDecoder) {
223 ImageDecodingStore::instance()->insertDecoder(this, decoderContainer.release(), DiscardablePixelRef::isDiscardable(cachedImage->bitmap().pixelRef()));
229 PassOwnPtr<ScaledImageFragment> ImageFrameGenerator::decode(size_t index, ImageDecoder** decoder)
231 TRACE_EVENT2("blink", "ImageFrameGenerator::decode", "width", m_fullSize.width(), "height", m_fullSize.height());
234 SharedBuffer* data = 0;
235 bool allDataReceived = false;
236 bool newDecoder = false;
237 m_data.data(&data, &allDataReceived);
239 // Try to create an ImageDecoder if we are not given one.
242 if (m_imageDecoderFactory)
243 *decoder = m_imageDecoderFactory->create().leakPtr();
246 *decoder = ImageDecoder::create(*data, ImageSource::AlphaPremultiplied, ImageSource::GammaAndColorProfileApplied).leakPtr();
252 // This variable is set to true if we can skip a memcpy of the decoded bitmap.
253 bool canSkipBitmapCopy = false;
255 if (!m_isMultiFrame && newDecoder && allDataReceived) {
256 // If we're using an external memory allocator that means we're decoding
257 // directly into the output memory and we can save one memcpy.
258 canSkipBitmapCopy = true;
259 if (m_externalAllocator)
260 (*decoder)->setMemoryAllocator(m_externalAllocator.get());
262 (*decoder)->setMemoryAllocator(m_discardableAllocator.get());
264 (*decoder)->setData(data, allDataReceived);
265 // If this call returns a newly allocated DiscardablePixelRef, then
266 // ImageFrame::m_bitmap and the contained DiscardablePixelRef are locked.
267 // They will be unlocked when ImageDecoder is destroyed since ImageDecoder
268 // owns the ImageFrame. Partially decoded SkBitmap is thus inserted into the
269 // ImageDecodingStore while locked.
270 ImageFrame* frame = (*decoder)->frameBufferAtIndex(index);
271 (*decoder)->setData(0, false); // Unref SharedBuffer from ImageDecoder.
272 (*decoder)->clearCacheExceptFrame(index);
273 (*decoder)->setMemoryAllocator(0);
275 if (!frame || frame->status() == ImageFrame::FrameEmpty)
278 // A cache object is considered complete if we can decode a complete frame.
279 // Or we have received all data. The image might not be fully decoded in
281 const bool isCacheComplete = frame->status() == ImageFrame::FrameComplete || allDataReceived;
282 SkBitmap fullSizeBitmap = frame->getSkBitmap();
283 if (fullSizeBitmap.isNull())
287 MutexLocker lock(m_alphaMutex);
288 if (index >= m_hasAlpha.size()) {
289 const size_t oldSize = m_hasAlpha.size();
290 m_hasAlpha.resize(index + 1);
291 for (size_t i = oldSize; i < m_hasAlpha.size(); ++i)
292 m_hasAlpha[i] = true;
294 m_hasAlpha[index] = !fullSizeBitmap.isOpaque();
296 ASSERT(fullSizeBitmap.width() == m_fullSize.width() && fullSizeBitmap.height() == m_fullSize.height());
298 // We early out and do not copy the memory if decoder writes directly to
299 // the memory provided by Skia and the decode was complete.
300 if (canSkipBitmapCopy && isCacheComplete)
301 return ScaledImageFragment::createComplete(m_fullSize, index, fullSizeBitmap);
303 // If the image is progressively decoded we need to return a copy.
304 // This is to avoid future decode operations writing to the same bitmap.
305 // FIXME: Note that discardable allocator is used. This is because the code
306 // is still used in the Android discardable memory path. When this code is
307 // used in the Skia discardable memory path |m_discardableAllocator| is empty.
308 // This is confusing and should be cleaned up when we can deprecate the use
309 // case for Android discardable memory.
311 if (!fullSizeBitmap.copyTo(©Bitmap, fullSizeBitmap.colorType(), m_discardableAllocator.get()))
315 return ScaledImageFragment::createComplete(m_fullSize, index, copyBitmap);
316 return ScaledImageFragment::createPartial(m_fullSize, index, nextGenerationId(), copyBitmap);
319 bool ImageFrameGenerator::hasAlpha(size_t index)
321 MutexLocker lock(m_alphaMutex);
322 if (index < m_hasAlpha.size())
323 return m_hasAlpha[index];