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