Graphics.cpp revision 4508218850faedea95371188da587b6734f5f3da
1#define LOG_TAG "GraphicsJNI"
2
3#include <unistd.h>
4#include <sys/mman.h>
5
6#include "jni.h"
7#include "JNIHelp.h"
8#include "GraphicsJNI.h"
9
10#include "SkCanvas.h"
11#include "SkDevice.h"
12#include "SkMath.h"
13#include "SkRegion.h"
14#include <android_runtime/AndroidRuntime.h>
15#include <cutils/ashmem.h>
16#include <hwui/Canvas.h>
17
18#include <Caches.h>
19#include <TextureCache.h>
20
21void doThrowNPE(JNIEnv* env) {
22    jniThrowNullPointerException(env, NULL);
23}
24
25void doThrowAIOOBE(JNIEnv* env) {
26    jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", NULL);
27}
28
29void doThrowRE(JNIEnv* env, const char* msg) {
30    jniThrowRuntimeException(env, msg);
31}
32
33void doThrowIAE(JNIEnv* env, const char* msg) {
34    jniThrowException(env, "java/lang/IllegalArgumentException", msg);
35}
36
37void doThrowISE(JNIEnv* env, const char* msg) {
38    jniThrowException(env, "java/lang/IllegalStateException", msg);
39}
40
41void doThrowOOME(JNIEnv* env, const char* msg) {
42    jniThrowException(env, "java/lang/OutOfMemoryError", msg);
43}
44
45void doThrowIOE(JNIEnv* env, const char* msg) {
46    jniThrowException(env, "java/io/IOException", msg);
47}
48
49bool GraphicsJNI::hasException(JNIEnv *env) {
50    if (env->ExceptionCheck() != 0) {
51        ALOGE("*** Uncaught exception returned from Java call!\n");
52        env->ExceptionDescribe();
53        return true;
54    }
55    return false;
56}
57
58///////////////////////////////////////////////////////////////////////////////
59
60AutoJavaFloatArray::AutoJavaFloatArray(JNIEnv* env, jfloatArray array,
61                                       int minLength, JNIAccess access)
62: fEnv(env), fArray(array), fPtr(NULL), fLen(0) {
63    SkASSERT(env);
64    if (array) {
65        fLen = env->GetArrayLength(array);
66        if (fLen < minLength) {
67            sk_throw();
68        }
69        fPtr = env->GetFloatArrayElements(array, NULL);
70    }
71    fReleaseMode = (access == kRO_JNIAccess) ? JNI_ABORT : 0;
72}
73
74AutoJavaFloatArray::~AutoJavaFloatArray() {
75    if (fPtr) {
76        fEnv->ReleaseFloatArrayElements(fArray, fPtr, fReleaseMode);
77    }
78}
79
80AutoJavaIntArray::AutoJavaIntArray(JNIEnv* env, jintArray array,
81                                       int minLength)
82: fEnv(env), fArray(array), fPtr(NULL), fLen(0) {
83    SkASSERT(env);
84    if (array) {
85        fLen = env->GetArrayLength(array);
86        if (fLen < minLength) {
87            sk_throw();
88        }
89        fPtr = env->GetIntArrayElements(array, NULL);
90    }
91}
92
93AutoJavaIntArray::~AutoJavaIntArray() {
94    if (fPtr) {
95        fEnv->ReleaseIntArrayElements(fArray, fPtr, 0);
96    }
97}
98
99AutoJavaShortArray::AutoJavaShortArray(JNIEnv* env, jshortArray array,
100                                       int minLength, JNIAccess access)
101: fEnv(env), fArray(array), fPtr(NULL), fLen(0) {
102    SkASSERT(env);
103    if (array) {
104        fLen = env->GetArrayLength(array);
105        if (fLen < minLength) {
106            sk_throw();
107        }
108        fPtr = env->GetShortArrayElements(array, NULL);
109    }
110    fReleaseMode = (access == kRO_JNIAccess) ? JNI_ABORT : 0;
111}
112
113AutoJavaShortArray::~AutoJavaShortArray() {
114    if (fPtr) {
115        fEnv->ReleaseShortArrayElements(fArray, fPtr, fReleaseMode);
116    }
117}
118
119AutoJavaByteArray::AutoJavaByteArray(JNIEnv* env, jbyteArray array,
120                                       int minLength)
121: fEnv(env), fArray(array), fPtr(NULL), fLen(0) {
122    SkASSERT(env);
123    if (array) {
124        fLen = env->GetArrayLength(array);
125        if (fLen < minLength) {
126            sk_throw();
127        }
128        fPtr = env->GetByteArrayElements(array, NULL);
129    }
130}
131
132AutoJavaByteArray::~AutoJavaByteArray() {
133    if (fPtr) {
134        fEnv->ReleaseByteArrayElements(fArray, fPtr, 0);
135    }
136}
137
138///////////////////////////////////////////////////////////////////////////////
139
140static jclass   gRect_class;
141static jfieldID gRect_leftFieldID;
142static jfieldID gRect_topFieldID;
143static jfieldID gRect_rightFieldID;
144static jfieldID gRect_bottomFieldID;
145
146static jclass   gRectF_class;
147static jfieldID gRectF_leftFieldID;
148static jfieldID gRectF_topFieldID;
149static jfieldID gRectF_rightFieldID;
150static jfieldID gRectF_bottomFieldID;
151
152static jclass   gPoint_class;
153static jfieldID gPoint_xFieldID;
154static jfieldID gPoint_yFieldID;
155
156static jclass   gPointF_class;
157static jfieldID gPointF_xFieldID;
158static jfieldID gPointF_yFieldID;
159
160static jclass   gBitmap_class;
161static jfieldID gBitmap_nativePtr;
162static jmethodID gBitmap_constructorMethodID;
163static jmethodID gBitmap_reinitMethodID;
164static jmethodID gBitmap_getAllocationByteCountMethodID;
165
166static jclass   gBitmapConfig_class;
167static jfieldID gBitmapConfig_nativeInstanceID;
168
169static jclass   gBitmapRegionDecoder_class;
170static jmethodID gBitmapRegionDecoder_constructorMethodID;
171
172static jclass   gCanvas_class;
173static jfieldID gCanvas_nativeInstanceID;
174
175static jclass   gPicture_class;
176static jfieldID gPicture_nativeInstanceID;
177
178static jclass   gRegion_class;
179static jfieldID gRegion_nativeInstanceID;
180static jmethodID gRegion_constructorMethodID;
181
182static jclass    gByte_class;
183static jobject   gVMRuntime;
184static jclass    gVMRuntime_class;
185static jmethodID gVMRuntime_newNonMovableArray;
186static jmethodID gVMRuntime_addressOf;
187
188///////////////////////////////////////////////////////////////////////////////
189
190void GraphicsJNI::get_jrect(JNIEnv* env, jobject obj, int* L, int* T, int* R, int* B)
191{
192    SkASSERT(env->IsInstanceOf(obj, gRect_class));
193
194    *L = env->GetIntField(obj, gRect_leftFieldID);
195    *T = env->GetIntField(obj, gRect_topFieldID);
196    *R = env->GetIntField(obj, gRect_rightFieldID);
197    *B = env->GetIntField(obj, gRect_bottomFieldID);
198}
199
200void GraphicsJNI::set_jrect(JNIEnv* env, jobject obj, int L, int T, int R, int B)
201{
202    SkASSERT(env->IsInstanceOf(obj, gRect_class));
203
204    env->SetIntField(obj, gRect_leftFieldID, L);
205    env->SetIntField(obj, gRect_topFieldID, T);
206    env->SetIntField(obj, gRect_rightFieldID, R);
207    env->SetIntField(obj, gRect_bottomFieldID, B);
208}
209
210SkIRect* GraphicsJNI::jrect_to_irect(JNIEnv* env, jobject obj, SkIRect* ir)
211{
212    SkASSERT(env->IsInstanceOf(obj, gRect_class));
213
214    ir->set(env->GetIntField(obj, gRect_leftFieldID),
215            env->GetIntField(obj, gRect_topFieldID),
216            env->GetIntField(obj, gRect_rightFieldID),
217            env->GetIntField(obj, gRect_bottomFieldID));
218    return ir;
219}
220
221void GraphicsJNI::irect_to_jrect(const SkIRect& ir, JNIEnv* env, jobject obj)
222{
223    SkASSERT(env->IsInstanceOf(obj, gRect_class));
224
225    env->SetIntField(obj, gRect_leftFieldID, ir.fLeft);
226    env->SetIntField(obj, gRect_topFieldID, ir.fTop);
227    env->SetIntField(obj, gRect_rightFieldID, ir.fRight);
228    env->SetIntField(obj, gRect_bottomFieldID, ir.fBottom);
229}
230
231SkRect* GraphicsJNI::jrectf_to_rect(JNIEnv* env, jobject obj, SkRect* r)
232{
233    SkASSERT(env->IsInstanceOf(obj, gRectF_class));
234
235    r->set(env->GetFloatField(obj, gRectF_leftFieldID),
236           env->GetFloatField(obj, gRectF_topFieldID),
237           env->GetFloatField(obj, gRectF_rightFieldID),
238           env->GetFloatField(obj, gRectF_bottomFieldID));
239    return r;
240}
241
242SkRect* GraphicsJNI::jrect_to_rect(JNIEnv* env, jobject obj, SkRect* r)
243{
244    SkASSERT(env->IsInstanceOf(obj, gRect_class));
245
246    r->set(SkIntToScalar(env->GetIntField(obj, gRect_leftFieldID)),
247           SkIntToScalar(env->GetIntField(obj, gRect_topFieldID)),
248           SkIntToScalar(env->GetIntField(obj, gRect_rightFieldID)),
249           SkIntToScalar(env->GetIntField(obj, gRect_bottomFieldID)));
250    return r;
251}
252
253void GraphicsJNI::rect_to_jrectf(const SkRect& r, JNIEnv* env, jobject obj)
254{
255    SkASSERT(env->IsInstanceOf(obj, gRectF_class));
256
257    env->SetFloatField(obj, gRectF_leftFieldID, SkScalarToFloat(r.fLeft));
258    env->SetFloatField(obj, gRectF_topFieldID, SkScalarToFloat(r.fTop));
259    env->SetFloatField(obj, gRectF_rightFieldID, SkScalarToFloat(r.fRight));
260    env->SetFloatField(obj, gRectF_bottomFieldID, SkScalarToFloat(r.fBottom));
261}
262
263SkIPoint* GraphicsJNI::jpoint_to_ipoint(JNIEnv* env, jobject obj, SkIPoint* point)
264{
265    SkASSERT(env->IsInstanceOf(obj, gPoint_class));
266
267    point->set(env->GetIntField(obj, gPoint_xFieldID),
268               env->GetIntField(obj, gPoint_yFieldID));
269    return point;
270}
271
272void GraphicsJNI::ipoint_to_jpoint(const SkIPoint& ir, JNIEnv* env, jobject obj)
273{
274    SkASSERT(env->IsInstanceOf(obj, gPoint_class));
275
276    env->SetIntField(obj, gPoint_xFieldID, ir.fX);
277    env->SetIntField(obj, gPoint_yFieldID, ir.fY);
278}
279
280SkPoint* GraphicsJNI::jpointf_to_point(JNIEnv* env, jobject obj, SkPoint* point)
281{
282    SkASSERT(env->IsInstanceOf(obj, gPointF_class));
283
284    point->set(env->GetIntField(obj, gPointF_xFieldID),
285               env->GetIntField(obj, gPointF_yFieldID));
286    return point;
287}
288
289void GraphicsJNI::point_to_jpointf(const SkPoint& r, JNIEnv* env, jobject obj)
290{
291    SkASSERT(env->IsInstanceOf(obj, gPointF_class));
292
293    env->SetFloatField(obj, gPointF_xFieldID, SkScalarToFloat(r.fX));
294    env->SetFloatField(obj, gPointF_yFieldID, SkScalarToFloat(r.fY));
295}
296
297// This enum must keep these int values, to match the int values
298// in the java Bitmap.Config enum.
299enum LegacyBitmapConfig {
300    kNo_LegacyBitmapConfig          = 0,
301    kA8_LegacyBitmapConfig          = 1,
302    kIndex8_LegacyBitmapConfig      = 2,
303    kRGB_565_LegacyBitmapConfig     = 3,
304    kARGB_4444_LegacyBitmapConfig   = 4,
305    kARGB_8888_LegacyBitmapConfig   = 5,
306
307    kLastEnum_LegacyBitmapConfig = kARGB_8888_LegacyBitmapConfig
308};
309
310jint GraphicsJNI::colorTypeToLegacyBitmapConfig(SkColorType colorType) {
311    switch (colorType) {
312        case kN32_SkColorType:
313            return kARGB_8888_LegacyBitmapConfig;
314        case kARGB_4444_SkColorType:
315            return kARGB_4444_LegacyBitmapConfig;
316        case kRGB_565_SkColorType:
317            return kRGB_565_LegacyBitmapConfig;
318        case kIndex_8_SkColorType:
319            return kIndex8_LegacyBitmapConfig;
320        case kAlpha_8_SkColorType:
321            return kA8_LegacyBitmapConfig;
322        case kUnknown_SkColorType:
323        default:
324            break;
325    }
326    return kNo_LegacyBitmapConfig;
327}
328
329SkColorType GraphicsJNI::legacyBitmapConfigToColorType(jint legacyConfig) {
330    const uint8_t gConfig2ColorType[] = {
331        kUnknown_SkColorType,
332        kAlpha_8_SkColorType,
333        kIndex_8_SkColorType,
334        kRGB_565_SkColorType,
335        kARGB_4444_SkColorType,
336        kN32_SkColorType
337    };
338
339    if (legacyConfig < 0 || legacyConfig > kLastEnum_LegacyBitmapConfig) {
340        legacyConfig = kNo_LegacyBitmapConfig;
341    }
342    return static_cast<SkColorType>(gConfig2ColorType[legacyConfig]);
343}
344
345android::Bitmap* GraphicsJNI::getBitmap(JNIEnv* env, jobject bitmap) {
346    SkASSERT(env);
347    SkASSERT(bitmap);
348    SkASSERT(env->IsInstanceOf(bitmap, gBitmap_class));
349    jlong bitmapHandle = env->GetLongField(bitmap, gBitmap_nativePtr);
350    android::Bitmap* b = reinterpret_cast<android::Bitmap*>(bitmapHandle);
351    SkASSERT(b);
352    return b;
353}
354
355void GraphicsJNI::getSkBitmap(JNIEnv* env, jobject bitmap, SkBitmap* outBitmap) {
356    getBitmap(env, bitmap)->getSkBitmap(outBitmap);
357}
358
359SkPixelRef* GraphicsJNI::refSkPixelRef(JNIEnv* env, jobject bitmap) {
360    return getBitmap(env, bitmap)->refPixelRef();
361}
362
363SkColorType GraphicsJNI::getNativeBitmapColorType(JNIEnv* env, jobject jconfig) {
364    SkASSERT(env);
365    if (NULL == jconfig) {
366        return kUnknown_SkColorType;
367    }
368    SkASSERT(env->IsInstanceOf(jconfig, gBitmapConfig_class));
369    int c = env->GetIntField(jconfig, gBitmapConfig_nativeInstanceID);
370    return legacyBitmapConfigToColorType(c);
371}
372
373android::Canvas* GraphicsJNI::getNativeCanvas(JNIEnv* env, jobject canvas) {
374    SkASSERT(env);
375    SkASSERT(canvas);
376    SkASSERT(env->IsInstanceOf(canvas, gCanvas_class));
377    jlong canvasHandle = env->GetLongField(canvas, gCanvas_nativeInstanceID);
378    if (!canvasHandle) {
379        return NULL;
380    }
381    return reinterpret_cast<android::Canvas*>(canvasHandle);
382}
383
384SkRegion* GraphicsJNI::getNativeRegion(JNIEnv* env, jobject region)
385{
386    SkASSERT(env);
387    SkASSERT(region);
388    SkASSERT(env->IsInstanceOf(region, gRegion_class));
389    jlong regionHandle = env->GetLongField(region, gRegion_nativeInstanceID);
390    SkRegion* r = reinterpret_cast<SkRegion*>(regionHandle);
391    SkASSERT(r);
392    return r;
393}
394
395///////////////////////////////////////////////////////////////////////////////////////////
396
397// Assert that bitmap's SkAlphaType is consistent with isPremultiplied.
398static void assert_premultiplied(const SkImageInfo& info, bool isPremultiplied) {
399    // kOpaque_SkAlphaType and kIgnore_SkAlphaType mean that isPremultiplied is
400    // irrelevant. This just tests to ensure that the SkAlphaType is not
401    // opposite of isPremultiplied.
402    if (isPremultiplied) {
403        SkASSERT(info.alphaType() != kUnpremul_SkAlphaType);
404    } else {
405        SkASSERT(info.alphaType() != kPremul_SkAlphaType);
406    }
407}
408
409jobject GraphicsJNI::createBitmap(JNIEnv* env, android::Bitmap* bitmap,
410        int bitmapCreateFlags, jbyteArray ninePatchChunk, jobject ninePatchInsets,
411        int density) {
412    bool isMutable = bitmapCreateFlags & kBitmapCreateFlag_Mutable;
413    bool isPremultiplied = bitmapCreateFlags & kBitmapCreateFlag_Premultiplied;
414    // The caller needs to have already set the alpha type properly, so the
415    // native SkBitmap stays in sync with the Java Bitmap.
416    assert_premultiplied(bitmap->info(), isPremultiplied);
417
418    jobject obj = env->NewObject(gBitmap_class, gBitmap_constructorMethodID,
419            reinterpret_cast<jlong>(bitmap), bitmap->width(), bitmap->height(), density, isMutable,
420            isPremultiplied, ninePatchChunk, ninePatchInsets);
421    hasException(env); // For the side effect of logging.
422    return obj;
423}
424
425void GraphicsJNI::reinitBitmap(JNIEnv* env, jobject javaBitmap, const SkImageInfo& info,
426        bool isPremultiplied)
427{
428    // The caller needs to have already set the alpha type properly, so the
429    // native SkBitmap stays in sync with the Java Bitmap.
430    assert_premultiplied(info, isPremultiplied);
431
432    env->CallVoidMethod(javaBitmap, gBitmap_reinitMethodID,
433            info.width(), info.height(), isPremultiplied);
434}
435
436int GraphicsJNI::getBitmapAllocationByteCount(JNIEnv* env, jobject javaBitmap)
437{
438    return env->CallIntMethod(javaBitmap, gBitmap_getAllocationByteCountMethodID);
439}
440
441jobject GraphicsJNI::createBitmapRegionDecoder(JNIEnv* env, SkBitmapRegionDecoder* bitmap)
442{
443    SkASSERT(bitmap != NULL);
444
445    jobject obj = env->NewObject(gBitmapRegionDecoder_class,
446            gBitmapRegionDecoder_constructorMethodID,
447            reinterpret_cast<jlong>(bitmap));
448    hasException(env); // For the side effect of logging.
449    return obj;
450}
451
452jobject GraphicsJNI::createRegion(JNIEnv* env, SkRegion* region)
453{
454    SkASSERT(region != NULL);
455    jobject obj = env->NewObject(gRegion_class, gRegion_constructorMethodID,
456                                 reinterpret_cast<jlong>(region), 0);
457    hasException(env); // For the side effect of logging.
458    return obj;
459}
460
461static JNIEnv* vm2env(JavaVM* vm)
462{
463    JNIEnv* env = NULL;
464    if (vm->GetEnv((void**)&env, JNI_VERSION_1_4) != JNI_OK || NULL == env)
465    {
466        SkDebugf("------- [%p] vm->GetEnv() failed\n", vm);
467        sk_throw();
468    }
469    return env;
470}
471
472///////////////////////////////////////////////////////////////////////////////
473
474static bool computeAllocationSize(const SkBitmap& bitmap, size_t* size) {
475    int32_t rowBytes32 = SkToS32(bitmap.rowBytes());
476    int64_t bigSize = (int64_t)bitmap.height() * rowBytes32;
477    if (rowBytes32 < 0 || !sk_64_isS32(bigSize)) {
478        return false; // allocation will be too large
479    }
480
481    *size = sk_64_asS32(bigSize);
482    return true;
483}
484
485android::Bitmap* GraphicsJNI::allocateHeapPixelRef(SkBitmap* bitmap, SkColorTable* ctable) {
486    const SkImageInfo& info = bitmap->info();
487    if (info.colorType() == kUnknown_SkColorType) {
488        LOG_ALWAYS_FATAL("unknown bitmap configuration");
489        return nullptr;
490    }
491
492    size_t size;
493    if (!computeAllocationSize(*bitmap, &size)) {
494        return nullptr;
495    }
496
497    // we must respect the rowBytes value already set on the bitmap instead of
498    // attempting to compute our own.
499    const size_t rowBytes = bitmap->rowBytes();
500
501    void* addr = calloc(size, 1);
502    if (!addr) {
503        return nullptr;
504    }
505
506    android::Bitmap* wrapper = new android::Bitmap(addr, size, info, rowBytes, ctable);
507    wrapper->getSkBitmap(bitmap);
508    // since we're already allocated, we lockPixels right away
509    // HeapAllocator behaves this way too
510    bitmap->lockPixels();
511
512    return wrapper;
513}
514
515struct AndroidPixelRefContext {
516    int32_t stableID;
517};
518
519static void allocatePixelsReleaseProc(void* ptr, void* ctx) {
520    AndroidPixelRefContext* context = (AndroidPixelRefContext*)ctx;
521    if (android::uirenderer::Caches::hasInstance()) {
522         android::uirenderer::Caches::getInstance().textureCache.releaseTexture(context->stableID);
523    }
524
525    sk_free(ptr);
526    delete context;
527}
528
529bool GraphicsJNI::allocatePixels(JNIEnv* env, SkBitmap* bitmap, SkColorTable* ctable) {
530    const SkImageInfo& info = bitmap->info();
531    if (info.colorType() == kUnknown_SkColorType) {
532        doThrowIAE(env, "unknown bitmap configuration");
533        return NULL;
534    }
535
536    size_t size;
537    if (!computeAllocationSize(*bitmap, &size)) {
538        return false;
539    }
540
541    // we must respect the rowBytes value already set on the bitmap instead of
542    // attempting to compute our own.
543    const size_t rowBytes = bitmap->rowBytes();
544
545    void* addr = sk_malloc_flags(size, 0);
546    if (NULL == addr) {
547        return false;
548    }
549
550    AndroidPixelRefContext* context = new AndroidPixelRefContext;
551    SkMallocPixelRef* pr = SkMallocPixelRef::NewWithProc(info, rowBytes, ctable, addr,
552                                                         &allocatePixelsReleaseProc, context);
553    if (!pr) {
554        delete context;
555        return false;
556    }
557
558    // set the stableID in the context so that it can be used later in
559    // allocatePixelsReleaseProc to remove the texture from the cache.
560    context->stableID = pr->getStableID();
561
562    bitmap->setPixelRef(pr)->unref();
563    // since we're already allocated, we can lockPixels right away
564    bitmap->lockPixels();
565
566    return true;
567}
568
569android::Bitmap* GraphicsJNI::allocateAshmemPixelRef(JNIEnv* env, SkBitmap* bitmap,
570                                                     SkColorTable* ctable) {
571    int fd;
572
573    const SkImageInfo& info = bitmap->info();
574    if (info.colorType() == kUnknown_SkColorType) {
575        doThrowIAE(env, "unknown bitmap configuration");
576        return nullptr;
577    }
578
579    size_t size;
580    if (!computeAllocationSize(*bitmap, &size)) {
581        return nullptr;
582    }
583
584    // we must respect the rowBytes value already set on the bitmap instead of
585    // attempting to compute our own.
586    const size_t rowBytes = bitmap->rowBytes();
587
588    // Create new ashmem region with read/write priv
589    fd = ashmem_create_region("bitmap", size);
590    if (fd < 0) {
591        return nullptr;
592    }
593
594    void* addr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
595    if (addr == MAP_FAILED) {
596        close(fd);
597        return nullptr;
598    }
599
600    if (ashmem_set_prot_region(fd, PROT_READ) < 0) {
601        munmap(addr, size);
602        close(fd);
603        return nullptr;
604    }
605
606    android::Bitmap* wrapper = new android::Bitmap(addr, fd, size, info, rowBytes, ctable);
607    wrapper->getSkBitmap(bitmap);
608    // since we're already allocated, we lockPixels right away
609    // HeapAllocator behaves this way too
610    bitmap->lockPixels();
611
612    return wrapper;
613}
614
615android::Bitmap* GraphicsJNI::mapAshmemPixelRef(JNIEnv* env, SkBitmap* bitmap,
616        SkColorTable* ctable, int fd, void* addr, size_t size, bool readOnly) {
617    const SkImageInfo& info = bitmap->info();
618    if (info.colorType() == kUnknown_SkColorType) {
619        doThrowIAE(env, "unknown bitmap configuration");
620        return nullptr;
621    }
622
623    if (!addr) {
624        // Map existing ashmem region if not already mapped.
625        int flags = readOnly ? (PROT_READ) : (PROT_READ | PROT_WRITE);
626        size = ashmem_get_size_region(fd);
627        addr = mmap(NULL, size, flags, MAP_SHARED, fd, 0);
628        if (addr == MAP_FAILED) {
629            return nullptr;
630        }
631    }
632
633    // we must respect the rowBytes value already set on the bitmap instead of
634    // attempting to compute our own.
635    const size_t rowBytes = bitmap->rowBytes();
636
637    android::Bitmap* wrapper = new android::Bitmap(addr, fd, size, info, rowBytes, ctable);
638    wrapper->getSkBitmap(bitmap);
639    if (readOnly) {
640        bitmap->pixelRef()->setImmutable();
641    }
642    // since we're already allocated, we lockPixels right away
643    // HeapAllocator behaves this way too
644    bitmap->lockPixels();
645
646    return wrapper;
647}
648
649///////////////////////////////////////////////////////////////////////////////
650
651HeapAllocator::HeapAllocator() {}
652
653HeapAllocator::~HeapAllocator() {
654    if (mStorage) {
655        mStorage->detachFromJava();
656    }
657}
658
659bool HeapAllocator::allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable) {
660    mStorage = GraphicsJNI::allocateHeapPixelRef(bitmap, ctable);
661    return mStorage != nullptr;
662}
663
664////////////////////////////////////////////////////////////////////////////////
665
666RecyclingClippingPixelAllocator::RecyclingClippingPixelAllocator(
667        android::Bitmap* recycledBitmap, size_t recycledBytes)
668    : mRecycledBitmap(recycledBitmap)
669    , mRecycledBytes(recycledBytes)
670    , mSkiaBitmap(nullptr)
671    , mNeedsCopy(false)
672{}
673
674RecyclingClippingPixelAllocator::~RecyclingClippingPixelAllocator() {}
675
676bool RecyclingClippingPixelAllocator::allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable) {
677    // Ensure that the caller did not pass in a NULL bitmap to the constructor or this
678    // function.
679    LOG_ALWAYS_FATAL_IF(!mRecycledBitmap);
680    LOG_ALWAYS_FATAL_IF(!bitmap);
681    mSkiaBitmap = bitmap;
682
683    // This behaves differently than the RecyclingPixelAllocator.  For backwards
684    // compatibility, the original color type of the recycled bitmap must be maintained.
685    if (mRecycledBitmap->info().colorType() != bitmap->colorType()) {
686        return false;
687    }
688
689    // The Skia bitmap specifies the width and height needed by the decoder.
690    // mRecycledBitmap specifies the width and height of the bitmap that we
691    // want to reuse.  Neither can be changed.  We will try to find a way
692    // to reuse the memory.
693    const int maxWidth = SkTMax(bitmap->width(), mRecycledBitmap->info().width());
694    const int maxHeight = SkTMax(bitmap->height(), mRecycledBitmap->info().height());
695    const SkImageInfo maxInfo = bitmap->info().makeWH(maxWidth, maxHeight);
696    const size_t rowBytes = maxInfo.minRowBytes();
697    const size_t bytesNeeded = maxInfo.getSafeSize(rowBytes);
698    if (bytesNeeded <= mRecycledBytes) {
699        // Here we take advantage of reconfigure() to reset the rowBytes and ctable
700        // of mRecycledBitmap.  It is very important that we pass in
701        // mRecycledBitmap->info() for the SkImageInfo.  According to the
702        // specification for BitmapRegionDecoder, we are not allowed to change
703        // the SkImageInfo.
704        mRecycledBitmap->reconfigure(mRecycledBitmap->info(), rowBytes, ctable);
705
706        // Give the bitmap the same pixelRef as mRecycledBitmap.
707        // skbug.com/4538: We also need to make sure that the rowBytes on the pixel ref
708        //                 match the rowBytes on the bitmap.
709        bitmap->setInfo(bitmap->info(), rowBytes);
710        bitmap->setPixelRef(mRecycledBitmap->refPixelRef())->unref();
711
712        // Make sure that the recycled bitmap has the correct alpha type.
713        mRecycledBitmap->setAlphaType(bitmap->alphaType());
714
715        bitmap->notifyPixelsChanged();
716        bitmap->lockPixels();
717        mNeedsCopy = false;
718
719        // TODO: If the dimensions of the SkBitmap are smaller than those of
720        // mRecycledBitmap, should we zero the memory in mRecycledBitmap?
721        return true;
722    }
723
724    // In the event that mRecycledBitmap is not large enough, allocate new memory
725    // on the heap.
726    SkBitmap::HeapAllocator heapAllocator;
727
728    // We will need to copy from heap memory to mRecycledBitmap's memory after the
729    // decode is complete.
730    mNeedsCopy = true;
731
732    return heapAllocator.allocPixelRef(bitmap, ctable);
733}
734
735void RecyclingClippingPixelAllocator::copyIfNecessary() {
736    if (mNeedsCopy) {
737        SkPixelRef* recycledPixels = mRecycledBitmap->refPixelRef();
738        void* dst = recycledPixels->pixels();
739        const size_t dstRowBytes = mRecycledBitmap->rowBytes();
740        const size_t bytesToCopy = std::min(mRecycledBitmap->info().minRowBytes(),
741                mSkiaBitmap->info().minRowBytes());
742        const int rowsToCopy = std::min(mRecycledBitmap->info().height(),
743                mSkiaBitmap->info().height());
744        for (int y = 0; y < rowsToCopy; y++) {
745            memcpy(dst, mSkiaBitmap->getAddr(0, y), bytesToCopy);
746            dst = SkTAddOffset<void>(dst, dstRowBytes);
747        }
748        recycledPixels->notifyPixelsChanged();
749        recycledPixels->unref();
750    }
751    mRecycledBitmap = nullptr;
752    mSkiaBitmap = nullptr;
753}
754
755////////////////////////////////////////////////////////////////////////////////
756
757AshmemPixelAllocator::AshmemPixelAllocator(JNIEnv *env) {
758    LOG_ALWAYS_FATAL_IF(env->GetJavaVM(&mJavaVM) != JNI_OK,
759            "env->GetJavaVM failed");
760}
761
762AshmemPixelAllocator::~AshmemPixelAllocator() {
763    if (mStorage) {
764        mStorage->detachFromJava();
765    }
766}
767
768bool AshmemPixelAllocator::allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable) {
769    JNIEnv* env = vm2env(mJavaVM);
770    mStorage = GraphicsJNI::allocateAshmemPixelRef(env, bitmap, ctable);
771    return mStorage != nullptr;
772}
773
774////////////////////////////////////////////////////////////////////////////////
775
776static jclass make_globalref(JNIEnv* env, const char classname[])
777{
778    jclass c = env->FindClass(classname);
779    SkASSERT(c);
780    return (jclass) env->NewGlobalRef(c);
781}
782
783static jfieldID getFieldIDCheck(JNIEnv* env, jclass clazz,
784                                const char fieldname[], const char type[])
785{
786    jfieldID id = env->GetFieldID(clazz, fieldname, type);
787    SkASSERT(id);
788    return id;
789}
790
791int register_android_graphics_Graphics(JNIEnv* env)
792{
793    jmethodID m;
794    jclass c;
795
796    gRect_class = make_globalref(env, "android/graphics/Rect");
797    gRect_leftFieldID = getFieldIDCheck(env, gRect_class, "left", "I");
798    gRect_topFieldID = getFieldIDCheck(env, gRect_class, "top", "I");
799    gRect_rightFieldID = getFieldIDCheck(env, gRect_class, "right", "I");
800    gRect_bottomFieldID = getFieldIDCheck(env, gRect_class, "bottom", "I");
801
802    gRectF_class = make_globalref(env, "android/graphics/RectF");
803    gRectF_leftFieldID = getFieldIDCheck(env, gRectF_class, "left", "F");
804    gRectF_topFieldID = getFieldIDCheck(env, gRectF_class, "top", "F");
805    gRectF_rightFieldID = getFieldIDCheck(env, gRectF_class, "right", "F");
806    gRectF_bottomFieldID = getFieldIDCheck(env, gRectF_class, "bottom", "F");
807
808    gPoint_class = make_globalref(env, "android/graphics/Point");
809    gPoint_xFieldID = getFieldIDCheck(env, gPoint_class, "x", "I");
810    gPoint_yFieldID = getFieldIDCheck(env, gPoint_class, "y", "I");
811
812    gPointF_class = make_globalref(env, "android/graphics/PointF");
813    gPointF_xFieldID = getFieldIDCheck(env, gPointF_class, "x", "F");
814    gPointF_yFieldID = getFieldIDCheck(env, gPointF_class, "y", "F");
815
816    gBitmap_class = make_globalref(env, "android/graphics/Bitmap");
817    gBitmap_nativePtr = getFieldIDCheck(env, gBitmap_class, "mNativePtr", "J");
818    gBitmap_constructorMethodID = env->GetMethodID(gBitmap_class, "<init>", "(JIIIZZ[BLandroid/graphics/NinePatch$InsetStruct;)V");
819    gBitmap_reinitMethodID = env->GetMethodID(gBitmap_class, "reinit", "(IIZ)V");
820    gBitmap_getAllocationByteCountMethodID = env->GetMethodID(gBitmap_class, "getAllocationByteCount", "()I");
821    gBitmapRegionDecoder_class = make_globalref(env, "android/graphics/BitmapRegionDecoder");
822    gBitmapRegionDecoder_constructorMethodID = env->GetMethodID(gBitmapRegionDecoder_class, "<init>", "(J)V");
823
824    gBitmapConfig_class = make_globalref(env, "android/graphics/Bitmap$Config");
825    gBitmapConfig_nativeInstanceID = getFieldIDCheck(env, gBitmapConfig_class,
826                                                     "nativeInt", "I");
827
828    gCanvas_class = make_globalref(env, "android/graphics/Canvas");
829    gCanvas_nativeInstanceID = getFieldIDCheck(env, gCanvas_class, "mNativeCanvasWrapper", "J");
830
831    gPicture_class = make_globalref(env, "android/graphics/Picture");
832    gPicture_nativeInstanceID = getFieldIDCheck(env, gPicture_class, "mNativePicture", "J");
833
834    gRegion_class = make_globalref(env, "android/graphics/Region");
835    gRegion_nativeInstanceID = getFieldIDCheck(env, gRegion_class, "mNativeRegion", "J");
836    gRegion_constructorMethodID = env->GetMethodID(gRegion_class, "<init>",
837        "(JI)V");
838
839    c = env->FindClass("java/lang/Byte");
840    gByte_class = (jclass) env->NewGlobalRef(
841        env->GetStaticObjectField(c, env->GetStaticFieldID(c, "TYPE", "Ljava/lang/Class;")));
842
843    gVMRuntime_class = make_globalref(env, "dalvik/system/VMRuntime");
844    m = env->GetStaticMethodID(gVMRuntime_class, "getRuntime", "()Ldalvik/system/VMRuntime;");
845    gVMRuntime = env->NewGlobalRef(env->CallStaticObjectMethod(gVMRuntime_class, m));
846    gVMRuntime_newNonMovableArray = env->GetMethodID(gVMRuntime_class, "newNonMovableArray",
847                                                     "(Ljava/lang/Class;I)Ljava/lang/Object;");
848    gVMRuntime_addressOf = env->GetMethodID(gVMRuntime_class, "addressOf", "(Ljava/lang/Object;)J");
849
850    return 0;
851}
852