Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / platform / graphics / ImageFrameGenerator.cpp
1 /*
2  * Copyright (C) 2012 Google Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
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.
12  *
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.
24  */
25
26 #include "config.h"
27
28 #include "platform/graphics/ImageFrameGenerator.h"
29
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"
36
37 #include "skia/ext/image_operations.h"
38 #include "third_party/skia/include/core/SkMallocPixelRef.h"
39
40 namespace WebCore {
41
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 {
45 public:
46     ExternalMemoryAllocator(const SkImageInfo& info, void* pixels, size_t rowBytes)
47         : m_info(info)
48         , m_pixels(pixels)
49         , m_rowBytes(rowBytes)
50     {
51     }
52
53     virtual bool allocPixelRef(SkBitmap* dst, SkColorTable* ctable) OVERRIDE
54     {
55         SkImageInfo info;
56         if (!dst->asImageInfo(&info))
57             return false;
58
59         if (info != m_info || m_rowBytes != dst->rowBytes())
60             return false;
61
62         if (!dst->installPixels(m_info, m_pixels, m_rowBytes, 0, 0))
63             return false;
64         dst->lockPixels();
65         return true;
66     }
67
68 private:
69     SkImageInfo m_info;
70     void* m_pixels;
71     size_t m_rowBytes;
72 };
73
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()))
80 {
81     setData(data.get(), allDataReceived);
82 }
83
84 ImageFrameGenerator::~ImageFrameGenerator()
85 {
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);
91 }
92
93 void ImageFrameGenerator::setData(PassRefPtr<SharedBuffer> data, bool allDataReceived)
94 {
95     m_data.setData(data.get(), allDataReceived);
96 }
97
98 void ImageFrameGenerator::copyData(RefPtr<SharedBuffer>* data, bool* allDataReceived)
99 {
100     SharedBuffer* buffer = 0;
101     m_data.data(&buffer, allDataReceived);
102     if (buffer)
103         *data = buffer->copy();
104 }
105
106 const ScaledImageFragment* ImageFrameGenerator::decodeAndScale(const SkISize& scaledSize, size_t index)
107 {
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)
112         return 0;
113
114     const ScaledImageFragment* cachedImage = 0;
115
116     cachedImage = tryToLockCompleteCache(scaledSize, index);
117     if (cachedImage)
118         return cachedImage;
119
120     TRACE_EVENT2("webkit", "ImageFrameGenerator::decodeAndScale", "generator", this, "decodeCount", static_cast<int>(m_decodeCount));
121
122     cachedImage = tryToResumeDecode(scaledSize, index);
123     if (cachedImage)
124         return cachedImage;
125     return 0;
126 }
127
128 bool ImageFrameGenerator::decodeAndScale(const SkImageInfo& info, size_t index, void* pixels, size_t rowBytes)
129 {
130     // This method is called to populate a discardable memory owned by Skia.
131
132     // Prevents concurrent decode or scale operations on the same image data.
133     MutexLocker lock(m_decodeMutex);
134
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);
138
139     if (m_decodeFailedAndEmpty)
140         return 0;
141
142     TRACE_EVENT2("webkit", "ImageFrameGenerator::decodeAndScale", "generator", this, "decodeCount", static_cast<int>(m_decodeCount));
143
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.
147     //
148     // TODO:
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));
155
156     const ScaledImageFragment* cachedImage = tryToResumeDecode(scaledSize, index);
157     if (!cachedImage)
158         return false;
159
160     // Don't keep the allocator because it contains a pointer to memory
161     // that we do not own.
162     m_externalAllocator.clear();
163
164     ASSERT(cachedImage->bitmap().width() == scaledSize.width());
165     ASSERT(cachedImage->bitmap().height() == scaledSize.height());
166
167     bool result = true;
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);
173     return result;
174 }
175
176 const ScaledImageFragment* ImageFrameGenerator::tryToLockCompleteCache(const SkISize& scaledSize, size_t index)
177 {
178     const ScaledImageFragment* cachedImage = 0;
179     if (ImageDecodingStore::instance()->lockCache(this, scaledSize, index, &cachedImage))
180         return cachedImage;
181     return 0;
182 }
183
184 const ScaledImageFragment* ImageFrameGenerator::tryToResumeDecode(const SkISize& scaledSize, size_t index)
185 {
186     TRACE_EVENT1("webkit", "ImageFrameGenerator::tryToResumeDecodeAndScale", "index", static_cast<int>(index));
187
188     ImageDecoder* decoder = 0;
189     const bool resumeDecoding = ImageDecodingStore::instance()->lockDecoder(this, m_fullSize, &decoder);
190     ASSERT(!resumeDecoding || decoder);
191
192     OwnPtr<ScaledImageFragment> fullSizeImage = decode(index, &decoder);
193
194     if (!decoder)
195         return 0;
196
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;
201     if (!resumeDecoding)
202         decoderContainer = adoptPtr(decoder);
203
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();
208
209         if (resumeDecoding)
210             ImageDecodingStore::instance()->unlockDecoder(this, decoder);
211         return 0;
212     }
213
214     const ScaledImageFragment* cachedImage = ImageDecodingStore::instance()->insertAndLockCache(this, fullSizeImage.release());
215
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;
220
221     if (resumeDecoding) {
222         if (removeDecoder)
223             ImageDecodingStore::instance()->removeDecoder(this, decoder);
224         else
225             ImageDecodingStore::instance()->unlockDecoder(this, decoder);
226     } else if (!removeDecoder) {
227         ImageDecodingStore::instance()->insertDecoder(this, decoderContainer.release(), DiscardablePixelRef::isDiscardable(cachedImage->bitmap().pixelRef()));
228     }
229
230     return cachedImage;
231 }
232
233 PassOwnPtr<ScaledImageFragment> ImageFrameGenerator::decode(size_t index, ImageDecoder** decoder)
234 {
235     TRACE_EVENT2("webkit", "ImageFrameGenerator::decode", "width", m_fullSize.width(), "height", m_fullSize.height());
236
237     ASSERT(decoder);
238     SharedBuffer* data = 0;
239     bool allDataReceived = false;
240     bool newDecoder = false;
241     m_data.data(&data, &allDataReceived);
242
243     // Try to create an ImageDecoder if we are not given one.
244     if (!*decoder) {
245         newDecoder = true;
246         if (m_imageDecoderFactory)
247             *decoder = m_imageDecoderFactory->create().leakPtr();
248
249         if (!*decoder)
250             *decoder = ImageDecoder::create(*data, ImageSource::AlphaPremultiplied, ImageSource::GammaAndColorProfileApplied).leakPtr();
251
252         if (!*decoder)
253             return nullptr;
254     }
255
256     // An external memory allocator is used if this variable is true.
257     bool useExternalAllocator = false;
258
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;
266         } else
267             (*decoder)->setMemoryAllocator(m_discardableAllocator.get());
268     }
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);
279
280     if (!frame || frame->status() == ImageFrame::FrameEmpty)
281         return nullptr;
282
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
285     // the latter case.
286     const bool isCacheComplete = frame->status() == ImageFrame::FrameComplete || allDataReceived;
287     SkBitmap fullSizeBitmap = frame->getSkBitmap();
288     if (fullSizeBitmap.isNull())
289         return nullptr;
290
291     {
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;
298         }
299         m_hasAlpha[index] = !fullSizeBitmap.isOpaque();
300     }
301     ASSERT(fullSizeBitmap.width() == m_fullSize.width() && fullSizeBitmap.height() == m_fullSize.height());
302
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);
307
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.
315     SkBitmap copyBitmap;
316     if (!fullSizeBitmap.copyTo(&copyBitmap, fullSizeBitmap.config(), m_discardableAllocator.get()))
317         return nullptr;
318
319     if (isCacheComplete)
320         return ScaledImageFragment::createComplete(m_fullSize, index, copyBitmap);
321     return ScaledImageFragment::createPartial(m_fullSize, index, nextGenerationId(), copyBitmap);
322 }
323
324 bool ImageFrameGenerator::hasAlpha(size_t index)
325 {
326     MutexLocker lock(m_alphaMutex);
327     if (index < m_hasAlpha.size())
328         return m_hasAlpha[index];
329     return true;
330 }
331
332 } // namespace