BitmapFactory.cpp revision 7ab249a18e08bfefb8c2d60af1fb668c67ba4368
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        return nullObjectReturn("decoder->decode returned false");
316    }
317
318    int scaledWidth = decodingBitmap.width();
319    int scaledHeight = decodingBitmap.height();
320
321    if (willScale && decodeMode != SkImageDecoder::kDecodeBounds_Mode) {
322        scaledWidth = int(scaledWidth * scale + 0.5f);
323        scaledHeight = int(scaledHeight * scale + 0.5f);
324    }
325
326    // update options (if any)
327    if (options != NULL) {
328        jstring mimeType = getMimeTypeString(env, decoder->getFormat());
329        if (env->ExceptionCheck()) {
330            return nullObjectReturn("OOM in getMimeTypeString()");
331        }
332        env->SetIntField(options, gOptions_widthFieldID, scaledWidth);
333        env->SetIntField(options, gOptions_heightFieldID, scaledHeight);
334        env->SetObjectField(options, gOptions_mimeFieldID, mimeType);
335    }
336
337    // if we're in justBounds mode, return now (skip the java bitmap)
338    if (decodeMode == SkImageDecoder::kDecodeBounds_Mode) {
339        return NULL;
340    }
341
342    jbyteArray ninePatchChunk = NULL;
343    if (peeker.mPatch != NULL) {
344        if (willScale) {
345            scaleNinePatchChunk(peeker.mPatch, scale, scaledWidth, scaledHeight);
346        }
347
348        size_t ninePatchArraySize = peeker.mPatch->serializedSize();
349        ninePatchChunk = env->NewByteArray(ninePatchArraySize);
350        if (ninePatchChunk == NULL) {
351            return nullObjectReturn("ninePatchChunk == null");
352        }
353
354        jbyte* array = (jbyte*) env->GetPrimitiveArrayCritical(ninePatchChunk, NULL);
355        if (array == NULL) {
356            return nullObjectReturn("primitive array == null");
357        }
358
359        memcpy(array, peeker.mPatch, peeker.mPatchSize);
360        env->ReleasePrimitiveArrayCritical(ninePatchChunk, array, 0);
361    }
362
363    jobject ninePatchInsets = NULL;
364    if (peeker.mHasInsets) {
365        ninePatchInsets = env->NewObject(gInsetStruct_class, gInsetStruct_constructorMethodID,
366                peeker.mOpticalInsets[0], peeker.mOpticalInsets[1], peeker.mOpticalInsets[2], peeker.mOpticalInsets[3],
367                peeker.mOutlineInsets[0], peeker.mOutlineInsets[1], peeker.mOutlineInsets[2], peeker.mOutlineInsets[3],
368                peeker.mOutlineRadius, peeker.mOutlineAlpha, scale);
369        if (ninePatchInsets == NULL) {
370            return nullObjectReturn("nine patch insets == null");
371        }
372        if (javaBitmap != NULL) {
373            env->SetObjectField(javaBitmap, gBitmap_ninePatchInsetsFieldID, ninePatchInsets);
374        }
375    }
376
377    if (willScale) {
378        // This is weird so let me explain: we could use the scale parameter
379        // directly, but for historical reasons this is how the corresponding
380        // Dalvik code has always behaved. We simply recreate the behavior here.
381        // The result is slightly different from simply using scale because of
382        // the 0.5f rounding bias applied when computing the target image size
383        const float sx = scaledWidth / float(decodingBitmap.width());
384        const float sy = scaledHeight / float(decodingBitmap.height());
385
386        // TODO: avoid copying when scaled size equals decodingBitmap size
387        SkColorType colorType = colorTypeForScaledOutput(decodingBitmap.colorType());
388        // FIXME: If the alphaType is kUnpremul and the image has alpha, the
389        // colors may not be correct, since Skia does not yet support drawing
390        // to/from unpremultiplied bitmaps.
391        outputBitmap->setInfo(SkImageInfo::Make(scaledWidth, scaledHeight,
392                colorType, decodingBitmap.alphaType()));
393        if (!outputBitmap->allocPixels(outputAllocator, NULL)) {
394            return nullObjectReturn("allocation failed for scaled bitmap");
395        }
396
397        // If outputBitmap's pixels are newly allocated by Java, there is no need
398        // to erase to 0, since the pixels were initialized to 0.
399        if (outputAllocator != &javaAllocator) {
400            outputBitmap->eraseColor(0);
401        }
402
403        SkPaint paint;
404        paint.setFilterLevel(SkPaint::kLow_FilterLevel);
405
406        SkCanvas canvas(*outputBitmap);
407        canvas.scale(sx, sy);
408        canvas.drawBitmap(decodingBitmap, 0.0f, 0.0f, &paint);
409    } else {
410        outputBitmap->swap(decodingBitmap);
411    }
412
413    if (padding) {
414        if (peeker.mPatch != NULL) {
415            GraphicsJNI::set_jrect(env, padding,
416                    peeker.mPatch->paddingLeft, peeker.mPatch->paddingTop,
417                    peeker.mPatch->paddingRight, peeker.mPatch->paddingBottom);
418        } else {
419            GraphicsJNI::set_jrect(env, padding, -1, -1, -1, -1);
420        }
421    }
422
423    // if we get here, we're in kDecodePixels_Mode and will therefore
424    // already have a pixelref installed.
425    if (outputBitmap->pixelRef() == NULL) {
426        return nullObjectReturn("Got null SkPixelRef");
427    }
428
429    if (!isMutable && javaBitmap == NULL) {
430        // promise we will never change our pixels (great for sharing and pictures)
431        outputBitmap->setImmutable();
432    }
433
434    // detach bitmap from its autodeleter, since we want to own it now
435    adb.detach();
436
437    if (javaBitmap != NULL) {
438        bool isPremultiplied = !requireUnpremultiplied;
439        GraphicsJNI::reinitBitmap(env, javaBitmap, outputBitmap, isPremultiplied);
440        outputBitmap->notifyPixelsChanged();
441        // If a java bitmap was passed in for reuse, pass it back
442        return javaBitmap;
443    }
444
445    int bitmapCreateFlags = 0x0;
446    if (isMutable) bitmapCreateFlags |= GraphicsJNI::kBitmapCreateFlag_Mutable;
447    if (!requireUnpremultiplied) bitmapCreateFlags |= GraphicsJNI::kBitmapCreateFlag_Premultiplied;
448
449    // now create the java bitmap
450    return GraphicsJNI::createBitmap(env, outputBitmap, javaAllocator.getStorageObj(),
451            bitmapCreateFlags, ninePatchChunk, ninePatchInsets, -1);
452}
453
454// Need to buffer enough input to be able to rewind as much as might be read by a decoder
455// trying to determine the stream's format. Currently the most is 64, read by
456// SkImageDecoder_libwebp.
457// FIXME: Get this number from SkImageDecoder
458#define BYTES_TO_BUFFER 64
459
460static jobject nativeDecodeStream(JNIEnv* env, jobject clazz, jobject is, jbyteArray storage,
461        jobject padding, jobject options) {
462
463    jobject bitmap = NULL;
464    SkAutoTUnref<SkStream> stream(CreateJavaInputStreamAdaptor(env, is, storage));
465
466    if (stream.get()) {
467        SkAutoTUnref<SkStreamRewindable> bufferedStream(
468                SkFrontBufferedStream::Create(stream, BYTES_TO_BUFFER));
469        SkASSERT(bufferedStream.get() != NULL);
470        bitmap = doDecode(env, bufferedStream, padding, options);
471    }
472    return bitmap;
473}
474
475static jobject nativeDecodeFileDescriptor(JNIEnv* env, jobject clazz, jobject fileDescriptor,
476        jobject padding, jobject bitmapFactoryOptions) {
477
478    NPE_CHECK_RETURN_ZERO(env, fileDescriptor);
479
480    int descriptor = jniGetFDFromFileDescriptor(env, fileDescriptor);
481
482    struct stat fdStat;
483    if (fstat(descriptor, &fdStat) == -1) {
484        doThrowIOE(env, "broken file descriptor");
485        return nullObjectReturn("fstat return -1");
486    }
487
488    // Restore the descriptor's offset on exiting this function. Even though
489    // we dup the descriptor, both the original and dup refer to the same open
490    // file description and changes to the file offset in one impact the other.
491    AutoFDSeek autoRestore(descriptor);
492
493    // Duplicate the descriptor here to prevent leaking memory. A leak occurs
494    // if we only close the file descriptor and not the file object it is used to
495    // create.  If we don't explicitly clean up the file (which in turn closes the
496    // descriptor) the buffers allocated internally by fseek will be leaked.
497    int dupDescriptor = dup(descriptor);
498
499    FILE* file = fdopen(dupDescriptor, "r");
500    if (file == NULL) {
501        // cleanup the duplicated descriptor since it will not be closed when the
502        // file is cleaned up (fclose).
503        close(dupDescriptor);
504        return nullObjectReturn("Could not open file");
505    }
506
507    SkAutoTUnref<SkFILEStream> fileStream(new SkFILEStream(file,
508                         SkFILEStream::kCallerPasses_Ownership));
509
510    // Use a buffered stream. Although an SkFILEStream can be rewound, this
511    // ensures that SkImageDecoder::Factory never rewinds beyond the
512    // current position of the file descriptor.
513    SkAutoTUnref<SkStreamRewindable> stream(SkFrontBufferedStream::Create(fileStream,
514            BYTES_TO_BUFFER));
515
516    return doDecode(env, stream, padding, bitmapFactoryOptions);
517}
518
519static jobject nativeDecodeAsset(JNIEnv* env, jobject clazz, jlong native_asset,
520        jobject padding, jobject options) {
521
522    Asset* asset = reinterpret_cast<Asset*>(native_asset);
523    // since we know we'll be done with the asset when we return, we can
524    // just use a simple wrapper
525    SkAutoTUnref<SkStreamRewindable> stream(new AssetStreamAdaptor(asset,
526            AssetStreamAdaptor::kNo_OwnAsset, AssetStreamAdaptor::kNo_HasMemoryBase));
527    return doDecode(env, stream, padding, options);
528}
529
530static jobject nativeDecodeByteArray(JNIEnv* env, jobject, jbyteArray byteArray,
531        jint offset, jint length, jobject options) {
532
533    AutoJavaByteArray ar(env, byteArray);
534    SkMemoryStream* stream = new SkMemoryStream(ar.ptr() + offset, length, false);
535    SkAutoUnref aur(stream);
536    return doDecode(env, stream, NULL, options);
537}
538
539static void nativeRequestCancel(JNIEnv*, jobject joptions) {
540    (void)AutoDecoderCancel::RequestCancel(joptions);
541}
542
543static jboolean nativeIsSeekable(JNIEnv* env, jobject, jobject fileDescriptor) {
544    jint descriptor = jniGetFDFromFileDescriptor(env, fileDescriptor);
545    return ::lseek64(descriptor, 0, SEEK_CUR) != -1 ? JNI_TRUE : JNI_FALSE;
546}
547
548///////////////////////////////////////////////////////////////////////////////
549
550static JNINativeMethod gMethods[] = {
551    {   "nativeDecodeStream",
552        "(Ljava/io/InputStream;[BLandroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
553        (void*)nativeDecodeStream
554    },
555
556    {   "nativeDecodeFileDescriptor",
557        "(Ljava/io/FileDescriptor;Landroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
558        (void*)nativeDecodeFileDescriptor
559    },
560
561    {   "nativeDecodeAsset",
562        "(JLandroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
563        (void*)nativeDecodeAsset
564    },
565
566    {   "nativeDecodeByteArray",
567        "([BIILandroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
568        (void*)nativeDecodeByteArray
569    },
570
571    {   "nativeIsSeekable",
572        "(Ljava/io/FileDescriptor;)Z",
573        (void*)nativeIsSeekable
574    },
575};
576
577static JNINativeMethod gOptionsMethods[] = {
578    {   "requestCancel", "()V", (void*)nativeRequestCancel }
579};
580
581int register_android_graphics_BitmapFactory(JNIEnv* env) {
582    jclass options_class = FindClassOrDie(env, "android/graphics/BitmapFactory$Options");
583    gOptions_bitmapFieldID = GetFieldIDOrDie(env, options_class, "inBitmap",
584            "Landroid/graphics/Bitmap;");
585    gOptions_justBoundsFieldID = GetFieldIDOrDie(env, options_class, "inJustDecodeBounds", "Z");
586    gOptions_sampleSizeFieldID = GetFieldIDOrDie(env, options_class, "inSampleSize", "I");
587    gOptions_configFieldID = GetFieldIDOrDie(env, options_class, "inPreferredConfig",
588            "Landroid/graphics/Bitmap$Config;");
589    gOptions_premultipliedFieldID = GetFieldIDOrDie(env, options_class, "inPremultiplied", "Z");
590    gOptions_mutableFieldID = GetFieldIDOrDie(env, options_class, "inMutable", "Z");
591    gOptions_ditherFieldID = GetFieldIDOrDie(env, options_class, "inDither", "Z");
592    gOptions_preferQualityOverSpeedFieldID = GetFieldIDOrDie(env, options_class,
593            "inPreferQualityOverSpeed", "Z");
594    gOptions_scaledFieldID = GetFieldIDOrDie(env, options_class, "inScaled", "Z");
595    gOptions_densityFieldID = GetFieldIDOrDie(env, options_class, "inDensity", "I");
596    gOptions_screenDensityFieldID = GetFieldIDOrDie(env, options_class, "inScreenDensity", "I");
597    gOptions_targetDensityFieldID = GetFieldIDOrDie(env, options_class, "inTargetDensity", "I");
598    gOptions_widthFieldID = GetFieldIDOrDie(env, options_class, "outWidth", "I");
599    gOptions_heightFieldID = GetFieldIDOrDie(env, options_class, "outHeight", "I");
600    gOptions_mimeFieldID = GetFieldIDOrDie(env, options_class, "outMimeType", "Ljava/lang/String;");
601    gOptions_mCancelID = GetFieldIDOrDie(env, options_class, "mCancel", "Z");
602
603    jclass bitmap_class = FindClassOrDie(env, "android/graphics/Bitmap");
604    gBitmap_nativeBitmapFieldID = GetFieldIDOrDie(env, bitmap_class, "mNativeBitmap", "J");
605    gBitmap_ninePatchInsetsFieldID = GetFieldIDOrDie(env, bitmap_class, "mNinePatchInsets",
606            "Landroid/graphics/NinePatch$InsetStruct;");
607
608    gInsetStruct_class = MakeGlobalRefOrDie(env, FindClassOrDie(env,
609        "android/graphics/NinePatch$InsetStruct"));
610    gInsetStruct_constructorMethodID = GetMethodIDOrDie(env, gInsetStruct_class, "<init>",
611                                                        "(IIIIIIIIFIF)V");
612
613    android::RegisterMethodsOrDie(env, "android/graphics/BitmapFactory$Options",
614                                  gOptionsMethods, NELEM(gOptionsMethods));
615    return android::RegisterMethodsOrDie(env, "android/graphics/BitmapFactory",
616                                         gMethods, NELEM(gMethods));
617}
618