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