8b086a0798b646f805f10a3410459473e3addbcd
[WebKit.git] / Source / WebCore / platform / graphics / skia / ImageBufferSkia.cpp
1 /*
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.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are
8  * met:
9  *
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
15  * distribution.
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.
19  *
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.
31  */
32
33 #include "config.h"
34 #include "ImageBuffer.h"
35
36 #include "Base64.h"
37 #include "BitmapImage.h"
38 #include "BitmapImageSingleFrameSkia.h"
39 #include "GrContext.h"
40 #include "GraphicsContext.h"
41 #include "ImageData.h"
42 #include "JPEGImageEncoder.h"
43 #include "MIMETypeRegistry.h"
44 #include "PNGImageEncoder.h"
45 #include "PlatformContextSkia.h"
46 #include "SharedGraphicsContext3D.h"
47 #include "SkColorPriv.h"
48 #include "SkDeferredCanvas.h"
49 #include "SkGpuDevice.h"
50 #include "SkiaUtils.h"
51 #include "WEBPImageEncoder.h"
52
53 #if USE(ACCELERATED_COMPOSITING)
54 #include "Canvas2DLayerChromium.h"
55 #endif
56
57 #include <wtf/text/WTFString.h>
58
59 using namespace std;
60
61 namespace WebCore {
62
63 // We pass a technically-uninitialized canvas to the platform context here since
64 // the canvas initialization completes in ImageBuffer::ImageBuffer. But
65 // PlatformContext doesn't actually need to use the object, and this makes all
66 // the ownership easier to manage.
67 ImageBufferData::ImageBufferData(const IntSize& size)
68     : m_platformContext(0)  // Canvas is set in ImageBuffer constructor.
69 {
70 }
71
72 #if USE(ACCELERATED_COMPOSITING)
73 class AcceleratedDeviceContext : public SkDeferredCanvas::DeviceContext {
74 public:
75     AcceleratedDeviceContext(GraphicsContext3D* context3D, Canvas2DLayerChromium* layer)
76         : m_platformLayer(layer)
77         , m_context3D()
78     {
79         ASSERT(context3D);
80         ASSERT(layer);
81         m_context3D = context3D;
82     }
83
84     virtual void prepareForDraw()
85     {
86         m_platformLayer->layerWillDraw(Canvas2DLayerChromium::WillDrawUnconditionally);
87         m_context3D->makeContextCurrent();
88     }
89
90 private:
91     Canvas2DLayerChromium* m_platformLayer;
92     GraphicsContext3D* m_context3D;
93 };
94 #endif
95
96 static SkCanvas* createAcceleratedCanvas(const IntSize& size, ImageBufferData* data, DeferralMode deferralMode)
97 {
98     RefPtr<GraphicsContext3D> context3D = SharedGraphicsContext3D::get();
99     if (!context3D)
100         return 0;
101     GrContext* gr = context3D->grContext();
102     if (!gr)
103         return 0;
104     gr->resetContext();
105     GrTextureDesc desc;
106     desc.fFlags = kRenderTarget_GrTextureFlagBit;
107     desc.fSampleCnt = 0;
108     desc.fWidth = size.width();
109     desc.fHeight = size.height();
110     desc.fConfig = kSkia8888_PM_GrPixelConfig;
111     SkAutoTUnref<GrTexture> texture(gr->createUncachedTexture(desc, 0, 0));
112     if (!texture.get())
113         return 0;
114     SkCanvas* canvas;
115     SkAutoTUnref<SkDevice> device(new SkGpuDevice(gr, texture.get()));
116 #if USE(ACCELERATED_COMPOSITING)
117     data->m_platformLayer = Canvas2DLayerChromium::create(context3D, size, deferralMode);
118     if (deferralMode == Deferred) {
119         SkAutoTUnref<AcceleratedDeviceContext> deviceContext(new AcceleratedDeviceContext(context3D.get(), data->m_platformLayer.get()));
120         canvas = new SkDeferredCanvas(device.get(), deviceContext.get());
121     } else
122         canvas = new SkCanvas(device.get());
123 #else
124     canvas = new SkCanvas(device.get());
125 #endif
126     data->m_platformContext.setAccelerated(true);
127 #if USE(ACCELERATED_COMPOSITING)
128     data->m_platformLayer->setTextureId(texture.get()->getTextureHandle());
129     data->m_platformLayer->setCanvas(canvas);
130 #endif
131     return canvas;
132 }
133
134 static SkCanvas* createNonPlatformCanvas(const IntSize& size)
135 {
136     SkCanvas* canvas = new SkCanvas();
137     canvas->setDevice(new SkDevice(SkBitmap::kARGB_8888_Config, size.width(), size.height()))->unref();
138     return canvas;
139 }
140
141 ImageBuffer::ImageBuffer(const IntSize& size, float /* resolutionScale */, ColorSpace, RenderingMode renderingMode, DeferralMode deferralMode, bool& success)
142     : m_data(size)
143     , m_size(size)
144     , m_logicalSize(size)
145     , m_resolutionScale(1)
146 {
147     OwnPtr<SkCanvas> canvas;
148
149     if (renderingMode == Accelerated)
150         canvas = adoptPtr(createAcceleratedCanvas(size, &m_data, deferralMode));
151     else if (renderingMode == UnacceleratedNonPlatformBuffer)
152         canvas = adoptPtr(createNonPlatformCanvas(size));
153
154     if (!canvas)
155         canvas = adoptPtr(skia::TryCreateBitmapCanvas(size.width(), size.height(), false));
156
157     if (!canvas) {
158         success = false;
159         return;
160     }
161
162     m_data.m_canvas = canvas.release();
163     m_data.m_platformContext.setCanvas(m_data.m_canvas.get());
164     m_context = adoptPtr(new GraphicsContext(&m_data.m_platformContext));
165     m_context->platformContext()->setDrawingToImageBuffer(true);
166
167     // Make the background transparent. It would be nice if this wasn't
168     // required, but the canvas is currently filled with the magic transparency
169     // color. Can we have another way to manage this?
170     m_data.m_canvas->drawARGB(0, 0, 0, 0, SkXfermode::kClear_Mode);
171
172     success = true;
173 }
174
175 ImageBuffer::~ImageBuffer()
176 {
177 #if USE(ACCELERATED_COMPOSITING)
178     if (m_data.m_platformLayer)
179         m_data.m_platformLayer->setTextureId(0);
180 #endif
181 }
182
183 GraphicsContext* ImageBuffer::context() const
184 {
185 #if USE(ACCELERATED_COMPOSITING)
186     if (m_data.m_platformLayer)
187         m_data.m_platformLayer->layerWillDraw(Canvas2DLayerChromium::WillDrawIfLayerNotDeferred);
188 #endif
189     return m_context.get();
190 }
191
192 PassRefPtr<Image> ImageBuffer::copyImage(BackingStoreCopy copyBehavior) const
193 {
194     return BitmapImageSingleFrameSkia::create(*m_data.m_platformContext.bitmap(), copyBehavior == CopyBackingStore);
195 }
196
197 PlatformLayer* ImageBuffer::platformLayer() const
198 {
199     return m_data.m_platformLayer.get();
200 }
201
202 void ImageBuffer::clip(GraphicsContext* context, const FloatRect& rect) const
203 {
204     context->platformContext()->beginLayerClippedToImage(rect, this);
205 }
206
207 static bool drawNeedsCopy(GraphicsContext* src, GraphicsContext* dst)
208 {
209     return dst->platformContext()->isDeferred() || src == dst;
210 }
211
212 void ImageBuffer::draw(GraphicsContext* context, ColorSpace styleColorSpace, const FloatRect& destRect, const FloatRect& srcRect,
213                        CompositeOperator op, bool useLowQualityScale)
214 {
215     RefPtr<Image> image = BitmapImageSingleFrameSkia::create(*m_data.m_platformContext.bitmap(), drawNeedsCopy(m_context.get(), context));
216     context->drawImage(image.get(), styleColorSpace, destRect, srcRect, op, DoNotRespectImageOrientation, useLowQualityScale);
217 }
218
219 void ImageBuffer::drawPattern(GraphicsContext* context, const FloatRect& srcRect, const AffineTransform& patternTransform,
220                               const FloatPoint& phase, ColorSpace styleColorSpace, CompositeOperator op, const FloatRect& destRect)
221 {
222     RefPtr<Image> image = BitmapImageSingleFrameSkia::create(*m_data.m_platformContext.bitmap(), drawNeedsCopy(m_context.get(), context));
223     image->drawPattern(context, srcRect, patternTransform, phase, styleColorSpace, op, destRect);
224 }
225
226 void ImageBuffer::platformTransformColorSpace(const Vector<int>& lookUpTable)
227 {
228     // FIXME: Disable color space conversions on accelerated canvases (for now).
229     if (m_data.m_platformContext.isAccelerated()) 
230         return;
231
232     const SkBitmap& bitmap = *context()->platformContext()->bitmap();
233     if (bitmap.isNull())
234         return;
235
236     ASSERT(bitmap.config() == SkBitmap::kARGB_8888_Config);
237     SkAutoLockPixels bitmapLock(bitmap);
238     for (int y = 0; y < m_size.height(); ++y) {
239         uint32_t* srcRow = bitmap.getAddr32(0, y);
240         for (int x = 0; x < m_size.width(); ++x) {
241             SkColor color = SkPMColorToColor(srcRow[x]);
242             srcRow[x] = SkPreMultiplyARGB(SkColorGetA(color),
243                                           lookUpTable[SkColorGetR(color)],
244                                           lookUpTable[SkColorGetG(color)],
245                                           lookUpTable[SkColorGetB(color)]);
246         }
247     }
248 }
249
250 template <Multiply multiplied>
251 PassRefPtr<Uint8ClampedArray> getImageData(const IntRect& rect, SkCanvas* canvas,
252                                    const IntSize& size)
253 {
254     float area = 4.0f * rect.width() * rect.height();
255     if (area > static_cast<float>(std::numeric_limits<int>::max()))
256         return 0;
257
258     RefPtr<Uint8ClampedArray> result = Uint8ClampedArray::createUninitialized(rect.width() * rect.height() * 4);
259
260     unsigned char* data = result->data();
261
262     if (rect.x() < 0
263         || rect.y() < 0
264         || rect.maxX() > size.width()
265         || rect.maxY() > size.height())
266         result->zeroFill();
267
268     unsigned destBytesPerRow = 4 * rect.width();
269     SkBitmap destBitmap;
270     destBitmap.setConfig(SkBitmap::kARGB_8888_Config, rect.width(), rect.height(), destBytesPerRow);
271     destBitmap.setPixels(data);
272
273     SkCanvas::Config8888 config8888;
274     if (multiplied == Premultiplied)
275         config8888 = SkCanvas::kRGBA_Premul_Config8888;
276     else
277         config8888 = SkCanvas::kRGBA_Unpremul_Config8888;
278
279     canvas->readPixels(&destBitmap, rect.x(), rect.y(), config8888);
280     return result.release();
281 }
282
283 PassRefPtr<Uint8ClampedArray> ImageBuffer::getUnmultipliedImageData(const IntRect& rect, CoordinateSystem) const
284 {
285     return getImageData<Unmultiplied>(rect, context()->platformContext()->canvas(), m_size);
286 }
287
288 PassRefPtr<Uint8ClampedArray> ImageBuffer::getPremultipliedImageData(const IntRect& rect, CoordinateSystem) const
289 {
290     return getImageData<Premultiplied>(rect, context()->platformContext()->canvas(), m_size);
291 }
292
293 void ImageBuffer::putByteArray(Multiply multiplied, Uint8ClampedArray* source, const IntSize& sourceSize, const IntRect& sourceRect, const IntPoint& destPoint, CoordinateSystem)
294 {
295     SkCanvas* canvas = context()->platformContext()->canvas();
296     ASSERT(sourceRect.width() > 0);
297     ASSERT(sourceRect.height() > 0);
298
299     int originX = sourceRect.x();
300     int destX = destPoint.x() + sourceRect.x();
301     ASSERT(destX >= 0);
302     ASSERT(destX < m_size.width());
303     ASSERT(originX >= 0);
304     ASSERT(originX < sourceRect.maxX());
305
306     int endX = destPoint.x() + sourceRect.maxX();
307     ASSERT(endX <= m_size.width());
308
309     int numColumns = endX - destX;
310
311     int originY = sourceRect.y();
312     int destY = destPoint.y() + sourceRect.y();
313     ASSERT(destY >= 0);
314     ASSERT(destY < m_size.height());
315     ASSERT(originY >= 0);
316     ASSERT(originY < sourceRect.maxY());
317
318     int endY = destPoint.y() + sourceRect.maxY();
319     ASSERT(endY <= m_size.height());
320     int numRows = endY - destY;
321
322     unsigned srcBytesPerRow = 4 * sourceSize.width();
323     SkBitmap srcBitmap;
324     srcBitmap.setConfig(SkBitmap::kARGB_8888_Config, numColumns, numRows, srcBytesPerRow);
325     srcBitmap.setPixels(source->data() + originY * srcBytesPerRow + originX * 4);
326
327     SkCanvas::Config8888 config8888;
328     if (multiplied == Premultiplied)
329         config8888 = SkCanvas::kRGBA_Premul_Config8888;
330     else
331         config8888 = SkCanvas::kRGBA_Unpremul_Config8888;
332
333     canvas->writePixels(srcBitmap, destX, destY, config8888);
334 }
335
336 template <typename T>
337 static bool encodeImage(T& source, const String& mimeType, const double* quality, Vector<char>* output)
338 {
339     Vector<unsigned char>* encodedImage = reinterpret_cast<Vector<unsigned char>*>(output);
340
341     if (mimeType == "image/jpeg") {
342         int compressionQuality = JPEGImageEncoder::DefaultCompressionQuality;
343         if (quality && *quality >= 0.0 && *quality <= 1.0)
344             compressionQuality = static_cast<int>(*quality * 100 + 0.5);
345         if (!JPEGImageEncoder::encode(source, compressionQuality, encodedImage))
346             return false;
347 #if USE(WEBP)
348     } else if (mimeType == "image/webp") {
349         int compressionQuality = WEBPImageEncoder::DefaultCompressionQuality;
350         if (quality && *quality >= 0.0 && *quality <= 1.0)
351             compressionQuality = static_cast<int>(*quality * 100 + 0.5);
352         if (!WEBPImageEncoder::encode(source, compressionQuality, encodedImage))
353             return false;
354 #endif
355     } else {
356         if (!PNGImageEncoder::encode(source, encodedImage))
357             return false;
358         ASSERT(mimeType == "image/png");
359     }
360
361     return true;
362 }
363
364 String ImageBuffer::toDataURL(const String& mimeType, const double* quality, CoordinateSystem) const
365 {
366     ASSERT(MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(mimeType));
367
368     Vector<char> encodedImage;
369     SkDevice* device = context()->platformContext()->canvas()->getDevice();
370     if (!encodeImage(device->accessBitmap(false), mimeType, quality, &encodedImage))
371         return "data:,";
372
373     Vector<char> base64Data;
374     base64Encode(encodedImage, base64Data);
375
376     return "data:" + mimeType + ";base64," + base64Data;
377 }
378
379 String ImageDataToDataURL(const ImageData& imageData, const String& mimeType, const double* quality)
380 {
381     ASSERT(MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(mimeType));
382
383     Vector<char> encodedImage;
384     if (!encodeImage(imageData, mimeType, quality, &encodedImage))
385         return "data:,";
386
387     Vector<char> base64Data;
388     base64Encode(encodedImage, base64Data);
389
390     return "data:" + mimeType + ";base64," + base64Data;
391 }
392
393 } // namespace WebCore