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