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