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