BitmapFactory.cpp revision 4e2986940b2ff456693a805026c6910e950c42e2
1#define LOG_TAG "BitmapFactory"
2
3#include "BitmapFactory.h"
4#include "NinePatchPeeker.h"
5#include "SkFrontBufferedStream.h"
6#include "SkImageDecoder.h"
7#include "SkMath.h"
8#include "SkPixelRef.h"
9#include "SkStream.h"
10#include "SkTemplates.h"
11#include "SkUtils.h"
12#include "CreateJavaOutputStreamAdaptor.h"
13#include "AutoDecodeCancel.h"
14#include "Utils.h"
15#include "JNIHelp.h"
16#include "GraphicsJNI.h"
17
18#include "core_jni_helpers.h"
19#include <androidfw/Asset.h>
20#include <androidfw/ResourceTypes.h>
21#include <cutils/compiler.h>
22#include <netinet/in.h>
23#include <stdio.h>
24#include <sys/mman.h>
25#include <sys/stat.h>
26
27jfieldID gOptions_justBoundsFieldID;
28jfieldID gOptions_sampleSizeFieldID;
29jfieldID gOptions_configFieldID;
30jfieldID gOptions_premultipliedFieldID;
31jfieldID gOptions_mutableFieldID;
32jfieldID gOptions_ditherFieldID;
33jfieldID gOptions_preferQualityOverSpeedFieldID;
34jfieldID gOptions_scaledFieldID;
35jfieldID gOptions_densityFieldID;
36jfieldID gOptions_screenDensityFieldID;
37jfieldID gOptions_targetDensityFieldID;
38jfieldID gOptions_widthFieldID;
39jfieldID gOptions_heightFieldID;
40jfieldID gOptions_mimeFieldID;
41jfieldID gOptions_mCancelID;
42jfieldID gOptions_bitmapFieldID;
43
44jfieldID gBitmap_nativeBitmapFieldID;
45jfieldID gBitmap_ninePatchInsetsFieldID;
46
47jclass gInsetStruct_class;
48jmethodID gInsetStruct_constructorMethodID;
49
50using namespace android;
51
52jstring getMimeTypeString(JNIEnv* env, SkImageDecoder::Format format) {
53    static const struct {
54        SkImageDecoder::Format fFormat;
55        const char*            fMimeType;
56    } gMimeTypes[] = {
57        { SkImageDecoder::kBMP_Format,  "image/bmp" },
58        { SkImageDecoder::kGIF_Format,  "image/gif" },
59        { SkImageDecoder::kICO_Format,  "image/x-ico" },
60        { SkImageDecoder::kJPEG_Format, "image/jpeg" },
61        { SkImageDecoder::kPNG_Format,  "image/png" },
62        { SkImageDecoder::kWEBP_Format, "image/webp" },
63        { SkImageDecoder::kWBMP_Format, "image/vnd.wap.wbmp" }
64    };
65
66    const char* cstr = nullptr;
67    for (size_t i = 0; i < SK_ARRAY_COUNT(gMimeTypes); i++) {
68        if (gMimeTypes[i].fFormat == format) {
69            cstr = gMimeTypes[i].fMimeType;
70            break;
71        }
72    }
73
74    jstring jstr = nullptr;
75    if (cstr != nullptr) {
76        // NOTE: Caller should env->ExceptionCheck() for OOM
77        // (can't check for nullptr as it's a valid return value)
78        jstr = env->NewStringUTF(cstr);
79    }
80    return jstr;
81}
82
83static bool optionsJustBounds(JNIEnv* env, jobject options) {
84    return options != NULL && env->GetBooleanField(options, gOptions_justBoundsFieldID);
85}
86
87static void scaleDivRange(int32_t* divs, int count, float scale, int maxValue) {
88    for (int i = 0; i < count; i++) {
89        divs[i] = int32_t(divs[i] * scale + 0.5f);
90        if (i > 0 && divs[i] == divs[i - 1]) {
91            divs[i]++; // avoid collisions
92        }
93    }
94
95    if (CC_UNLIKELY(divs[count - 1] > maxValue)) {
96        // if the collision avoidance above put some divs outside the bounds of the bitmap,
97        // slide outer stretchable divs inward to stay within bounds
98        int highestAvailable = maxValue;
99        for (int i = count - 1; i >= 0; i--) {
100            divs[i] = highestAvailable;
101            if (i > 0 && divs[i] <= divs[i-1]){
102                // keep shifting
103                highestAvailable = divs[i] - 1;
104            } else {
105                break;
106            }
107        }
108    }
109}
110
111static void scaleNinePatchChunk(android::Res_png_9patch* chunk, float scale,
112        int scaledWidth, int scaledHeight) {
113    chunk->paddingLeft = int(chunk->paddingLeft * scale + 0.5f);
114    chunk->paddingTop = int(chunk->paddingTop * scale + 0.5f);
115    chunk->paddingRight = int(chunk->paddingRight * scale + 0.5f);
116    chunk->paddingBottom = int(chunk->paddingBottom * scale + 0.5f);
117
118    scaleDivRange(chunk->getXDivs(), chunk->numXDivs, scale, scaledWidth);
119    scaleDivRange(chunk->getYDivs(), chunk->numYDivs, scale, scaledHeight);
120}
121
122static SkColorType colorTypeForScaledOutput(SkColorType colorType) {
123    switch (colorType) {
124        case kUnknown_SkColorType:
125        case kIndex_8_SkColorType:
126            return kN32_SkColorType;
127        default:
128            break;
129    }
130    return colorType;
131}
132
133class ScaleCheckingAllocator : public SkBitmap::HeapAllocator {
134public:
135    ScaleCheckingAllocator(float scale, int size)
136            : mScale(scale), mSize(size) {
137    }
138
139    virtual bool allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable) {
140        // accounts for scale in final allocation, using eventual size and config
141        const int bytesPerPixel = SkColorTypeBytesPerPixel(
142                colorTypeForScaledOutput(bitmap->colorType()));
143        const int requestedSize = bytesPerPixel *
144                int(bitmap->width() * mScale + 0.5f) *
145                int(bitmap->height() * mScale + 0.5f);
146        if (requestedSize > mSize) {
147            ALOGW("bitmap for alloc reuse (%d bytes) can't fit scaled bitmap (%d bytes)",
148                    mSize, requestedSize);
149            return false;
150        }
151        return SkBitmap::HeapAllocator::allocPixelRef(bitmap, ctable);
152    }
153private:
154    const float mScale;
155    const int mSize;
156};
157
158class RecyclingPixelAllocator : public SkBitmap::Allocator {
159public:
160    RecyclingPixelAllocator(SkPixelRef* pixelRef, unsigned int size)
161            : mPixelRef(pixelRef), mSize(size) {
162        SkSafeRef(mPixelRef);
163    }
164
165    ~RecyclingPixelAllocator() {
166        SkSafeUnref(mPixelRef);
167    }
168
169    virtual bool allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable) {
170        const SkImageInfo& info = bitmap->info();
171        if (info.fColorType == kUnknown_SkColorType) {
172            ALOGW("unable to reuse a bitmap as the target has an unknown bitmap configuration");
173            return false;
174        }
175
176        const int64_t size64 = info.getSafeSize64(bitmap->rowBytes());
177        if (!sk_64_isS32(size64)) {
178            ALOGW("bitmap is too large");
179            return false;
180        }
181
182        const size_t size = sk_64_asS32(size64);
183        if (size > mSize) {
184            ALOGW("bitmap marked for reuse (%u bytes) can't fit new bitmap "
185                  "(%zu bytes)", mSize, size);
186            return false;
187        }
188
189        // Create a new pixelref with the new ctable that wraps the previous pixelref
190        SkPixelRef* pr = new AndroidPixelRef(*static_cast<AndroidPixelRef*>(mPixelRef),
191                info, bitmap->rowBytes(), ctable);
192
193        bitmap->setPixelRef(pr)->unref();
194        // since we're already allocated, we lockPixels right away
195        // HeapAllocator/JavaPixelAllocator behaves this way too
196        bitmap->lockPixels();
197        return true;
198    }
199
200private:
201    SkPixelRef* const mPixelRef;
202    const unsigned int mSize;
203};
204
205static jobject doDecode(JNIEnv* env, SkStreamRewindable* stream, jobject padding, jobject options) {
206
207    int sampleSize = 1;
208
209    SkImageDecoder::Mode decodeMode = SkImageDecoder::kDecodePixels_Mode;
210    SkColorType prefColorType = kN32_SkColorType;
211
212    bool doDither = true;
213    bool isMutable = false;
214    float scale = 1.0f;
215    bool preferQualityOverSpeed = false;
216    bool requireUnpremultiplied = false;
217
218    jobject javaBitmap = NULL;
219
220    if (options != NULL) {
221        sampleSize = env->GetIntField(options, gOptions_sampleSizeFieldID);
222        if (optionsJustBounds(env, options)) {
223            decodeMode = SkImageDecoder::kDecodeBounds_Mode;
224        }
225
226        // initialize these, in case we fail later on
227        env->SetIntField(options, gOptions_widthFieldID, -1);
228        env->SetIntField(options, gOptions_heightFieldID, -1);
229        env->SetObjectField(options, gOptions_mimeFieldID, 0);
230
231        jobject jconfig = env->GetObjectField(options, gOptions_configFieldID);
232        prefColorType = GraphicsJNI::getNativeBitmapColorType(env, jconfig);
233        isMutable = env->GetBooleanField(options, gOptions_mutableFieldID);
234        doDither = env->GetBooleanField(options, gOptions_ditherFieldID);
235        preferQualityOverSpeed = env->GetBooleanField(options,
236                gOptions_preferQualityOverSpeedFieldID);
237        requireUnpremultiplied = !env->GetBooleanField(options, gOptions_premultipliedFieldID);
238        javaBitmap = env->GetObjectField(options, gOptions_bitmapFieldID);
239
240        if (env->GetBooleanField(options, gOptions_scaledFieldID)) {
241            const int density = env->GetIntField(options, gOptions_densityFieldID);
242            const int targetDensity = env->GetIntField(options, gOptions_targetDensityFieldID);
243            const int screenDensity = env->GetIntField(options, gOptions_screenDensityFieldID);
244            if (density != 0 && targetDensity != 0 && density != screenDensity) {
245                scale = (float) targetDensity / density;
246            }
247        }
248    }
249
250    const bool willScale = scale != 1.0f;
251
252    SkImageDecoder* decoder = SkImageDecoder::Factory(stream);
253    if (decoder == NULL) {
254        return nullObjectReturn("SkImageDecoder::Factory returned null");
255    }
256
257    decoder->setSampleSize(sampleSize);
258    decoder->setDitherImage(doDither);
259    decoder->setPreferQualityOverSpeed(preferQualityOverSpeed);
260    decoder->setRequireUnpremultipliedColors(requireUnpremultiplied);
261
262    SkBitmap* outputBitmap = NULL;
263    unsigned int existingBufferSize = 0;
264    if (javaBitmap != NULL) {
265        outputBitmap = (SkBitmap*) env->GetLongField(javaBitmap, gBitmap_nativeBitmapFieldID);
266        if (outputBitmap->isImmutable()) {
267            ALOGW("Unable to reuse an immutable bitmap as an image decoder target.");
268            javaBitmap = NULL;
269            outputBitmap = NULL;
270        } else {
271            existingBufferSize = GraphicsJNI::getBitmapAllocationByteCount(env, javaBitmap);
272        }
273    }
274
275    SkAutoTDelete<SkBitmap> adb(outputBitmap == NULL ? new SkBitmap : NULL);
276    if (outputBitmap == NULL) outputBitmap = adb.get();
277
278    NinePatchPeeker peeker(decoder);
279    decoder->setPeeker(&peeker);
280
281    JavaPixelAllocator javaAllocator(env);
282    RecyclingPixelAllocator recyclingAllocator(outputBitmap->pixelRef(), existingBufferSize);
283    ScaleCheckingAllocator scaleCheckingAllocator(scale, existingBufferSize);
284    SkBitmap::Allocator* outputAllocator = (javaBitmap != NULL) ?
285            (SkBitmap::Allocator*)&recyclingAllocator : (SkBitmap::Allocator*)&javaAllocator;
286    if (decodeMode != SkImageDecoder::kDecodeBounds_Mode) {
287        if (!willScale) {
288            // If the java allocator is being used to allocate the pixel memory, the decoder
289            // need not write zeroes, since the memory is initialized to 0.
290            decoder->setSkipWritingZeroes(outputAllocator == &javaAllocator);
291            decoder->setAllocator(outputAllocator);
292        } else if (javaBitmap != NULL) {
293            // check for eventual scaled bounds at allocation time, so we don't decode the bitmap
294            // only to find the scaled result too large to fit in the allocation
295            decoder->setAllocator(&scaleCheckingAllocator);
296        }
297    }
298
299    // Only setup the decoder to be deleted after its stack-based, refcounted
300    // components (allocators, peekers, etc) are declared. This prevents RefCnt
301    // asserts from firing due to the order objects are deleted from the stack.
302    SkAutoTDelete<SkImageDecoder> add(decoder);
303
304    AutoDecoderCancel adc(options, decoder);
305
306    // To fix the race condition in case "requestCancelDecode"
307    // happens earlier than AutoDecoderCancel object is added
308    // to the gAutoDecoderCancelMutex linked list.
309    if (options != NULL && env->GetBooleanField(options, gOptions_mCancelID)) {
310        return nullObjectReturn("gOptions_mCancelID");
311    }
312
313    SkBitmap decodingBitmap;
314    if (decoder->decode(stream, &decodingBitmap, prefColorType, decodeMode)
315                != SkImageDecoder::kSuccess) {
316        return nullObjectReturn("decoder->decode returned false");
317    }
318
319    int scaledWidth = decodingBitmap.width();
320    int scaledHeight = decodingBitmap.height();
321
322    if (willScale && decodeMode != SkImageDecoder::kDecodeBounds_Mode) {
323        scaledWidth = int(scaledWidth * scale + 0.5f);
324        scaledHeight = int(scaledHeight * scale + 0.5f);
325    }
326
327    // update options (if any)
328    if (options != NULL) {
329        jstring mimeType = getMimeTypeString(env, decoder->getFormat());
330        if (env->ExceptionCheck()) {
331            return nullObjectReturn("OOM in getMimeTypeString()");
332        }
333        env->SetIntField(options, gOptions_widthFieldID, scaledWidth);
334        env->SetIntField(options, gOptions_heightFieldID, scaledHeight);
335        env->SetObjectField(options, gOptions_mimeFieldID, mimeType);
336    }
337
338    // if we're in justBounds mode, return now (skip the java bitmap)
339    if (decodeMode == SkImageDecoder::kDecodeBounds_Mode) {
340        return NULL;
341    }
342
343    jbyteArray ninePatchChunk = NULL;
344    if (peeker.mPatch != NULL) {
345        if (willScale) {
346            scaleNinePatchChunk(peeker.mPatch, scale, scaledWidth, scaledHeight);
347        }
348
349        size_t ninePatchArraySize = peeker.mPatch->serializedSize();
350        ninePatchChunk = env->NewByteArray(ninePatchArraySize);
351        if (ninePatchChunk == NULL) {
352            return nullObjectReturn("ninePatchChunk == null");
353        }
354
355        jbyte* array = (jbyte*) env->GetPrimitiveArrayCritical(ninePatchChunk, NULL);
356        if (array == NULL) {
357            return nullObjectReturn("primitive array == null");
358        }
359
360        memcpy(array, peeker.mPatch, peeker.mPatchSize);
361        env->ReleasePrimitiveArrayCritical(ninePatchChunk, array, 0);
362    }
363
364    jobject ninePatchInsets = NULL;
365    if (peeker.mHasInsets) {
366        ninePatchInsets = env->NewObject(gInsetStruct_class, gInsetStruct_constructorMethodID,
367                peeker.mOpticalInsets[0], peeker.mOpticalInsets[1], peeker.mOpticalInsets[2], peeker.mOpticalInsets[3],
368                peeker.mOutlineInsets[0], peeker.mOutlineInsets[1], peeker.mOutlineInsets[2], peeker.mOutlineInsets[3],
369                peeker.mOutlineRadius, peeker.mOutlineAlpha, scale);
370        if (ninePatchInsets == NULL) {
371            return nullObjectReturn("nine patch insets == null");
372        }
373        if (javaBitmap != NULL) {
374            env->SetObjectField(javaBitmap, gBitmap_ninePatchInsetsFieldID, ninePatchInsets);
375        }
376    }
377
378    if (willScale) {
379        // This is weird so let me explain: we could use the scale parameter
380        // directly, but for historical reasons this is how the corresponding
381        // Dalvik code has always behaved. We simply recreate the behavior here.
382        // The result is slightly different from simply using scale because of
383        // the 0.5f rounding bias applied when computing the target image size
384        const float sx = scaledWidth / float(decodingBitmap.width());
385        const float sy = scaledHeight / float(decodingBitmap.height());
386
387        // TODO: avoid copying when scaled size equals decodingBitmap size
388        SkColorType colorType = colorTypeForScaledOutput(decodingBitmap.colorType());
389        // FIXME: If the alphaType is kUnpremul and the image has alpha, the
390        // colors may not be correct, since Skia does not yet support drawing
391        // to/from unpremultiplied bitmaps.
392        outputBitmap->setInfo(SkImageInfo::Make(scaledWidth, scaledHeight,
393                colorType, decodingBitmap.alphaType()));
394        if (!outputBitmap->allocPixels(outputAllocator, NULL)) {
395            return nullObjectReturn("allocation failed for scaled bitmap");
396        }
397
398        // If outputBitmap's pixels are newly allocated by Java, there is no need
399        // to erase to 0, since the pixels were initialized to 0.
400        if (outputAllocator != &javaAllocator) {
401            outputBitmap->eraseColor(0);
402        }
403
404        SkPaint paint;
405        paint.setFilterLevel(SkPaint::kLow_FilterLevel);
406
407        SkCanvas canvas(*outputBitmap);
408        canvas.scale(sx, sy);
409        canvas.drawBitmap(decodingBitmap, 0.0f, 0.0f, &paint);
410    } else {
411        outputBitmap->swap(decodingBitmap);
412    }
413
414    if (padding) {
415        if (peeker.mPatch != NULL) {
416            GraphicsJNI::set_jrect(env, padding,
417                    peeker.mPatch->paddingLeft, peeker.mPatch->paddingTop,
418                    peeker.mPatch->paddingRight, peeker.mPatch->paddingBottom);
419        } else {
420            GraphicsJNI::set_jrect(env, padding, -1, -1, -1, -1);
421        }
422    }
423
424    // if we get here, we're in kDecodePixels_Mode and will therefore
425    // already have a pixelref installed.
426    if (outputBitmap->pixelRef() == NULL) {
427        return nullObjectReturn("Got null SkPixelRef");
428    }
429
430    if (!isMutable && javaBitmap == NULL) {
431        // promise we will never change our pixels (great for sharing and pictures)
432        outputBitmap->setImmutable();
433    }
434
435    // detach bitmap from its autodeleter, since we want to own it now
436    adb.detach();
437
438    if (javaBitmap != NULL) {
439        bool isPremultiplied = !requireUnpremultiplied;
440        GraphicsJNI::reinitBitmap(env, javaBitmap, outputBitmap, isPremultiplied);
441        outputBitmap->notifyPixelsChanged();
442        // If a java bitmap was passed in for reuse, pass it back
443        return javaBitmap;
444    }
445
446    int bitmapCreateFlags = 0x0;
447    if (isMutable) bitmapCreateFlags |= GraphicsJNI::kBitmapCreateFlag_Mutable;
448    if (!requireUnpremultiplied) bitmapCreateFlags |= GraphicsJNI::kBitmapCreateFlag_Premultiplied;
449
450    // now create the java bitmap
451    return GraphicsJNI::createBitmap(env, outputBitmap, javaAllocator.getStorageObj(),
452            bitmapCreateFlags, ninePatchChunk, ninePatchInsets, -1);
453}
454
455// Need to buffer enough input to be able to rewind as much as might be read by a decoder
456// trying to determine the stream's format. Currently the most is 64, read by
457// SkImageDecoder_libwebp.
458// FIXME: Get this number from SkImageDecoder
459#define BYTES_TO_BUFFER 64
460
461static jobject nativeDecodeStream(JNIEnv* env, jobject clazz, jobject is, jbyteArray storage,
462        jobject padding, jobject options) {
463
464    jobject bitmap = NULL;
465    SkAutoTUnref<SkStream> stream(CreateJavaInputStreamAdaptor(env, is, storage));
466
467    if (stream.get()) {
468        SkAutoTUnref<SkStreamRewindable> bufferedStream(
469                SkFrontBufferedStream::Create(stream, BYTES_TO_BUFFER));
470        SkASSERT(bufferedStream.get() != NULL);
471        bitmap = doDecode(env, bufferedStream, padding, options);
472    }
473    return bitmap;
474}
475
476static jobject nativeDecodeFileDescriptor(JNIEnv* env, jobject clazz, jobject fileDescriptor,
477        jobject padding, jobject bitmapFactoryOptions) {
478
479    NPE_CHECK_RETURN_ZERO(env, fileDescriptor);
480
481    int descriptor = jniGetFDFromFileDescriptor(env, fileDescriptor);
482
483    struct stat fdStat;
484    if (fstat(descriptor, &fdStat) == -1) {
485        doThrowIOE(env, "broken file descriptor");
486        return nullObjectReturn("fstat return -1");
487    }
488
489    // Restore the descriptor's offset on exiting this function. Even though
490    // we dup the descriptor, both the original and dup refer to the same open
491    // file description and changes to the file offset in one impact the other.
492    AutoFDSeek autoRestore(descriptor);
493
494    // Duplicate the descriptor here to prevent leaking memory. A leak occurs
495    // if we only close the file descriptor and not the file object it is used to
496    // create.  If we don't explicitly clean up the file (which in turn closes the
497    // descriptor) the buffers allocated internally by fseek will be leaked.
498    int dupDescriptor = dup(descriptor);
499
500    FILE* file = fdopen(dupDescriptor, "r");
501    if (file == NULL) {
502        // cleanup the duplicated descriptor since it will not be closed when the
503        // file is cleaned up (fclose).
504        close(dupDescriptor);
505        return nullObjectReturn("Could not open file");
506    }
507
508    SkAutoTUnref<SkFILEStream> fileStream(new SkFILEStream(file,
509                         SkFILEStream::kCallerPasses_Ownership));
510
511    // Use a buffered stream. Although an SkFILEStream can be rewound, this
512    // ensures that SkImageDecoder::Factory never rewinds beyond the
513    // current position of the file descriptor.
514    SkAutoTUnref<SkStreamRewindable> stream(SkFrontBufferedStream::Create(fileStream,
515            BYTES_TO_BUFFER));
516
517    return doDecode(env, stream, padding, bitmapFactoryOptions);
518}
519
520static jobject nativeDecodeAsset(JNIEnv* env, jobject clazz, jlong native_asset,
521        jobject padding, jobject options) {
522
523    Asset* asset = reinterpret_cast<Asset*>(native_asset);
524    // since we know we'll be done with the asset when we return, we can
525    // just use a simple wrapper
526    SkAutoTUnref<SkStreamRewindable> stream(new AssetStreamAdaptor(asset,
527            AssetStreamAdaptor::kNo_OwnAsset, AssetStreamAdaptor::kNo_HasMemoryBase));
528    return doDecode(env, stream, padding, options);
529}
530
531static jobject nativeDecodeByteArray(JNIEnv* env, jobject, jbyteArray byteArray,
532        jint offset, jint length, jobject options) {
533
534    AutoJavaByteArray ar(env, byteArray);
535    SkMemoryStream* stream = new SkMemoryStream(ar.ptr() + offset, length, false);
536    SkAutoUnref aur(stream);
537    return doDecode(env, stream, NULL, options);
538}
539
540static void nativeRequestCancel(JNIEnv*, jobject joptions) {
541    (void)AutoDecoderCancel::RequestCancel(joptions);
542}
543
544static jboolean nativeIsSeekable(JNIEnv* env, jobject, jobject fileDescriptor) {
545    jint descriptor = jniGetFDFromFileDescriptor(env, fileDescriptor);
546    return ::lseek64(descriptor, 0, SEEK_CUR) != -1 ? JNI_TRUE : JNI_FALSE;
547}
548
549///////////////////////////////////////////////////////////////////////////////
550
551static JNINativeMethod gMethods[] = {
552    {   "nativeDecodeStream",
553        "(Ljava/io/InputStream;[BLandroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
554        (void*)nativeDecodeStream
555    },
556
557    {   "nativeDecodeFileDescriptor",
558        "(Ljava/io/FileDescriptor;Landroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
559        (void*)nativeDecodeFileDescriptor
560    },
561
562    {   "nativeDecodeAsset",
563        "(JLandroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
564        (void*)nativeDecodeAsset
565    },
566
567    {   "nativeDecodeByteArray",
568        "([BIILandroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
569        (void*)nativeDecodeByteArray
570    },
571
572    {   "nativeIsSeekable",
573        "(Ljava/io/FileDescriptor;)Z",
574        (void*)nativeIsSeekable
575    },
576};
577
578static JNINativeMethod gOptionsMethods[] = {
579    {   "requestCancel", "()V", (void*)nativeRequestCancel }
580};
581
582int register_android_graphics_BitmapFactory(JNIEnv* env) {
583    jclass options_class = FindClassOrDie(env, "android/graphics/BitmapFactory$Options");
584    gOptions_bitmapFieldID = GetFieldIDOrDie(env, options_class, "inBitmap",
585            "Landroid/graphics/Bitmap;");
586    gOptions_justBoundsFieldID = GetFieldIDOrDie(env, options_class, "inJustDecodeBounds", "Z");
587    gOptions_sampleSizeFieldID = GetFieldIDOrDie(env, options_class, "inSampleSize", "I");
588    gOptions_configFieldID = GetFieldIDOrDie(env, options_class, "inPreferredConfig",
589            "Landroid/graphics/Bitmap$Config;");
590    gOptions_premultipliedFieldID = GetFieldIDOrDie(env, options_class, "inPremultiplied", "Z");
591    gOptions_mutableFieldID = GetFieldIDOrDie(env, options_class, "inMutable", "Z");
592    gOptions_ditherFieldID = GetFieldIDOrDie(env, options_class, "inDither", "Z");
593    gOptions_preferQualityOverSpeedFieldID = GetFieldIDOrDie(env, options_class,
594            "inPreferQualityOverSpeed", "Z");
595    gOptions_scaledFieldID = GetFieldIDOrDie(env, options_class, "inScaled", "Z");
596    gOptions_densityFieldID = GetFieldIDOrDie(env, options_class, "inDensity", "I");
597    gOptions_screenDensityFieldID = GetFieldIDOrDie(env, options_class, "inScreenDensity", "I");
598    gOptions_targetDensityFieldID = GetFieldIDOrDie(env, options_class, "inTargetDensity", "I");
599    gOptions_widthFieldID = GetFieldIDOrDie(env, options_class, "outWidth", "I");
600    gOptions_heightFieldID = GetFieldIDOrDie(env, options_class, "outHeight", "I");
601    gOptions_mimeFieldID = GetFieldIDOrDie(env, options_class, "outMimeType", "Ljava/lang/String;");
602    gOptions_mCancelID = GetFieldIDOrDie(env, options_class, "mCancel", "Z");
603
604    jclass bitmap_class = FindClassOrDie(env, "android/graphics/Bitmap");
605    gBitmap_nativeBitmapFieldID = GetFieldIDOrDie(env, bitmap_class, "mNativeBitmap", "J");
606    gBitmap_ninePatchInsetsFieldID = GetFieldIDOrDie(env, bitmap_class, "mNinePatchInsets",
607            "Landroid/graphics/NinePatch$InsetStruct;");
608
609    gInsetStruct_class = MakeGlobalRefOrDie(env, FindClassOrDie(env,
610        "android/graphics/NinePatch$InsetStruct"));
611    gInsetStruct_constructorMethodID = GetMethodIDOrDie(env, gInsetStruct_class, "<init>",
612                                                        "(IIIIIIIIFIF)V");
613
614    android::RegisterMethodsOrDie(env, "android/graphics/BitmapFactory$Options",
615                                  gOptionsMethods, NELEM(gOptionsMethods));
616    return android::RegisterMethodsOrDie(env, "android/graphics/BitmapFactory",
617                                         gMethods, NELEM(gMethods));
618}
619