blob: df6605b33c613980980495a7e113b12a42cc7136 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001#define LOG_TAG "BitmapFactory"
2
Joseph Wenf1f48bc2010-07-19 16:59:51 +08003#include "BitmapFactory.h"
Leon Scrogginsa06d86a2011-03-02 16:56:54 -05004#include "NinePatchPeeker.h"
Leon Scroggins III7315f1b2013-09-10 20:26:05 -04005#include "SkFrontBufferedStream.h"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006#include "SkImageDecoder.h"
Leon Scroggins46cb9bd2014-03-06 15:36:39 -05007#include "SkMath.h"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008#include "SkPixelRef.h"
9#include "SkStream.h"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010#include "SkTemplates.h"
11#include "SkUtils.h"
12#include "CreateJavaOutputStreamAdaptor.h"
Joseph Wenf1f48bc2010-07-19 16:59:51 +080013#include "AutoDecodeCancel.h"
Wei-Ta Chen6b849e22010-09-07 17:32:18 +080014#include "Utils.h"
Elliott Hughesa3804cf2011-04-11 16:50:19 -070015#include "JNIHelp.h"
Chris Craik1abf5d62013-08-16 12:47:03 -070016#include "GraphicsJNI.h"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080017
Andreas Gampeed6b9df2014-11-20 22:02:20 -080018#include "core_jni_helpers.h"
Mathias Agopianb13b9bd2012-02-17 18:27:36 -080019#include <androidfw/Asset.h>
20#include <androidfw/ResourceTypes.h>
Chris Craikbd8db2e82014-08-20 16:31:57 -070021#include <cutils/compiler.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022#include <netinet/in.h>
Leon Scroggins III0102f8a2014-01-14 15:14:57 -050023#include <stdio.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024#include <sys/mman.h>
Joseph Wen2dcfbef2010-09-10 10:15:09 +080025#include <sys/stat.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026
Joseph Wenf1f48bc2010-07-19 16:59:51 +080027jfieldID gOptions_justBoundsFieldID;
28jfieldID gOptions_sampleSizeFieldID;
29jfieldID gOptions_configFieldID;
Chris Craik1abf5d62013-08-16 12:47:03 -070030jfieldID gOptions_premultipliedFieldID;
Romain Guy23610982011-01-17 12:51:55 -080031jfieldID gOptions_mutableFieldID;
Joseph Wenf1f48bc2010-07-19 16:59:51 +080032jfieldID gOptions_ditherFieldID;
Wei-Ta Chen953f9092010-12-03 14:06:18 -080033jfieldID gOptions_preferQualityOverSpeedFieldID;
Chris Craik905e8242013-06-05 09:59:05 -070034jfieldID gOptions_scaledFieldID;
35jfieldID gOptions_densityFieldID;
36jfieldID gOptions_screenDensityFieldID;
37jfieldID gOptions_targetDensityFieldID;
Joseph Wenf1f48bc2010-07-19 16:59:51 +080038jfieldID gOptions_widthFieldID;
39jfieldID gOptions_heightFieldID;
40jfieldID gOptions_mimeFieldID;
41jfieldID gOptions_mCancelID;
Chet Haase37f74ca2010-12-08 17:56:36 -080042jfieldID gOptions_bitmapFieldID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043
Chris Craik47cd8e92014-07-08 17:13:08 -070044jfieldID gBitmap_nativeBitmapFieldID;
45jfieldID gBitmap_ninePatchInsetsFieldID;
46
47jclass gInsetStruct_class;
48jmethodID gInsetStruct_constructorMethodID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050using namespace android;
51
Joseph Wenf1f48bc2010-07-19 16:59:51 +080052jstring getMimeTypeString(JNIEnv* env, SkImageDecoder::Format format) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053 static const struct {
54 SkImageDecoder::Format fFormat;
55 const char* fMimeType;
56 } gMimeTypes[] = {
57 { SkImageDecoder::kBMP_Format, "image/bmp" },
58 { SkImageDecoder::kGIF_Format, "image/gif" },
59 { SkImageDecoder::kICO_Format, "image/x-ico" },
60 { SkImageDecoder::kJPEG_Format, "image/jpeg" },
61 { SkImageDecoder::kPNG_Format, "image/png" },
Chris Craik95587f92013-07-12 19:46:19 -070062 { SkImageDecoder::kWEBP_Format, "image/webp" },
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063 { SkImageDecoder::kWBMP_Format, "image/vnd.wap.wbmp" }
64 };
Elliott Hughesa3804cf2011-04-11 16:50:19 -070065
Vladimir Marko7ab249a2015-01-06 18:17:52 +000066 const char* cstr = nullptr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067 for (size_t i = 0; i < SK_ARRAY_COUNT(gMimeTypes); i++) {
68 if (gMimeTypes[i].fFormat == format) {
69 cstr = gMimeTypes[i].fMimeType;
70 break;
71 }
72 }
73
Vladimir Marko7ab249a2015-01-06 18:17:52 +000074 jstring jstr = nullptr;
75 if (cstr != nullptr) {
76 // NOTE: Caller should env->ExceptionCheck() for OOM
77 // (can't check for nullptr as it's a valid return value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078 jstr = env->NewStringUTF(cstr);
79 }
80 return jstr;
81}
82
Bryan Mawhinney2a3d7542010-11-03 17:23:57 +000083static bool optionsJustBounds(JNIEnv* env, jobject options) {
Romain Guycaf813f2012-03-15 18:57:48 -070084 return options != NULL && env->GetBooleanField(options, gOptions_justBoundsFieldID);
Bryan Mawhinney2a3d7542010-11-03 17:23:57 +000085}
86
Chris Craikbd8db2e82014-08-20 16:31:57 -070087static void scaleDivRange(int32_t* divs, int count, float scale, int maxValue) {
88 for (int i = 0; i < count; i++) {
89 divs[i] = int32_t(divs[i] * scale + 0.5f);
90 if (i > 0 && divs[i] == divs[i - 1]) {
91 divs[i]++; // avoid collisions
92 }
93 }
94
95 if (CC_UNLIKELY(divs[count - 1] > maxValue)) {
96 // if the collision avoidance above put some divs outside the bounds of the bitmap,
97 // slide outer stretchable divs inward to stay within bounds
98 int highestAvailable = maxValue;
99 for (int i = count - 1; i >= 0; i--) {
100 divs[i] = highestAvailable;
101 if (i > 0 && divs[i] <= divs[i-1]){
102 // keep shifting
103 highestAvailable = divs[i] - 1;
104 } else {
105 break;
106 }
107 }
108 }
109}
110
111static void scaleNinePatchChunk(android::Res_png_9patch* chunk, float scale,
112 int scaledWidth, int scaledHeight) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700113 chunk->paddingLeft = int(chunk->paddingLeft * scale + 0.5f);
114 chunk->paddingTop = int(chunk->paddingTop * scale + 0.5f);
115 chunk->paddingRight = int(chunk->paddingRight * scale + 0.5f);
116 chunk->paddingBottom = int(chunk->paddingBottom * scale + 0.5f);
117
Chris Craikbd8db2e82014-08-20 16:31:57 -0700118 scaleDivRange(chunk->getXDivs(), chunk->numXDivs, scale, scaledWidth);
119 scaleDivRange(chunk->getYDivs(), chunk->numYDivs, scale, scaledHeight);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700120}
121
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500122static SkColorType colorTypeForScaledOutput(SkColorType colorType) {
123 switch (colorType) {
124 case kUnknown_SkColorType:
125 case kIndex_8_SkColorType:
Mike Reed4a9c3892014-07-07 15:44:40 -0400126 return kN32_SkColorType;
Chris Craik905e8242013-06-05 09:59:05 -0700127 default:
128 break;
129 }
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500130 return colorType;
Chris Craik905e8242013-06-05 09:59:05 -0700131}
132
133class ScaleCheckingAllocator : public SkBitmap::HeapAllocator {
134public:
135 ScaleCheckingAllocator(float scale, int size)
136 : mScale(scale), mSize(size) {
137 }
138
139 virtual bool allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable) {
140 // accounts for scale in final allocation, using eventual size and config
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500141 const int bytesPerPixel = SkColorTypeBytesPerPixel(
142 colorTypeForScaledOutput(bitmap->colorType()));
Chris Craik905e8242013-06-05 09:59:05 -0700143 const int requestedSize = bytesPerPixel *
144 int(bitmap->width() * mScale + 0.5f) *
145 int(bitmap->height() * mScale + 0.5f);
146 if (requestedSize > mSize) {
147 ALOGW("bitmap for alloc reuse (%d bytes) can't fit scaled bitmap (%d bytes)",
148 mSize, requestedSize);
149 return false;
150 }
151 return SkBitmap::HeapAllocator::allocPixelRef(bitmap, ctable);
152 }
153private:
154 const float mScale;
155 const int mSize;
156};
157
Chris Craik7e8c03c2013-06-03 13:53:36 -0700158class RecyclingPixelAllocator : public SkBitmap::Allocator {
159public:
160 RecyclingPixelAllocator(SkPixelRef* pixelRef, unsigned int size)
Chris Craik905e8242013-06-05 09:59:05 -0700161 : mPixelRef(pixelRef), mSize(size) {
Chris Craik7e8c03c2013-06-03 13:53:36 -0700162 SkSafeRef(mPixelRef);
163 }
164
165 ~RecyclingPixelAllocator() {
166 SkSafeUnref(mPixelRef);
167 }
168
169 virtual bool allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable) {
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500170 const SkImageInfo& info = bitmap->info();
171 if (info.fColorType == kUnknown_SkColorType) {
172 ALOGW("unable to reuse a bitmap as the target has an unknown bitmap configuration");
Chris Craik7e8c03c2013-06-03 13:53:36 -0700173 return false;
174 }
Chris Craikcd0ba712013-09-06 14:40:30 -0700175
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500176 const int64_t size64 = info.getSafeSize64(bitmap->rowBytes());
177 if (!sk_64_isS32(size64)) {
178 ALOGW("bitmap is too large");
179 return false;
180 }
181
182 const size_t size = sk_64_asS32(size64);
183 if (size > mSize) {
Dan Albert46d84442014-11-18 16:07:51 -0800184 ALOGW("bitmap marked for reuse (%u bytes) can't fit new bitmap "
185 "(%zu bytes)", mSize, size);
Derek Sollenbergerb644a3b2014-01-17 15:45:10 -0500186 return false;
187 }
188
Chris Craikcd0ba712013-09-06 14:40:30 -0700189 // Create a new pixelref with the new ctable that wraps the previous pixelref
Derek Sollenbergerb644a3b2014-01-17 15:45:10 -0500190 SkPixelRef* pr = new AndroidPixelRef(*static_cast<AndroidPixelRef*>(mPixelRef),
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500191 info, bitmap->rowBytes(), ctable);
Chris Craikcd0ba712013-09-06 14:40:30 -0700192
193 bitmap->setPixelRef(pr)->unref();
194 // since we're already allocated, we lockPixels right away
195 // HeapAllocator/JavaPixelAllocator behaves this way too
Chris Craik7e8c03c2013-06-03 13:53:36 -0700196 bitmap->lockPixels();
197 return true;
198 }
199
200private:
201 SkPixelRef* const mPixelRef;
202 const unsigned int mSize;
203};
204
Chris Craik47cd8e92014-07-08 17:13:08 -0700205static jobject doDecode(JNIEnv* env, SkStreamRewindable* stream, jobject padding, jobject options) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700206
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207 int sampleSize = 1;
Romain Guy7b2f8b82012-03-19 17:18:54 -0700208
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400209 SkImageDecoder::Mode decodeMode = SkImageDecoder::kDecodePixels_Mode;
Mike Reed42a1d082014-07-07 18:06:18 -0400210 SkColorType prefColorType = kN32_SkColorType;
Romain Guy7b2f8b82012-03-19 17:18:54 -0700211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212 bool doDither = true;
Romain Guy23610982011-01-17 12:51:55 -0800213 bool isMutable = false;
Chris Craik905e8242013-06-05 09:59:05 -0700214 float scale = 1.0f;
Wei-Ta Chen953f9092010-12-03 14:06:18 -0800215 bool preferQualityOverSpeed = false;
Chris Craik1abf5d62013-08-16 12:47:03 -0700216 bool requireUnpremultiplied = false;
Romain Guy7b2f8b82012-03-19 17:18:54 -0700217
Chet Haase37f74ca2010-12-08 17:56:36 -0800218 jobject javaBitmap = NULL;
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700219
Romain Guy7b2f8b82012-03-19 17:18:54 -0700220 if (options != NULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 sampleSize = env->GetIntField(options, gOptions_sampleSizeFieldID);
Bryan Mawhinney2a3d7542010-11-03 17:23:57 +0000222 if (optionsJustBounds(env, options)) {
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400223 decodeMode = SkImageDecoder::kDecodeBounds_Mode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224 }
Romain Guy7b2f8b82012-03-19 17:18:54 -0700225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 // initialize these, in case we fail later on
227 env->SetIntField(options, gOptions_widthFieldID, -1);
228 env->SetIntField(options, gOptions_heightFieldID, -1);
229 env->SetObjectField(options, gOptions_mimeFieldID, 0);
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 jobject jconfig = env->GetObjectField(options, gOptions_configFieldID);
Mike Reed42a1d082014-07-07 18:06:18 -0400232 prefColorType = GraphicsJNI::getNativeBitmapColorType(env, jconfig);
Romain Guy23610982011-01-17 12:51:55 -0800233 isMutable = env->GetBooleanField(options, gOptions_mutableFieldID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 doDither = env->GetBooleanField(options, gOptions_ditherFieldID);
Wei-Ta Chen953f9092010-12-03 14:06:18 -0800235 preferQualityOverSpeed = env->GetBooleanField(options,
236 gOptions_preferQualityOverSpeedFieldID);
Chris Craik1abf5d62013-08-16 12:47:03 -0700237 requireUnpremultiplied = !env->GetBooleanField(options, gOptions_premultipliedFieldID);
Chet Haase37f74ca2010-12-08 17:56:36 -0800238 javaBitmap = env->GetObjectField(options, gOptions_bitmapFieldID);
Chris Craik905e8242013-06-05 09:59:05 -0700239
240 if (env->GetBooleanField(options, gOptions_scaledFieldID)) {
241 const int density = env->GetIntField(options, gOptions_densityFieldID);
242 const int targetDensity = env->GetIntField(options, gOptions_targetDensityFieldID);
243 const int screenDensity = env->GetIntField(options, gOptions_screenDensityFieldID);
244 if (density != 0 && targetDensity != 0 && density != screenDensity) {
245 scale = (float) targetDensity / density;
246 }
247 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 }
249
Chris Craik905e8242013-06-05 09:59:05 -0700250 const bool willScale = scale != 1.0f;
Romain Guy7b2f8b82012-03-19 17:18:54 -0700251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 SkImageDecoder* decoder = SkImageDecoder::Factory(stream);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700253 if (decoder == NULL) {
Mike Reedc70e06b2009-04-24 11:09:12 -0400254 return nullObjectReturn("SkImageDecoder::Factory returned null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 }
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257 decoder->setSampleSize(sampleSize);
258 decoder->setDitherImage(doDither);
Wei-Ta Chen953f9092010-12-03 14:06:18 -0800259 decoder->setPreferQualityOverSpeed(preferQualityOverSpeed);
Chris Craik1abf5d62013-08-16 12:47:03 -0700260 decoder->setRequireUnpremultipliedColors(requireUnpremultiplied);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800261
Chris Craik7e8c03c2013-06-03 13:53:36 -0700262 SkBitmap* outputBitmap = NULL;
Chris Craik9f583612013-05-20 18:13:47 -0700263 unsigned int existingBufferSize = 0;
Chris Craik7e8c03c2013-06-03 13:53:36 -0700264 if (javaBitmap != NULL) {
Ashok Bhat36bef0b2014-01-20 20:08:01 +0000265 outputBitmap = (SkBitmap*) env->GetLongField(javaBitmap, gBitmap_nativeBitmapFieldID);
Chris Craik7e8c03c2013-06-03 13:53:36 -0700266 if (outputBitmap->isImmutable()) {
Derek Sollenberger2a6ecae2012-08-31 14:03:51 -0400267 ALOGW("Unable to reuse an immutable bitmap as an image decoder target.");
Chris Craik7e8c03c2013-06-03 13:53:36 -0700268 javaBitmap = NULL;
269 outputBitmap = NULL;
270 } else {
271 existingBufferSize = GraphicsJNI::getBitmapAllocationByteCount(env, javaBitmap);
Derek Sollenberger2a6ecae2012-08-31 14:03:51 -0400272 }
Chet Haase37f74ca2010-12-08 17:56:36 -0800273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274
Chris Craik7e8c03c2013-06-03 13:53:36 -0700275 SkAutoTDelete<SkBitmap> adb(outputBitmap == NULL ? new SkBitmap : NULL);
276 if (outputBitmap == NULL) outputBitmap = adb.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800277
Chris Craik7e8c03c2013-06-03 13:53:36 -0700278 NinePatchPeeker peeker(decoder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279 decoder->setPeeker(&peeker);
Mike Reedc70e06b2009-04-24 11:09:12 -0400280
Chris Craik905e8242013-06-05 09:59:05 -0700281 JavaPixelAllocator javaAllocator(env);
282 RecyclingPixelAllocator recyclingAllocator(outputBitmap->pixelRef(), existingBufferSize);
283 ScaleCheckingAllocator scaleCheckingAllocator(scale, existingBufferSize);
284 SkBitmap::Allocator* outputAllocator = (javaBitmap != NULL) ?
285 (SkBitmap::Allocator*)&recyclingAllocator : (SkBitmap::Allocator*)&javaAllocator;
286 if (decodeMode != SkImageDecoder::kDecodeBounds_Mode) {
287 if (!willScale) {
Leon Scroggins III1ffe7272013-09-19 11:34:06 -0400288 // If the java allocator is being used to allocate the pixel memory, the decoder
289 // need not write zeroes, since the memory is initialized to 0.
290 decoder->setSkipWritingZeroes(outputAllocator == &javaAllocator);
Chris Craik905e8242013-06-05 09:59:05 -0700291 decoder->setAllocator(outputAllocator);
292 } else if (javaBitmap != NULL) {
293 // check for eventual scaled bounds at allocation time, so we don't decode the bitmap
294 // only to find the scaled result too large to fit in the allocation
295 decoder->setAllocator(&scaleCheckingAllocator);
296 }
297 }
298
Derek Sollenberger6b0437c2013-06-24 15:40:54 -0400299 // Only setup the decoder to be deleted after its stack-based, refcounted
300 // components (allocators, peekers, etc) are declared. This prevents RefCnt
301 // asserts from firing due to the order objects are deleted from the stack.
302 SkAutoTDelete<SkImageDecoder> add(decoder);
303
304 AutoDecoderCancel adc(options, decoder);
305
306 // To fix the race condition in case "requestCancelDecode"
307 // happens earlier than AutoDecoderCancel object is added
308 // to the gAutoDecoderCancelMutex linked list.
309 if (options != NULL && env->GetBooleanField(options, gOptions_mCancelID)) {
310 return nullObjectReturn("gOptions_mCancelID");
311 }
312
Chris Craik7e8c03c2013-06-03 13:53:36 -0700313 SkBitmap decodingBitmap;
Leon Scroggins III14494262014-10-17 15:23:37 -0400314 if (decoder->decode(stream, &decodingBitmap, prefColorType, decodeMode)
315 != SkImageDecoder::kSuccess) {
Mike Reedc70e06b2009-04-24 11:09:12 -0400316 return nullObjectReturn("decoder->decode returned false");
317 }
318
Chris Craik7e8c03c2013-06-03 13:53:36 -0700319 int scaledWidth = decodingBitmap.width();
320 int scaledHeight = decodingBitmap.height();
Romain Guy7b2f8b82012-03-19 17:18:54 -0700321
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400322 if (willScale && decodeMode != SkImageDecoder::kDecodeBounds_Mode) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700323 scaledWidth = int(scaledWidth * scale + 0.5f);
324 scaledHeight = int(scaledHeight * scale + 0.5f);
325 }
326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 // update options (if any)
Romain Guy7b2f8b82012-03-19 17:18:54 -0700328 if (options != NULL) {
Vladimir Marko7ab249a2015-01-06 18:17:52 +0000329 jstring mimeType = getMimeTypeString(env, decoder->getFormat());
330 if (env->ExceptionCheck()) {
331 return nullObjectReturn("OOM in getMimeTypeString()");
332 }
Romain Guy7b2f8b82012-03-19 17:18:54 -0700333 env->SetIntField(options, gOptions_widthFieldID, scaledWidth);
334 env->SetIntField(options, gOptions_heightFieldID, scaledHeight);
Vladimir Marko7ab249a2015-01-06 18:17:52 +0000335 env->SetObjectField(options, gOptions_mimeFieldID, mimeType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800336 }
Mike Reedc70e06b2009-04-24 11:09:12 -0400337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800338 // if we're in justBounds mode, return now (skip the java bitmap)
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400339 if (decodeMode == SkImageDecoder::kDecodeBounds_Mode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800340 return NULL;
341 }
342
343 jbyteArray ninePatchChunk = NULL;
Chris Craik47cd8e92014-07-08 17:13:08 -0700344 if (peeker.mPatch != NULL) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700345 if (willScale) {
Chris Craikbd8db2e82014-08-20 16:31:57 -0700346 scaleNinePatchChunk(peeker.mPatch, scale, scaledWidth, scaledHeight);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700347 }
348
Chris Craik47cd8e92014-07-08 17:13:08 -0700349 size_t ninePatchArraySize = peeker.mPatch->serializedSize();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800350 ninePatchChunk = env->NewByteArray(ninePatchArraySize);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700351 if (ninePatchChunk == NULL) {
Mike Reedc70e06b2009-04-24 11:09:12 -0400352 return nullObjectReturn("ninePatchChunk == null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800353 }
Romain Guy7b2f8b82012-03-19 17:18:54 -0700354
355 jbyte* array = (jbyte*) env->GetPrimitiveArrayCritical(ninePatchChunk, NULL);
356 if (array == NULL) {
Mike Reedc70e06b2009-04-24 11:09:12 -0400357 return nullObjectReturn("primitive array == null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800358 }
Romain Guy7b2f8b82012-03-19 17:18:54 -0700359
Chris Craik47cd8e92014-07-08 17:13:08 -0700360 memcpy(array, peeker.mPatch, peeker.mPatchSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 env->ReleasePrimitiveArrayCritical(ninePatchChunk, array, 0);
362 }
363
Chris Craik47cd8e92014-07-08 17:13:08 -0700364 jobject ninePatchInsets = NULL;
365 if (peeker.mHasInsets) {
366 ninePatchInsets = env->NewObject(gInsetStruct_class, gInsetStruct_constructorMethodID,
367 peeker.mOpticalInsets[0], peeker.mOpticalInsets[1], peeker.mOpticalInsets[2], peeker.mOpticalInsets[3],
368 peeker.mOutlineInsets[0], peeker.mOutlineInsets[1], peeker.mOutlineInsets[2], peeker.mOutlineInsets[3],
Chris Craik77b5cad2014-07-30 18:23:07 -0700369 peeker.mOutlineRadius, peeker.mOutlineAlpha, scale);
Mathieu Chartiera08d10f2014-08-29 16:55:55 -0700370 if (ninePatchInsets == NULL) {
371 return nullObjectReturn("nine patch insets == null");
372 }
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700373 if (javaBitmap != NULL) {
Chris Craik47cd8e92014-07-08 17:13:08 -0700374 env->SetObjectField(javaBitmap, gBitmap_ninePatchInsetsFieldID, ninePatchInsets);
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700375 }
376 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800377
Romain Guy7b2f8b82012-03-19 17:18:54 -0700378 if (willScale) {
379 // This is weird so let me explain: we could use the scale parameter
380 // directly, but for historical reasons this is how the corresponding
381 // Dalvik code has always behaved. We simply recreate the behavior here.
382 // The result is slightly different from simply using scale because of
383 // the 0.5f rounding bias applied when computing the target image size
Chris Craik7e8c03c2013-06-03 13:53:36 -0700384 const float sx = scaledWidth / float(decodingBitmap.width());
385 const float sy = scaledHeight / float(decodingBitmap.height());
Romain Guy7b2f8b82012-03-19 17:18:54 -0700386
Chris Craik905e8242013-06-05 09:59:05 -0700387 // TODO: avoid copying when scaled size equals decodingBitmap size
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500388 SkColorType colorType = colorTypeForScaledOutput(decodingBitmap.colorType());
Leon Scroggins III8790be62013-12-03 16:26:51 -0500389 // FIXME: If the alphaType is kUnpremul and the image has alpha, the
390 // colors may not be correct, since Skia does not yet support drawing
391 // to/from unpremultiplied bitmaps.
Mike Reedb9330552014-06-16 17:31:48 -0400392 outputBitmap->setInfo(SkImageInfo::Make(scaledWidth, scaledHeight,
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500393 colorType, decodingBitmap.alphaType()));
Chris Craik905e8242013-06-05 09:59:05 -0700394 if (!outputBitmap->allocPixels(outputAllocator, NULL)) {
Raph Levien005bfc62012-09-20 22:51:47 -0700395 return nullObjectReturn("allocation failed for scaled bitmap");
396 }
Leon Scroggins III1ffe7272013-09-19 11:34:06 -0400397
398 // If outputBitmap's pixels are newly allocated by Java, there is no need
399 // to erase to 0, since the pixels were initialized to 0.
400 if (outputAllocator != &javaAllocator) {
401 outputBitmap->eraseColor(0);
402 }
Romain Guy7b2f8b82012-03-19 17:18:54 -0700403
404 SkPaint paint;
Derek Sollenbergerb644a3b2014-01-17 15:45:10 -0500405 paint.setFilterLevel(SkPaint::kLow_FilterLevel);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700406
Chris Craik7e8c03c2013-06-03 13:53:36 -0700407 SkCanvas canvas(*outputBitmap);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700408 canvas.scale(sx, sy);
Chris Craik7e8c03c2013-06-03 13:53:36 -0700409 canvas.drawBitmap(decodingBitmap, 0.0f, 0.0f, &paint);
410 } else {
411 outputBitmap->swap(decodingBitmap);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700412 }
413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800414 if (padding) {
Chris Craik47cd8e92014-07-08 17:13:08 -0700415 if (peeker.mPatch != NULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800416 GraphicsJNI::set_jrect(env, padding,
Chris Craik47cd8e92014-07-08 17:13:08 -0700417 peeker.mPatch->paddingLeft, peeker.mPatch->paddingTop,
418 peeker.mPatch->paddingRight, peeker.mPatch->paddingBottom);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800419 } else {
420 GraphicsJNI::set_jrect(env, padding, -1, -1, -1, -1);
421 }
422 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800423
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400424 // if we get here, we're in kDecodePixels_Mode and will therefore
425 // already have a pixelref installed.
426 if (outputBitmap->pixelRef() == NULL) {
Marco Nelissenb2fe3be2012-05-07 11:24:13 -0700427 return nullObjectReturn("Got null SkPixelRef");
428 }
Romain Guy23610982011-01-17 12:51:55 -0800429
Chris Craik7e8c03c2013-06-03 13:53:36 -0700430 if (!isMutable && javaBitmap == NULL) {
Romain Guy23610982011-01-17 12:51:55 -0800431 // promise we will never change our pixels (great for sharing and pictures)
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400432 outputBitmap->setImmutable();
Romain Guy23610982011-01-17 12:51:55 -0800433 }
Chet Haase37f74ca2010-12-08 17:56:36 -0800434
Jeff Brown27d83832012-05-09 17:30:31 -0700435 // detach bitmap from its autodeleter, since we want to own it now
436 adb.detach();
437
Chris Craik7e8c03c2013-06-03 13:53:36 -0700438 if (javaBitmap != NULL) {
Chris Craik1abf5d62013-08-16 12:47:03 -0700439 bool isPremultiplied = !requireUnpremultiplied;
440 GraphicsJNI::reinitBitmap(env, javaBitmap, outputBitmap, isPremultiplied);
Chris Craik7e8c03c2013-06-03 13:53:36 -0700441 outputBitmap->notifyPixelsChanged();
Chet Haase37f74ca2010-12-08 17:56:36 -0800442 // If a java bitmap was passed in for reuse, pass it back
443 return javaBitmap;
444 }
Chris Craik1abf5d62013-08-16 12:47:03 -0700445
446 int bitmapCreateFlags = 0x0;
447 if (isMutable) bitmapCreateFlags |= GraphicsJNI::kBitmapCreateFlag_Mutable;
448 if (!requireUnpremultiplied) bitmapCreateFlags |= GraphicsJNI::kBitmapCreateFlag_Premultiplied;
449
Mike Reedc70e06b2009-04-24 11:09:12 -0400450 // now create the java bitmap
Chris Craik7e8c03c2013-06-03 13:53:36 -0700451 return GraphicsJNI::createBitmap(env, outputBitmap, javaAllocator.getStorageObj(),
Chris Craik47cd8e92014-07-08 17:13:08 -0700452 bitmapCreateFlags, ninePatchChunk, ninePatchInsets, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453}
454
Leon Scroggins III2826e5f2014-02-05 19:46:02 -0500455// Need to buffer enough input to be able to rewind as much as might be read by a decoder
456// trying to determine the stream's format. Currently the most is 64, read by
457// SkImageDecoder_libwebp.
458// FIXME: Get this number from SkImageDecoder
459#define BYTES_TO_BUFFER 64
460
Chris Craik905e8242013-06-05 09:59:05 -0700461static jobject nativeDecodeStream(JNIEnv* env, jobject clazz, jobject is, jbyteArray storage,
462 jobject padding, jobject options) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800464 jobject bitmap = NULL;
Leon Scroggins III7315f1b2013-09-10 20:26:05 -0400465 SkAutoTUnref<SkStream> stream(CreateJavaInputStreamAdaptor(env, is, storage));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800466
Leon Scroggins IIIca320212013-08-20 17:59:39 -0400467 if (stream.get()) {
Leon Scroggins III2826e5f2014-02-05 19:46:02 -0500468 SkAutoTUnref<SkStreamRewindable> bufferedStream(
469 SkFrontBufferedStream::Create(stream, BYTES_TO_BUFFER));
Leon Scroggins III7315f1b2013-09-10 20:26:05 -0400470 SkASSERT(bufferedStream.get() != NULL);
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400471 bitmap = doDecode(env, bufferedStream, padding, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800472 }
473 return bitmap;
474}
475
Romain Guy7b2f8b82012-03-19 17:18:54 -0700476static jobject nativeDecodeFileDescriptor(JNIEnv* env, jobject clazz, jobject fileDescriptor,
477 jobject padding, jobject bitmapFactoryOptions) {
478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800479 NPE_CHECK_RETURN_ZERO(env, fileDescriptor);
480
Derek Sollenberger5cb769d2014-09-24 09:20:09 -0400481 int descriptor = jniGetFDFromFileDescriptor(env, fileDescriptor);
Mike Reedc70e06b2009-04-24 11:09:12 -0400482
Derek Sollenberger5827cb52013-07-26 14:58:06 -0400483 struct stat fdStat;
484 if (fstat(descriptor, &fdStat) == -1) {
485 doThrowIOE(env, "broken file descriptor");
486 return nullObjectReturn("fstat return -1");
487 }
488
Derek Sollenberger5cb769d2014-09-24 09:20:09 -0400489 // Restore the descriptor's offset on exiting this function. Even though
490 // we dup the descriptor, both the original and dup refer to the same open
491 // file description and changes to the file offset in one impact the other.
Jérôme Poichetd29c9022014-09-26 18:59:11 +0000492 AutoFDSeek autoRestore(descriptor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800493
Derek Sollenberger5cb769d2014-09-24 09:20:09 -0400494 // Duplicate the descriptor here to prevent leaking memory. A leak occurs
495 // if we only close the file descriptor and not the file object it is used to
496 // create. If we don't explicitly clean up the file (which in turn closes the
497 // descriptor) the buffers allocated internally by fseek will be leaked.
498 int dupDescriptor = dup(descriptor);
499
500 FILE* file = fdopen(dupDescriptor, "r");
Leon Scroggins III0102f8a2014-01-14 15:14:57 -0500501 if (file == NULL) {
Derek Sollenberger5cb769d2014-09-24 09:20:09 -0400502 // cleanup the duplicated descriptor since it will not be closed when the
503 // file is cleaned up (fclose).
504 close(dupDescriptor);
Leon Scroggins III0102f8a2014-01-14 15:14:57 -0500505 return nullObjectReturn("Could not open file");
Leon Scroggins IIIf65183f2013-10-07 16:32:14 -0400506 }
Leon Scroggins III0102f8a2014-01-14 15:14:57 -0500507
Leon Scroggins III2826e5f2014-02-05 19:46:02 -0500508 SkAutoTUnref<SkFILEStream> fileStream(new SkFILEStream(file,
Derek Sollenberger5cb769d2014-09-24 09:20:09 -0400509 SkFILEStream::kCallerPasses_Ownership));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800510
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400511 // Use a buffered stream. Although an SkFILEStream can be rewound, this
512 // ensures that SkImageDecoder::Factory never rewinds beyond the
513 // current position of the file descriptor.
514 SkAutoTUnref<SkStreamRewindable> stream(SkFrontBufferedStream::Create(fileStream,
515 BYTES_TO_BUFFER));
Leon Scroggins III2826e5f2014-02-05 19:46:02 -0500516
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400517 return doDecode(env, stream, padding, bitmapFactoryOptions);
Mike Reedc70e06b2009-04-24 11:09:12 -0400518}
519
Ashok Bhat36bef0b2014-01-20 20:08:01 +0000520static jobject nativeDecodeAsset(JNIEnv* env, jobject clazz, jlong native_asset,
Chris Craik905e8242013-06-05 09:59:05 -0700521 jobject padding, jobject options) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700522
Mike Reedc70e06b2009-04-24 11:09:12 -0400523 Asset* asset = reinterpret_cast<Asset*>(native_asset);
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400524 // since we know we'll be done with the asset when we return, we can
525 // just use a simple wrapper
526 SkAutoTUnref<SkStreamRewindable> stream(new AssetStreamAdaptor(asset,
527 AssetStreamAdaptor::kNo_OwnAsset, AssetStreamAdaptor::kNo_HasMemoryBase));
528 return doDecode(env, stream, padding, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800529}
530
531static jobject nativeDecodeByteArray(JNIEnv* env, jobject, jbyteArray byteArray,
Ashok Bhat36bef0b2014-01-20 20:08:01 +0000532 jint offset, jint length, jobject options) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700533
Mike Reedc70e06b2009-04-24 11:09:12 -0400534 AutoJavaByteArray ar(env, byteArray);
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400535 SkMemoryStream* stream = new SkMemoryStream(ar.ptr() + offset, length, false);
Mike Reedc70e06b2009-04-24 11:09:12 -0400536 SkAutoUnref aur(stream);
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400537 return doDecode(env, stream, NULL, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538}
539
540static void nativeRequestCancel(JNIEnv*, jobject joptions) {
541 (void)AutoDecoderCancel::RequestCancel(joptions);
542}
543
Owen Lina9d0d472011-01-18 17:39:15 +0800544static jboolean nativeIsSeekable(JNIEnv* env, jobject, jobject fileDescriptor) {
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700545 jint descriptor = jniGetFDFromFileDescriptor(env, fileDescriptor);
Owen Lina9d0d472011-01-18 17:39:15 +0800546 return ::lseek64(descriptor, 0, SEEK_CUR) != -1 ? JNI_TRUE : JNI_FALSE;
547}
548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549///////////////////////////////////////////////////////////////////////////////
550
Daniel Micay76f6a862015-09-19 17:31:01 -0400551static const JNINativeMethod gMethods[] = {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 { "nativeDecodeStream",
553 "(Ljava/io/InputStream;[BLandroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
554 (void*)nativeDecodeStream
555 },
556
557 { "nativeDecodeFileDescriptor",
558 "(Ljava/io/FileDescriptor;Landroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
559 (void*)nativeDecodeFileDescriptor
560 },
561
562 { "nativeDecodeAsset",
Ashok Bhat36bef0b2014-01-20 20:08:01 +0000563 "(JLandroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 (void*)nativeDecodeAsset
565 },
566
567 { "nativeDecodeByteArray",
568 "([BIILandroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
569 (void*)nativeDecodeByteArray
570 },
571
Owen Lina9d0d472011-01-18 17:39:15 +0800572 { "nativeIsSeekable",
573 "(Ljava/io/FileDescriptor;)Z",
574 (void*)nativeIsSeekable
575 },
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576};
577
Daniel Micay76f6a862015-09-19 17:31:01 -0400578static const JNINativeMethod gOptionsMethods[] = {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579 { "requestCancel", "()V", (void*)nativeRequestCancel }
580};
581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800582int register_android_graphics_BitmapFactory(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800583 jclass options_class = FindClassOrDie(env, "android/graphics/BitmapFactory$Options");
584 gOptions_bitmapFieldID = GetFieldIDOrDie(env, options_class, "inBitmap",
Chris Craik47cd8e92014-07-08 17:13:08 -0700585 "Landroid/graphics/Bitmap;");
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800586 gOptions_justBoundsFieldID = GetFieldIDOrDie(env, options_class, "inJustDecodeBounds", "Z");
587 gOptions_sampleSizeFieldID = GetFieldIDOrDie(env, options_class, "inSampleSize", "I");
588 gOptions_configFieldID = GetFieldIDOrDie(env, options_class, "inPreferredConfig",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800589 "Landroid/graphics/Bitmap$Config;");
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800590 gOptions_premultipliedFieldID = GetFieldIDOrDie(env, options_class, "inPremultiplied", "Z");
591 gOptions_mutableFieldID = GetFieldIDOrDie(env, options_class, "inMutable", "Z");
592 gOptions_ditherFieldID = GetFieldIDOrDie(env, options_class, "inDither", "Z");
593 gOptions_preferQualityOverSpeedFieldID = GetFieldIDOrDie(env, options_class,
Wei-Ta Chen953f9092010-12-03 14:06:18 -0800594 "inPreferQualityOverSpeed", "Z");
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800595 gOptions_scaledFieldID = GetFieldIDOrDie(env, options_class, "inScaled", "Z");
596 gOptions_densityFieldID = GetFieldIDOrDie(env, options_class, "inDensity", "I");
597 gOptions_screenDensityFieldID = GetFieldIDOrDie(env, options_class, "inScreenDensity", "I");
598 gOptions_targetDensityFieldID = GetFieldIDOrDie(env, options_class, "inTargetDensity", "I");
599 gOptions_widthFieldID = GetFieldIDOrDie(env, options_class, "outWidth", "I");
600 gOptions_heightFieldID = GetFieldIDOrDie(env, options_class, "outHeight", "I");
601 gOptions_mimeFieldID = GetFieldIDOrDie(env, options_class, "outMimeType", "Ljava/lang/String;");
602 gOptions_mCancelID = GetFieldIDOrDie(env, options_class, "mCancel", "Z");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800604 jclass bitmap_class = FindClassOrDie(env, "android/graphics/Bitmap");
605 gBitmap_nativeBitmapFieldID = GetFieldIDOrDie(env, bitmap_class, "mNativeBitmap", "J");
606 gBitmap_ninePatchInsetsFieldID = GetFieldIDOrDie(env, bitmap_class, "mNinePatchInsets",
Chris Craik47cd8e92014-07-08 17:13:08 -0700607 "Landroid/graphics/NinePatch$InsetStruct;");
608
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800609 gInsetStruct_class = MakeGlobalRefOrDie(env, FindClassOrDie(env,
610 "android/graphics/NinePatch$InsetStruct"));
611 gInsetStruct_constructorMethodID = GetMethodIDOrDie(env, gInsetStruct_class, "<init>",
612 "(IIIIIIIIFIF)V");
Chris Craik47cd8e92014-07-08 17:13:08 -0700613
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800614 android::RegisterMethodsOrDie(env, "android/graphics/BitmapFactory$Options",
615 gOptionsMethods, NELEM(gOptionsMethods));
616 return android::RegisterMethodsOrDie(env, "android/graphics/BitmapFactory",
617 gMethods, NELEM(gMethods));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618}