Graphics.cpp revision 253f2c213f6ecda63b6872aee77bd30d5ec07c82
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   gBitmapConfig_class;
161static jfieldID gBitmapConfig_nativeInstanceID;
162
163static jclass   gBitmapRegionDecoder_class;
164static jmethodID gBitmapRegionDecoder_constructorMethodID;
165
166static jclass   gCanvas_class;
167static jfieldID gCanvas_nativeInstanceID;
168
169static jclass   gPicture_class;
170static jfieldID gPicture_nativeInstanceID;
171
172static jclass   gRegion_class;
173static jfieldID gRegion_nativeInstanceID;
174static jmethodID gRegion_constructorMethodID;
175
176static jclass    gByte_class;
177static jobject   gVMRuntime;
178static jclass    gVMRuntime_class;
179static jmethodID gVMRuntime_newNonMovableArray;
180static jmethodID gVMRuntime_addressOf;
181
182///////////////////////////////////////////////////////////////////////////////
183
184void GraphicsJNI::get_jrect(JNIEnv* env, jobject obj, int* L, int* T, int* R, int* B)
185{
186    SkASSERT(env->IsInstanceOf(obj, gRect_class));
187
188    *L = env->GetIntField(obj, gRect_leftFieldID);
189    *T = env->GetIntField(obj, gRect_topFieldID);
190    *R = env->GetIntField(obj, gRect_rightFieldID);
191    *B = env->GetIntField(obj, gRect_bottomFieldID);
192}
193
194void GraphicsJNI::set_jrect(JNIEnv* env, jobject obj, int L, int T, int R, int B)
195{
196    SkASSERT(env->IsInstanceOf(obj, gRect_class));
197
198    env->SetIntField(obj, gRect_leftFieldID, L);
199    env->SetIntField(obj, gRect_topFieldID, T);
200    env->SetIntField(obj, gRect_rightFieldID, R);
201    env->SetIntField(obj, gRect_bottomFieldID, B);
202}
203
204SkIRect* GraphicsJNI::jrect_to_irect(JNIEnv* env, jobject obj, SkIRect* ir)
205{
206    SkASSERT(env->IsInstanceOf(obj, gRect_class));
207
208    ir->set(env->GetIntField(obj, gRect_leftFieldID),
209            env->GetIntField(obj, gRect_topFieldID),
210            env->GetIntField(obj, gRect_rightFieldID),
211            env->GetIntField(obj, gRect_bottomFieldID));
212    return ir;
213}
214
215void GraphicsJNI::irect_to_jrect(const SkIRect& ir, JNIEnv* env, jobject obj)
216{
217    SkASSERT(env->IsInstanceOf(obj, gRect_class));
218
219    env->SetIntField(obj, gRect_leftFieldID, ir.fLeft);
220    env->SetIntField(obj, gRect_topFieldID, ir.fTop);
221    env->SetIntField(obj, gRect_rightFieldID, ir.fRight);
222    env->SetIntField(obj, gRect_bottomFieldID, ir.fBottom);
223}
224
225SkRect* GraphicsJNI::jrectf_to_rect(JNIEnv* env, jobject obj, SkRect* r)
226{
227    SkASSERT(env->IsInstanceOf(obj, gRectF_class));
228
229    r->set(env->GetFloatField(obj, gRectF_leftFieldID),
230           env->GetFloatField(obj, gRectF_topFieldID),
231           env->GetFloatField(obj, gRectF_rightFieldID),
232           env->GetFloatField(obj, gRectF_bottomFieldID));
233    return r;
234}
235
236SkRect* GraphicsJNI::jrect_to_rect(JNIEnv* env, jobject obj, SkRect* r)
237{
238    SkASSERT(env->IsInstanceOf(obj, gRect_class));
239
240    r->set(SkIntToScalar(env->GetIntField(obj, gRect_leftFieldID)),
241           SkIntToScalar(env->GetIntField(obj, gRect_topFieldID)),
242           SkIntToScalar(env->GetIntField(obj, gRect_rightFieldID)),
243           SkIntToScalar(env->GetIntField(obj, gRect_bottomFieldID)));
244    return r;
245}
246
247void GraphicsJNI::rect_to_jrectf(const SkRect& r, JNIEnv* env, jobject obj)
248{
249    SkASSERT(env->IsInstanceOf(obj, gRectF_class));
250
251    env->SetFloatField(obj, gRectF_leftFieldID, SkScalarToFloat(r.fLeft));
252    env->SetFloatField(obj, gRectF_topFieldID, SkScalarToFloat(r.fTop));
253    env->SetFloatField(obj, gRectF_rightFieldID, SkScalarToFloat(r.fRight));
254    env->SetFloatField(obj, gRectF_bottomFieldID, SkScalarToFloat(r.fBottom));
255}
256
257SkIPoint* GraphicsJNI::jpoint_to_ipoint(JNIEnv* env, jobject obj, SkIPoint* point)
258{
259    SkASSERT(env->IsInstanceOf(obj, gPoint_class));
260
261    point->set(env->GetIntField(obj, gPoint_xFieldID),
262               env->GetIntField(obj, gPoint_yFieldID));
263    return point;
264}
265
266void GraphicsJNI::ipoint_to_jpoint(const SkIPoint& ir, JNIEnv* env, jobject obj)
267{
268    SkASSERT(env->IsInstanceOf(obj, gPoint_class));
269
270    env->SetIntField(obj, gPoint_xFieldID, ir.fX);
271    env->SetIntField(obj, gPoint_yFieldID, ir.fY);
272}
273
274SkPoint* GraphicsJNI::jpointf_to_point(JNIEnv* env, jobject obj, SkPoint* point)
275{
276    SkASSERT(env->IsInstanceOf(obj, gPointF_class));
277
278    point->set(env->GetIntField(obj, gPointF_xFieldID),
279               env->GetIntField(obj, gPointF_yFieldID));
280    return point;
281}
282
283void GraphicsJNI::point_to_jpointf(const SkPoint& r, JNIEnv* env, jobject obj)
284{
285    SkASSERT(env->IsInstanceOf(obj, gPointF_class));
286
287    env->SetFloatField(obj, gPointF_xFieldID, SkScalarToFloat(r.fX));
288    env->SetFloatField(obj, gPointF_yFieldID, SkScalarToFloat(r.fY));
289}
290
291// This enum must keep these int values, to match the int values
292// in the java Bitmap.Config enum.
293enum LegacyBitmapConfig {
294    kNo_LegacyBitmapConfig          = 0,
295    kA8_LegacyBitmapConfig          = 1,
296    kIndex8_LegacyBitmapConfig      = 2,
297    kRGB_565_LegacyBitmapConfig     = 3,
298    kARGB_4444_LegacyBitmapConfig   = 4,
299    kARGB_8888_LegacyBitmapConfig   = 5,
300
301    kLastEnum_LegacyBitmapConfig = kARGB_8888_LegacyBitmapConfig
302};
303
304jint GraphicsJNI::colorTypeToLegacyBitmapConfig(SkColorType colorType) {
305    switch (colorType) {
306        case kN32_SkColorType:
307            return kARGB_8888_LegacyBitmapConfig;
308        case kARGB_4444_SkColorType:
309            return kARGB_4444_LegacyBitmapConfig;
310        case kRGB_565_SkColorType:
311            return kRGB_565_LegacyBitmapConfig;
312        case kIndex_8_SkColorType:
313            return kIndex8_LegacyBitmapConfig;
314        case kAlpha_8_SkColorType:
315            return kA8_LegacyBitmapConfig;
316        case kUnknown_SkColorType:
317        default:
318            break;
319    }
320    return kNo_LegacyBitmapConfig;
321}
322
323SkColorType GraphicsJNI::legacyBitmapConfigToColorType(jint legacyConfig) {
324    const uint8_t gConfig2ColorType[] = {
325        kUnknown_SkColorType,
326        kAlpha_8_SkColorType,
327        kIndex_8_SkColorType,
328        kRGB_565_SkColorType,
329        kARGB_4444_SkColorType,
330        kN32_SkColorType
331    };
332
333    if (legacyConfig < 0 || legacyConfig > kLastEnum_LegacyBitmapConfig) {
334        legacyConfig = kNo_LegacyBitmapConfig;
335    }
336    return static_cast<SkColorType>(gConfig2ColorType[legacyConfig]);
337}
338
339void GraphicsJNI::getSkBitmap(JNIEnv* env, jobject bitmap, SkBitmap* outBitmap) {
340    android::bitmap::toPixelRef(env, bitmap)->getSkBitmap(outBitmap);
341}
342
343SkPixelRef* GraphicsJNI::refSkPixelRef(JNIEnv* env, jobject bitmap) {
344    SkPixelRef* pixelRef = android::bitmap::toPixelRef(env, bitmap);
345    pixelRef->ref();
346    return pixelRef;
347}
348SkColorType GraphicsJNI::getNativeBitmapColorType(JNIEnv* env, jobject jconfig) {
349    SkASSERT(env);
350    if (NULL == jconfig) {
351        return kUnknown_SkColorType;
352    }
353    SkASSERT(env->IsInstanceOf(jconfig, gBitmapConfig_class));
354    int c = env->GetIntField(jconfig, gBitmapConfig_nativeInstanceID);
355    return legacyBitmapConfigToColorType(c);
356}
357
358android::Canvas* GraphicsJNI::getNativeCanvas(JNIEnv* env, jobject canvas) {
359    SkASSERT(env);
360    SkASSERT(canvas);
361    SkASSERT(env->IsInstanceOf(canvas, gCanvas_class));
362    jlong canvasHandle = env->GetLongField(canvas, gCanvas_nativeInstanceID);
363    if (!canvasHandle) {
364        return NULL;
365    }
366    return reinterpret_cast<android::Canvas*>(canvasHandle);
367}
368
369SkRegion* GraphicsJNI::getNativeRegion(JNIEnv* env, jobject region)
370{
371    SkASSERT(env);
372    SkASSERT(region);
373    SkASSERT(env->IsInstanceOf(region, gRegion_class));
374    jlong regionHandle = env->GetLongField(region, gRegion_nativeInstanceID);
375    SkRegion* r = reinterpret_cast<SkRegion*>(regionHandle);
376    SkASSERT(r);
377    return r;
378}
379
380///////////////////////////////////////////////////////////////////////////////////////////
381
382jobject GraphicsJNI::createBitmapRegionDecoder(JNIEnv* env, SkBitmapRegionDecoder* bitmap)
383{
384    SkASSERT(bitmap != NULL);
385
386    jobject obj = env->NewObject(gBitmapRegionDecoder_class,
387            gBitmapRegionDecoder_constructorMethodID,
388            reinterpret_cast<jlong>(bitmap));
389    hasException(env); // For the side effect of logging.
390    return obj;
391}
392
393jobject GraphicsJNI::createRegion(JNIEnv* env, SkRegion* region)
394{
395    SkASSERT(region != NULL);
396    jobject obj = env->NewObject(gRegion_class, gRegion_constructorMethodID,
397                                 reinterpret_cast<jlong>(region), 0);
398    hasException(env); // For the side effect of logging.
399    return obj;
400}
401
402static JNIEnv* vm2env(JavaVM* vm)
403{
404    JNIEnv* env = NULL;
405    if (vm->GetEnv((void**)&env, JNI_VERSION_1_4) != JNI_OK || NULL == env)
406    {
407        SkDebugf("------- [%p] vm->GetEnv() failed\n", vm);
408        sk_throw();
409    }
410    return env;
411}
412
413///////////////////////////////////////////////////////////////////////////////
414
415static bool computeAllocationSize(const SkBitmap& bitmap, size_t* size) {
416    int32_t rowBytes32 = SkToS32(bitmap.rowBytes());
417    int64_t bigSize = (int64_t)bitmap.height() * rowBytes32;
418    if (rowBytes32 < 0 || !sk_64_isS32(bigSize)) {
419        return false; // allocation will be too large
420    }
421
422    *size = sk_64_asS32(bigSize);
423    return true;
424}
425
426android::PixelRef* GraphicsJNI::allocateHeapPixelRef(SkBitmap* bitmap, SkColorTable* ctable) {
427    const SkImageInfo& info = bitmap->info();
428    if (info.colorType() == kUnknown_SkColorType) {
429        LOG_ALWAYS_FATAL("unknown bitmap configuration");
430        return nullptr;
431    }
432
433    size_t size;
434    if (!computeAllocationSize(*bitmap, &size)) {
435        return nullptr;
436    }
437
438    // we must respect the rowBytes value already set on the bitmap instead of
439    // attempting to compute our own.
440    const size_t rowBytes = bitmap->rowBytes();
441
442    void* addr = calloc(size, 1);
443    if (!addr) {
444        return nullptr;
445    }
446
447    auto wrapper = new android::PixelRef(addr, size, info, rowBytes, ctable);
448    wrapper->getSkBitmap(bitmap);
449    // since we're already allocated, we lockPixels right away
450    // HeapAllocator behaves this way too
451    bitmap->lockPixels();
452
453    return wrapper;
454}
455
456struct AndroidPixelRefContext {
457    int32_t stableID;
458};
459
460static void allocatePixelsReleaseProc(void* ptr, void* ctx) {
461    AndroidPixelRefContext* context = (AndroidPixelRefContext*)ctx;
462    if (android::uirenderer::Caches::hasInstance()) {
463         android::uirenderer::Caches::getInstance().textureCache.releaseTexture(context->stableID);
464    }
465
466    sk_free(ptr);
467    delete context;
468}
469
470bool GraphicsJNI::allocatePixels(JNIEnv* env, SkBitmap* bitmap, SkColorTable* ctable) {
471    const SkImageInfo& info = bitmap->info();
472    if (info.colorType() == kUnknown_SkColorType) {
473        doThrowIAE(env, "unknown bitmap configuration");
474        return NULL;
475    }
476
477    size_t size;
478    if (!computeAllocationSize(*bitmap, &size)) {
479        return false;
480    }
481
482    // we must respect the rowBytes value already set on the bitmap instead of
483    // attempting to compute our own.
484    const size_t rowBytes = bitmap->rowBytes();
485
486    void* addr = sk_malloc_flags(size, 0);
487    if (NULL == addr) {
488        return false;
489    }
490
491    AndroidPixelRefContext* context = new AndroidPixelRefContext;
492    SkMallocPixelRef* pr = SkMallocPixelRef::NewWithProc(info, rowBytes, ctable, addr,
493                                                         &allocatePixelsReleaseProc, context);
494    if (!pr) {
495        delete context;
496        return false;
497    }
498
499    // set the stableID in the context so that it can be used later in
500    // allocatePixelsReleaseProc to remove the texture from the cache.
501    context->stableID = pr->getStableID();
502
503    bitmap->setPixelRef(pr)->unref();
504    // since we're already allocated, we can lockPixels right away
505    bitmap->lockPixels();
506
507    return true;
508}
509
510android::PixelRef* GraphicsJNI::allocateAshmemPixelRef(JNIEnv* env, SkBitmap* bitmap,
511                                                     SkColorTable* ctable) {
512    int fd;
513
514    const SkImageInfo& info = bitmap->info();
515    if (info.colorType() == kUnknown_SkColorType) {
516        doThrowIAE(env, "unknown bitmap configuration");
517        return nullptr;
518    }
519
520    size_t size;
521    if (!computeAllocationSize(*bitmap, &size)) {
522        return nullptr;
523    }
524
525    // we must respect the rowBytes value already set on the bitmap instead of
526    // attempting to compute our own.
527    const size_t rowBytes = bitmap->rowBytes();
528
529    // Create new ashmem region with read/write priv
530    fd = ashmem_create_region("bitmap", size);
531    if (fd < 0) {
532        return nullptr;
533    }
534
535    void* addr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
536    if (addr == MAP_FAILED) {
537        close(fd);
538        return nullptr;
539    }
540
541    if (ashmem_set_prot_region(fd, PROT_READ) < 0) {
542        munmap(addr, size);
543        close(fd);
544        return nullptr;
545    }
546
547    auto wrapper = new android::PixelRef(addr, fd, size, info, rowBytes, ctable);
548    wrapper->getSkBitmap(bitmap);
549    // since we're already allocated, we lockPixels right away
550    // HeapAllocator behaves this way too
551    bitmap->lockPixels();
552
553    return wrapper;
554}
555
556android::PixelRef* GraphicsJNI::mapAshmemPixelRef(JNIEnv* env, SkBitmap* bitmap,
557        SkColorTable* ctable, int fd, void* addr, size_t size, bool readOnly) {
558    const SkImageInfo& info = bitmap->info();
559    if (info.colorType() == kUnknown_SkColorType) {
560        doThrowIAE(env, "unknown bitmap configuration");
561        return nullptr;
562    }
563
564    if (!addr) {
565        // Map existing ashmem region if not already mapped.
566        int flags = readOnly ? (PROT_READ) : (PROT_READ | PROT_WRITE);
567        size = ashmem_get_size_region(fd);
568        addr = mmap(NULL, size, flags, MAP_SHARED, fd, 0);
569        if (addr == MAP_FAILED) {
570            return nullptr;
571        }
572    }
573
574    // we must respect the rowBytes value already set on the bitmap instead of
575    // attempting to compute our own.
576    const size_t rowBytes = bitmap->rowBytes();
577
578    auto wrapper = new android::PixelRef(addr, fd, size, info, rowBytes, ctable);
579    wrapper->getSkBitmap(bitmap);
580    if (readOnly) {
581        bitmap->pixelRef()->setImmutable();
582    }
583    // since we're already allocated, we lockPixels right away
584    // HeapAllocator behaves this way too
585    bitmap->lockPixels();
586
587    return wrapper;
588}
589
590sk_sp<SkColorSpace> GraphicsJNI::defaultColorSpace() {
591#ifdef ANDROID_ENABLE_LINEAR_BLENDING
592    return SkColorSpace::NewNamed(SkColorSpace::kSRGB_Named);
593#else
594    return nullptr;
595#endif
596}
597
598///////////////////////////////////////////////////////////////////////////////
599bool HeapAllocator::allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable) {
600    mStorage.reset(GraphicsJNI::allocateHeapPixelRef(bitmap, ctable));
601    return !!mStorage;
602}
603
604////////////////////////////////////////////////////////////////////////////////
605
606RecyclingClippingPixelAllocator::RecyclingClippingPixelAllocator(
607        android::PixelRef* recycledBitmap, size_t recycledBytes)
608    : mRecycledBitmap(recycledBitmap)
609    , mRecycledBytes(recycledBytes)
610    , mSkiaBitmap(nullptr)
611    , mNeedsCopy(false)
612{}
613
614RecyclingClippingPixelAllocator::~RecyclingClippingPixelAllocator() {}
615
616bool RecyclingClippingPixelAllocator::allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable) {
617    // Ensure that the caller did not pass in a NULL bitmap to the constructor or this
618    // function.
619    LOG_ALWAYS_FATAL_IF(!mRecycledBitmap);
620    LOG_ALWAYS_FATAL_IF(!bitmap);
621    mSkiaBitmap = bitmap;
622
623    // This behaves differently than the RecyclingPixelAllocator.  For backwards
624    // compatibility, the original color type of the recycled bitmap must be maintained.
625    if (mRecycledBitmap->info().colorType() != bitmap->colorType()) {
626        return false;
627    }
628
629    // The Skia bitmap specifies the width and height needed by the decoder.
630    // mRecycledBitmap specifies the width and height of the bitmap that we
631    // want to reuse.  Neither can be changed.  We will try to find a way
632    // to reuse the memory.
633    const int maxWidth = SkTMax(bitmap->width(), mRecycledBitmap->info().width());
634    const int maxHeight = SkTMax(bitmap->height(), mRecycledBitmap->info().height());
635    const SkImageInfo maxInfo = bitmap->info().makeWH(maxWidth, maxHeight);
636    const size_t rowBytes = maxInfo.minRowBytes();
637    const size_t bytesNeeded = maxInfo.getSafeSize(rowBytes);
638    if (bytesNeeded <= mRecycledBytes) {
639        // Here we take advantage of reconfigure() to reset the rowBytes and ctable
640        // of mRecycledBitmap.  It is very important that we pass in
641        // mRecycledBitmap->info() for the SkImageInfo.  According to the
642        // specification for BitmapRegionDecoder, we are not allowed to change
643        // the SkImageInfo.
644        mRecycledBitmap->reconfigure(mRecycledBitmap->info(), rowBytes, ctable);
645
646        // Give the bitmap the same pixelRef as mRecycledBitmap.
647        // skbug.com/4538: We also need to make sure that the rowBytes on the pixel ref
648        //                 match the rowBytes on the bitmap.
649        bitmap->setInfo(bitmap->info(), rowBytes);
650        mRecycledBitmap->ref();
651        bitmap->setPixelRef(mRecycledBitmap)->unref();
652
653        // Make sure that the recycled bitmap has the correct alpha type.
654        mRecycledBitmap->setAlphaType(bitmap->alphaType());
655
656        bitmap->notifyPixelsChanged();
657        bitmap->lockPixels();
658        mNeedsCopy = false;
659
660        // TODO: If the dimensions of the SkBitmap are smaller than those of
661        // mRecycledBitmap, should we zero the memory in mRecycledBitmap?
662        return true;
663    }
664
665    // In the event that mRecycledBitmap is not large enough, allocate new memory
666    // on the heap.
667    SkBitmap::HeapAllocator heapAllocator;
668
669    // We will need to copy from heap memory to mRecycledBitmap's memory after the
670    // decode is complete.
671    mNeedsCopy = true;
672
673    return heapAllocator.allocPixelRef(bitmap, ctable);
674}
675
676void RecyclingClippingPixelAllocator::copyIfNecessary() {
677    if (mNeedsCopy) {
678        mRecycledBitmap->ref();
679        SkPixelRef* recycledPixels = mRecycledBitmap;
680        void* dst = recycledPixels->pixels();
681        const size_t dstRowBytes = mRecycledBitmap->rowBytes();
682        const size_t bytesToCopy = std::min(mRecycledBitmap->info().minRowBytes(),
683                mSkiaBitmap->info().minRowBytes());
684        const int rowsToCopy = std::min(mRecycledBitmap->info().height(),
685                mSkiaBitmap->info().height());
686        for (int y = 0; y < rowsToCopy; y++) {
687            memcpy(dst, mSkiaBitmap->getAddr(0, y), bytesToCopy);
688            dst = SkTAddOffset<void>(dst, dstRowBytes);
689        }
690        recycledPixels->notifyPixelsChanged();
691        recycledPixels->unref();
692    }
693    mRecycledBitmap = nullptr;
694    mSkiaBitmap = nullptr;
695}
696
697////////////////////////////////////////////////////////////////////////////////
698
699AshmemPixelAllocator::AshmemPixelAllocator(JNIEnv *env) {
700    LOG_ALWAYS_FATAL_IF(env->GetJavaVM(&mJavaVM) != JNI_OK,
701            "env->GetJavaVM failed");
702}
703
704bool AshmemPixelAllocator::allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable) {
705    JNIEnv* env = vm2env(mJavaVM);
706    mStorage.reset(GraphicsJNI::allocateAshmemPixelRef(env, bitmap, ctable));
707    return !!mStorage;
708}
709
710////////////////////////////////////////////////////////////////////////////////
711
712static jclass make_globalref(JNIEnv* env, const char classname[])
713{
714    jclass c = env->FindClass(classname);
715    SkASSERT(c);
716    return (jclass) env->NewGlobalRef(c);
717}
718
719static jfieldID getFieldIDCheck(JNIEnv* env, jclass clazz,
720                                const char fieldname[], const char type[])
721{
722    jfieldID id = env->GetFieldID(clazz, fieldname, type);
723    SkASSERT(id);
724    return id;
725}
726
727int register_android_graphics_Graphics(JNIEnv* env)
728{
729    jmethodID m;
730    jclass c;
731
732    gRect_class = make_globalref(env, "android/graphics/Rect");
733    gRect_leftFieldID = getFieldIDCheck(env, gRect_class, "left", "I");
734    gRect_topFieldID = getFieldIDCheck(env, gRect_class, "top", "I");
735    gRect_rightFieldID = getFieldIDCheck(env, gRect_class, "right", "I");
736    gRect_bottomFieldID = getFieldIDCheck(env, gRect_class, "bottom", "I");
737
738    gRectF_class = make_globalref(env, "android/graphics/RectF");
739    gRectF_leftFieldID = getFieldIDCheck(env, gRectF_class, "left", "F");
740    gRectF_topFieldID = getFieldIDCheck(env, gRectF_class, "top", "F");
741    gRectF_rightFieldID = getFieldIDCheck(env, gRectF_class, "right", "F");
742    gRectF_bottomFieldID = getFieldIDCheck(env, gRectF_class, "bottom", "F");
743
744    gPoint_class = make_globalref(env, "android/graphics/Point");
745    gPoint_xFieldID = getFieldIDCheck(env, gPoint_class, "x", "I");
746    gPoint_yFieldID = getFieldIDCheck(env, gPoint_class, "y", "I");
747
748    gPointF_class = make_globalref(env, "android/graphics/PointF");
749    gPointF_xFieldID = getFieldIDCheck(env, gPointF_class, "x", "F");
750    gPointF_yFieldID = getFieldIDCheck(env, gPointF_class, "y", "F");
751
752    gBitmapRegionDecoder_class = make_globalref(env, "android/graphics/BitmapRegionDecoder");
753    gBitmapRegionDecoder_constructorMethodID = env->GetMethodID(gBitmapRegionDecoder_class, "<init>", "(J)V");
754
755    gBitmapConfig_class = make_globalref(env, "android/graphics/Bitmap$Config");
756    gBitmapConfig_nativeInstanceID = getFieldIDCheck(env, gBitmapConfig_class,
757                                                     "nativeInt", "I");
758
759    gCanvas_class = make_globalref(env, "android/graphics/Canvas");
760    gCanvas_nativeInstanceID = getFieldIDCheck(env, gCanvas_class, "mNativeCanvasWrapper", "J");
761
762    gPicture_class = make_globalref(env, "android/graphics/Picture");
763    gPicture_nativeInstanceID = getFieldIDCheck(env, gPicture_class, "mNativePicture", "J");
764
765    gRegion_class = make_globalref(env, "android/graphics/Region");
766    gRegion_nativeInstanceID = getFieldIDCheck(env, gRegion_class, "mNativeRegion", "J");
767    gRegion_constructorMethodID = env->GetMethodID(gRegion_class, "<init>",
768        "(JI)V");
769
770    c = env->FindClass("java/lang/Byte");
771    gByte_class = (jclass) env->NewGlobalRef(
772        env->GetStaticObjectField(c, env->GetStaticFieldID(c, "TYPE", "Ljava/lang/Class;")));
773
774    gVMRuntime_class = make_globalref(env, "dalvik/system/VMRuntime");
775    m = env->GetStaticMethodID(gVMRuntime_class, "getRuntime", "()Ldalvik/system/VMRuntime;");
776    gVMRuntime = env->NewGlobalRef(env->CallStaticObjectMethod(gVMRuntime_class, m));
777    gVMRuntime_newNonMovableArray = env->GetMethodID(gVMRuntime_class, "newNonMovableArray",
778                                                     "(Ljava/lang/Class;I)Ljava/lang/Object;");
779    gVMRuntime_addressOf = env->GetMethodID(gVMRuntime_class, "addressOf", "(Ljava/lang/Object;)J");
780
781    return 0;
782}
783