Stop including UnusedParam.h
[WebKit-https.git] / Source / WebCore / platform / graphics / cg / ImageBufferCG.cpp
1 /*
2  * Copyright (C) 2006 Nikolas Zimmermann <zimmermann@kde.org>
3  * Copyright (C) 2008 Apple Inc. All rights reserved.
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
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
16  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
19  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
23  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27
28 #include "config.h"
29 #include "ImageBuffer.h"
30
31 #include "BitmapImage.h"
32 #include "GraphicsContext.h"
33 #include "GraphicsContextCG.h"
34 #include "ImageData.h"
35 #include "MIMETypeRegistry.h"
36 #include <ApplicationServices/ApplicationServices.h>
37 #include <math.h>
38 #include <wtf/Assertions.h>
39 #include <wtf/CheckedArithmetic.h>
40 #include <wtf/MainThread.h>
41 #include <wtf/OwnArrayPtr.h>
42 #include <wtf/RetainPtr.h>
43 #include <wtf/text/Base64.h>
44 #include <wtf/text/WTFString.h>
45
46 #if PLATFORM(MAC)
47 #include "WebCoreSystemInterface.h"
48 #endif
49
50 #if USE(IOSURFACE_CANVAS_BACKING_STORE)
51 #include <IOSurface/IOSurface.h>
52 #endif
53
54 #if !PLATFORM(IOS) && __MAC_OS_X_VERSION_MIN_REQUIRED == 1070
55 #include <wtf/CurrentTime.h>
56 #endif
57
58 using namespace std;
59
60 namespace WebCore {
61
62 #if USE(IOSURFACE_CANVAS_BACKING_STORE)
63 static const int maxIOSurfaceDimension = 4096;
64
65 static RetainPtr<IOSurfaceRef> createIOSurface(const IntSize& size)
66 {
67     unsigned pixelFormat = 'BGRA';
68     unsigned bytesPerElement = 4;
69     int width = size.width();
70     int height = size.height();
71
72     unsigned long bytesPerRow = IOSurfaceAlignProperty(kIOSurfaceBytesPerRow, size.width() * bytesPerElement);
73     if (!bytesPerRow)
74         return 0;
75
76     unsigned long allocSize = IOSurfaceAlignProperty(kIOSurfaceAllocSize, size.height() * bytesPerRow);
77     if (!allocSize)
78         return 0;
79
80     const void *keys[6];
81     const void *values[6];
82     keys[0] = kIOSurfaceWidth;
83     values[0] = CFNumberCreate(0, kCFNumberIntType, &width);
84     keys[1] = kIOSurfaceHeight;
85     values[1] = CFNumberCreate(0, kCFNumberIntType, &height);
86     keys[2] = kIOSurfacePixelFormat;
87     values[2] = CFNumberCreate(0, kCFNumberIntType, &pixelFormat);
88     keys[3] = kIOSurfaceBytesPerElement;
89     values[3] = CFNumberCreate(0, kCFNumberIntType, &bytesPerElement);
90     keys[4] = kIOSurfaceBytesPerRow;
91     values[4] = CFNumberCreate(0, kCFNumberLongType, &bytesPerRow);
92     keys[5] = kIOSurfaceAllocSize;
93     values[5] = CFNumberCreate(0, kCFNumberLongType, &allocSize);
94
95     RetainPtr<CFDictionaryRef> dict = adoptCF(CFDictionaryCreate(0, keys, values, 6, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
96     for (unsigned i = 0; i < 6; i++)
97         CFRelease(values[i]);
98
99     return adoptCF(IOSurfaceCreate(dict.get()));
100 }
101 #endif
102
103 static void releaseImageData(void*, const void* data, size_t)
104 {
105     fastFree(const_cast<void*>(data));
106 }
107
108 ImageBuffer::ImageBuffer(const IntSize& size, float resolutionScale, ColorSpace imageColorSpace, RenderingMode renderingMode, bool& success)
109     : m_data(size) // NOTE: The input here isn't important as ImageBufferDataCG's constructor just ignores it.
110     , m_logicalSize(size)
111     , m_resolutionScale(resolutionScale)
112 {
113     float scaledWidth = ceilf(resolutionScale * size.width());
114     float scaledHeight = ceilf(resolutionScale * size.height());
115
116     // FIXME: Should we automatically use a lower resolution?
117     if (!FloatSize(scaledWidth, scaledHeight).isExpressibleAsIntSize())
118         return;
119
120     m_size = IntSize(scaledWidth, scaledHeight);
121
122     success = false;  // Make early return mean failure.
123     bool accelerateRendering = renderingMode == Accelerated;
124     if (m_size.width() <= 0 || m_size.height() <= 0)
125         return;
126
127     Checked<int, RecordOverflow> width = m_size.width();
128     Checked<int, RecordOverflow> height = m_size.height();
129
130     // Prevent integer overflows
131     m_data.m_bytesPerRow = 4 * width;
132     Checked<size_t, RecordOverflow> numBytes = height * m_data.m_bytesPerRow;
133     if (numBytes.hasOverflowed())
134         return;
135
136 #if USE(IOSURFACE_CANVAS_BACKING_STORE)
137     if (width.unsafeGet() >= maxIOSurfaceDimension || height.unsafeGet() >= maxIOSurfaceDimension)
138         accelerateRendering = false;
139 #else
140     ASSERT(renderingMode == Unaccelerated);
141 #endif
142
143     switch (imageColorSpace) {
144     case ColorSpaceDeviceRGB:
145         m_data.m_colorSpace = deviceRGBColorSpaceRef();
146         break;
147     case ColorSpaceSRGB:
148         m_data.m_colorSpace = sRGBColorSpaceRef();
149         break;
150     case ColorSpaceLinearRGB:
151         m_data.m_colorSpace = linearRGBColorSpaceRef();
152         break;
153     }
154
155     RetainPtr<CGContextRef> cgContext;
156     if (accelerateRendering) {
157 #if USE(IOSURFACE_CANVAS_BACKING_STORE)
158         m_data.m_surface = createIOSurface(m_size);
159         cgContext = adoptCF(wkIOSurfaceContextCreate(m_data.m_surface.get(), width.unsafeGet(), height.unsafeGet(), m_data.m_colorSpace));
160 #endif
161         if (!cgContext)
162             accelerateRendering = false; // If allocation fails, fall back to non-accelerated path.
163     }
164
165     if (!accelerateRendering) {
166         if (!tryFastCalloc(height.unsafeGet(), m_data.m_bytesPerRow.unsafeGet()).getValue(m_data.m_data))
167             return;
168         ASSERT(!(reinterpret_cast<size_t>(m_data.m_data) & 2));
169
170         m_data.m_bitmapInfo = kCGImageAlphaPremultipliedLast;
171         cgContext = adoptCF(CGBitmapContextCreate(m_data.m_data, width.unsafeGet(), height.unsafeGet(), 8, m_data.m_bytesPerRow.unsafeGet(), m_data.m_colorSpace, m_data.m_bitmapInfo));
172         // Create a live image that wraps the data.
173         m_data.m_dataProvider = adoptCF(CGDataProviderCreateWithData(0, m_data.m_data, numBytes.unsafeGet(), releaseImageData));
174     }
175
176     if (!cgContext)
177         return;
178
179     m_context = adoptPtr(new GraphicsContext(cgContext.get()));
180     m_context->applyDeviceScaleFactor(m_resolutionScale);
181     m_context->scale(FloatSize(1, -1));
182     m_context->translate(0, -size.height());
183     m_context->setIsAcceleratedContext(accelerateRendering);
184 #if !PLATFORM(IOS) && __MAC_OS_X_VERSION_MIN_REQUIRED == 1070
185     m_data.m_lastFlushTime = currentTimeMS();
186 #endif
187     success = true;
188 }
189
190 ImageBuffer::~ImageBuffer()
191 {
192 }
193
194 GraphicsContext* ImageBuffer::context() const
195 {
196 #if !PLATFORM(IOS) && __MAC_OS_X_VERSION_MIN_REQUIRED == 1070
197     // Force a flush if last flush was more than 20ms ago
198     if (m_context->isAcceleratedContext()) {
199         double elapsedTime = currentTimeMS() - m_data.m_lastFlushTime;
200         double maxFlushInterval = 20; // in ms
201
202         if (elapsedTime > maxFlushInterval) {
203             CGContextRef context = m_context->platformContext();
204             CGContextFlush(context);
205             m_data.m_lastFlushTime = currentTimeMS();
206         }
207     }
208 #endif
209
210     return m_context.get();
211 }
212
213 PassRefPtr<Image> ImageBuffer::copyImage(BackingStoreCopy copyBehavior, ScaleBehavior scaleBehavior) const
214 {
215     RetainPtr<CGImageRef> image;
216     if (m_resolutionScale == 1 || scaleBehavior == Unscaled)
217         image = copyNativeImage(copyBehavior);
218     else {
219         image = adoptCF(copyNativeImage(DontCopyBackingStore));
220         RetainPtr<CGContextRef> context = adoptCF(CGBitmapContextCreate(0, logicalSize().width(), logicalSize().height(), 8, 4 * logicalSize().width(), deviceRGBColorSpaceRef(), kCGImageAlphaPremultipliedLast));
221         CGContextSetBlendMode(context.get(), kCGBlendModeCopy);
222         CGContextDrawImage(context.get(), CGRectMake(0, 0, logicalSize().width(), logicalSize().height()), image.get());
223         image = CGBitmapContextCreateImage(context.get());
224     }
225
226     if (!image)
227         return 0;
228
229     return BitmapImage::create(image.get());
230 }
231
232 BackingStoreCopy ImageBuffer::fastCopyImageMode()
233 {
234     return DontCopyBackingStore;
235 }
236
237 PassNativeImagePtr ImageBuffer::copyNativeImage(BackingStoreCopy copyBehavior) const
238 {
239     CGImageRef image = 0;
240     if (!m_context->isAcceleratedContext()) {
241         switch (copyBehavior) {
242         case DontCopyBackingStore:
243             image = CGImageCreate(internalSize().width(), internalSize().height(), 8, 32, m_data.m_bytesPerRow.unsafeGet(), m_data.m_colorSpace, m_data.m_bitmapInfo, m_data.m_dataProvider.get(), 0, true, kCGRenderingIntentDefault);
244             break;
245         case CopyBackingStore:
246             image = CGBitmapContextCreateImage(context()->platformContext());
247             break;
248         default:
249             ASSERT_NOT_REACHED();
250             break;
251         }
252     }
253 #if USE(IOSURFACE_CANVAS_BACKING_STORE)
254     else {
255         image = wkIOSurfaceContextCreateImage(context()->platformContext());
256 #if !PLATFORM(IOS) && __MAC_OS_X_VERSION_MIN_REQUIRED == 1070
257         m_data.m_lastFlushTime = currentTimeMS();
258 #endif
259     }
260 #endif
261
262     return image;
263 }
264
265 void ImageBuffer::draw(GraphicsContext* destContext, ColorSpace styleColorSpace, const FloatRect& destRect, const FloatRect& srcRect, CompositeOperator op, BlendMode blendMode, bool useLowQualityScale)
266 {
267     UNUSED_PARAM(useLowQualityScale);
268     ColorSpace colorSpace = (destContext == m_context) ? ColorSpaceDeviceRGB : styleColorSpace;
269
270     RetainPtr<CGImageRef> image;
271     if (destContext == m_context || destContext->isAcceleratedContext())
272         image = adoptCF(copyNativeImage(CopyBackingStore)); // Drawing into our own buffer, need to deep copy.
273     else
274         image = adoptCF(copyNativeImage(DontCopyBackingStore));
275
276     FloatRect adjustedSrcRect = srcRect;
277     adjustedSrcRect.scale(m_resolutionScale, m_resolutionScale);
278     destContext->drawNativeImage(image.get(), internalSize(), colorSpace, destRect, adjustedSrcRect, op, blendMode);
279 }
280
281 void ImageBuffer::drawPattern(GraphicsContext* destContext, const FloatRect& srcRect, const AffineTransform& patternTransform, const FloatPoint& phase, ColorSpace styleColorSpace, CompositeOperator op, const FloatRect& destRect)
282 {
283     FloatRect adjustedSrcRect = srcRect;
284     adjustedSrcRect.scale(m_resolutionScale, m_resolutionScale);
285
286     if (!m_context->isAcceleratedContext()) {
287         if (destContext == m_context || destContext->isAcceleratedContext()) {
288             RefPtr<Image> copy = copyImage(CopyBackingStore); // Drawing into our own buffer, need to deep copy.
289             copy->drawPattern(destContext, adjustedSrcRect, patternTransform, phase, styleColorSpace, op, destRect);
290         } else {
291             RefPtr<Image> imageForRendering = copyImage(DontCopyBackingStore);
292             imageForRendering->drawPattern(destContext, adjustedSrcRect, patternTransform, phase, styleColorSpace, op, destRect);
293         }
294     } else {
295         RefPtr<Image> copy = copyImage(CopyBackingStore);
296         copy->drawPattern(destContext, adjustedSrcRect, patternTransform, phase, styleColorSpace, op, destRect);
297     }
298 }
299
300 void ImageBuffer::clip(GraphicsContext* contextToClip, const FloatRect& rect) const
301 {
302     CGContextRef platformContextToClip = contextToClip->platformContext();
303     // FIXME: This image needs to be grayscale to be used as an alpha mask here.
304     RetainPtr<CGImageRef> image = adoptCF(copyNativeImage(DontCopyBackingStore));
305     CGContextTranslateCTM(platformContextToClip, rect.x(), rect.y() + rect.height());
306     CGContextScaleCTM(platformContextToClip, 1, -1);
307     CGContextClipToMask(platformContextToClip, FloatRect(FloatPoint(), rect.size()), image.get());
308     CGContextScaleCTM(platformContextToClip, 1, -1);
309     CGContextTranslateCTM(platformContextToClip, -rect.x(), -rect.y() - rect.height());
310 }
311
312 PassRefPtr<Uint8ClampedArray> ImageBuffer::getUnmultipliedImageData(const IntRect& rect, CoordinateSystem coordinateSystem) const
313 {
314     if (m_context->isAcceleratedContext()) {
315         CGContextFlush(context()->platformContext());
316 #if !PLATFORM(IOS) && __MAC_OS_X_VERSION_MIN_REQUIRED == 1070
317         m_data.m_lastFlushTime = currentTimeMS();
318 #endif
319     }
320     return m_data.getData(rect, internalSize(), m_context->isAcceleratedContext(), true, coordinateSystem == LogicalCoordinateSystem ? m_resolutionScale : 1);
321 }
322
323 PassRefPtr<Uint8ClampedArray> ImageBuffer::getPremultipliedImageData(const IntRect& rect, CoordinateSystem coordinateSystem) const
324 {
325     if (m_context->isAcceleratedContext()) {
326         CGContextFlush(context()->platformContext());
327 #if !PLATFORM(IOS) && __MAC_OS_X_VERSION_MIN_REQUIRED == 1070
328         m_data.m_lastFlushTime = currentTimeMS();
329 #endif
330     }
331     return m_data.getData(rect, internalSize(), m_context->isAcceleratedContext(), false, coordinateSystem == LogicalCoordinateSystem ? m_resolutionScale : 1);
332 }
333
334 void ImageBuffer::putByteArray(Multiply multiplied, Uint8ClampedArray* source, const IntSize& sourceSize, const IntRect& sourceRect, const IntPoint& destPoint, CoordinateSystem coordinateSystem)
335 {
336     if (!m_context->isAcceleratedContext()) {
337         m_data.putData(source, sourceSize, sourceRect, destPoint, internalSize(), m_context->isAcceleratedContext(), multiplied == Unmultiplied, coordinateSystem == LogicalCoordinateSystem ? m_resolutionScale : 1);
338         return;
339     }
340
341 #if USE(IOSURFACE_CANVAS_BACKING_STORE)
342     // Make a copy of the source to ensure the bits don't change before being drawn
343     IntSize sourceCopySize(sourceRect.width(), sourceRect.height());
344     OwnPtr<ImageBuffer> sourceCopy = ImageBuffer::create(sourceCopySize, 1, ColorSpaceDeviceRGB, Unaccelerated);
345     if (!sourceCopy)
346         return;
347
348     sourceCopy->m_data.putData(source, sourceSize, sourceRect, IntPoint(-sourceRect.x(), -sourceRect.y()), sourceCopy->internalSize(), sourceCopy->context()->isAcceleratedContext(), multiplied == Unmultiplied, 1);
349
350     // Set up context for using drawImage as a direct bit copy
351     CGContextRef destContext = context()->platformContext();
352     CGContextSaveGState(destContext);
353     if (coordinateSystem == LogicalCoordinateSystem)
354         CGContextConcatCTM(destContext, AffineTransform(wkGetUserToBaseCTM(destContext)).inverse());
355     else
356         CGContextConcatCTM(destContext, AffineTransform(CGContextGetCTM(destContext)).inverse());
357     wkCGContextResetClip(destContext);
358     CGContextSetInterpolationQuality(destContext, kCGInterpolationNone);
359     CGContextSetAlpha(destContext, 1.0);
360     CGContextSetBlendMode(destContext, kCGBlendModeCopy);
361     CGContextSetShadowWithColor(destContext, CGSizeZero, 0, 0);
362
363     // Draw the image in CG coordinate space
364     IntPoint destPointInCGCoords(destPoint.x() + sourceRect.x(), (coordinateSystem == LogicalCoordinateSystem ? logicalSize() : internalSize()).height() - (destPoint.y() + sourceRect.y()) - sourceRect.height());
365     IntRect destRectInCGCoords(destPointInCGCoords, sourceCopySize);
366     RetainPtr<CGImageRef> sourceCopyImage = adoptCF(sourceCopy->copyNativeImage());
367     CGContextDrawImage(destContext, destRectInCGCoords, sourceCopyImage.get());
368     CGContextRestoreGState(destContext);
369 #endif
370 }
371
372 static inline CFStringRef jpegUTI()
373 {
374 #if PLATFORM(WIN)
375     static const CFStringRef kUTTypeJPEG = CFSTR("public.jpeg");
376 #endif
377     return kUTTypeJPEG;
378 }
379     
380 static RetainPtr<CFStringRef> utiFromMIMEType(const String& mimeType)
381 {
382 #if PLATFORM(MAC)
383     return adoptCF(UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, mimeType.createCFString().get(), 0));
384 #else
385     ASSERT(isMainThread()); // It is unclear if CFSTR is threadsafe.
386
387     // FIXME: Add Windows support for all the supported UTIs when a way to convert from MIMEType to UTI reliably is found.
388     // For now, only support PNG, JPEG, and GIF. See <rdar://problem/6095286>.
389     static const CFStringRef kUTTypePNG = CFSTR("public.png");
390     static const CFStringRef kUTTypeGIF = CFSTR("com.compuserve.gif");
391
392     if (equalIgnoringCase(mimeType, "image/png"))
393         return kUTTypePNG;
394     if (equalIgnoringCase(mimeType, "image/jpeg"))
395         return jpegUTI();
396     if (equalIgnoringCase(mimeType, "image/gif"))
397         return kUTTypeGIF;
398
399     ASSERT_NOT_REACHED();
400     return kUTTypePNG;
401 #endif
402 }
403
404 static bool CGImageEncodeToData(CGImageRef image, CFStringRef uti, const double* quality, CFMutableDataRef data)
405 {
406     if (!image || !uti || !data)
407         return false;
408
409     RetainPtr<CGImageDestinationRef> destination = adoptCF(CGImageDestinationCreateWithData(data, uti, 1, 0));
410     if (!destination)
411         return false;
412
413     RetainPtr<CFDictionaryRef> imageProperties = 0;
414     if (CFEqual(uti, jpegUTI()) && quality && *quality >= 0.0 && *quality <= 1.0) {
415         // Apply the compression quality to the JPEG image destination.
416         RetainPtr<CFNumberRef> compressionQuality = adoptCF(CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, quality));
417         const void* key = kCGImageDestinationLossyCompressionQuality;
418         const void* value = compressionQuality.get();
419         imageProperties = adoptCF(CFDictionaryCreate(0, &key, &value, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
420     }
421
422     // Setting kCGImageDestinationBackgroundColor to black for JPEG images in imageProperties would save some math
423     // in the calling functions, but it doesn't seem to work.
424
425     CGImageDestinationAddImage(destination.get(), image, imageProperties.get());
426     return CGImageDestinationFinalize(destination.get());
427 }
428
429 static String CGImageToDataURL(CGImageRef image, const String& mimeType, const double* quality)
430 {
431     RetainPtr<CFStringRef> uti = utiFromMIMEType(mimeType);
432     ASSERT(uti);
433
434     RetainPtr<CFMutableDataRef> data = adoptCF(CFDataCreateMutable(kCFAllocatorDefault, 0));
435     if (!CGImageEncodeToData(image, uti.get(), quality, data.get()))
436         return "data:,";
437
438     Vector<char> base64Data;
439     base64Encode(reinterpret_cast<const char*>(CFDataGetBytePtr(data.get())), CFDataGetLength(data.get()), base64Data);
440
441     return "data:" + mimeType + ";base64," + base64Data;
442 }
443
444 String ImageBuffer::toDataURL(const String& mimeType, const double* quality, CoordinateSystem) const
445 {
446     ASSERT(MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(mimeType));
447
448     RetainPtr<CFStringRef> uti = utiFromMIMEType(mimeType);
449     ASSERT(uti);
450
451     RefPtr<Uint8ClampedArray> premultipliedData;
452     RetainPtr<CGImageRef> image;
453
454     if (CFEqual(uti.get(), jpegUTI())) {
455         // JPEGs don't have an alpha channel, so we have to manually composite on top of black.
456         premultipliedData = getPremultipliedImageData(IntRect(IntPoint(0, 0), logicalSize()));
457         if (!premultipliedData)
458             return "data:,";
459
460         RetainPtr<CGDataProviderRef> dataProvider;
461         dataProvider = adoptCF(CGDataProviderCreateWithData(0, premultipliedData->data(), 4 * logicalSize().width() * logicalSize().height(), 0));
462         if (!dataProvider)
463             return "data:,";
464
465         image = adoptCF(CGImageCreate(logicalSize().width(), logicalSize().height(), 8, 32, 4 * logicalSize().width(),
466                                     deviceRGBColorSpaceRef(), kCGBitmapByteOrderDefault | kCGImageAlphaNoneSkipLast,
467                                     dataProvider.get(), 0, false, kCGRenderingIntentDefault));
468     } else if (m_resolutionScale == 1)
469         image = adoptCF(copyNativeImage(CopyBackingStore));
470     else {
471         image = adoptCF(copyNativeImage(DontCopyBackingStore));
472         RetainPtr<CGContextRef> context = adoptCF(CGBitmapContextCreate(0, logicalSize().width(), logicalSize().height(), 8, 4 * logicalSize().width(), deviceRGBColorSpaceRef(), kCGImageAlphaPremultipliedLast));
473         CGContextSetBlendMode(context.get(), kCGBlendModeCopy);
474         CGContextDrawImage(context.get(), CGRectMake(0, 0, logicalSize().width(), logicalSize().height()), image.get());
475         image = adoptCF(CGBitmapContextCreateImage(context.get()));
476     }
477
478     return CGImageToDataURL(image.get(), mimeType, quality);
479 }
480
481 String ImageDataToDataURL(const ImageData& source, const String& mimeType, const double* quality)
482 {
483     ASSERT(MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(mimeType));
484
485     RetainPtr<CFStringRef> uti = utiFromMIMEType(mimeType);
486     ASSERT(uti);
487
488     CGImageAlphaInfo dataAlphaInfo = kCGImageAlphaLast;
489     unsigned char* data = source.data()->data();
490     Vector<uint8_t> premultipliedData;
491
492     if (CFEqual(uti.get(), jpegUTI())) {
493         // JPEGs don't have an alpha channel, so we have to manually composite on top of black.
494         size_t size = 4 * source.width() * source.height();
495         if (!premultipliedData.tryReserveCapacity(size))
496             return "data:,";
497
498         unsigned char *buffer = premultipliedData.data();
499         for (size_t i = 0; i < size; i += 4) {
500             unsigned alpha = data[i + 3];
501             if (alpha != 255) {
502                 buffer[i + 0] = data[i + 0] * alpha / 255;
503                 buffer[i + 1] = data[i + 1] * alpha / 255;
504                 buffer[i + 2] = data[i + 2] * alpha / 255;
505             } else {
506                 buffer[i + 0] = data[i + 0];
507                 buffer[i + 1] = data[i + 1];
508                 buffer[i + 2] = data[i + 2];
509             }
510         }
511
512         dataAlphaInfo = kCGImageAlphaNoneSkipLast; // Ignore the alpha channel.
513         data = premultipliedData.data();
514     }
515
516     RetainPtr<CGDataProviderRef> dataProvider;
517     dataProvider = adoptCF(CGDataProviderCreateWithData(0, data, 4 * source.width() * source.height(), 0));
518     if (!dataProvider)
519         return "data:,";
520
521     RetainPtr<CGImageRef> image;
522     image = adoptCF(CGImageCreate(source.width(), source.height(), 8, 32, 4 * source.width(),
523                                 deviceRGBColorSpaceRef(), kCGBitmapByteOrderDefault | dataAlphaInfo,
524                                 dataProvider.get(), 0, false, kCGRenderingIntentDefault));
525
526     return CGImageToDataURL(image.get(), mimeType, quality);
527 }
528
529 } // namespace WebCore