Home | History | Annotate | Download | only in graphics
      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 <android_runtime/AndroidRuntime.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 
     27 jfieldID gOptions_justBoundsFieldID;
     28 jfieldID gOptions_sampleSizeFieldID;
     29 jfieldID gOptions_configFieldID;
     30 jfieldID gOptions_premultipliedFieldID;
     31 jfieldID gOptions_mutableFieldID;
     32 jfieldID gOptions_ditherFieldID;
     33 jfieldID gOptions_preferQualityOverSpeedFieldID;
     34 jfieldID gOptions_scaledFieldID;
     35 jfieldID gOptions_densityFieldID;
     36 jfieldID gOptions_screenDensityFieldID;
     37 jfieldID gOptions_targetDensityFieldID;
     38 jfieldID gOptions_widthFieldID;
     39 jfieldID gOptions_heightFieldID;
     40 jfieldID gOptions_mimeFieldID;
     41 jfieldID gOptions_mCancelID;
     42 jfieldID gOptions_bitmapFieldID;
     43 
     44 jfieldID gBitmap_nativeBitmapFieldID;
     45 jfieldID gBitmap_ninePatchInsetsFieldID;
     46 
     47 jclass gInsetStruct_class;
     48 jmethodID gInsetStruct_constructorMethodID;
     49 
     50 using namespace android;
     51 
     52 static inline int32_t validOrNeg1(bool isValid, int32_t value) {
     53 //    return isValid ? value : -1;
     54     SkASSERT((int)isValid == 0 || (int)isValid == 1);
     55     return ((int32_t)isValid - 1) | value;
     56 }
     57 
     58 jstring getMimeTypeString(JNIEnv* env, SkImageDecoder::Format format) {
     59     static const struct {
     60         SkImageDecoder::Format fFormat;
     61         const char*            fMimeType;
     62     } gMimeTypes[] = {
     63         { SkImageDecoder::kBMP_Format,  "image/bmp" },
     64         { SkImageDecoder::kGIF_Format,  "image/gif" },
     65         { SkImageDecoder::kICO_Format,  "image/x-ico" },
     66         { SkImageDecoder::kJPEG_Format, "image/jpeg" },
     67         { SkImageDecoder::kPNG_Format,  "image/png" },
     68         { SkImageDecoder::kWEBP_Format, "image/webp" },
     69         { SkImageDecoder::kWBMP_Format, "image/vnd.wap.wbmp" }
     70     };
     71 
     72     const char* cstr = NULL;
     73     for (size_t i = 0; i < SK_ARRAY_COUNT(gMimeTypes); i++) {
     74         if (gMimeTypes[i].fFormat == format) {
     75             cstr = gMimeTypes[i].fMimeType;
     76             break;
     77         }
     78     }
     79 
     80     jstring jstr = 0;
     81     if (NULL != cstr) {
     82         jstr = env->NewStringUTF(cstr);
     83     }
     84     return jstr;
     85 }
     86 
     87 static bool optionsJustBounds(JNIEnv* env, jobject options) {
     88     return options != NULL && env->GetBooleanField(options, gOptions_justBoundsFieldID);
     89 }
     90 
     91 static void scaleDivRange(int32_t* divs, int count, float scale, int maxValue) {
     92     for (int i = 0; i < count; i++) {
     93         divs[i] = int32_t(divs[i] * scale + 0.5f);
     94         if (i > 0 && divs[i] == divs[i - 1]) {
     95             divs[i]++; // avoid collisions
     96         }
     97     }
     98 
     99     if (CC_UNLIKELY(divs[count - 1] > maxValue)) {
    100         // if the collision avoidance above put some divs outside the bounds of the bitmap,
    101         // slide outer stretchable divs inward to stay within bounds
    102         int highestAvailable = maxValue;
    103         for (int i = count - 1; i >= 0; i--) {
    104             divs[i] = highestAvailable;
    105             if (i > 0 && divs[i] <= divs[i-1]){
    106                 // keep shifting
    107                 highestAvailable = divs[i] - 1;
    108             } else {
    109                 break;
    110             }
    111         }
    112     }
    113 }
    114 
    115 static void scaleNinePatchChunk(android::Res_png_9patch* chunk, float scale,
    116         int scaledWidth, int scaledHeight) {
    117     chunk->paddingLeft = int(chunk->paddingLeft * scale + 0.5f);
    118     chunk->paddingTop = int(chunk->paddingTop * scale + 0.5f);
    119     chunk->paddingRight = int(chunk->paddingRight * scale + 0.5f);
    120     chunk->paddingBottom = int(chunk->paddingBottom * scale + 0.5f);
    121 
    122     scaleDivRange(chunk->getXDivs(), chunk->numXDivs, scale, scaledWidth);
    123     scaleDivRange(chunk->getYDivs(), chunk->numYDivs, scale, scaledHeight);
    124 }
    125 
    126 static SkColorType colorTypeForScaledOutput(SkColorType colorType) {
    127     switch (colorType) {
    128         case kUnknown_SkColorType:
    129         case kIndex_8_SkColorType:
    130             return kN32_SkColorType;
    131         default:
    132             break;
    133     }
    134     return colorType;
    135 }
    136 
    137 class ScaleCheckingAllocator : public SkBitmap::HeapAllocator {
    138 public:
    139     ScaleCheckingAllocator(float scale, int size)
    140             : mScale(scale), mSize(size) {
    141     }
    142 
    143     virtual bool allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable) {
    144         // accounts for scale in final allocation, using eventual size and config
    145         const int bytesPerPixel = SkColorTypeBytesPerPixel(
    146                 colorTypeForScaledOutput(bitmap->colorType()));
    147         const int requestedSize = bytesPerPixel *
    148                 int(bitmap->width() * mScale + 0.5f) *
    149                 int(bitmap->height() * mScale + 0.5f);
    150         if (requestedSize > mSize) {
    151             ALOGW("bitmap for alloc reuse (%d bytes) can't fit scaled bitmap (%d bytes)",
    152                     mSize, requestedSize);
    153             return false;
    154         }
    155         return SkBitmap::HeapAllocator::allocPixelRef(bitmap, ctable);
    156     }
    157 private:
    158     const float mScale;
    159     const int mSize;
    160 };
    161 
    162 class RecyclingPixelAllocator : public SkBitmap::Allocator {
    163 public:
    164     RecyclingPixelAllocator(SkPixelRef* pixelRef, unsigned int size)
    165             : mPixelRef(pixelRef), mSize(size) {
    166         SkSafeRef(mPixelRef);
    167     }
    168 
    169     ~RecyclingPixelAllocator() {
    170         SkSafeUnref(mPixelRef);
    171     }
    172 
    173     virtual bool allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable) {
    174         const SkImageInfo& info = bitmap->info();
    175         if (info.fColorType == kUnknown_SkColorType) {
    176             ALOGW("unable to reuse a bitmap as the target has an unknown bitmap configuration");
    177             return false;
    178         }
    179 
    180         const int64_t size64 = info.getSafeSize64(bitmap->rowBytes());
    181         if (!sk_64_isS32(size64)) {
    182             ALOGW("bitmap is too large");
    183             return false;
    184         }
    185 
    186         const size_t size = sk_64_asS32(size64);
    187         if (size > mSize) {
    188             ALOGW("bitmap marked for reuse (%d bytes) can't fit new bitmap (%d bytes)",
    189                     mSize, size);
    190             return false;
    191         }
    192 
    193         // Create a new pixelref with the new ctable that wraps the previous pixelref
    194         SkPixelRef* pr = new AndroidPixelRef(*static_cast<AndroidPixelRef*>(mPixelRef),
    195                 info, bitmap->rowBytes(), ctable);
    196 
    197         bitmap->setPixelRef(pr)->unref();
    198         // since we're already allocated, we lockPixels right away
    199         // HeapAllocator/JavaPixelAllocator behaves this way too
    200         bitmap->lockPixels();
    201         return true;
    202     }
    203 
    204 private:
    205     SkPixelRef* const mPixelRef;
    206     const unsigned int mSize;
    207 };
    208 
    209 static jobject doDecode(JNIEnv* env, SkStreamRewindable* stream, jobject padding, jobject options) {
    210 
    211     int sampleSize = 1;
    212 
    213     SkImageDecoder::Mode decodeMode = SkImageDecoder::kDecodePixels_Mode;
    214     SkColorType prefColorType = kN32_SkColorType;
    215 
    216     bool doDither = true;
    217     bool isMutable = false;
    218     float scale = 1.0f;
    219     bool preferQualityOverSpeed = false;
    220     bool requireUnpremultiplied = false;
    221 
    222     jobject javaBitmap = NULL;
    223 
    224     if (options != NULL) {
    225         sampleSize = env->GetIntField(options, gOptions_sampleSizeFieldID);
    226         if (optionsJustBounds(env, options)) {
    227             decodeMode = SkImageDecoder::kDecodeBounds_Mode;
    228         }
    229 
    230         // initialize these, in case we fail later on
    231         env->SetIntField(options, gOptions_widthFieldID, -1);
    232         env->SetIntField(options, gOptions_heightFieldID, -1);
    233         env->SetObjectField(options, gOptions_mimeFieldID, 0);
    234 
    235         jobject jconfig = env->GetObjectField(options, gOptions_configFieldID);
    236         prefColorType = GraphicsJNI::getNativeBitmapColorType(env, jconfig);
    237         isMutable = env->GetBooleanField(options, gOptions_mutableFieldID);
    238         doDither = env->GetBooleanField(options, gOptions_ditherFieldID);
    239         preferQualityOverSpeed = env->GetBooleanField(options,
    240                 gOptions_preferQualityOverSpeedFieldID);
    241         requireUnpremultiplied = !env->GetBooleanField(options, gOptions_premultipliedFieldID);
    242         javaBitmap = env->GetObjectField(options, gOptions_bitmapFieldID);
    243 
    244         if (env->GetBooleanField(options, gOptions_scaledFieldID)) {
    245             const int density = env->GetIntField(options, gOptions_densityFieldID);
    246             const int targetDensity = env->GetIntField(options, gOptions_targetDensityFieldID);
    247             const int screenDensity = env->GetIntField(options, gOptions_screenDensityFieldID);
    248             if (density != 0 && targetDensity != 0 && density != screenDensity) {
    249                 scale = (float) targetDensity / density;
    250             }
    251         }
    252     }
    253 
    254     const bool willScale = scale != 1.0f;
    255 
    256     SkImageDecoder* decoder = SkImageDecoder::Factory(stream);
    257     if (decoder == NULL) {
    258         return nullObjectReturn("SkImageDecoder::Factory returned null");
    259     }
    260 
    261     decoder->setSampleSize(sampleSize);
    262     decoder->setDitherImage(doDither);
    263     decoder->setPreferQualityOverSpeed(preferQualityOverSpeed);
    264     decoder->setRequireUnpremultipliedColors(requireUnpremultiplied);
    265 
    266     SkBitmap* outputBitmap = NULL;
    267     unsigned int existingBufferSize = 0;
    268     if (javaBitmap != NULL) {
    269         outputBitmap = (SkBitmap*) env->GetLongField(javaBitmap, gBitmap_nativeBitmapFieldID);
    270         if (outputBitmap->isImmutable()) {
    271             ALOGW("Unable to reuse an immutable bitmap as an image decoder target.");
    272             javaBitmap = NULL;
    273             outputBitmap = NULL;
    274         } else {
    275             existingBufferSize = GraphicsJNI::getBitmapAllocationByteCount(env, javaBitmap);
    276         }
    277     }
    278 
    279     SkAutoTDelete<SkBitmap> adb(outputBitmap == NULL ? new SkBitmap : NULL);
    280     if (outputBitmap == NULL) outputBitmap = adb.get();
    281 
    282     NinePatchPeeker peeker(decoder);
    283     decoder->setPeeker(&peeker);
    284 
    285     JavaPixelAllocator javaAllocator(env);
    286     RecyclingPixelAllocator recyclingAllocator(outputBitmap->pixelRef(), existingBufferSize);
    287     ScaleCheckingAllocator scaleCheckingAllocator(scale, existingBufferSize);
    288     SkBitmap::Allocator* outputAllocator = (javaBitmap != NULL) ?
    289             (SkBitmap::Allocator*)&recyclingAllocator : (SkBitmap::Allocator*)&javaAllocator;
    290     if (decodeMode != SkImageDecoder::kDecodeBounds_Mode) {
    291         if (!willScale) {
    292             // If the java allocator is being used to allocate the pixel memory, the decoder
    293             // need not write zeroes, since the memory is initialized to 0.
    294             decoder->setSkipWritingZeroes(outputAllocator == &javaAllocator);
    295             decoder->setAllocator(outputAllocator);
    296         } else if (javaBitmap != NULL) {
    297             // check for eventual scaled bounds at allocation time, so we don't decode the bitmap
    298             // only to find the scaled result too large to fit in the allocation
    299             decoder->setAllocator(&scaleCheckingAllocator);
    300         }
    301     }
    302 
    303     // Only setup the decoder to be deleted after its stack-based, refcounted
    304     // components (allocators, peekers, etc) are declared. This prevents RefCnt
    305     // asserts from firing due to the order objects are deleted from the stack.
    306     SkAutoTDelete<SkImageDecoder> add(decoder);
    307 
    308     AutoDecoderCancel adc(options, decoder);
    309 
    310     // To fix the race condition in case "requestCancelDecode"
    311     // happens earlier than AutoDecoderCancel object is added
    312     // to the gAutoDecoderCancelMutex linked list.
    313     if (options != NULL && env->GetBooleanField(options, gOptions_mCancelID)) {
    314         return nullObjectReturn("gOptions_mCancelID");
    315     }
    316 
    317     SkBitmap decodingBitmap;
    318     if (!decoder->decode(stream, &decodingBitmap, prefColorType, decodeMode)) {
    319         return nullObjectReturn("decoder->decode returned false");
    320     }
    321 
    322     int scaledWidth = decodingBitmap.width();
    323     int scaledHeight = decodingBitmap.height();
    324 
    325     if (willScale && decodeMode != SkImageDecoder::kDecodeBounds_Mode) {
    326         scaledWidth = int(scaledWidth * scale + 0.5f);
    327         scaledHeight = int(scaledHeight * scale + 0.5f);
    328     }
    329 
    330     // update options (if any)
    331     if (options != NULL) {
    332         env->SetIntField(options, gOptions_widthFieldID, scaledWidth);
    333         env->SetIntField(options, gOptions_heightFieldID, scaledHeight);
    334         env->SetObjectField(options, gOptions_mimeFieldID,
    335                 getMimeTypeString(env, decoder->getFormat()));
    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 
    461 static 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 
    476 static jobject nativeDecodeFileDescriptor(JNIEnv* env, jobject clazz, jobject fileDescriptor,
    477         jobject padding, jobject bitmapFactoryOptions) {
    478 
    479     NPE_CHECK_RETURN_ZERO(env, fileDescriptor);
    480 
    481     jint 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.
    490     AutoFDSeek autoRestore(descriptor);
    491 
    492     FILE* file = fdopen(descriptor, "r");
    493     if (file == NULL) {
    494         return nullObjectReturn("Could not open file");
    495     }
    496 
    497     SkAutoTUnref<SkFILEStream> fileStream(new SkFILEStream(file,
    498                          SkFILEStream::kCallerRetains_Ownership));
    499 
    500     // Use a buffered stream. Although an SkFILEStream can be rewound, this
    501     // ensures that SkImageDecoder::Factory never rewinds beyond the
    502     // current position of the file descriptor.
    503     SkAutoTUnref<SkStreamRewindable> stream(SkFrontBufferedStream::Create(fileStream,
    504             BYTES_TO_BUFFER));
    505 
    506     return doDecode(env, stream, padding, bitmapFactoryOptions);
    507 }
    508 
    509 static jobject nativeDecodeAsset(JNIEnv* env, jobject clazz, jlong native_asset,
    510         jobject padding, jobject options) {
    511 
    512     Asset* asset = reinterpret_cast<Asset*>(native_asset);
    513     // since we know we'll be done with the asset when we return, we can
    514     // just use a simple wrapper
    515     SkAutoTUnref<SkStreamRewindable> stream(new AssetStreamAdaptor(asset,
    516             AssetStreamAdaptor::kNo_OwnAsset, AssetStreamAdaptor::kNo_HasMemoryBase));
    517     return doDecode(env, stream, padding, options);
    518 }
    519 
    520 static jobject nativeDecodeByteArray(JNIEnv* env, jobject, jbyteArray byteArray,
    521         jint offset, jint length, jobject options) {
    522 
    523     AutoJavaByteArray ar(env, byteArray);
    524     SkMemoryStream* stream = new SkMemoryStream(ar.ptr() + offset, length, false);
    525     SkAutoUnref aur(stream);
    526     return doDecode(env, stream, NULL, options);
    527 }
    528 
    529 static void nativeRequestCancel(JNIEnv*, jobject joptions) {
    530     (void)AutoDecoderCancel::RequestCancel(joptions);
    531 }
    532 
    533 static 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 
    538 ///////////////////////////////////////////////////////////////////////////////
    539 
    540 static JNINativeMethod gMethods[] = {
    541     {   "nativeDecodeStream",
    542         "(Ljava/io/InputStream;[BLandroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
    543         (void*)nativeDecodeStream
    544     },
    545 
    546     {   "nativeDecodeFileDescriptor",
    547         "(Ljava/io/FileDescriptor;Landroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
    548         (void*)nativeDecodeFileDescriptor
    549     },
    550 
    551     {   "nativeDecodeAsset",
    552         "(JLandroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
    553         (void*)nativeDecodeAsset
    554     },
    555 
    556     {   "nativeDecodeByteArray",
    557         "([BIILandroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
    558         (void*)nativeDecodeByteArray
    559     },
    560 
    561     {   "nativeIsSeekable",
    562         "(Ljava/io/FileDescriptor;)Z",
    563         (void*)nativeIsSeekable
    564     },
    565 };
    566 
    567 static JNINativeMethod gOptionsMethods[] = {
    568     {   "requestCancel", "()V", (void*)nativeRequestCancel }
    569 };
    570 
    571 static jfieldID getFieldIDCheck(JNIEnv* env, jclass clazz,
    572                                 const char fieldname[], const char type[]) {
    573     jfieldID id = env->GetFieldID(clazz, fieldname, type);
    574     SkASSERT(id);
    575     return id;
    576 }
    577 
    578 int register_android_graphics_BitmapFactory(JNIEnv* env) {
    579     jclass options_class = env->FindClass("android/graphics/BitmapFactory$Options");
    580     SkASSERT(options_class);
    581     gOptions_bitmapFieldID = getFieldIDCheck(env, options_class, "inBitmap",
    582             "Landroid/graphics/Bitmap;");
    583     gOptions_justBoundsFieldID = getFieldIDCheck(env, options_class, "inJustDecodeBounds", "Z");
    584     gOptions_sampleSizeFieldID = getFieldIDCheck(env, options_class, "inSampleSize", "I");
    585     gOptions_configFieldID = getFieldIDCheck(env, options_class, "inPreferredConfig",
    586             "Landroid/graphics/Bitmap$Config;");
    587     gOptions_premultipliedFieldID = getFieldIDCheck(env, options_class, "inPremultiplied", "Z");
    588     gOptions_mutableFieldID = getFieldIDCheck(env, options_class, "inMutable", "Z");
    589     gOptions_ditherFieldID = getFieldIDCheck(env, options_class, "inDither", "Z");
    590     gOptions_preferQualityOverSpeedFieldID = getFieldIDCheck(env, options_class,
    591             "inPreferQualityOverSpeed", "Z");
    592     gOptions_scaledFieldID = getFieldIDCheck(env, options_class, "inScaled", "Z");
    593     gOptions_densityFieldID = getFieldIDCheck(env, options_class, "inDensity", "I");
    594     gOptions_screenDensityFieldID = getFieldIDCheck(env, options_class, "inScreenDensity", "I");
    595     gOptions_targetDensityFieldID = getFieldIDCheck(env, options_class, "inTargetDensity", "I");
    596     gOptions_widthFieldID = getFieldIDCheck(env, options_class, "outWidth", "I");
    597     gOptions_heightFieldID = getFieldIDCheck(env, options_class, "outHeight", "I");
    598     gOptions_mimeFieldID = getFieldIDCheck(env, options_class, "outMimeType", "Ljava/lang/String;");
    599     gOptions_mCancelID = getFieldIDCheck(env, options_class, "mCancel", "Z");
    600 
    601     jclass bitmap_class = env->FindClass("android/graphics/Bitmap");
    602     SkASSERT(bitmap_class);
    603     gBitmap_nativeBitmapFieldID = getFieldIDCheck(env, bitmap_class, "mNativeBitmap", "J");
    604     gBitmap_ninePatchInsetsFieldID = getFieldIDCheck(env, bitmap_class, "mNinePatchInsets",
    605             "Landroid/graphics/NinePatch$InsetStruct;");
    606 
    607     gInsetStruct_class = (jclass) env->NewGlobalRef(env->FindClass("android/graphics/NinePatch$InsetStruct"));
    608     gInsetStruct_constructorMethodID = env->GetMethodID(gInsetStruct_class, "<init>", "(IIIIIIIIFIF)V");
    609 
    610     int ret = AndroidRuntime::registerNativeMethods(env,
    611                                     "android/graphics/BitmapFactory$Options",
    612                                     gOptionsMethods,
    613                                     SK_ARRAY_COUNT(gOptionsMethods));
    614     if (ret) {
    615         return ret;
    616     }
    617     return android::AndroidRuntime::registerNativeMethods(env, "android/graphics/BitmapFactory",
    618                                          gMethods, SK_ARRAY_COUNT(gMethods));
    619 }
    620