BitmapFactory.cpp revision 02eb6bfd66d0afc4b1d81824558e136649a5a4df
1#define LOG_TAG "BitmapFactory"
2
3#include "BitmapFactory.h"
4#include "NinePatchPeeker.h"
5#include "SkData.h"
6#include "SkFrontBufferedStream.h"
7#include "SkImageDecoder.h"
8#include "SkImageRef_ashmem.h"
9#include "SkImageRef_GlobalPool.h"
10#include "SkPixelRef.h"
11#include "SkStream.h"
12#include "SkTemplates.h"
13#include "SkUtils.h"
14#include "CreateJavaOutputStreamAdaptor.h"
15#include "AutoDecodeCancel.h"
16#include "Utils.h"
17#include "JNIHelp.h"
18#include "GraphicsJNI.h"
19
20#include <android_runtime/AndroidRuntime.h>
21#include <androidfw/Asset.h>
22#include <androidfw/ResourceTypes.h>
23#include <netinet/in.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_purgeableFieldID;
34jfieldID gOptions_shareableFieldID;
35jfieldID gOptions_preferQualityOverSpeedFieldID;
36jfieldID gOptions_scaledFieldID;
37jfieldID gOptions_densityFieldID;
38jfieldID gOptions_screenDensityFieldID;
39jfieldID gOptions_targetDensityFieldID;
40jfieldID gOptions_widthFieldID;
41jfieldID gOptions_heightFieldID;
42jfieldID gOptions_mimeFieldID;
43jfieldID gOptions_mCancelID;
44jfieldID gOptions_bitmapFieldID;
45jfieldID gBitmap_nativeBitmapFieldID;
46jfieldID gBitmap_layoutBoundsFieldID;
47
48#if 0
49    #define TRACE_BITMAP(code)  code
50#else
51    #define TRACE_BITMAP(code)
52#endif
53
54using namespace android;
55
56static inline int32_t validOrNeg1(bool isValid, int32_t value) {
57//    return isValid ? value : -1;
58    SkASSERT((int)isValid == 0 || (int)isValid == 1);
59    return ((int32_t)isValid - 1) | value;
60}
61
62jstring getMimeTypeString(JNIEnv* env, SkImageDecoder::Format format) {
63    static const struct {
64        SkImageDecoder::Format fFormat;
65        const char*            fMimeType;
66    } gMimeTypes[] = {
67        { SkImageDecoder::kBMP_Format,  "image/bmp" },
68        { SkImageDecoder::kGIF_Format,  "image/gif" },
69        { SkImageDecoder::kICO_Format,  "image/x-ico" },
70        { SkImageDecoder::kJPEG_Format, "image/jpeg" },
71        { SkImageDecoder::kPNG_Format,  "image/png" },
72        { SkImageDecoder::kWEBP_Format, "image/webp" },
73        { SkImageDecoder::kWBMP_Format, "image/vnd.wap.wbmp" }
74    };
75
76    const char* cstr = NULL;
77    for (size_t i = 0; i < SK_ARRAY_COUNT(gMimeTypes); i++) {
78        if (gMimeTypes[i].fFormat == format) {
79            cstr = gMimeTypes[i].fMimeType;
80            break;
81        }
82    }
83
84    jstring jstr = 0;
85    if (NULL != cstr) {
86        jstr = env->NewStringUTF(cstr);
87    }
88    return jstr;
89}
90
91static bool optionsPurgeable(JNIEnv* env, jobject options) {
92    return options != NULL && env->GetBooleanField(options, gOptions_purgeableFieldID);
93}
94
95static bool optionsShareable(JNIEnv* env, jobject options) {
96    return options != NULL && env->GetBooleanField(options, gOptions_shareableFieldID);
97}
98
99static bool optionsJustBounds(JNIEnv* env, jobject options) {
100    return options != NULL && env->GetBooleanField(options, gOptions_justBoundsFieldID);
101}
102
103static void scaleNinePatchChunk(android::Res_png_9patch* chunk, float scale) {
104    chunk->paddingLeft = int(chunk->paddingLeft * scale + 0.5f);
105    chunk->paddingTop = int(chunk->paddingTop * scale + 0.5f);
106    chunk->paddingRight = int(chunk->paddingRight * scale + 0.5f);
107    chunk->paddingBottom = int(chunk->paddingBottom * scale + 0.5f);
108
109    int32_t* xDivs = chunk->getXDivs();
110    for (int i = 0; i < chunk->numXDivs; i++) {
111        xDivs[i] = int32_t(xDivs[i] * scale + 0.5f);
112        if (i > 0 && xDivs[i] == xDivs[i - 1]) {
113            xDivs[i]++;
114        }
115    }
116
117    int32_t* yDivs = chunk->getYDivs();
118    for (int i = 0; i < chunk->numYDivs; i++) {
119        yDivs[i] = int32_t(yDivs[i] * scale + 0.5f);
120        if (i > 0 && yDivs[i] == yDivs[i - 1]) {
121            yDivs[i]++;
122        }
123    }
124}
125
126static SkPixelRef* installPixelRef(SkBitmap* bitmap, SkStreamRewindable* stream,
127        int sampleSize, bool ditherImage) {
128
129    SkImageRef* pr;
130    // only use ashmem for large images, since mmaps come at a price
131    if (bitmap->getSize() >= 32 * 1024) {
132        pr = new SkImageRef_ashmem(stream, bitmap->config(), sampleSize);
133    } else {
134        pr = new SkImageRef_GlobalPool(stream, bitmap->config(), sampleSize);
135    }
136    pr->setDitherImage(ditherImage);
137    bitmap->setPixelRef(pr)->unref();
138    pr->isOpaque(bitmap);
139    return pr;
140}
141
142static SkBitmap::Config configForScaledOutput(SkBitmap::Config config) {
143    switch (config) {
144        case SkBitmap::kNo_Config:
145        case SkBitmap::kIndex8_Config:
146            return SkBitmap::kARGB_8888_Config;
147        default:
148            break;
149    }
150    return config;
151}
152
153class ScaleCheckingAllocator : public SkBitmap::HeapAllocator {
154public:
155    ScaleCheckingAllocator(float scale, int size)
156            : mScale(scale), mSize(size) {
157    }
158
159    virtual bool allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable) {
160        // accounts for scale in final allocation, using eventual size and config
161        const int bytesPerPixel = SkBitmap::ComputeBytesPerPixel(
162                configForScaledOutput(bitmap->getConfig()));
163        const int requestedSize = bytesPerPixel *
164                int(bitmap->width() * mScale + 0.5f) *
165                int(bitmap->height() * mScale + 0.5f);
166        if (requestedSize > mSize) {
167            ALOGW("bitmap for alloc reuse (%d bytes) can't fit scaled bitmap (%d bytes)",
168                    mSize, requestedSize);
169            return false;
170        }
171        return SkBitmap::HeapAllocator::allocPixelRef(bitmap, ctable);
172    }
173private:
174    const float mScale;
175    const int mSize;
176};
177
178class RecyclingPixelAllocator : public SkBitmap::Allocator {
179public:
180    RecyclingPixelAllocator(SkPixelRef* pixelRef, unsigned int size)
181            : mPixelRef(pixelRef), mSize(size) {
182        SkSafeRef(mPixelRef);
183    }
184
185    ~RecyclingPixelAllocator() {
186        SkSafeUnref(mPixelRef);
187    }
188
189    virtual bool allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable) {
190        if (!bitmap->getSize64().is32() || bitmap->getSize() > mSize) {
191            ALOGW("bitmap marked for reuse (%d bytes) can't fit new bitmap (%d bytes)",
192                    mSize, bitmap->getSize());
193            return false;
194        }
195
196        // Create a new pixelref with the new ctable that wraps the previous pixelref
197        SkPixelRef* pr = new AndroidPixelRef(*static_cast<AndroidPixelRef*>(mPixelRef), ctable);
198
199        bitmap->setPixelRef(pr)->unref();
200        // since we're already allocated, we lockPixels right away
201        // HeapAllocator/JavaPixelAllocator behaves this way too
202        bitmap->lockPixels();
203        return true;
204    }
205
206private:
207    SkPixelRef* const mPixelRef;
208    const unsigned int mSize;
209};
210
211// since we "may" create a purgeable imageref, we require the stream be ref'able
212// i.e. dynamically allocated, since its lifetime may exceed the current stack
213// frame.
214static jobject doDecode(JNIEnv* env, SkStreamRewindable* stream, jobject padding,
215        jobject options, bool allowPurgeable, bool forcePurgeable = false) {
216
217    int sampleSize = 1;
218
219    SkImageDecoder::Mode mode = SkImageDecoder::kDecodePixels_Mode;
220    SkBitmap::Config prefConfig = SkBitmap::kARGB_8888_Config;
221
222    bool doDither = true;
223    bool isMutable = false;
224    float scale = 1.0f;
225    bool isPurgeable = forcePurgeable || (allowPurgeable && optionsPurgeable(env, options));
226    bool preferQualityOverSpeed = false;
227    bool requireUnpremultiplied = false;
228
229    jobject javaBitmap = NULL;
230
231    if (options != NULL) {
232        sampleSize = env->GetIntField(options, gOptions_sampleSizeFieldID);
233        if (optionsJustBounds(env, options)) {
234            mode = SkImageDecoder::kDecodeBounds_Mode;
235        }
236
237        // initialize these, in case we fail later on
238        env->SetIntField(options, gOptions_widthFieldID, -1);
239        env->SetIntField(options, gOptions_heightFieldID, -1);
240        env->SetObjectField(options, gOptions_mimeFieldID, 0);
241
242        jobject jconfig = env->GetObjectField(options, gOptions_configFieldID);
243        prefConfig = GraphicsJNI::getNativeBitmapConfig(env, jconfig);
244        isMutable = env->GetBooleanField(options, gOptions_mutableFieldID);
245        doDither = env->GetBooleanField(options, gOptions_ditherFieldID);
246        preferQualityOverSpeed = env->GetBooleanField(options,
247                gOptions_preferQualityOverSpeedFieldID);
248        requireUnpremultiplied = !env->GetBooleanField(options, gOptions_premultipliedFieldID);
249        javaBitmap = env->GetObjectField(options, gOptions_bitmapFieldID);
250
251        if (env->GetBooleanField(options, gOptions_scaledFieldID)) {
252            const int density = env->GetIntField(options, gOptions_densityFieldID);
253            const int targetDensity = env->GetIntField(options, gOptions_targetDensityFieldID);
254            const int screenDensity = env->GetIntField(options, gOptions_screenDensityFieldID);
255            if (density != 0 && targetDensity != 0 && density != screenDensity) {
256                scale = (float) targetDensity / density;
257            }
258        }
259    }
260
261    const bool willScale = scale != 1.0f;
262    isPurgeable &= !willScale;
263
264    SkImageDecoder* decoder = SkImageDecoder::Factory(stream);
265    if (decoder == NULL) {
266        return nullObjectReturn("SkImageDecoder::Factory returned null");
267    }
268
269    decoder->setSampleSize(sampleSize);
270    decoder->setDitherImage(doDither);
271    decoder->setPreferQualityOverSpeed(preferQualityOverSpeed);
272    decoder->setRequireUnpremultipliedColors(requireUnpremultiplied);
273
274    SkBitmap* outputBitmap = NULL;
275    unsigned int existingBufferSize = 0;
276    if (javaBitmap != NULL) {
277        outputBitmap = (SkBitmap*) env->GetLongField(javaBitmap, gBitmap_nativeBitmapFieldID);
278        if (outputBitmap->isImmutable()) {
279            ALOGW("Unable to reuse an immutable bitmap as an image decoder target.");
280            javaBitmap = NULL;
281            outputBitmap = NULL;
282        } else {
283            existingBufferSize = GraphicsJNI::getBitmapAllocationByteCount(env, javaBitmap);
284        }
285    }
286
287    SkAutoTDelete<SkBitmap> adb(outputBitmap == NULL ? new SkBitmap : NULL);
288    if (outputBitmap == NULL) outputBitmap = adb.get();
289
290    NinePatchPeeker peeker(decoder);
291    decoder->setPeeker(&peeker);
292
293    SkImageDecoder::Mode decodeMode = isPurgeable ? SkImageDecoder::kDecodeBounds_Mode : mode;
294
295    JavaPixelAllocator javaAllocator(env);
296    RecyclingPixelAllocator recyclingAllocator(outputBitmap->pixelRef(), existingBufferSize);
297    ScaleCheckingAllocator scaleCheckingAllocator(scale, existingBufferSize);
298    SkBitmap::Allocator* outputAllocator = (javaBitmap != NULL) ?
299            (SkBitmap::Allocator*)&recyclingAllocator : (SkBitmap::Allocator*)&javaAllocator;
300    if (decodeMode != SkImageDecoder::kDecodeBounds_Mode) {
301        if (!willScale) {
302            // If the java allocator is being used to allocate the pixel memory, the decoder
303            // need not write zeroes, since the memory is initialized to 0.
304            decoder->setSkipWritingZeroes(outputAllocator == &javaAllocator);
305            decoder->setAllocator(outputAllocator);
306        } else if (javaBitmap != NULL) {
307            // check for eventual scaled bounds at allocation time, so we don't decode the bitmap
308            // only to find the scaled result too large to fit in the allocation
309            decoder->setAllocator(&scaleCheckingAllocator);
310        }
311    }
312
313    // Only setup the decoder to be deleted after its stack-based, refcounted
314    // components (allocators, peekers, etc) are declared. This prevents RefCnt
315    // asserts from firing due to the order objects are deleted from the stack.
316    SkAutoTDelete<SkImageDecoder> add(decoder);
317
318    AutoDecoderCancel adc(options, decoder);
319
320    // To fix the race condition in case "requestCancelDecode"
321    // happens earlier than AutoDecoderCancel object is added
322    // to the gAutoDecoderCancelMutex linked list.
323    if (options != NULL && env->GetBooleanField(options, gOptions_mCancelID)) {
324        return nullObjectReturn("gOptions_mCancelID");
325    }
326
327    SkBitmap decodingBitmap;
328    if (!decoder->decode(stream, &decodingBitmap, prefConfig, decodeMode)) {
329        return nullObjectReturn("decoder->decode returned false");
330    }
331
332    int scaledWidth = decodingBitmap.width();
333    int scaledHeight = decodingBitmap.height();
334
335    if (willScale && mode != SkImageDecoder::kDecodeBounds_Mode) {
336        scaledWidth = int(scaledWidth * scale + 0.5f);
337        scaledHeight = int(scaledHeight * scale + 0.5f);
338    }
339
340    // update options (if any)
341    if (options != NULL) {
342        env->SetIntField(options, gOptions_widthFieldID, scaledWidth);
343        env->SetIntField(options, gOptions_heightFieldID, scaledHeight);
344        env->SetObjectField(options, gOptions_mimeFieldID,
345                getMimeTypeString(env, decoder->getFormat()));
346    }
347
348    // if we're in justBounds mode, return now (skip the java bitmap)
349    if (mode == SkImageDecoder::kDecodeBounds_Mode) {
350        return NULL;
351    }
352
353    jbyteArray ninePatchChunk = NULL;
354    if (peeker.fPatch != NULL) {
355        if (willScale) {
356            scaleNinePatchChunk(peeker.fPatch, scale);
357        }
358
359        size_t ninePatchArraySize = peeker.fPatch->serializedSize();
360        ninePatchChunk = env->NewByteArray(ninePatchArraySize);
361        if (ninePatchChunk == NULL) {
362            return nullObjectReturn("ninePatchChunk == null");
363        }
364
365        jbyte* array = (jbyte*) env->GetPrimitiveArrayCritical(ninePatchChunk, NULL);
366        if (array == NULL) {
367            return nullObjectReturn("primitive array == null");
368        }
369
370        memcpy(array, peeker.fPatch, peeker.fPatchSize);
371        env->ReleasePrimitiveArrayCritical(ninePatchChunk, array, 0);
372    }
373
374    jintArray layoutBounds = NULL;
375    if (peeker.fLayoutBounds != NULL) {
376        layoutBounds = env->NewIntArray(4);
377        if (layoutBounds == NULL) {
378            return nullObjectReturn("layoutBounds == null");
379        }
380
381        jint scaledBounds[4];
382        if (willScale) {
383            for (int i=0; i<4; i++) {
384                scaledBounds[i] = (jint)((((jint*)peeker.fLayoutBounds)[i]*scale) + .5f);
385            }
386        } else {
387            memcpy(scaledBounds, (jint*)peeker.fLayoutBounds, sizeof(scaledBounds));
388        }
389        env->SetIntArrayRegion(layoutBounds, 0, 4, scaledBounds);
390        if (javaBitmap != NULL) {
391            env->SetObjectField(javaBitmap, gBitmap_layoutBoundsFieldID, layoutBounds);
392        }
393    }
394
395    if (willScale) {
396        // This is weird so let me explain: we could use the scale parameter
397        // directly, but for historical reasons this is how the corresponding
398        // Dalvik code has always behaved. We simply recreate the behavior here.
399        // The result is slightly different from simply using scale because of
400        // the 0.5f rounding bias applied when computing the target image size
401        const float sx = scaledWidth / float(decodingBitmap.width());
402        const float sy = scaledHeight / float(decodingBitmap.height());
403
404        // TODO: avoid copying when scaled size equals decodingBitmap size
405        SkBitmap::Config config = configForScaledOutput(decodingBitmap.config());
406        outputBitmap->setConfig(config, scaledWidth, scaledHeight);
407        outputBitmap->setIsOpaque(decodingBitmap.isOpaque());
408        if (!outputBitmap->allocPixels(outputAllocator, NULL)) {
409            return nullObjectReturn("allocation failed for scaled bitmap");
410        }
411
412        // If outputBitmap's pixels are newly allocated by Java, there is no need
413        // to erase to 0, since the pixels were initialized to 0.
414        if (outputAllocator != &javaAllocator) {
415            outputBitmap->eraseColor(0);
416        }
417
418        SkPaint paint;
419        paint.setFilterBitmap(true);
420
421        SkCanvas canvas(*outputBitmap);
422        canvas.scale(sx, sy);
423        canvas.drawBitmap(decodingBitmap, 0.0f, 0.0f, &paint);
424    } else {
425        outputBitmap->swap(decodingBitmap);
426    }
427
428    if (padding) {
429        if (peeker.fPatch != NULL) {
430            GraphicsJNI::set_jrect(env, padding,
431                    peeker.fPatch->paddingLeft, peeker.fPatch->paddingTop,
432                    peeker.fPatch->paddingRight, peeker.fPatch->paddingBottom);
433        } else {
434            GraphicsJNI::set_jrect(env, padding, -1, -1, -1, -1);
435        }
436    }
437
438    SkPixelRef* pr;
439    if (isPurgeable) {
440        pr = installPixelRef(outputBitmap, stream, sampleSize, doDither);
441    } else {
442        // if we get here, we're in kDecodePixels_Mode and will therefore
443        // already have a pixelref installed.
444        pr = outputBitmap->pixelRef();
445    }
446    if (pr == NULL) {
447        return nullObjectReturn("Got null SkPixelRef");
448    }
449
450    if (!isMutable && javaBitmap == NULL) {
451        // promise we will never change our pixels (great for sharing and pictures)
452        pr->setImmutable();
453    }
454
455    // detach bitmap from its autodeleter, since we want to own it now
456    adb.detach();
457
458    if (javaBitmap != NULL) {
459        bool isPremultiplied = !requireUnpremultiplied;
460        GraphicsJNI::reinitBitmap(env, javaBitmap, outputBitmap, isPremultiplied);
461        outputBitmap->notifyPixelsChanged();
462        // If a java bitmap was passed in for reuse, pass it back
463        return javaBitmap;
464    }
465
466    int bitmapCreateFlags = 0x0;
467    if (isMutable) bitmapCreateFlags |= GraphicsJNI::kBitmapCreateFlag_Mutable;
468    if (!requireUnpremultiplied) bitmapCreateFlags |= GraphicsJNI::kBitmapCreateFlag_Premultiplied;
469
470    // now create the java bitmap
471    return GraphicsJNI::createBitmap(env, outputBitmap, javaAllocator.getStorageObj(),
472            bitmapCreateFlags, ninePatchChunk, layoutBounds, -1);
473}
474
475static jobject nativeDecodeStream(JNIEnv* env, jobject clazz, jobject is, jbyteArray storage,
476        jobject padding, jobject options) {
477
478    jobject bitmap = NULL;
479    SkAutoTUnref<SkStream> stream(CreateJavaInputStreamAdaptor(env, is, storage));
480
481    if (stream.get()) {
482        // Need to buffer enough input to be able to rewind as much as might be read by a decoder
483        // trying to determine the stream's format. Currently the most is 64, read by
484        // SkImageDecoder_libwebp.
485        // FIXME: Get this number from SkImageDecoder
486        SkAutoTUnref<SkStreamRewindable> bufferedStream(SkFrontBufferedStream::Create(stream, 64));
487        SkASSERT(bufferedStream.get() != NULL);
488        // for now we don't allow purgeable with java inputstreams
489        bitmap = doDecode(env, bufferedStream, padding, options, false, false);
490    }
491    return bitmap;
492}
493
494static jobject nativeDecodeFileDescriptor(JNIEnv* env, jobject clazz, jobject fileDescriptor,
495        jobject padding, jobject bitmapFactoryOptions) {
496
497    NPE_CHECK_RETURN_ZERO(env, fileDescriptor);
498
499    jint descriptor = jniGetFDFromFileDescriptor(env, fileDescriptor);
500
501    struct stat fdStat;
502    if (fstat(descriptor, &fdStat) == -1) {
503        doThrowIOE(env, "broken file descriptor");
504        return nullObjectReturn("fstat return -1");
505    }
506
507    bool isPurgeable = optionsPurgeable(env, bitmapFactoryOptions);
508    bool isShareable = optionsShareable(env, bitmapFactoryOptions);
509    bool weOwnTheFD = false;
510    if (isPurgeable && isShareable) {
511        int newFD = ::dup(descriptor);
512        if (-1 != newFD) {
513            weOwnTheFD = true;
514            descriptor = newFD;
515        }
516    }
517
518    SkAutoTUnref<SkData> data(SkData::NewFromFD(descriptor));
519    if (data.get() == NULL) {
520        return nullObjectReturn("NewFromFD failed in nativeDecodeFileDescriptor");
521    }
522    SkAutoTUnref<SkMemoryStream> stream(new SkMemoryStream(data));
523
524    /* Allow purgeable iff we own the FD, i.e., in the puregeable and
525       shareable case.
526    */
527    return doDecode(env, stream, padding, bitmapFactoryOptions, weOwnTheFD);
528}
529
530static jobject nativeDecodeAsset(JNIEnv* env, jobject clazz, jlong native_asset,
531        jobject padding, jobject options) {
532
533    SkStreamRewindable* stream;
534    Asset* asset = reinterpret_cast<Asset*>(native_asset);
535    bool forcePurgeable = optionsPurgeable(env, options);
536    if (forcePurgeable) {
537        // if we could "ref/reopen" the asset, we may not need to copy it here
538        // and we could assume optionsShareable, since assets are always RO
539        stream = CopyAssetToStream(asset);
540        if (stream == NULL) {
541            return NULL;
542        }
543    } else {
544        // since we know we'll be done with the asset when we return, we can
545        // just use a simple wrapper
546        stream = new AssetStreamAdaptor(asset);
547    }
548    SkAutoUnref aur(stream);
549    return doDecode(env, stream, padding, options, forcePurgeable, forcePurgeable);
550}
551
552static jobject nativeDecodeByteArray(JNIEnv* env, jobject, jbyteArray byteArray,
553        jint offset, jint length, jobject options) {
554
555    /*  If optionsShareable() we could decide to just wrap the java array and
556        share it, but that means adding a globalref to the java array object
557        and managing its lifetime. For now we just always copy the array's data
558        if optionsPurgeable(), unless we're just decoding bounds.
559     */
560    bool purgeable = optionsPurgeable(env, options) && !optionsJustBounds(env, options);
561    AutoJavaByteArray ar(env, byteArray);
562    SkMemoryStream* stream = new SkMemoryStream(ar.ptr() + offset, length, purgeable);
563    SkAutoUnref aur(stream);
564    return doDecode(env, stream, NULL, options, purgeable);
565}
566
567static void nativeRequestCancel(JNIEnv*, jobject joptions) {
568    (void)AutoDecoderCancel::RequestCancel(joptions);
569}
570
571static jboolean nativeIsSeekable(JNIEnv* env, jobject, jobject fileDescriptor) {
572    jint descriptor = jniGetFDFromFileDescriptor(env, fileDescriptor);
573    return ::lseek64(descriptor, 0, SEEK_CUR) != -1 ? JNI_TRUE : JNI_FALSE;
574}
575
576///////////////////////////////////////////////////////////////////////////////
577
578static JNINativeMethod gMethods[] = {
579    {   "nativeDecodeStream",
580        "(Ljava/io/InputStream;[BLandroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
581        (void*)nativeDecodeStream
582    },
583
584    {   "nativeDecodeFileDescriptor",
585        "(Ljava/io/FileDescriptor;Landroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
586        (void*)nativeDecodeFileDescriptor
587    },
588
589    {   "nativeDecodeAsset",
590        "(JLandroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
591        (void*)nativeDecodeAsset
592    },
593
594    {   "nativeDecodeByteArray",
595        "([BIILandroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
596        (void*)nativeDecodeByteArray
597    },
598
599    {   "nativeIsSeekable",
600        "(Ljava/io/FileDescriptor;)Z",
601        (void*)nativeIsSeekable
602    },
603};
604
605static JNINativeMethod gOptionsMethods[] = {
606    {   "requestCancel", "()V", (void*)nativeRequestCancel }
607};
608
609static jfieldID getFieldIDCheck(JNIEnv* env, jclass clazz,
610                                const char fieldname[], const char type[]) {
611    jfieldID id = env->GetFieldID(clazz, fieldname, type);
612    SkASSERT(id);
613    return id;
614}
615
616int register_android_graphics_BitmapFactory(JNIEnv* env) {
617    jclass options_class = env->FindClass("android/graphics/BitmapFactory$Options");
618    SkASSERT(options_class);
619    gOptions_bitmapFieldID = getFieldIDCheck(env, options_class, "inBitmap",
620        "Landroid/graphics/Bitmap;");
621    gOptions_justBoundsFieldID = getFieldIDCheck(env, options_class, "inJustDecodeBounds", "Z");
622    gOptions_sampleSizeFieldID = getFieldIDCheck(env, options_class, "inSampleSize", "I");
623    gOptions_configFieldID = getFieldIDCheck(env, options_class, "inPreferredConfig",
624            "Landroid/graphics/Bitmap$Config;");
625    gOptions_premultipliedFieldID = getFieldIDCheck(env, options_class, "inPremultiplied", "Z");
626    gOptions_mutableFieldID = getFieldIDCheck(env, options_class, "inMutable", "Z");
627    gOptions_ditherFieldID = getFieldIDCheck(env, options_class, "inDither", "Z");
628    gOptions_purgeableFieldID = getFieldIDCheck(env, options_class, "inPurgeable", "Z");
629    gOptions_shareableFieldID = getFieldIDCheck(env, options_class, "inInputShareable", "Z");
630    gOptions_preferQualityOverSpeedFieldID = getFieldIDCheck(env, options_class,
631            "inPreferQualityOverSpeed", "Z");
632    gOptions_scaledFieldID = getFieldIDCheck(env, options_class, "inScaled", "Z");
633    gOptions_densityFieldID = getFieldIDCheck(env, options_class, "inDensity", "I");
634    gOptions_screenDensityFieldID = getFieldIDCheck(env, options_class, "inScreenDensity", "I");
635    gOptions_targetDensityFieldID = getFieldIDCheck(env, options_class, "inTargetDensity", "I");
636    gOptions_widthFieldID = getFieldIDCheck(env, options_class, "outWidth", "I");
637    gOptions_heightFieldID = getFieldIDCheck(env, options_class, "outHeight", "I");
638    gOptions_mimeFieldID = getFieldIDCheck(env, options_class, "outMimeType", "Ljava/lang/String;");
639    gOptions_mCancelID = getFieldIDCheck(env, options_class, "mCancel", "Z");
640
641    jclass bitmap_class = env->FindClass("android/graphics/Bitmap");
642    SkASSERT(bitmap_class);
643    gBitmap_nativeBitmapFieldID = getFieldIDCheck(env, bitmap_class, "mNativeBitmap", "J");
644    gBitmap_layoutBoundsFieldID = getFieldIDCheck(env, bitmap_class, "mLayoutBounds", "[I");
645    int ret = AndroidRuntime::registerNativeMethods(env,
646                                    "android/graphics/BitmapFactory$Options",
647                                    gOptionsMethods,
648                                    SK_ARRAY_COUNT(gOptionsMethods));
649    if (ret) {
650        return ret;
651    }
652    return android::AndroidRuntime::registerNativeMethods(env, "android/graphics/BitmapFactory",
653                                         gMethods, SK_ARRAY_COUNT(gMethods));
654}
655