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