blob: 3ca4e726c918d3e6024e294418a475d1f57bf8ea [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_ninePatchInsetsFieldID;
45
46jclass gInsetStruct_class;
47jmethodID gInsetStruct_constructorMethodID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049using namespace android;
50
Joseph Wenf1f48bc2010-07-19 16:59:51 +080051jstring getMimeTypeString(JNIEnv* env, SkImageDecoder::Format format) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052 static const struct {
53 SkImageDecoder::Format fFormat;
54 const char* fMimeType;
55 } gMimeTypes[] = {
56 { SkImageDecoder::kBMP_Format, "image/bmp" },
57 { SkImageDecoder::kGIF_Format, "image/gif" },
58 { SkImageDecoder::kICO_Format, "image/x-ico" },
59 { SkImageDecoder::kJPEG_Format, "image/jpeg" },
60 { SkImageDecoder::kPNG_Format, "image/png" },
Chris Craik95587f92013-07-12 19:46:19 -070061 { SkImageDecoder::kWEBP_Format, "image/webp" },
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062 { SkImageDecoder::kWBMP_Format, "image/vnd.wap.wbmp" }
63 };
Elliott Hughesa3804cf2011-04-11 16:50:19 -070064
Vladimir Marko7ab249a2015-01-06 18:17:52 +000065 const char* cstr = nullptr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066 for (size_t i = 0; i < SK_ARRAY_COUNT(gMimeTypes); i++) {
67 if (gMimeTypes[i].fFormat == format) {
68 cstr = gMimeTypes[i].fMimeType;
69 break;
70 }
71 }
72
Vladimir Marko7ab249a2015-01-06 18:17:52 +000073 jstring jstr = nullptr;
74 if (cstr != nullptr) {
75 // NOTE: Caller should env->ExceptionCheck() for OOM
76 // (can't check for nullptr as it's a valid return value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077 jstr = env->NewStringUTF(cstr);
78 }
79 return jstr;
80}
81
Bryan Mawhinney2a3d7542010-11-03 17:23:57 +000082static bool optionsJustBounds(JNIEnv* env, jobject options) {
Romain Guycaf813f2012-03-15 18:57:48 -070083 return options != NULL && env->GetBooleanField(options, gOptions_justBoundsFieldID);
Bryan Mawhinney2a3d7542010-11-03 17:23:57 +000084}
85
Chris Craikbd8db2e82014-08-20 16:31:57 -070086static void scaleDivRange(int32_t* divs, int count, float scale, int maxValue) {
87 for (int i = 0; i < count; i++) {
88 divs[i] = int32_t(divs[i] * scale + 0.5f);
89 if (i > 0 && divs[i] == divs[i - 1]) {
90 divs[i]++; // avoid collisions
91 }
92 }
93
94 if (CC_UNLIKELY(divs[count - 1] > maxValue)) {
95 // if the collision avoidance above put some divs outside the bounds of the bitmap,
96 // slide outer stretchable divs inward to stay within bounds
97 int highestAvailable = maxValue;
98 for (int i = count - 1; i >= 0; i--) {
99 divs[i] = highestAvailable;
100 if (i > 0 && divs[i] <= divs[i-1]){
101 // keep shifting
102 highestAvailable = divs[i] - 1;
103 } else {
104 break;
105 }
106 }
107 }
108}
109
110static void scaleNinePatchChunk(android::Res_png_9patch* chunk, float scale,
111 int scaledWidth, int scaledHeight) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700112 chunk->paddingLeft = int(chunk->paddingLeft * scale + 0.5f);
113 chunk->paddingTop = int(chunk->paddingTop * scale + 0.5f);
114 chunk->paddingRight = int(chunk->paddingRight * scale + 0.5f);
115 chunk->paddingBottom = int(chunk->paddingBottom * scale + 0.5f);
116
Chris Craikbd8db2e82014-08-20 16:31:57 -0700117 scaleDivRange(chunk->getXDivs(), chunk->numXDivs, scale, scaledWidth);
118 scaleDivRange(chunk->getYDivs(), chunk->numYDivs, scale, scaledHeight);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700119}
120
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500121static SkColorType colorTypeForScaledOutput(SkColorType colorType) {
122 switch (colorType) {
123 case kUnknown_SkColorType:
124 case kIndex_8_SkColorType:
Mike Reed4a9c3892014-07-07 15:44:40 -0400125 return kN32_SkColorType;
Chris Craik905e8242013-06-05 09:59:05 -0700126 default:
127 break;
128 }
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500129 return colorType;
Chris Craik905e8242013-06-05 09:59:05 -0700130}
131
132class ScaleCheckingAllocator : public SkBitmap::HeapAllocator {
133public:
134 ScaleCheckingAllocator(float scale, int size)
135 : mScale(scale), mSize(size) {
136 }
137
138 virtual bool allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable) {
139 // accounts for scale in final allocation, using eventual size and config
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500140 const int bytesPerPixel = SkColorTypeBytesPerPixel(
141 colorTypeForScaledOutput(bitmap->colorType()));
Chris Craik905e8242013-06-05 09:59:05 -0700142 const int requestedSize = bytesPerPixel *
143 int(bitmap->width() * mScale + 0.5f) *
144 int(bitmap->height() * mScale + 0.5f);
145 if (requestedSize > mSize) {
146 ALOGW("bitmap for alloc reuse (%d bytes) can't fit scaled bitmap (%d bytes)",
147 mSize, requestedSize);
148 return false;
149 }
150 return SkBitmap::HeapAllocator::allocPixelRef(bitmap, ctable);
151 }
152private:
153 const float mScale;
154 const int mSize;
155};
156
Chris Craik7e8c03c2013-06-03 13:53:36 -0700157class RecyclingPixelAllocator : public SkBitmap::Allocator {
158public:
John Reckf29ed282015-04-07 07:32:03 -0700159 RecyclingPixelAllocator(android::Bitmap* bitmap, unsigned int size)
160 : mBitmap(bitmap), mSize(size) {
Chris Craik7e8c03c2013-06-03 13:53:36 -0700161 }
162
163 ~RecyclingPixelAllocator() {
Chris Craik7e8c03c2013-06-03 13:53:36 -0700164 }
165
166 virtual bool allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable) {
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500167 const SkImageInfo& info = bitmap->info();
168 if (info.fColorType == kUnknown_SkColorType) {
169 ALOGW("unable to reuse a bitmap as the target has an unknown bitmap configuration");
Chris Craik7e8c03c2013-06-03 13:53:36 -0700170 return false;
171 }
Chris Craikcd0ba712013-09-06 14:40:30 -0700172
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500173 const int64_t size64 = info.getSafeSize64(bitmap->rowBytes());
174 if (!sk_64_isS32(size64)) {
175 ALOGW("bitmap is too large");
176 return false;
177 }
178
179 const size_t size = sk_64_asS32(size64);
180 if (size > mSize) {
Dan Albert46d84442014-11-18 16:07:51 -0800181 ALOGW("bitmap marked for reuse (%u bytes) can't fit new bitmap "
182 "(%zu bytes)", mSize, size);
Derek Sollenbergerb644a3b2014-01-17 15:45:10 -0500183 return false;
184 }
185
John Reckf29ed282015-04-07 07:32:03 -0700186 mBitmap->reconfigure(info, bitmap->rowBytes(), ctable);
John Reckae2e8b42015-05-06 14:55:05 -0700187 bitmap->setPixelRef(mBitmap->refPixelRef())->unref();
Chris Craikcd0ba712013-09-06 14:40:30 -0700188
Chris Craikcd0ba712013-09-06 14:40:30 -0700189 // since we're already allocated, we lockPixels right away
190 // HeapAllocator/JavaPixelAllocator behaves this way too
Chris Craik7e8c03c2013-06-03 13:53:36 -0700191 bitmap->lockPixels();
192 return true;
193 }
194
195private:
John Reckf29ed282015-04-07 07:32:03 -0700196 android::Bitmap* const mBitmap;
Chris Craik7e8c03c2013-06-03 13:53:36 -0700197 const unsigned int mSize;
198};
199
Chris Craik47cd8e92014-07-08 17:13:08 -0700200static jobject doDecode(JNIEnv* env, SkStreamRewindable* stream, jobject padding, jobject options) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 int sampleSize = 1;
Romain Guy7b2f8b82012-03-19 17:18:54 -0700203
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400204 SkImageDecoder::Mode decodeMode = SkImageDecoder::kDecodePixels_Mode;
Mike Reed42a1d082014-07-07 18:06:18 -0400205 SkColorType prefColorType = kN32_SkColorType;
Romain Guy7b2f8b82012-03-19 17:18:54 -0700206
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207 bool doDither = true;
Romain Guy23610982011-01-17 12:51:55 -0800208 bool isMutable = false;
Chris Craik905e8242013-06-05 09:59:05 -0700209 float scale = 1.0f;
Wei-Ta Chen953f9092010-12-03 14:06:18 -0800210 bool preferQualityOverSpeed = false;
Chris Craik1abf5d62013-08-16 12:47:03 -0700211 bool requireUnpremultiplied = false;
Romain Guy7b2f8b82012-03-19 17:18:54 -0700212
Chet Haase37f74ca2010-12-08 17:56:36 -0800213 jobject javaBitmap = NULL;
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700214
Romain Guy7b2f8b82012-03-19 17:18:54 -0700215 if (options != NULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216 sampleSize = env->GetIntField(options, gOptions_sampleSizeFieldID);
Bryan Mawhinney2a3d7542010-11-03 17:23:57 +0000217 if (optionsJustBounds(env, options)) {
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400218 decodeMode = SkImageDecoder::kDecodeBounds_Mode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219 }
Romain Guy7b2f8b82012-03-19 17:18:54 -0700220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 // initialize these, in case we fail later on
222 env->SetIntField(options, gOptions_widthFieldID, -1);
223 env->SetIntField(options, gOptions_heightFieldID, -1);
224 env->SetObjectField(options, gOptions_mimeFieldID, 0);
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 jobject jconfig = env->GetObjectField(options, gOptions_configFieldID);
Mike Reed42a1d082014-07-07 18:06:18 -0400227 prefColorType = GraphicsJNI::getNativeBitmapColorType(env, jconfig);
Romain Guy23610982011-01-17 12:51:55 -0800228 isMutable = env->GetBooleanField(options, gOptions_mutableFieldID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 doDither = env->GetBooleanField(options, gOptions_ditherFieldID);
Wei-Ta Chen953f9092010-12-03 14:06:18 -0800230 preferQualityOverSpeed = env->GetBooleanField(options,
231 gOptions_preferQualityOverSpeedFieldID);
Chris Craik1abf5d62013-08-16 12:47:03 -0700232 requireUnpremultiplied = !env->GetBooleanField(options, gOptions_premultipliedFieldID);
Chet Haase37f74ca2010-12-08 17:56:36 -0800233 javaBitmap = env->GetObjectField(options, gOptions_bitmapFieldID);
Chris Craik905e8242013-06-05 09:59:05 -0700234
235 if (env->GetBooleanField(options, gOptions_scaledFieldID)) {
236 const int density = env->GetIntField(options, gOptions_densityFieldID);
237 const int targetDensity = env->GetIntField(options, gOptions_targetDensityFieldID);
238 const int screenDensity = env->GetIntField(options, gOptions_screenDensityFieldID);
239 if (density != 0 && targetDensity != 0 && density != screenDensity) {
240 scale = (float) targetDensity / density;
241 }
242 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243 }
244
Chris Craik905e8242013-06-05 09:59:05 -0700245 const bool willScale = scale != 1.0f;
Romain Guy7b2f8b82012-03-19 17:18:54 -0700246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 SkImageDecoder* decoder = SkImageDecoder::Factory(stream);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700248 if (decoder == NULL) {
Mike Reedc70e06b2009-04-24 11:09:12 -0400249 return nullObjectReturn("SkImageDecoder::Factory returned null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 }
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 decoder->setSampleSize(sampleSize);
253 decoder->setDitherImage(doDither);
Wei-Ta Chen953f9092010-12-03 14:06:18 -0800254 decoder->setPreferQualityOverSpeed(preferQualityOverSpeed);
Chris Craik1abf5d62013-08-16 12:47:03 -0700255 decoder->setRequireUnpremultipliedColors(requireUnpremultiplied);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256
John Reckf29ed282015-04-07 07:32:03 -0700257 android::Bitmap* reuseBitmap = nullptr;
Chris Craik9f583612013-05-20 18:13:47 -0700258 unsigned int existingBufferSize = 0;
Chris Craik7e8c03c2013-06-03 13:53:36 -0700259 if (javaBitmap != NULL) {
John Reckf29ed282015-04-07 07:32:03 -0700260 reuseBitmap = GraphicsJNI::getBitmap(env, javaBitmap);
John Reckae2e8b42015-05-06 14:55:05 -0700261 if (reuseBitmap->peekAtPixelRef()->isImmutable()) {
Derek Sollenberger2a6ecae2012-08-31 14:03:51 -0400262 ALOGW("Unable to reuse an immutable bitmap as an image decoder target.");
Chris Craik7e8c03c2013-06-03 13:53:36 -0700263 javaBitmap = NULL;
John Reckf29ed282015-04-07 07:32:03 -0700264 reuseBitmap = nullptr;
Chris Craik7e8c03c2013-06-03 13:53:36 -0700265 } else {
266 existingBufferSize = GraphicsJNI::getBitmapAllocationByteCount(env, javaBitmap);
Derek Sollenberger2a6ecae2012-08-31 14:03:51 -0400267 }
Chet Haase37f74ca2010-12-08 17:56:36 -0800268 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269
Chris Craik7e8c03c2013-06-03 13:53:36 -0700270 NinePatchPeeker peeker(decoder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800271 decoder->setPeeker(&peeker);
Mike Reedc70e06b2009-04-24 11:09:12 -0400272
Chris Craik905e8242013-06-05 09:59:05 -0700273 JavaPixelAllocator javaAllocator(env);
John Reckf29ed282015-04-07 07:32:03 -0700274 RecyclingPixelAllocator recyclingAllocator(reuseBitmap, existingBufferSize);
Chris Craik905e8242013-06-05 09:59:05 -0700275 ScaleCheckingAllocator scaleCheckingAllocator(scale, existingBufferSize);
276 SkBitmap::Allocator* outputAllocator = (javaBitmap != NULL) ?
277 (SkBitmap::Allocator*)&recyclingAllocator : (SkBitmap::Allocator*)&javaAllocator;
278 if (decodeMode != SkImageDecoder::kDecodeBounds_Mode) {
279 if (!willScale) {
Leon Scroggins III1ffe7272013-09-19 11:34:06 -0400280 // If the java allocator is being used to allocate the pixel memory, the decoder
281 // need not write zeroes, since the memory is initialized to 0.
282 decoder->setSkipWritingZeroes(outputAllocator == &javaAllocator);
Chris Craik905e8242013-06-05 09:59:05 -0700283 decoder->setAllocator(outputAllocator);
284 } else if (javaBitmap != NULL) {
285 // check for eventual scaled bounds at allocation time, so we don't decode the bitmap
286 // only to find the scaled result too large to fit in the allocation
287 decoder->setAllocator(&scaleCheckingAllocator);
288 }
289 }
290
Derek Sollenberger6b0437c2013-06-24 15:40:54 -0400291 // Only setup the decoder to be deleted after its stack-based, refcounted
292 // components (allocators, peekers, etc) are declared. This prevents RefCnt
293 // asserts from firing due to the order objects are deleted from the stack.
294 SkAutoTDelete<SkImageDecoder> add(decoder);
295
296 AutoDecoderCancel adc(options, decoder);
297
298 // To fix the race condition in case "requestCancelDecode"
299 // happens earlier than AutoDecoderCancel object is added
300 // to the gAutoDecoderCancelMutex linked list.
301 if (options != NULL && env->GetBooleanField(options, gOptions_mCancelID)) {
302 return nullObjectReturn("gOptions_mCancelID");
303 }
304
Chris Craik7e8c03c2013-06-03 13:53:36 -0700305 SkBitmap decodingBitmap;
Leon Scroggins III14494262014-10-17 15:23:37 -0400306 if (decoder->decode(stream, &decodingBitmap, prefColorType, decodeMode)
307 != SkImageDecoder::kSuccess) {
Mike Reedc70e06b2009-04-24 11:09:12 -0400308 return nullObjectReturn("decoder->decode returned false");
309 }
310
Chris Craik7e8c03c2013-06-03 13:53:36 -0700311 int scaledWidth = decodingBitmap.width();
312 int scaledHeight = decodingBitmap.height();
Romain Guy7b2f8b82012-03-19 17:18:54 -0700313
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400314 if (willScale && decodeMode != SkImageDecoder::kDecodeBounds_Mode) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700315 scaledWidth = int(scaledWidth * scale + 0.5f);
316 scaledHeight = int(scaledHeight * scale + 0.5f);
317 }
318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319 // update options (if any)
Romain Guy7b2f8b82012-03-19 17:18:54 -0700320 if (options != NULL) {
Vladimir Marko7ab249a2015-01-06 18:17:52 +0000321 jstring mimeType = getMimeTypeString(env, decoder->getFormat());
322 if (env->ExceptionCheck()) {
323 return nullObjectReturn("OOM in getMimeTypeString()");
324 }
Romain Guy7b2f8b82012-03-19 17:18:54 -0700325 env->SetIntField(options, gOptions_widthFieldID, scaledWidth);
326 env->SetIntField(options, gOptions_heightFieldID, scaledHeight);
Vladimir Marko7ab249a2015-01-06 18:17:52 +0000327 env->SetObjectField(options, gOptions_mimeFieldID, mimeType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800328 }
Mike Reedc70e06b2009-04-24 11:09:12 -0400329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330 // if we're in justBounds mode, return now (skip the java bitmap)
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400331 if (decodeMode == SkImageDecoder::kDecodeBounds_Mode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332 return NULL;
333 }
334
335 jbyteArray ninePatchChunk = NULL;
Chris Craik47cd8e92014-07-08 17:13:08 -0700336 if (peeker.mPatch != NULL) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700337 if (willScale) {
Chris Craikbd8db2e82014-08-20 16:31:57 -0700338 scaleNinePatchChunk(peeker.mPatch, scale, scaledWidth, scaledHeight);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700339 }
340
Chris Craik47cd8e92014-07-08 17:13:08 -0700341 size_t ninePatchArraySize = peeker.mPatch->serializedSize();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800342 ninePatchChunk = env->NewByteArray(ninePatchArraySize);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700343 if (ninePatchChunk == NULL) {
Mike Reedc70e06b2009-04-24 11:09:12 -0400344 return nullObjectReturn("ninePatchChunk == null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345 }
Romain Guy7b2f8b82012-03-19 17:18:54 -0700346
347 jbyte* array = (jbyte*) env->GetPrimitiveArrayCritical(ninePatchChunk, NULL);
348 if (array == NULL) {
Mike Reedc70e06b2009-04-24 11:09:12 -0400349 return nullObjectReturn("primitive array == null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800350 }
Romain Guy7b2f8b82012-03-19 17:18:54 -0700351
Chris Craik47cd8e92014-07-08 17:13:08 -0700352 memcpy(array, peeker.mPatch, peeker.mPatchSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800353 env->ReleasePrimitiveArrayCritical(ninePatchChunk, array, 0);
354 }
355
Chris Craik47cd8e92014-07-08 17:13:08 -0700356 jobject ninePatchInsets = NULL;
357 if (peeker.mHasInsets) {
358 ninePatchInsets = env->NewObject(gInsetStruct_class, gInsetStruct_constructorMethodID,
359 peeker.mOpticalInsets[0], peeker.mOpticalInsets[1], peeker.mOpticalInsets[2], peeker.mOpticalInsets[3],
360 peeker.mOutlineInsets[0], peeker.mOutlineInsets[1], peeker.mOutlineInsets[2], peeker.mOutlineInsets[3],
Chris Craik77b5cad2014-07-30 18:23:07 -0700361 peeker.mOutlineRadius, peeker.mOutlineAlpha, scale);
Mathieu Chartiera08d10f2014-08-29 16:55:55 -0700362 if (ninePatchInsets == NULL) {
363 return nullObjectReturn("nine patch insets == null");
364 }
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700365 if (javaBitmap != NULL) {
Chris Craik47cd8e92014-07-08 17:13:08 -0700366 env->SetObjectField(javaBitmap, gBitmap_ninePatchInsetsFieldID, ninePatchInsets);
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700367 }
368 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369
John Reckf29ed282015-04-07 07:32:03 -0700370 SkBitmap outputBitmap;
Romain Guy7b2f8b82012-03-19 17:18:54 -0700371 if (willScale) {
372 // This is weird so let me explain: we could use the scale parameter
373 // directly, but for historical reasons this is how the corresponding
374 // Dalvik code has always behaved. We simply recreate the behavior here.
375 // The result is slightly different from simply using scale because of
376 // the 0.5f rounding bias applied when computing the target image size
Chris Craik7e8c03c2013-06-03 13:53:36 -0700377 const float sx = scaledWidth / float(decodingBitmap.width());
378 const float sy = scaledHeight / float(decodingBitmap.height());
Romain Guy7b2f8b82012-03-19 17:18:54 -0700379
Chris Craik905e8242013-06-05 09:59:05 -0700380 // TODO: avoid copying when scaled size equals decodingBitmap size
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500381 SkColorType colorType = colorTypeForScaledOutput(decodingBitmap.colorType());
Leon Scroggins III8790be62013-12-03 16:26:51 -0500382 // FIXME: If the alphaType is kUnpremul and the image has alpha, the
383 // colors may not be correct, since Skia does not yet support drawing
384 // to/from unpremultiplied bitmaps.
John Reckf29ed282015-04-07 07:32:03 -0700385 outputBitmap.setInfo(SkImageInfo::Make(scaledWidth, scaledHeight,
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500386 colorType, decodingBitmap.alphaType()));
John Reckf29ed282015-04-07 07:32:03 -0700387 if (!outputBitmap.tryAllocPixels(outputAllocator, NULL)) {
Raph Levien005bfc62012-09-20 22:51:47 -0700388 return nullObjectReturn("allocation failed for scaled bitmap");
389 }
Leon Scroggins III1ffe7272013-09-19 11:34:06 -0400390
391 // If outputBitmap's pixels are newly allocated by Java, there is no need
392 // to erase to 0, since the pixels were initialized to 0.
393 if (outputAllocator != &javaAllocator) {
John Reckf29ed282015-04-07 07:32:03 -0700394 outputBitmap.eraseColor(0);
Leon Scroggins III1ffe7272013-09-19 11:34:06 -0400395 }
Romain Guy7b2f8b82012-03-19 17:18:54 -0700396
397 SkPaint paint;
Mike Reed2a1ce8a2015-03-16 11:16:09 -0400398 paint.setFilterQuality(kLow_SkFilterQuality);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700399
John Reckf29ed282015-04-07 07:32:03 -0700400 SkCanvas canvas(outputBitmap);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700401 canvas.scale(sx, sy);
John Reckf29ed282015-04-07 07:32:03 -0700402 canvas.drawARGB(0x00, 0x00, 0x00, 0x00);
Chris Craik7e8c03c2013-06-03 13:53:36 -0700403 canvas.drawBitmap(decodingBitmap, 0.0f, 0.0f, &paint);
404 } else {
John Reckf29ed282015-04-07 07:32:03 -0700405 outputBitmap.swap(decodingBitmap);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700406 }
407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800408 if (padding) {
Chris Craik47cd8e92014-07-08 17:13:08 -0700409 if (peeker.mPatch != NULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800410 GraphicsJNI::set_jrect(env, padding,
Chris Craik47cd8e92014-07-08 17:13:08 -0700411 peeker.mPatch->paddingLeft, peeker.mPatch->paddingTop,
412 peeker.mPatch->paddingRight, peeker.mPatch->paddingBottom);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800413 } else {
414 GraphicsJNI::set_jrect(env, padding, -1, -1, -1, -1);
415 }
416 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800417
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400418 // if we get here, we're in kDecodePixels_Mode and will therefore
419 // already have a pixelref installed.
John Reckf29ed282015-04-07 07:32:03 -0700420 if (outputBitmap.pixelRef() == NULL) {
Marco Nelissenb2fe3be2012-05-07 11:24:13 -0700421 return nullObjectReturn("Got null SkPixelRef");
422 }
Romain Guy23610982011-01-17 12:51:55 -0800423
Chris Craik7e8c03c2013-06-03 13:53:36 -0700424 if (!isMutable && javaBitmap == NULL) {
Romain Guy23610982011-01-17 12:51:55 -0800425 // promise we will never change our pixels (great for sharing and pictures)
John Reckf29ed282015-04-07 07:32:03 -0700426 outputBitmap.setImmutable();
Romain Guy23610982011-01-17 12:51:55 -0800427 }
Chet Haase37f74ca2010-12-08 17:56:36 -0800428
Chris Craik7e8c03c2013-06-03 13:53:36 -0700429 if (javaBitmap != NULL) {
Chris Craik1abf5d62013-08-16 12:47:03 -0700430 bool isPremultiplied = !requireUnpremultiplied;
John Reckf29ed282015-04-07 07:32:03 -0700431 GraphicsJNI::reinitBitmap(env, javaBitmap, outputBitmap.info(), isPremultiplied);
432 outputBitmap.notifyPixelsChanged();
Chet Haase37f74ca2010-12-08 17:56:36 -0800433 // If a java bitmap was passed in for reuse, pass it back
434 return javaBitmap;
435 }
Chris Craik1abf5d62013-08-16 12:47:03 -0700436
437 int bitmapCreateFlags = 0x0;
438 if (isMutable) bitmapCreateFlags |= GraphicsJNI::kBitmapCreateFlag_Mutable;
439 if (!requireUnpremultiplied) bitmapCreateFlags |= GraphicsJNI::kBitmapCreateFlag_Premultiplied;
440
Mike Reedc70e06b2009-04-24 11:09:12 -0400441 // now create the java bitmap
John Reckf29ed282015-04-07 07:32:03 -0700442 return GraphicsJNI::createBitmap(env, javaAllocator.getStorageObjAndReset(),
Chris Craik47cd8e92014-07-08 17:13:08 -0700443 bitmapCreateFlags, ninePatchChunk, ninePatchInsets, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800444}
445
Leon Scroggins III2826e5f2014-02-05 19:46:02 -0500446// Need to buffer enough input to be able to rewind as much as might be read by a decoder
447// trying to determine the stream's format. Currently the most is 64, read by
448// SkImageDecoder_libwebp.
449// FIXME: Get this number from SkImageDecoder
450#define BYTES_TO_BUFFER 64
451
Chris Craik905e8242013-06-05 09:59:05 -0700452static jobject nativeDecodeStream(JNIEnv* env, jobject clazz, jobject is, jbyteArray storage,
453 jobject padding, jobject options) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455 jobject bitmap = NULL;
Leon Scroggins III34497892015-01-20 15:52:43 -0500456 SkAutoTDelete<SkStream> stream(CreateJavaInputStreamAdaptor(env, is, storage));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800457
Leon Scroggins IIIca320212013-08-20 17:59:39 -0400458 if (stream.get()) {
Leon Scroggins III34497892015-01-20 15:52:43 -0500459 SkAutoTDelete<SkStreamRewindable> bufferedStream(
460 SkFrontBufferedStream::Create(stream.detach(), BYTES_TO_BUFFER));
Leon Scroggins III7315f1b2013-09-10 20:26:05 -0400461 SkASSERT(bufferedStream.get() != NULL);
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400462 bitmap = doDecode(env, bufferedStream, padding, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800463 }
464 return bitmap;
465}
466
Romain Guy7b2f8b82012-03-19 17:18:54 -0700467static jobject nativeDecodeFileDescriptor(JNIEnv* env, jobject clazz, jobject fileDescriptor,
468 jobject padding, jobject bitmapFactoryOptions) {
469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800470 NPE_CHECK_RETURN_ZERO(env, fileDescriptor);
471
Derek Sollenberger5cb769d2014-09-24 09:20:09 -0400472 int descriptor = jniGetFDFromFileDescriptor(env, fileDescriptor);
Mike Reedc70e06b2009-04-24 11:09:12 -0400473
Derek Sollenberger5827cb52013-07-26 14:58:06 -0400474 struct stat fdStat;
475 if (fstat(descriptor, &fdStat) == -1) {
476 doThrowIOE(env, "broken file descriptor");
477 return nullObjectReturn("fstat return -1");
478 }
479
Derek Sollenberger5cb769d2014-09-24 09:20:09 -0400480 // Restore the descriptor's offset on exiting this function. Even though
481 // we dup the descriptor, both the original and dup refer to the same open
482 // file description and changes to the file offset in one impact the other.
Jérôme Poichetd29c9022014-09-26 18:59:11 +0000483 AutoFDSeek autoRestore(descriptor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484
Derek Sollenberger5cb769d2014-09-24 09:20:09 -0400485 // Duplicate the descriptor here to prevent leaking memory. A leak occurs
486 // if we only close the file descriptor and not the file object it is used to
487 // create. If we don't explicitly clean up the file (which in turn closes the
488 // descriptor) the buffers allocated internally by fseek will be leaked.
489 int dupDescriptor = dup(descriptor);
490
491 FILE* file = fdopen(dupDescriptor, "r");
Leon Scroggins III0102f8a2014-01-14 15:14:57 -0500492 if (file == NULL) {
Derek Sollenberger5cb769d2014-09-24 09:20:09 -0400493 // cleanup the duplicated descriptor since it will not be closed when the
494 // file is cleaned up (fclose).
495 close(dupDescriptor);
Leon Scroggins III0102f8a2014-01-14 15:14:57 -0500496 return nullObjectReturn("Could not open file");
Leon Scroggins IIIf65183f2013-10-07 16:32:14 -0400497 }
Leon Scroggins III0102f8a2014-01-14 15:14:57 -0500498
Leon Scroggins III34497892015-01-20 15:52:43 -0500499 SkAutoTDelete<SkFILEStream> fileStream(new SkFILEStream(file,
500 SkFILEStream::kCallerPasses_Ownership));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800501
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400502 // Use a buffered stream. Although an SkFILEStream can be rewound, this
503 // ensures that SkImageDecoder::Factory never rewinds beyond the
504 // current position of the file descriptor.
Leon Scroggins III34497892015-01-20 15:52:43 -0500505 SkAutoTDelete<SkStreamRewindable> stream(SkFrontBufferedStream::Create(fileStream.detach(),
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400506 BYTES_TO_BUFFER));
Leon Scroggins III2826e5f2014-02-05 19:46:02 -0500507
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400508 return doDecode(env, stream, padding, bitmapFactoryOptions);
Mike Reedc70e06b2009-04-24 11:09:12 -0400509}
510
Ashok Bhat36bef0b2014-01-20 20:08:01 +0000511static jobject nativeDecodeAsset(JNIEnv* env, jobject clazz, jlong native_asset,
Chris Craik905e8242013-06-05 09:59:05 -0700512 jobject padding, jobject options) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700513
Mike Reedc70e06b2009-04-24 11:09:12 -0400514 Asset* asset = reinterpret_cast<Asset*>(native_asset);
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400515 // since we know we'll be done with the asset when we return, we can
516 // just use a simple wrapper
Leon Scroggins III34497892015-01-20 15:52:43 -0500517 SkAutoTDelete<SkStreamRewindable> stream(new AssetStreamAdaptor(asset));
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400518 return doDecode(env, stream, padding, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800519}
520
521static jobject nativeDecodeByteArray(JNIEnv* env, jobject, jbyteArray byteArray,
Ashok Bhat36bef0b2014-01-20 20:08:01 +0000522 jint offset, jint length, jobject options) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700523
Mike Reedc70e06b2009-04-24 11:09:12 -0400524 AutoJavaByteArray ar(env, byteArray);
Leon Scroggins III34497892015-01-20 15:52:43 -0500525 SkAutoTDelete<SkMemoryStream> stream(new SkMemoryStream(ar.ptr() + offset, length, false));
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400526 return doDecode(env, stream, NULL, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800527}
528
529static void nativeRequestCancel(JNIEnv*, jobject joptions) {
530 (void)AutoDecoderCancel::RequestCancel(joptions);
531}
532
Owen Lina9d0d472011-01-18 17:39:15 +0800533static jboolean nativeIsSeekable(JNIEnv* env, jobject, jobject fileDescriptor) {
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700534 jint descriptor = jniGetFDFromFileDescriptor(env, fileDescriptor);
Owen Lina9d0d472011-01-18 17:39:15 +0800535 return ::lseek64(descriptor, 0, SEEK_CUR) != -1 ? JNI_TRUE : JNI_FALSE;
536}
537
John Reck41478772015-04-10 13:35:27 -0700538jobject decodeBitmap(JNIEnv* env, void* data, size_t size) {
539 SkMemoryStream stream(data, size);
540 return doDecode(env, &stream, NULL, NULL);
541}
542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800543///////////////////////////////////////////////////////////////////////////////
544
545static JNINativeMethod gMethods[] = {
546 { "nativeDecodeStream",
547 "(Ljava/io/InputStream;[BLandroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
548 (void*)nativeDecodeStream
549 },
550
551 { "nativeDecodeFileDescriptor",
552 "(Ljava/io/FileDescriptor;Landroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
553 (void*)nativeDecodeFileDescriptor
554 },
555
556 { "nativeDecodeAsset",
Ashok Bhat36bef0b2014-01-20 20:08:01 +0000557 "(JLandroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800558 (void*)nativeDecodeAsset
559 },
560
561 { "nativeDecodeByteArray",
562 "([BIILandroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
563 (void*)nativeDecodeByteArray
564 },
565
Owen Lina9d0d472011-01-18 17:39:15 +0800566 { "nativeIsSeekable",
567 "(Ljava/io/FileDescriptor;)Z",
568 (void*)nativeIsSeekable
569 },
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800570};
571
572static JNINativeMethod gOptionsMethods[] = {
573 { "requestCancel", "()V", (void*)nativeRequestCancel }
574};
575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576int register_android_graphics_BitmapFactory(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800577 jclass options_class = FindClassOrDie(env, "android/graphics/BitmapFactory$Options");
578 gOptions_bitmapFieldID = GetFieldIDOrDie(env, options_class, "inBitmap",
Chris Craik47cd8e92014-07-08 17:13:08 -0700579 "Landroid/graphics/Bitmap;");
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800580 gOptions_justBoundsFieldID = GetFieldIDOrDie(env, options_class, "inJustDecodeBounds", "Z");
581 gOptions_sampleSizeFieldID = GetFieldIDOrDie(env, options_class, "inSampleSize", "I");
582 gOptions_configFieldID = GetFieldIDOrDie(env, options_class, "inPreferredConfig",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 "Landroid/graphics/Bitmap$Config;");
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800584 gOptions_premultipliedFieldID = GetFieldIDOrDie(env, options_class, "inPremultiplied", "Z");
585 gOptions_mutableFieldID = GetFieldIDOrDie(env, options_class, "inMutable", "Z");
586 gOptions_ditherFieldID = GetFieldIDOrDie(env, options_class, "inDither", "Z");
587 gOptions_preferQualityOverSpeedFieldID = GetFieldIDOrDie(env, options_class,
Wei-Ta Chen953f9092010-12-03 14:06:18 -0800588 "inPreferQualityOverSpeed", "Z");
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800589 gOptions_scaledFieldID = GetFieldIDOrDie(env, options_class, "inScaled", "Z");
590 gOptions_densityFieldID = GetFieldIDOrDie(env, options_class, "inDensity", "I");
591 gOptions_screenDensityFieldID = GetFieldIDOrDie(env, options_class, "inScreenDensity", "I");
592 gOptions_targetDensityFieldID = GetFieldIDOrDie(env, options_class, "inTargetDensity", "I");
593 gOptions_widthFieldID = GetFieldIDOrDie(env, options_class, "outWidth", "I");
594 gOptions_heightFieldID = GetFieldIDOrDie(env, options_class, "outHeight", "I");
595 gOptions_mimeFieldID = GetFieldIDOrDie(env, options_class, "outMimeType", "Ljava/lang/String;");
596 gOptions_mCancelID = GetFieldIDOrDie(env, options_class, "mCancel", "Z");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800598 jclass bitmap_class = FindClassOrDie(env, "android/graphics/Bitmap");
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800599 gBitmap_ninePatchInsetsFieldID = GetFieldIDOrDie(env, bitmap_class, "mNinePatchInsets",
Chris Craik47cd8e92014-07-08 17:13:08 -0700600 "Landroid/graphics/NinePatch$InsetStruct;");
601
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800602 gInsetStruct_class = MakeGlobalRefOrDie(env, FindClassOrDie(env,
603 "android/graphics/NinePatch$InsetStruct"));
604 gInsetStruct_constructorMethodID = GetMethodIDOrDie(env, gInsetStruct_class, "<init>",
605 "(IIIIIIIIFIF)V");
Chris Craik47cd8e92014-07-08 17:13:08 -0700606
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800607 android::RegisterMethodsOrDie(env, "android/graphics/BitmapFactory$Options",
608 gOptionsMethods, NELEM(gOptionsMethods));
609 return android::RegisterMethodsOrDie(env, "android/graphics/BitmapFactory",
610 gMethods, NELEM(gMethods));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611}