BitmapFactory.cpp revision 2826e5f20295a1adb3b341c8b32f27d748e2ee19
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->GetLongField(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 477// Need to buffer enough input to be able to rewind as much as might be read by a decoder 478// trying to determine the stream's format. Currently the most is 64, read by 479// SkImageDecoder_libwebp. 480// FIXME: Get this number from SkImageDecoder 481#define BYTES_TO_BUFFER 64 482 483static jobject nativeDecodeStream(JNIEnv* env, jobject clazz, jobject is, jbyteArray storage, 484 jobject padding, jobject options) { 485 486 jobject bitmap = NULL; 487 SkAutoTUnref<SkStream> stream(CreateJavaInputStreamAdaptor(env, is, storage)); 488 489 if (stream.get()) { 490 SkAutoTUnref<SkStreamRewindable> bufferedStream( 491 SkFrontBufferedStream::Create(stream, BYTES_TO_BUFFER)); 492 SkASSERT(bufferedStream.get() != NULL); 493 // for now we don't allow purgeable with java inputstreams 494 bitmap = doDecode(env, bufferedStream, padding, options, false, false); 495 } 496 return bitmap; 497} 498 499static jobject nativeDecodeFileDescriptor(JNIEnv* env, jobject clazz, jobject fileDescriptor, 500 jobject padding, jobject bitmapFactoryOptions) { 501 502 NPE_CHECK_RETURN_ZERO(env, fileDescriptor); 503 504 jint descriptor = jniGetFDFromFileDescriptor(env, fileDescriptor); 505 506 struct stat fdStat; 507 if (fstat(descriptor, &fdStat) == -1) { 508 doThrowIOE(env, "broken file descriptor"); 509 return nullObjectReturn("fstat return -1"); 510 } 511 512 // Restore the descriptor's offset on exiting this function. 513 AutoFDSeek autoRestore(descriptor); 514 515 FILE* file = fdopen(descriptor, "r"); 516 if (file == NULL) { 517 return nullObjectReturn("Could not open file"); 518 } 519 520 SkAutoTUnref<SkFILEStream> fileStream(new SkFILEStream(file, 521 SkFILEStream::kCallerRetains_Ownership)); 522 523 SkAutoTUnref<SkStreamRewindable> stream; 524 525 // Retain the old behavior of allowing purgeable if both purgeable and 526 // shareable are set to true. 527 bool isPurgeable = optionsPurgeable(env, bitmapFactoryOptions) 528 && optionsShareable(env, bitmapFactoryOptions); 529 if (isPurgeable) { 530 // Copy the stream, so the image can be decoded multiple times without 531 // continuing to modify the original file descriptor. 532 // Copy beginning from the current position. 533 const size_t fileSize = fileStream->getLength() - fileStream->getPosition(); 534 void* buffer = sk_malloc_flags(fileSize, 0); 535 if (buffer == NULL) { 536 return nullObjectReturn("Could not make a copy for ashmem"); 537 } 538 539 SkAutoTUnref<SkData> data(SkData::NewFromMalloc(buffer, fileSize)); 540 541 if (fileStream->read(buffer, fileSize) != fileSize) { 542 return nullObjectReturn("Could not read the file."); 543 } 544 545 stream.reset(new SkMemoryStream(data)); 546 } else { 547 // Use a buffered stream. Although an SkFILEStream can be rewound, this 548 // ensures that SkImageDecoder::Factory never rewinds beyond the 549 // current position of the file descriptor. 550 stream.reset(SkFrontBufferedStream::Create(fileStream, BYTES_TO_BUFFER)); 551 } 552 553 return doDecode(env, stream, padding, bitmapFactoryOptions, isPurgeable); 554} 555 556static jobject nativeDecodeAsset(JNIEnv* env, jobject clazz, jlong native_asset, 557 jobject padding, jobject options) { 558 559 SkStreamRewindable* stream; 560 Asset* asset = reinterpret_cast<Asset*>(native_asset); 561 bool forcePurgeable = optionsPurgeable(env, options); 562 if (forcePurgeable) { 563 // if we could "ref/reopen" the asset, we may not need to copy it here 564 // and we could assume optionsShareable, since assets are always RO 565 stream = CopyAssetToStream(asset); 566 if (stream == NULL) { 567 return NULL; 568 } 569 } else { 570 // since we know we'll be done with the asset when we return, we can 571 // just use a simple wrapper 572 stream = new AssetStreamAdaptor(asset, 573 AssetStreamAdaptor::kNo_OwnAsset, 574 AssetStreamAdaptor::kNo_HasMemoryBase); 575 } 576 SkAutoUnref aur(stream); 577 return doDecode(env, stream, padding, options, forcePurgeable, forcePurgeable); 578} 579 580static jobject nativeDecodeByteArray(JNIEnv* env, jobject, jbyteArray byteArray, 581 jint offset, jint length, jobject options) { 582 583 /* If optionsShareable() we could decide to just wrap the java array and 584 share it, but that means adding a globalref to the java array object 585 and managing its lifetime. For now we just always copy the array's data 586 if optionsPurgeable(), unless we're just decoding bounds. 587 */ 588 bool purgeable = optionsPurgeable(env, options) && !optionsJustBounds(env, options); 589 AutoJavaByteArray ar(env, byteArray); 590 SkMemoryStream* stream = new SkMemoryStream(ar.ptr() + offset, length, purgeable); 591 SkAutoUnref aur(stream); 592 return doDecode(env, stream, NULL, options, purgeable); 593} 594 595static void nativeRequestCancel(JNIEnv*, jobject joptions) { 596 (void)AutoDecoderCancel::RequestCancel(joptions); 597} 598 599static jboolean nativeIsSeekable(JNIEnv* env, jobject, jobject fileDescriptor) { 600 jint descriptor = jniGetFDFromFileDescriptor(env, fileDescriptor); 601 return ::lseek64(descriptor, 0, SEEK_CUR) != -1 ? JNI_TRUE : JNI_FALSE; 602} 603 604/////////////////////////////////////////////////////////////////////////////// 605 606static JNINativeMethod gMethods[] = { 607 { "nativeDecodeStream", 608 "(Ljava/io/InputStream;[BLandroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;", 609 (void*)nativeDecodeStream 610 }, 611 612 { "nativeDecodeFileDescriptor", 613 "(Ljava/io/FileDescriptor;Landroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;", 614 (void*)nativeDecodeFileDescriptor 615 }, 616 617 { "nativeDecodeAsset", 618 "(JLandroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;", 619 (void*)nativeDecodeAsset 620 }, 621 622 { "nativeDecodeByteArray", 623 "([BIILandroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;", 624 (void*)nativeDecodeByteArray 625 }, 626 627 { "nativeIsSeekable", 628 "(Ljava/io/FileDescriptor;)Z", 629 (void*)nativeIsSeekable 630 }, 631}; 632 633static JNINativeMethod gOptionsMethods[] = { 634 { "requestCancel", "()V", (void*)nativeRequestCancel } 635}; 636 637static jfieldID getFieldIDCheck(JNIEnv* env, jclass clazz, 638 const char fieldname[], const char type[]) { 639 jfieldID id = env->GetFieldID(clazz, fieldname, type); 640 SkASSERT(id); 641 return id; 642} 643 644int register_android_graphics_BitmapFactory(JNIEnv* env) { 645 jclass options_class = env->FindClass("android/graphics/BitmapFactory$Options"); 646 SkASSERT(options_class); 647 gOptions_bitmapFieldID = getFieldIDCheck(env, options_class, "inBitmap", 648 "Landroid/graphics/Bitmap;"); 649 gOptions_justBoundsFieldID = getFieldIDCheck(env, options_class, "inJustDecodeBounds", "Z"); 650 gOptions_sampleSizeFieldID = getFieldIDCheck(env, options_class, "inSampleSize", "I"); 651 gOptions_configFieldID = getFieldIDCheck(env, options_class, "inPreferredConfig", 652 "Landroid/graphics/Bitmap$Config;"); 653 gOptions_premultipliedFieldID = getFieldIDCheck(env, options_class, "inPremultiplied", "Z"); 654 gOptions_mutableFieldID = getFieldIDCheck(env, options_class, "inMutable", "Z"); 655 gOptions_ditherFieldID = getFieldIDCheck(env, options_class, "inDither", "Z"); 656 gOptions_purgeableFieldID = getFieldIDCheck(env, options_class, "inPurgeable", "Z"); 657 gOptions_shareableFieldID = getFieldIDCheck(env, options_class, "inInputShareable", "Z"); 658 gOptions_preferQualityOverSpeedFieldID = getFieldIDCheck(env, options_class, 659 "inPreferQualityOverSpeed", "Z"); 660 gOptions_scaledFieldID = getFieldIDCheck(env, options_class, "inScaled", "Z"); 661 gOptions_densityFieldID = getFieldIDCheck(env, options_class, "inDensity", "I"); 662 gOptions_screenDensityFieldID = getFieldIDCheck(env, options_class, "inScreenDensity", "I"); 663 gOptions_targetDensityFieldID = getFieldIDCheck(env, options_class, "inTargetDensity", "I"); 664 gOptions_widthFieldID = getFieldIDCheck(env, options_class, "outWidth", "I"); 665 gOptions_heightFieldID = getFieldIDCheck(env, options_class, "outHeight", "I"); 666 gOptions_mimeFieldID = getFieldIDCheck(env, options_class, "outMimeType", "Ljava/lang/String;"); 667 gOptions_mCancelID = getFieldIDCheck(env, options_class, "mCancel", "Z"); 668 669 jclass bitmap_class = env->FindClass("android/graphics/Bitmap"); 670 SkASSERT(bitmap_class); 671 gBitmap_nativeBitmapFieldID = getFieldIDCheck(env, bitmap_class, "mNativeBitmap", "J"); 672 gBitmap_layoutBoundsFieldID = getFieldIDCheck(env, bitmap_class, "mLayoutBounds", "[I"); 673 int ret = AndroidRuntime::registerNativeMethods(env, 674 "android/graphics/BitmapFactory$Options", 675 gOptionsMethods, 676 SK_ARRAY_COUNT(gOptionsMethods)); 677 if (ret) { 678 return ret; 679 } 680 return android::AndroidRuntime::registerNativeMethods(env, "android/graphics/BitmapFactory", 681 gMethods, SK_ARRAY_COUNT(gMethods)); 682} 683