2 * Copyright (c) 2008, Google Inc. All rights reserved.
3 * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
4 * Copyright (C) 2010 Torch Mobile (Beijing) Co. Ltd. All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are
10 * * Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * * Redistributions in binary form must reproduce the above
13 * copyright notice, this list of conditions and the following disclaimer
14 * in the documentation and/or other materials provided with the
16 * * Neither the name of Google Inc. nor the names of its
17 * contributors may be used to endorse or promote products derived from
18 * this software without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 #include "platform/graphics/ImageBuffer.h"
36 #include "GrContext.h"
37 #include "platform/MIMETypeRegistry.h"
38 #include "platform/geometry/IntRect.h"
39 #include "platform/graphics/BitmapImage.h"
40 #include "platform/graphics/GraphicsContext.h"
41 #include "platform/graphics/GraphicsTypes3D.h"
42 #include "platform/graphics/ImageBufferClient.h"
43 #include "platform/graphics/UnacceleratedImageBufferSurface.h"
44 #include "platform/graphics/gpu/DrawingBuffer.h"
45 #include "platform/graphics/gpu/Extensions3DUtil.h"
46 #include "platform/graphics/skia/NativeImageSkia.h"
47 #include "platform/graphics/skia/SkiaUtils.h"
48 #include "platform/image-encoders/skia/JPEGImageEncoder.h"
49 #include "platform/image-encoders/skia/PNGImageEncoder.h"
50 #include "platform/image-encoders/skia/WEBPImageEncoder.h"
51 #include "public/platform/Platform.h"
52 #include "public/platform/WebExternalTextureMailbox.h"
53 #include "public/platform/WebGraphicsContext3D.h"
54 #include "public/platform/WebGraphicsContext3DProvider.h"
55 #include "third_party/skia/include/core/SkPicture.h"
56 #include "third_party/skia/include/effects/SkTableColorFilter.h"
57 #include "wtf/MathExtras.h"
58 #include "wtf/Vector.h"
59 #include "wtf/text/Base64.h"
60 #include "wtf/text/WTFString.h"
66 PassOwnPtr<ImageBuffer> ImageBuffer::create(PassOwnPtr<ImageBufferSurface> surface)
68 if (!surface->isValid())
70 return adoptPtr(new ImageBuffer(surface));
73 PassOwnPtr<ImageBuffer> ImageBuffer::create(const IntSize& size, OpacityMode opacityMode)
75 OwnPtr<ImageBufferSurface> surface = adoptPtr(new UnacceleratedImageBufferSurface(size, opacityMode));
76 if (!surface->isValid())
78 return adoptPtr(new ImageBuffer(surface.release()));
81 ImageBuffer::ImageBuffer(PassOwnPtr<ImageBufferSurface> surface)
85 if (m_surface->canvas()) {
86 m_context = adoptPtr(new GraphicsContext(m_surface->canvas()));
87 m_context->setCertainlyOpaque(m_surface->opacityMode() == Opaque);
88 m_context->setAccelerated(m_surface->isAccelerated());
90 m_surface->setImageBuffer(this);
93 ImageBuffer::~ImageBuffer()
97 GraphicsContext* ImageBuffer::context() const
99 if (!isSurfaceValid())
101 ASSERT(m_context.get());
102 return m_context.get();
105 const SkBitmap& ImageBuffer::bitmap() const
107 return m_surface->bitmap();
110 bool ImageBuffer::isSurfaceValid() const
112 return m_surface->isValid();
115 bool ImageBuffer::isDirty()
117 return m_client ? m_client->isDirty() : false;
120 void ImageBuffer::didFinalizeFrame()
123 m_client->didFinalizeFrame();
126 void ImageBuffer::finalizeFrame()
128 m_surface->finalizeFrame();
132 bool ImageBuffer::restoreSurface() const
134 return m_surface->isValid() || m_surface->restore();
137 void ImageBuffer::notifySurfaceInvalid()
140 m_client->notifySurfaceInvalid();
143 static SkBitmap deepSkBitmapCopy(const SkBitmap& bitmap)
146 if (!bitmap.deepCopyTo(&tmp))
147 bitmap.copyTo(&tmp, bitmap.colorType());
152 PassRefPtr<Image> ImageBuffer::copyImage(BackingStoreCopy copyBehavior, ScaleBehavior) const
154 if (!isSurfaceValid())
155 return BitmapImage::create(NativeImageSkia::create());
157 const SkBitmap& bitmap = m_surface->bitmap();
158 return BitmapImage::create(NativeImageSkia::create(copyBehavior == CopyBackingStore ? deepSkBitmapCopy(bitmap) : bitmap));
161 BackingStoreCopy ImageBuffer::fastCopyImageMode()
163 return DontCopyBackingStore;
166 WebLayer* ImageBuffer::platformLayer() const
168 return m_surface->layer();
171 bool ImageBuffer::copyToPlatformTexture(WebGraphicsContext3D* context, Platform3DObject texture, GLenum internalFormat, GLenum destType, GLint level, bool premultiplyAlpha, bool flipY)
173 if (!m_surface->isAccelerated() || !platformLayer() || !isSurfaceValid())
176 if (!Extensions3DUtil::canUseCopyTextureCHROMIUM(internalFormat, destType, level))
179 OwnPtr<WebGraphicsContext3DProvider> provider = adoptPtr(Platform::current()->createSharedOffscreenGraphicsContext3DProvider());
182 WebGraphicsContext3D* sharedContext = provider->context3d();
183 if (!sharedContext || !sharedContext->makeContextCurrent())
186 OwnPtr<WebExternalTextureMailbox> mailbox = adoptPtr(new WebExternalTextureMailbox);
188 // Contexts may be in a different share group. We must transfer the texture through a mailbox first
189 sharedContext->genMailboxCHROMIUM(mailbox->name);
190 sharedContext->produceTextureDirectCHROMIUM(getBackingTexture(), GL_TEXTURE_2D, mailbox->name);
191 sharedContext->flush();
193 mailbox->syncPoint = sharedContext->insertSyncPoint();
195 if (!context->makeContextCurrent())
198 context->waitSyncPoint(mailbox->syncPoint);
199 Platform3DObject sourceTexture = context->createAndConsumeTextureCHROMIUM(GL_TEXTURE_2D, mailbox->name);
201 // The canvas is stored in a premultiplied format, so unpremultiply if necessary.
202 context->pixelStorei(GC3D_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM, !premultiplyAlpha);
204 // The canvas is stored in an inverted position, so the flip semantics are reversed.
205 context->pixelStorei(GC3D_UNPACK_FLIP_Y_CHROMIUM, !flipY);
206 context->copyTextureCHROMIUM(GL_TEXTURE_2D, sourceTexture, texture, level, internalFormat, destType);
208 context->pixelStorei(GC3D_UNPACK_FLIP_Y_CHROMIUM, false);
209 context->pixelStorei(GC3D_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM, false);
211 context->deleteTexture(sourceTexture);
214 sharedContext->waitSyncPoint(context->insertSyncPoint());
216 // Undo grContext texture binding changes introduced in this function
217 provider->grContext()->resetContext(kTextureBinding_GrGLBackendState);
222 static bool drawNeedsCopy(GraphicsContext* src, GraphicsContext* dst)
228 Platform3DObject ImageBuffer::getBackingTexture()
230 return m_surface->getBackingTexture();
233 bool ImageBuffer::copyRenderingResultsFromDrawingBuffer(DrawingBuffer* drawingBuffer, bool fromFrontBuffer)
237 OwnPtr<WebGraphicsContext3DProvider> provider = adoptPtr(Platform::current()->createSharedOffscreenGraphicsContext3DProvider());
240 WebGraphicsContext3D* context3D = provider->context3d();
241 Platform3DObject tex = m_surface->getBackingTexture();
242 if (!context3D || !tex)
245 m_surface->invalidateCachedBitmap();
246 return drawingBuffer->copyToPlatformTexture(context3D, tex, GL_RGBA,
247 GL_UNSIGNED_BYTE, 0, true, false, fromFrontBuffer);
250 void ImageBuffer::draw(GraphicsContext* context, const FloatRect& destRect, const FloatRect* srcPtr, CompositeOperator op, WebBlendMode blendMode)
252 if (!isSurfaceValid())
255 FloatRect srcRect = srcPtr ? *srcPtr : FloatRect(FloatPoint(), size());
256 RefPtr<SkPicture> picture = m_surface->getPicture();
258 context->drawPicture(picture.release(), destRect, srcRect, op, blendMode);
262 SkBitmap bitmap = m_surface->bitmap();
263 // For ImageBufferSurface that enables cachedBitmap, Use the cached Bitmap for CPU side usage
264 // if it is available, otherwise generate and use it.
265 if (!context->isAccelerated() && m_surface->isAccelerated() && m_surface->cachedBitmapEnabled() && isSurfaceValid()) {
266 m_surface->updateCachedBitmapIfNeeded();
267 bitmap = m_surface->cachedBitmap();
270 RefPtr<Image> image = BitmapImage::create(NativeImageSkia::create(drawNeedsCopy(m_context.get(), context) ? deepSkBitmapCopy(bitmap) : bitmap));
272 context->drawImage(image.get(), destRect, srcRect, op, blendMode, DoNotRespectImageOrientation);
275 void ImageBuffer::flush()
277 if (m_surface->canvas()) {
278 m_surface->canvas()->flush();
282 void ImageBuffer::drawPattern(GraphicsContext* context, const FloatRect& srcRect, const FloatSize& scale,
283 const FloatPoint& phase, CompositeOperator op, const FloatRect& destRect, WebBlendMode blendMode, const IntSize& repeatSpacing)
285 if (!isSurfaceValid())
288 const SkBitmap& bitmap = m_surface->bitmap();
289 RefPtr<Image> image = BitmapImage::create(NativeImageSkia::create(drawNeedsCopy(m_context.get(), context) ? deepSkBitmapCopy(bitmap) : bitmap));
290 image->drawPattern(context, srcRect, scale, phase, op, destRect, blendMode, repeatSpacing);
293 void ImageBuffer::transformColorSpace(ColorSpace srcColorSpace, ColorSpace dstColorSpace)
295 const uint8_t* lookUpTable = ColorSpaceUtilities::getConversionLUT(dstColorSpace, srcColorSpace);
299 // FIXME: Disable color space conversions on accelerated canvases (for now).
300 if (context()->isAccelerated() || !isSurfaceValid())
303 const SkBitmap& bitmap = m_surface->bitmap();
307 ASSERT(bitmap.colorType() == kN32_SkColorType);
308 IntSize size = m_surface->size();
309 SkAutoLockPixels bitmapLock(bitmap);
310 for (int y = 0; y < size.height(); ++y) {
311 uint32_t* srcRow = bitmap.getAddr32(0, y);
312 for (int x = 0; x < size.width(); ++x) {
313 SkColor color = SkPMColorToColor(srcRow[x]);
314 srcRow[x] = SkPreMultiplyARGB(
316 lookUpTable[SkColorGetR(color)],
317 lookUpTable[SkColorGetG(color)],
318 lookUpTable[SkColorGetB(color)]);
323 PassRefPtr<SkColorFilter> ImageBuffer::createColorSpaceFilter(ColorSpace srcColorSpace,
324 ColorSpace dstColorSpace)
326 const uint8_t* lut = ColorSpaceUtilities::getConversionLUT(dstColorSpace, srcColorSpace);
330 return adoptRef(SkTableColorFilter::CreateARGB(0, lut, lut, lut));
333 PassRefPtr<Uint8ClampedArray> ImageBuffer::getImageData(Multiply multiplied, const IntRect& rect) const
335 if (!isSurfaceValid())
336 return Uint8ClampedArray::create(rect.width() * rect.height() * 4);
338 float area = 4.0f * rect.width() * rect.height();
339 if (area > static_cast<float>(std::numeric_limits<int>::max()))
342 RefPtr<Uint8ClampedArray> result = Uint8ClampedArray::createUninitialized(rect.width() * rect.height() * 4);
346 || rect.maxX() > m_surface->size().width()
347 || rect.maxY() > m_surface->size().height())
350 SkAlphaType alphaType = (multiplied == Premultiplied) ? kPremul_SkAlphaType : kUnpremul_SkAlphaType;
351 SkImageInfo info = SkImageInfo::Make(rect.width(), rect.height(), kRGBA_8888_SkColorType, alphaType);
353 m_surface->willAccessPixels();
354 context()->readPixels(info, result->data(), 4 * rect.width(), rect.x(), rect.y());
355 return result.release();
358 void ImageBuffer::putByteArray(Multiply multiplied, Uint8ClampedArray* source, const IntSize& sourceSize, const IntRect& sourceRect, const IntPoint& destPoint)
360 if (!isSurfaceValid())
363 ASSERT(sourceRect.width() > 0);
364 ASSERT(sourceRect.height() > 0);
366 int originX = sourceRect.x();
367 int destX = destPoint.x() + sourceRect.x();
369 ASSERT(destX < m_surface->size().width());
370 ASSERT(originX >= 0);
371 ASSERT(originX < sourceRect.maxX());
373 int originY = sourceRect.y();
374 int destY = destPoint.y() + sourceRect.y();
376 ASSERT(destY < m_surface->size().height());
377 ASSERT(originY >= 0);
378 ASSERT(originY < sourceRect.maxY());
380 const size_t srcBytesPerRow = 4 * sourceSize.width();
381 const void* srcAddr = source->data() + originY * srcBytesPerRow + originX * 4;
382 SkAlphaType alphaType = (multiplied == Premultiplied) ? kPremul_SkAlphaType : kUnpremul_SkAlphaType;
383 SkImageInfo info = SkImageInfo::Make(sourceRect.width(), sourceRect.height(), kRGBA_8888_SkColorType, alphaType);
385 m_surface->willAccessPixels();
387 context()->writePixels(info, srcAddr, srcBytesPerRow, destX, destY);
390 template <typename T>
391 static bool encodeImage(T& source, const String& mimeType, const double* quality, Vector<char>* output)
393 Vector<unsigned char>* encodedImage = reinterpret_cast<Vector<unsigned char>*>(output);
395 if (mimeType == "image/jpeg") {
396 int compressionQuality = JPEGImageEncoder::DefaultCompressionQuality;
397 if (quality && *quality >= 0.0 && *quality <= 1.0)
398 compressionQuality = static_cast<int>(*quality * 100 + 0.5);
399 if (!JPEGImageEncoder::encode(source, compressionQuality, encodedImage))
401 } else if (mimeType == "image/webp") {
402 int compressionQuality = WEBPImageEncoder::DefaultCompressionQuality;
403 if (quality && *quality >= 0.0 && *quality <= 1.0)
404 compressionQuality = static_cast<int>(*quality * 100 + 0.5);
405 if (!WEBPImageEncoder::encode(source, compressionQuality, encodedImage))
408 if (!PNGImageEncoder::encode(source, encodedImage))
410 ASSERT(mimeType == "image/png");
416 String ImageBuffer::toDataURL(const String& mimeType, const double* quality) const
418 ASSERT(MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(mimeType));
420 Vector<char> encodedImage;
421 if (!isSurfaceValid() || !encodeImage(m_surface->bitmap(), mimeType, quality, &encodedImage))
423 Vector<char> base64Data;
424 base64Encode(encodedImage, base64Data);
426 return "data:" + mimeType + ";base64," + base64Data;
429 String ImageDataToDataURL(const ImageDataBuffer& imageData, const String& mimeType, const double* quality)
431 ASSERT(MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(mimeType));
433 Vector<char> encodedImage;
434 if (!encodeImage(imageData, mimeType, quality, &encodedImage))
437 Vector<char> base64Data;
438 base64Encode(encodedImage, base64Data);
440 return "data:" + mimeType + ";base64," + base64Data;