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