Bitmap.cpp revision f8d8777dddf91c741981b4f795f2fb2b1d81c1b6
1#include "SkBitmap.h"
2#include "SkPixelRef.h"
3#include "SkImageEncoder.h"
4#include "SkColorPriv.h"
5#include "GraphicsJNI.h"
6#include "SkDither.h"
7#include "SkUnPreMultiply.h"
8#include "SkStream.h"
9
10#include <binder/Parcel.h>
11#include "android_os_Parcel.h"
12#include "android_util_Binder.h"
13#include "android_nio_utils.h"
14#include "CreateJavaOutputStreamAdaptor.h"
15
16#include <jni.h>
17
18#include <Caches.h>
19
20#if 0
21    #define TRACE_BITMAP(code)  code
22#else
23    #define TRACE_BITMAP(code)
24#endif
25
26///////////////////////////////////////////////////////////////////////////////
27// Conversions to/from SkColor, for get/setPixels, and the create method, which
28// is basically like setPixels
29
30typedef void (*FromColorProc)(void* dst, const SkColor src[], int width,
31                              int x, int y);
32
33static void FromColor_D32(void* dst, const SkColor src[], int width,
34                          int, int) {
35    SkPMColor* d = (SkPMColor*)dst;
36
37    for (int i = 0; i < width; i++) {
38        *d++ = SkPreMultiplyColor(*src++);
39    }
40}
41
42static void FromColor_D32_Raw(void* dst, const SkColor src[], int width,
43                          int, int) {
44    // SkColor's ordering may be different from SkPMColor
45    if (SK_COLOR_MATCHES_PMCOLOR_BYTE_ORDER) {
46        memcpy(dst, src, width * sizeof(SkColor));
47        return;
48    }
49
50    // order isn't same, repack each pixel manually
51    SkPMColor* d = (SkPMColor*)dst;
52    for (int i = 0; i < width; i++) {
53        SkColor c = *src++;
54        *d++ = SkPackARGB32NoCheck(SkColorGetA(c), SkColorGetR(c),
55                                   SkColorGetG(c), SkColorGetB(c));
56    }
57}
58
59static void FromColor_D565(void* dst, const SkColor src[], int width,
60                           int x, int y) {
61    uint16_t* d = (uint16_t*)dst;
62
63    DITHER_565_SCAN(y);
64    for (int stop = x + width; x < stop; x++) {
65        SkColor c = *src++;
66        *d++ = SkDitherRGBTo565(SkColorGetR(c), SkColorGetG(c), SkColorGetB(c),
67                                DITHER_VALUE(x));
68    }
69}
70
71static void FromColor_D4444(void* dst, const SkColor src[], int width,
72                            int x, int y) {
73    SkPMColor16* d = (SkPMColor16*)dst;
74
75    DITHER_4444_SCAN(y);
76    for (int stop = x + width; x < stop; x++) {
77        SkPMColor pmc = SkPreMultiplyColor(*src++);
78        *d++ = SkDitherARGB32To4444(pmc, DITHER_VALUE(x));
79//        *d++ = SkPixel32ToPixel4444(pmc);
80    }
81}
82
83static void FromColor_D4444_Raw(void* dst, const SkColor src[], int width,
84                            int x, int y) {
85    SkPMColor16* d = (SkPMColor16*)dst;
86
87    DITHER_4444_SCAN(y);
88    for (int stop = x + width; x < stop; x++) {
89        SkColor c = *src++;
90
91        // SkPMColor is used because the ordering is ARGB32, even though the target actually premultiplied
92        SkPMColor pmc = SkPackARGB32NoCheck(SkColorGetA(c), SkColorGetR(c),
93                                            SkColorGetG(c), SkColorGetB(c));
94        *d++ = SkDitherARGB32To4444(pmc, DITHER_VALUE(x));
95//        *d++ = SkPixel32ToPixel4444(pmc);
96    }
97}
98
99// can return NULL
100static FromColorProc ChooseFromColorProc(SkBitmap::Config config, bool isPremultiplied) {
101    switch (config) {
102        case SkBitmap::kARGB_8888_Config:
103            return isPremultiplied ? FromColor_D32 : FromColor_D32_Raw;
104        case SkBitmap::kARGB_4444_Config:
105            return isPremultiplied ? FromColor_D4444 : FromColor_D4444_Raw;
106        case SkBitmap::kRGB_565_Config:
107            return FromColor_D565;
108        default:
109            break;
110    }
111    return NULL;
112}
113
114bool GraphicsJNI::SetPixels(JNIEnv* env, jintArray srcColors, int srcOffset, int srcStride,
115        int x, int y, int width, int height,
116        const SkBitmap& dstBitmap, bool isPremultiplied) {
117    SkAutoLockPixels alp(dstBitmap);
118    void* dst = dstBitmap.getPixels();
119    FromColorProc proc = ChooseFromColorProc(dstBitmap.config(), isPremultiplied);
120
121    if (NULL == dst || NULL == proc) {
122        return false;
123    }
124
125    const jint* array = env->GetIntArrayElements(srcColors, NULL);
126    const SkColor* src = (const SkColor*)array + srcOffset;
127
128    // reset to to actual choice from caller
129    dst = dstBitmap.getAddr(x, y);
130    // now copy/convert each scanline
131    for (int y = 0; y < height; y++) {
132        proc(dst, src, width, x, y);
133        src += srcStride;
134        dst = (char*)dst + dstBitmap.rowBytes();
135    }
136
137    dstBitmap.notifyPixelsChanged();
138
139    env->ReleaseIntArrayElements(srcColors, const_cast<jint*>(array),
140                                 JNI_ABORT);
141    return true;
142}
143
144//////////////////// ToColor procs
145
146typedef void (*ToColorProc)(SkColor dst[], const void* src, int width,
147                            SkColorTable*);
148
149static void ToColor_S32_Alpha(SkColor dst[], const void* src, int width,
150                              SkColorTable*) {
151    SkASSERT(width > 0);
152    const SkPMColor* s = (const SkPMColor*)src;
153    do {
154        *dst++ = SkUnPreMultiply::PMColorToColor(*s++);
155    } while (--width != 0);
156}
157
158static void ToColor_S32_Raw(SkColor dst[], const void* src, int width,
159                              SkColorTable*) {
160    SkASSERT(width > 0);
161    const SkPMColor* s = (const SkPMColor*)src;
162    do {
163        SkPMColor c = *s++;
164        *dst++ = SkColorSetARGB(SkGetPackedA32(c), SkGetPackedR32(c),
165                                SkGetPackedG32(c), SkGetPackedB32(c));
166    } while (--width != 0);
167}
168
169static void ToColor_S32_Opaque(SkColor dst[], const void* src, int width,
170                               SkColorTable*) {
171    SkASSERT(width > 0);
172    const SkPMColor* s = (const SkPMColor*)src;
173    do {
174        SkPMColor c = *s++;
175        *dst++ = SkColorSetRGB(SkGetPackedR32(c), SkGetPackedG32(c),
176                               SkGetPackedB32(c));
177    } while (--width != 0);
178}
179
180static void ToColor_S4444_Alpha(SkColor dst[], const void* src, int width,
181                                SkColorTable*) {
182    SkASSERT(width > 0);
183    const SkPMColor16* s = (const SkPMColor16*)src;
184    do {
185        *dst++ = SkUnPreMultiply::PMColorToColor(SkPixel4444ToPixel32(*s++));
186    } while (--width != 0);
187}
188
189static void ToColor_S4444_Raw(SkColor dst[], const void* src, int width,
190                                SkColorTable*) {
191    SkASSERT(width > 0);
192    const SkPMColor16* s = (const SkPMColor16*)src;
193    do {
194        SkPMColor c = SkPixel4444ToPixel32(*s++);
195        *dst++ = SkColorSetARGB(SkGetPackedA32(c), SkGetPackedR32(c),
196                                SkGetPackedG32(c), SkGetPackedB32(c));
197    } while (--width != 0);
198}
199
200static void ToColor_S4444_Opaque(SkColor dst[], const void* src, int width,
201                                 SkColorTable*) {
202    SkASSERT(width > 0);
203    const SkPMColor16* s = (const SkPMColor16*)src;
204    do {
205        SkPMColor c = SkPixel4444ToPixel32(*s++);
206        *dst++ = SkColorSetRGB(SkGetPackedR32(c), SkGetPackedG32(c),
207                               SkGetPackedB32(c));
208    } while (--width != 0);
209}
210
211static void ToColor_S565(SkColor dst[], const void* src, int width,
212                         SkColorTable*) {
213    SkASSERT(width > 0);
214    const uint16_t* s = (const uint16_t*)src;
215    do {
216        uint16_t c = *s++;
217        *dst++ =  SkColorSetRGB(SkPacked16ToR32(c), SkPacked16ToG32(c),
218                                SkPacked16ToB32(c));
219    } while (--width != 0);
220}
221
222static void ToColor_SI8_Alpha(SkColor dst[], const void* src, int width,
223                              SkColorTable* ctable) {
224    SkASSERT(width > 0);
225    const uint8_t* s = (const uint8_t*)src;
226    const SkPMColor* colors = ctable->lockColors();
227    do {
228        *dst++ = SkUnPreMultiply::PMColorToColor(colors[*s++]);
229    } while (--width != 0);
230    ctable->unlockColors();
231}
232
233static void ToColor_SI8_Raw(SkColor dst[], const void* src, int width,
234                              SkColorTable* ctable) {
235    SkASSERT(width > 0);
236    const uint8_t* s = (const uint8_t*)src;
237    const SkPMColor* colors = ctable->lockColors();
238    do {
239        SkPMColor c = colors[*s++];
240        *dst++ = SkColorSetARGB(SkGetPackedA32(c), SkGetPackedR32(c),
241                                SkGetPackedG32(c), SkGetPackedB32(c));
242    } while (--width != 0);
243    ctable->unlockColors();
244}
245
246static void ToColor_SI8_Opaque(SkColor dst[], const void* src, int width,
247                               SkColorTable* ctable) {
248    SkASSERT(width > 0);
249    const uint8_t* s = (const uint8_t*)src;
250    const SkPMColor* colors = ctable->lockColors();
251    do {
252        SkPMColor c = colors[*s++];
253        *dst++ = SkColorSetRGB(SkGetPackedR32(c), SkGetPackedG32(c),
254                               SkGetPackedB32(c));
255    } while (--width != 0);
256    ctable->unlockColors();
257}
258
259// can return NULL
260static ToColorProc ChooseToColorProc(const SkBitmap& src, bool isPremultiplied) {
261    switch (src.config()) {
262        case SkBitmap::kARGB_8888_Config:
263            if (src.isOpaque()) return ToColor_S32_Opaque;
264            return isPremultiplied ? ToColor_S32_Alpha : ToColor_S32_Raw;
265        case SkBitmap::kARGB_4444_Config:
266            if (src.isOpaque()) return ToColor_S4444_Opaque;
267            return isPremultiplied ? ToColor_S4444_Alpha : ToColor_S4444_Raw;
268        case SkBitmap::kRGB_565_Config:
269            return ToColor_S565;
270        case SkBitmap::kIndex8_Config:
271            if (src.getColorTable() == NULL) {
272                return NULL;
273            }
274            if (src.isOpaque()) return ToColor_SI8_Opaque;
275            return isPremultiplied ? ToColor_SI8_Raw : ToColor_SI8_Alpha;
276        default:
277            break;
278    }
279    return NULL;
280}
281
282///////////////////////////////////////////////////////////////////////////////
283///////////////////////////////////////////////////////////////////////////////
284
285static int getPremulBitmapCreateFlags(bool isMutable) {
286    int flags = GraphicsJNI::kBitmapCreateFlag_Premultiplied;
287    if (isMutable) flags |= GraphicsJNI::kBitmapCreateFlag_Mutable;
288    return flags;
289}
290
291static jobject Bitmap_creator(JNIEnv* env, jobject, jintArray jColors,
292                              jint offset, jint stride, jint width, jint height,
293                              jint configHandle, jboolean isMutable) {
294    SkBitmap::Config config = static_cast<SkBitmap::Config>(configHandle);
295    if (NULL != jColors) {
296        size_t n = env->GetArrayLength(jColors);
297        if (n < SkAbs32(stride) * (size_t)height) {
298            doThrowAIOOBE(env);
299            return NULL;
300        }
301    }
302
303    // ARGB_4444 is a deprecated format, convert automatically to 8888
304    if (config == SkBitmap::kARGB_4444_Config) {
305        config = SkBitmap::kARGB_8888_Config;
306    }
307
308    SkBitmap bitmap;
309    bitmap.setConfig(config, width, height);
310
311    jbyteArray buff = GraphicsJNI::allocateJavaPixelRef(env, &bitmap, NULL);
312    if (NULL == buff) {
313        return NULL;
314    }
315
316    if (jColors != NULL) {
317        GraphicsJNI::SetPixels(env, jColors, offset, stride,
318                0, 0, width, height, bitmap, true);
319    }
320
321    return GraphicsJNI::createBitmap(env, new SkBitmap(bitmap), buff,
322            getPremulBitmapCreateFlags(isMutable), NULL, NULL);
323}
324
325static jobject Bitmap_copy(JNIEnv* env, jobject, jlong srcHandle,
326                           jint dstConfigHandle, jboolean isMutable) {
327    const SkBitmap* src = reinterpret_cast<SkBitmap*>(srcHandle);
328    SkBitmap::Config dstConfig = static_cast<SkBitmap::Config>(dstConfigHandle);
329    SkBitmap            result;
330    JavaPixelAllocator  allocator(env);
331
332    if (!src->copyTo(&result, dstConfig, &allocator)) {
333        return NULL;
334    }
335    return GraphicsJNI::createBitmap(env, new SkBitmap(result), allocator.getStorageObj(),
336            getPremulBitmapCreateFlags(isMutable), NULL, NULL);
337}
338
339static void Bitmap_destructor(JNIEnv* env, jobject, jlong bitmapHandle) {
340    SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
341#ifdef USE_OPENGL_RENDERER
342    if (android::uirenderer::Caches::hasInstance()) {
343        android::uirenderer::Caches::getInstance().resourceCache.destructor(bitmap);
344        return;
345    }
346#endif // USE_OPENGL_RENDERER
347    delete bitmap;
348}
349
350static jboolean Bitmap_recycle(JNIEnv* env, jobject, jlong bitmapHandle) {
351    SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
352#ifdef USE_OPENGL_RENDERER
353    if (android::uirenderer::Caches::hasInstance()) {
354        bool result;
355        result = android::uirenderer::Caches::getInstance().resourceCache.recycle(bitmap);
356        return result ? JNI_TRUE : JNI_FALSE;
357    }
358#endif // USE_OPENGL_RENDERER
359    bitmap->setPixels(NULL, NULL);
360    return JNI_TRUE;
361}
362
363static void Bitmap_reconfigure(JNIEnv* env, jobject clazz, jlong bitmapHandle,
364        jint width, jint height, jint configHandle, jint allocSize) {
365    SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
366    SkBitmap::Config config = static_cast<SkBitmap::Config>(configHandle);
367    if (width * height * SkBitmap::ComputeBytesPerPixel(config) > allocSize) {
368        // done in native as there's no way to get BytesPerPixel in Java
369        doThrowIAE(env, "Bitmap not large enough to support new configuration");
370        return;
371    }
372    SkPixelRef* ref = bitmap->pixelRef();
373    SkSafeRef(ref);
374    bitmap->setConfig(config, width, height);
375    bitmap->setPixelRef(ref);
376
377    // notifyPixelsChanged will increment the generation ID even though the actual pixel data
378    // hasn't been touched. This signals the renderer that the bitmap (including width, height,
379    // and config) has changed.
380    ref->notifyPixelsChanged();
381    SkSafeUnref(ref);
382}
383
384// These must match the int values in Bitmap.java
385enum JavaEncodeFormat {
386    kJPEG_JavaEncodeFormat = 0,
387    kPNG_JavaEncodeFormat = 1,
388    kWEBP_JavaEncodeFormat = 2
389};
390
391static jboolean Bitmap_compress(JNIEnv* env, jobject clazz, jlong bitmapHandle,
392                                jint format, jint quality,
393                                jobject jstream, jbyteArray jstorage) {
394    SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
395    SkImageEncoder::Type fm;
396
397    switch (format) {
398    case kJPEG_JavaEncodeFormat:
399        fm = SkImageEncoder::kJPEG_Type;
400        break;
401    case kPNG_JavaEncodeFormat:
402        fm = SkImageEncoder::kPNG_Type;
403        break;
404    case kWEBP_JavaEncodeFormat:
405        fm = SkImageEncoder::kWEBP_Type;
406        break;
407    default:
408        return JNI_FALSE;
409    }
410
411    bool success = false;
412    if (NULL != bitmap) {
413        SkAutoLockPixels alp(*bitmap);
414
415        if (NULL == bitmap->getPixels()) {
416            return JNI_FALSE;
417        }
418
419        SkWStream* strm = CreateJavaOutputStreamAdaptor(env, jstream, jstorage);
420        if (NULL == strm) {
421            return JNI_FALSE;
422        }
423
424        SkImageEncoder* encoder = SkImageEncoder::Create(fm);
425        if (NULL != encoder) {
426            success = encoder->encodeStream(strm, *bitmap, quality);
427            delete encoder;
428        }
429        delete strm;
430    }
431    return success ? JNI_TRUE : JNI_FALSE;
432}
433
434static void Bitmap_erase(JNIEnv* env, jobject, jlong bitmapHandle, jint color) {
435    SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
436    bitmap->eraseColor(color);
437}
438
439static jint Bitmap_rowBytes(JNIEnv* env, jobject, jlong bitmapHandle) {
440    SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
441    return static_cast<jint>(bitmap->rowBytes());
442}
443
444static jint Bitmap_config(JNIEnv* env, jobject, jlong bitmapHandle) {
445    SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
446    return static_cast<jint>(bitmap->config());
447}
448
449static jint Bitmap_getGenerationId(JNIEnv* env, jobject, jlong bitmapHandle) {
450    SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
451    return static_cast<jint>(bitmap->getGenerationID());
452}
453
454static jboolean Bitmap_hasAlpha(JNIEnv* env, jobject, jlong bitmapHandle) {
455    SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
456    return !bitmap->isOpaque() ? JNI_TRUE : JNI_FALSE;
457}
458
459static void Bitmap_setAlphaAndPremultiplied(JNIEnv* env, jobject, jlong bitmapHandle,
460                                            jboolean hasAlpha, jboolean isPremul) {
461    SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
462    if (!hasAlpha) {
463        bitmap->setAlphaType(kOpaque_SkAlphaType);
464    } else if (isPremul) {
465        bitmap->setAlphaType(kPremul_SkAlphaType);
466    } else {
467        bitmap->setAlphaType(kUnpremul_SkAlphaType);
468    }
469}
470
471static jboolean Bitmap_hasMipMap(JNIEnv* env, jobject, jlong bitmapHandle) {
472    SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
473    return bitmap->hasHardwareMipMap() ? JNI_TRUE : JNI_FALSE;
474}
475
476static void Bitmap_setHasMipMap(JNIEnv* env, jobject, jlong bitmapHandle,
477                                jboolean hasMipMap) {
478    SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
479    bitmap->setHasHardwareMipMap(hasMipMap);
480}
481
482///////////////////////////////////////////////////////////////////////////////
483
484static jobject Bitmap_createFromParcel(JNIEnv* env, jobject, jobject parcel) {
485    if (parcel == NULL) {
486        SkDebugf("-------- unparcel parcel is NULL\n");
487        return NULL;
488    }
489
490    android::Parcel* p = android::parcelForJavaObject(env, parcel);
491
492    const bool              isMutable = p->readInt32() != 0;
493    const SkBitmap::Config  config = (SkBitmap::Config)p->readInt32();
494    const int               width = p->readInt32();
495    const int               height = p->readInt32();
496    const int               rowBytes = p->readInt32();
497    const int               density = p->readInt32();
498
499    if (SkBitmap::kARGB_8888_Config != config &&
500            SkBitmap::kRGB_565_Config != config &&
501            SkBitmap::kARGB_4444_Config != config &&
502            SkBitmap::kIndex8_Config != config &&
503            SkBitmap::kA8_Config != config) {
504        SkDebugf("Bitmap_createFromParcel unknown config: %d\n", config);
505        return NULL;
506    }
507
508    SkBitmap* bitmap = new SkBitmap;
509
510    bitmap->setConfig(config, width, height, rowBytes);
511
512    SkColorTable* ctable = NULL;
513    if (config == SkBitmap::kIndex8_Config) {
514        int count = p->readInt32();
515        if (count > 0) {
516            size_t size = count * sizeof(SkPMColor);
517            const SkPMColor* src = (const SkPMColor*)p->readInplace(size);
518            ctable = new SkColorTable(src, count);
519        }
520    }
521
522    jbyteArray buffer = GraphicsJNI::allocateJavaPixelRef(env, bitmap, ctable);
523    if (NULL == buffer) {
524        SkSafeUnref(ctable);
525        delete bitmap;
526        return NULL;
527    }
528
529    SkSafeUnref(ctable);
530
531    size_t size = bitmap->getSize();
532
533    android::Parcel::ReadableBlob blob;
534    android::status_t status = p->readBlob(size, &blob);
535    if (status) {
536        doThrowRE(env, "Could not read bitmap from parcel blob.");
537        delete bitmap;
538        return NULL;
539    }
540
541    bitmap->lockPixels();
542    memcpy(bitmap->getPixels(), blob.data(), size);
543    bitmap->unlockPixels();
544
545    blob.release();
546
547    return GraphicsJNI::createBitmap(env, bitmap, buffer, getPremulBitmapCreateFlags(isMutable),
548            NULL, NULL, density);
549}
550
551static jboolean Bitmap_writeToParcel(JNIEnv* env, jobject,
552                                     jlong bitmapHandle,
553                                     jboolean isMutable, jint density,
554                                     jobject parcel) {
555    const SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
556    if (parcel == NULL) {
557        SkDebugf("------- writeToParcel null parcel\n");
558        return JNI_FALSE;
559    }
560
561    android::Parcel* p = android::parcelForJavaObject(env, parcel);
562
563    p->writeInt32(isMutable);
564    p->writeInt32(bitmap->config());
565    p->writeInt32(bitmap->width());
566    p->writeInt32(bitmap->height());
567    p->writeInt32(bitmap->rowBytes());
568    p->writeInt32(density);
569
570    if (bitmap->config() == SkBitmap::kIndex8_Config) {
571        SkColorTable* ctable = bitmap->getColorTable();
572        if (ctable != NULL) {
573            int count = ctable->count();
574            p->writeInt32(count);
575            memcpy(p->writeInplace(count * sizeof(SkPMColor)),
576                   ctable->lockColors(), count * sizeof(SkPMColor));
577            ctable->unlockColors();
578        } else {
579            p->writeInt32(0);   // indicate no ctable
580        }
581    }
582
583    size_t size = bitmap->getSize();
584
585    android::Parcel::WritableBlob blob;
586    android::status_t status = p->writeBlob(size, &blob);
587    if (status) {
588        doThrowRE(env, "Could not write bitmap to parcel blob.");
589        return JNI_FALSE;
590    }
591
592    bitmap->lockPixels();
593    const void* pSrc =  bitmap->getPixels();
594    if (pSrc == NULL) {
595        memset(blob.data(), 0, size);
596    } else {
597        memcpy(blob.data(), pSrc, size);
598    }
599    bitmap->unlockPixels();
600
601    blob.release();
602    return JNI_TRUE;
603}
604
605static jobject Bitmap_extractAlpha(JNIEnv* env, jobject clazz,
606                                   jlong srcHandle, jlong paintHandle,
607                                   jintArray offsetXY) {
608    const SkBitmap* src = reinterpret_cast<SkBitmap*>(srcHandle);
609    const SkPaint* paint = reinterpret_cast<SkPaint*>(paintHandle);
610    SkIPoint  offset;
611    SkBitmap* dst = new SkBitmap;
612    JavaPixelAllocator allocator(env);
613
614    src->extractAlpha(dst, paint, &allocator, &offset);
615    // If Skia can't allocate pixels for destination bitmap, it resets
616    // it, that is set its pixels buffer to NULL, and zero width and height.
617    if (dst->getPixels() == NULL && src->getPixels() != NULL) {
618        delete dst;
619        doThrowOOME(env, "failed to allocate pixels for alpha");
620        return NULL;
621    }
622    if (offsetXY != 0 && env->GetArrayLength(offsetXY) >= 2) {
623        int* array = env->GetIntArrayElements(offsetXY, NULL);
624        array[0] = offset.fX;
625        array[1] = offset.fY;
626        env->ReleaseIntArrayElements(offsetXY, array, 0);
627    }
628
629    return GraphicsJNI::createBitmap(env, dst, allocator.getStorageObj(),
630            GraphicsJNI::kBitmapCreateFlag_Mutable, NULL, NULL);
631}
632
633///////////////////////////////////////////////////////////////////////////////
634
635static jint Bitmap_getPixel(JNIEnv* env, jobject, jlong bitmapHandle,
636        jint x, jint y, jboolean isPremultiplied) {
637    const SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
638    SkAutoLockPixels alp(*bitmap);
639
640    ToColorProc proc = ChooseToColorProc(*bitmap, isPremultiplied);
641    if (NULL == proc) {
642        return 0;
643    }
644    const void* src = bitmap->getAddr(x, y);
645    if (NULL == src) {
646        return 0;
647    }
648
649    SkColor dst[1];
650    proc(dst, src, 1, bitmap->getColorTable());
651    return static_cast<jint>(dst[0]);
652}
653
654static void Bitmap_getPixels(JNIEnv* env, jobject, jlong bitmapHandle,
655        jintArray pixelArray, jint offset, jint stride,
656        jint x, jint y, jint width, jint height, jboolean isPremultiplied) {
657    const SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
658    SkAutoLockPixels alp(*bitmap);
659
660    ToColorProc proc = ChooseToColorProc(*bitmap, isPremultiplied);
661    if (NULL == proc) {
662        return;
663    }
664    const void* src = bitmap->getAddr(x, y);
665    if (NULL == src) {
666        return;
667    }
668
669    SkColorTable* ctable = bitmap->getColorTable();
670    jint* dst = env->GetIntArrayElements(pixelArray, NULL);
671    SkColor* d = (SkColor*)dst + offset;
672    while (--height >= 0) {
673        proc(d, src, width, ctable);
674        d += stride;
675        src = (void*)((const char*)src + bitmap->rowBytes());
676    }
677    env->ReleaseIntArrayElements(pixelArray, dst, 0);
678}
679
680///////////////////////////////////////////////////////////////////////////////
681
682static void Bitmap_setPixel(JNIEnv* env, jobject, jlong bitmapHandle,
683        jint x, jint y, jint colorHandle, jboolean isPremultiplied) {
684    const SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
685    SkColor color = static_cast<SkColor>(colorHandle);
686    SkAutoLockPixels alp(*bitmap);
687    if (NULL == bitmap->getPixels()) {
688        return;
689    }
690
691    FromColorProc proc = ChooseFromColorProc(bitmap->config(), isPremultiplied);
692    if (NULL == proc) {
693        return;
694    }
695
696    proc(bitmap->getAddr(x, y), &color, 1, x, y);
697    bitmap->notifyPixelsChanged();
698}
699
700static void Bitmap_setPixels(JNIEnv* env, jobject, jlong bitmapHandle,
701        jintArray pixelArray, jint offset, jint stride,
702        jint x, jint y, jint width, jint height, jboolean isPremultiplied) {
703    const SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
704    GraphicsJNI::SetPixels(env, pixelArray, offset, stride,
705            x, y, width, height, *bitmap, isPremultiplied);
706}
707
708static void Bitmap_copyPixelsToBuffer(JNIEnv* env, jobject,
709                                      jlong bitmapHandle, jobject jbuffer) {
710    const SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
711    SkAutoLockPixels alp(*bitmap);
712    const void* src = bitmap->getPixels();
713
714    if (NULL != src) {
715        android::AutoBufferPointer abp(env, jbuffer, JNI_TRUE);
716
717        // the java side has already checked that buffer is large enough
718        memcpy(abp.pointer(), src, bitmap->getSize());
719    }
720}
721
722static void Bitmap_copyPixelsFromBuffer(JNIEnv* env, jobject,
723                                        jlong bitmapHandle, jobject jbuffer) {
724    SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
725    SkAutoLockPixels alp(*bitmap);
726    void* dst = bitmap->getPixels();
727
728    if (NULL != dst) {
729        android::AutoBufferPointer abp(env, jbuffer, JNI_FALSE);
730        // the java side has already checked that buffer is large enough
731        memcpy(dst, abp.pointer(), bitmap->getSize());
732        bitmap->notifyPixelsChanged();
733    }
734}
735
736static jboolean Bitmap_sameAs(JNIEnv* env, jobject, jlong bm0Handle,
737                              jlong bm1Handle) {
738    const SkBitmap* bm0 = reinterpret_cast<SkBitmap*>(bm0Handle);
739    const SkBitmap* bm1 = reinterpret_cast<SkBitmap*>(bm1Handle);
740    if (bm0->width() != bm1->width() ||
741        bm0->height() != bm1->height() ||
742        bm0->config() != bm1->config()) {
743        return JNI_FALSE;
744    }
745
746    SkAutoLockPixels alp0(*bm0);
747    SkAutoLockPixels alp1(*bm1);
748
749    // if we can't load the pixels, return false
750    if (NULL == bm0->getPixels() || NULL == bm1->getPixels()) {
751        return JNI_FALSE;
752    }
753
754    if (bm0->config() == SkBitmap::kIndex8_Config) {
755        SkColorTable* ct0 = bm0->getColorTable();
756        SkColorTable* ct1 = bm1->getColorTable();
757        if (NULL == ct0 || NULL == ct1) {
758            return JNI_FALSE;
759        }
760        if (ct0->count() != ct1->count()) {
761            return JNI_FALSE;
762        }
763
764        SkAutoLockColors alc0(ct0);
765        SkAutoLockColors alc1(ct1);
766        const size_t size = ct0->count() * sizeof(SkPMColor);
767        if (memcmp(alc0.colors(), alc1.colors(), size) != 0) {
768            return JNI_FALSE;
769        }
770    }
771
772    // now compare each scanline. We can't do the entire buffer at once,
773    // since we don't care about the pixel values that might extend beyond
774    // the width (since the scanline might be larger than the logical width)
775    const int h = bm0->height();
776    const size_t size = bm0->width() * bm0->bytesPerPixel();
777    for (int y = 0; y < h; y++) {
778        if (memcmp(bm0->getAddr(0, y), bm1->getAddr(0, y), size) != 0) {
779            return JNI_FALSE;
780        }
781    }
782    return JNI_TRUE;
783}
784
785static void Bitmap_prepareToDraw(JNIEnv* env, jobject, jlong bitmapHandle) {
786    SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
787    bitmap->lockPixels();
788    bitmap->unlockPixels();
789}
790
791///////////////////////////////////////////////////////////////////////////////
792
793#include <android_runtime/AndroidRuntime.h>
794
795static JNINativeMethod gBitmapMethods[] = {
796    {   "nativeCreate",             "([IIIIIIZ)Landroid/graphics/Bitmap;",
797        (void*)Bitmap_creator },
798    {   "nativeCopy",               "(JIZ)Landroid/graphics/Bitmap;",
799        (void*)Bitmap_copy },
800    {   "nativeDestructor",         "(J)V", (void*)Bitmap_destructor },
801    {   "nativeRecycle",            "(J)Z", (void*)Bitmap_recycle },
802    {   "nativeReconfigure",        "(JIIII)V", (void*)Bitmap_reconfigure },
803    {   "nativeCompress",           "(JIILjava/io/OutputStream;[B)Z",
804        (void*)Bitmap_compress },
805    {   "nativeErase",              "(JI)V", (void*)Bitmap_erase },
806    {   "nativeRowBytes",           "(J)I", (void*)Bitmap_rowBytes },
807    {   "nativeConfig",             "(J)I", (void*)Bitmap_config },
808    {   "nativeHasAlpha",           "(J)Z", (void*)Bitmap_hasAlpha },
809    {   "nativeSetAlphaAndPremultiplied", "(JZZ)V", (void*)Bitmap_setAlphaAndPremultiplied},
810    {   "nativeHasMipMap",          "(J)Z", (void*)Bitmap_hasMipMap },
811    {   "nativeSetHasMipMap",       "(JZ)V", (void*)Bitmap_setHasMipMap },
812    {   "nativeCreateFromParcel",
813        "(Landroid/os/Parcel;)Landroid/graphics/Bitmap;",
814        (void*)Bitmap_createFromParcel },
815    {   "nativeWriteToParcel",      "(JZILandroid/os/Parcel;)Z",
816        (void*)Bitmap_writeToParcel },
817    {   "nativeExtractAlpha",       "(JJ[I)Landroid/graphics/Bitmap;",
818        (void*)Bitmap_extractAlpha },
819    {   "nativeGenerationId",       "(J)I", (void*)Bitmap_getGenerationId },
820    {   "nativeGetPixel",           "(JIIZ)I", (void*)Bitmap_getPixel },
821    {   "nativeGetPixels",          "(J[IIIIIIIZ)V", (void*)Bitmap_getPixels },
822    {   "nativeSetPixel",           "(JIIIZ)V", (void*)Bitmap_setPixel },
823    {   "nativeSetPixels",          "(J[IIIIIIIZ)V", (void*)Bitmap_setPixels },
824    {   "nativeCopyPixelsToBuffer", "(JLjava/nio/Buffer;)V",
825                                            (void*)Bitmap_copyPixelsToBuffer },
826    {   "nativeCopyPixelsFromBuffer", "(JLjava/nio/Buffer;)V",
827                                            (void*)Bitmap_copyPixelsFromBuffer },
828    {   "nativeSameAs",             "(JJ)Z", (void*)Bitmap_sameAs },
829    {   "nativePrepareToDraw",      "(J)V", (void*)Bitmap_prepareToDraw },
830};
831
832#define kClassPathName  "android/graphics/Bitmap"
833
834int register_android_graphics_Bitmap(JNIEnv* env)
835{
836    return android::AndroidRuntime::registerNativeMethods(env, kClassPathName,
837                                gBitmapMethods, SK_ARRAY_COUNT(gBitmapMethods));
838}
839