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